-
Notifications
You must be signed in to change notification settings - Fork 1
/
elf.ts
426 lines (364 loc) · 11.4 KB
/
elf.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
const fs = require('fs');
const EI_NIDENT = 16;
const ELFMAG = [127, 69, 76, 70];
const EI_CLASS = 4;
const ELFCLASSNONE = 0 /* Invalid class */
const ELFCLASS32 = 1; /* 32-bit objects */
const ELFCLASS64 = 2; /* 64-bit objects */
const ELFCLASSNUM = 3;
const EI_DATA = 5; /* Data encoding byte index */
const ELFDATANONE = 0; /* Invalid data encoding */
const ELFDATA2LSB = 1; /* 2's complement, little endian */
const ELFDATA2MSB = 2; /* 2's complement, big endian */
const ELFDATANUM = 3;
const EI_VERSION = 6; /* File version byte index */
const EI_OSABI = 7; /* OS ABI identification */
const ELFOSABI_LABELS: {[key: string]: string} = {
'0': 'SYSV',
'1': 'HPUX',
'2': 'NETBSD',
'3': 'LINUX',
'6': 'SOLARIS',
'7': 'AIX',
'8': 'IRIX',
'9': 'FREEBSD',
'10': 'TRU64',
'11': 'MODESTO',
'12': 'OPENBSD',
'64': 'ARM_AEABI',
'97': 'ARM',
'255': 'STANDALONE',
}
const EI_ABIVERSION = 8;
const sizeOfType: { [key: string]: number } = {
'u8': 1,
'u16': 2,
'u32': 4,
'u64': 8,
};
sizeOfType['half'] = sizeOfType['u16'];
sizeOfType['word'] = sizeOfType['u32'];
sizeOfType['addr'] = sizeOfType['u64'];
sizeOfType['off'] = sizeOfType['u64'];
sizeOfType['xword'] = sizeOfType['u64'];
type Scheme = Array<[string, string]>
type Struct = { [key: string]: number }
const Elf64_Ehdr: Scheme = [
['half', 'e_type'],
['half', 'e_machine'],
['word', 'e_version'],
['addr', 'e_entry'],
['off', 'e_phoff'],
['off', 'e_shoff'],
['word', 'e_flags'],
['half', 'e_ehsize'],
['half', 'e_phentsize'],
['half', 'e_phnum'],
['half', 'e_shentsize'],
['half', 'e_shnum'],
['half', 'e_shstrndx'],
];
const Elf64_Phdr: Scheme = [
['word', 'p_type'],
['word', 'p_flags'],
['off', 'p_offset'],
['addr', 'p_vaddr'],
['addr', 'p_paddr'],
['xword', 'p_filesz'],
['xword', 'p_memsz'],
['xword', 'p_align'],
];
type Endian = 'LSB' | 'MSB';
function serializeStruct(scheme: Scheme, struct: Struct, endian: Endian) {
// TODO: Get rid of Buffer. It is Node.js only. We need more universal code.
const result = Buffer.alloc(sizeOfStruct(scheme));
let bytesIndex = 0;
for (let i = 0; i < scheme.length; ++i) {
const [type, field] = scheme[i];
const size = sizeOfType[type];
const value = struct[field];
switch (endian) {
case 'LSB':
if (size == 8) result.writeBigUInt64LE(BigInt(value), bytesIndex);
else result.writeUIntLE(value, bytesIndex, size);
break;
case 'MSB':
if (size == 8) result.writeBigUInt64BE(BigInt(value), bytesIndex);
else result.writeUIntBE(value, bytesIndex, size);
break;
default:
throw 'unreachable';
}
bytesIndex += size;
}
return result;
}
function parseStruct(scheme: Scheme, bytes: Buffer, endian: Endian): Struct {
console.assert(endian === 'LSB');
console.assert(sizeOfStruct(scheme) === bytes.length);
const result: Struct = {};
let bytesIndex = 0;
for (let i = 0; i < scheme.length; ++i) {
const [type, field] = scheme[i];
const size = sizeOfType[type];
switch (endian) {
case 'LSB':
if (size == 8) {
const x = Number(bytes.readBigUInt64LE(bytesIndex));
console.assert(Number.isSafeInteger(x));
result[field] = x;
} else result[field] = bytes.readUIntLE(bytesIndex, size);
break;
case 'MSB':
if (size == 8) {
const x = Number(bytes.readBigUInt64BE(bytesIndex));
console.assert(Number.isSafeInteger(x));
result[field] = x;
}
else result[field] = bytes.readUIntBE(bytesIndex, size);
break;
default: throw 'unreachable';
}
bytesIndex += size;
}
return result;
}
function sizeOfStruct(scheme: Scheme) {
let size = 0;
for (let i = 0; i < scheme.length; ++i) {
size += sizeOfType[scheme[i][0]];
}
return size;
}
function verifyElfMag(bytes: Buffer) {
for (let i = 0; i < 4; ++i) {
if (bytes[i] != ELFMAG[i]) {
return false;
}
}
return true;
}
function getPhdrByIndex(fd: number, ehdr: Struct, index: number) {
const phdrBuffer = Buffer.alloc(sizeOfStruct(Elf64_Phdr));
const offset = ehdr.e_phoff + index*ehdr.e_phentsize;
fs.readSync(fd, phdrBuffer, 0, sizeOfStruct(Elf64_Phdr), offset);
const phdr = parseStruct(Elf64_Phdr, phdrBuffer, 'LSB');
return phdr;
}
type Reg = 0xC0 | 0xC7 | 0xC6 | 0xC2;
const RAX: Reg = 0xC0;
const RDI: Reg = 0xC7;
const RSI: Reg = 0xC6;
const RDX: Reg = 0xC2;
function syscall(): Buffer {
return Buffer.from([0x0f, 0x05]);
}
function mov(reg: Reg, value: number): Buffer {
const inst = Buffer.from([0x48, 0xc7, 0, 0, 0, 0, 0]);
inst.writeUInt8(reg, 2);
inst.writeUInt32LE(value, 3);
return inst;
}
const SYS_write = 1;
const SYS_exit = 60;
const STDOUT = 1;
type Addr = number;
function write(hello: Addr, hello_sz: number) {
return Buffer.concat([
mov(RAX, SYS_write),
mov(RDI, STDOUT),
mov(RSI, hello),
mov(RDX, hello_sz),
syscall()
]);
}
function exit(code: number) {
return Buffer.concat([
mov(RAX, SYS_exit),
mov(RDI, code),
syscall()
]);
}
function helloWorldProgram(hello: Addr, hello_sz: number) {
return Buffer.concat([
write(hello, hello_sz),
exit(0),
]);
}
interface Subcmd {
description: string
args: string
run: (args: Array<string>) => void
}
const subcmds: {[key: string]: Subcmd} = {
'parse': {
'description': 'Parse provided executable',
'args': '<FILE>',
'run': parseExecutable,
},
'gen': {
'description': 'Generate a new test executable that prints specified message',
'args': '<FILE> <MESSAGE>',
'run': generateExecutable,
},
'help': {
'description': 'Print this help message',
'args': '[SUBCOMMAND]',
'run': (args) => {
const name: string = args[0];
if (name) {
const subcmd = subcmds[name];
console.error(`Usage: node elf.js ${name} ${subcmd.args}`);
console.error(`Description:`);
console.error(` ${subcmd.description}`);
} else {
console.error('Usage: node elf.js [SUBCOMMAND] [ARGUMENTS]');
console.error('SUBCOMMANDS:');
for (let name in subcmds) {
console.error(` ${name} ${subcmds[name].args} - ${subcmds[name].description}`);
}
}
}
},
};
function parseExecutable(argv: Array<string>) {
const FILE_PATH = argv[0];
if (!FILE_PATH) {
subcmds.help.run(['parse']);
console.error('ERROR: No executable file is provided');
process.exit(1);
}
const fd = fs.openSync(FILE_PATH, 'r')
// TODO: use serialization "framework" for parsing e_ident
const n = 16;
const e_ident = Buffer.alloc(n);
fs.readSync(fd, e_ident, 0, n, null);
if (!verifyElfMag(e_ident.slice(0, 4))) {
console.error("ERROR: Invalid ELF magic");
return;
}
console.log(e_ident);
if (e_ident[EI_CLASS] == ELFCLASS32) {
console.log("Class: ELF32");
} else if (e_ident[EI_CLASS] == ELFCLASS64) {
console.log("Class: ELF64");
} else {
console.error("ERROR: invalid EI_CLASS ${e_ident[EI_CLASS]}");
return;
}
if (e_ident[EI_DATA] == ELFDATA2LSB) {
console.log("Data: 2's complement, little endian");
} else if (e_ident[EI_DATA] == ELFDATA2MSB) {
console.log("Data: 2's complement, big endian");
} else {
console.error("ERROR: invalid EI_DATA ${e_ident[EI_DATA]}");
return;
}
console.log(`Version: ${e_ident[EI_VERSION]}`);
console.log(`OS/ABI: ${ELFOSABI_LABELS[e_ident[EI_OSABI]]}`);
console.log(`ABI Version: ${e_ident[EI_ABIVERSION]}`)
console.log();
console.log("Ehdr:");
const ehdrBuffer = Buffer.alloc(sizeOfStruct(Elf64_Ehdr));
fs.readSync(fd, ehdrBuffer, 0, sizeOfStruct(Elf64_Ehdr), null);
// TODO: unhardcode endianess parsing
const ehdr = parseStruct(Elf64_Ehdr, ehdrBuffer, 'LSB');
console.log(ehdr);
console.log();
console.log("Phdrs:");
for (let i = 0; i < ehdr.e_phnum; ++i) {
console.log(getPhdrByIndex(fd, ehdr, i));
}
// * * * * * *
// 5 6 7 8 9 10
// ^ ^
//
// 6 - 3
console.log();
console.log("Machine Code:");
const dataPhdr = getPhdrByIndex(fd, ehdr, 0);
const offset = dataPhdr.p_offset + ehdr.e_entry - dataPhdr.p_vaddr;
const filesz = dataPhdr.p_filesz - offset;
const dataBuffer = Buffer.alloc(filesz);
fs.readSync(fd, dataBuffer, 0, filesz, offset);
console.log(dataBuffer);
}
function generateExecutable(args: Array<string>) {
const e_ident = Buffer.from([0x7F, 0x45, 0x4C, 0x46, 0x02, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
const FILE_PATH = args[0];
if (!FILE_PATH) {
subcmds.help.run(['gen']);
console.error('ERROR: no file path is provided');
process.exit(1);
}
const data = args[1];
if (!data) {
subcmds.help.run(['gen']);
console.error('ERROR: no message is provided');
process.exit(1);
}
const fd = fs.openSync(FILE_PATH, 'w');
fs.writeSync(fd, e_ident);
const ehdr = {
e_type: 2,
e_machine: 62,
e_version: 1,
e_entry: 4194480,
e_phoff: 64,
e_shoff: 0,
e_flags: 0,
e_ehsize: 64,
e_phentsize: 56,
e_phnum: 2,
e_shentsize: 64,
e_shnum: 0,
e_shstrndx: 0
};
fs.writeSync(fd, serializeStruct(Elf64_Ehdr, ehdr, 'LSB'));
const dataStartAddr = 4198622;
const eIdentSize = 16;
const elfGarbageSize = eIdentSize + sizeOfStruct(Elf64_Ehdr) + sizeOfStruct(Elf64_Phdr)*2;
const machineCode = helloWorldProgram(dataStartAddr, data.length);
const codePhdr = {
p_type: 1,
p_flags: 5,
p_offset: 0,
p_vaddr: 4194304,
p_paddr: 4194304,
p_filesz: elfGarbageSize + machineCode.length,
p_memsz: elfGarbageSize + machineCode.length,
p_align: 4096
};
// console.log(codePhdr);
fs.writeSync(fd, serializeStruct(Elf64_Phdr, codePhdr, 'LSB'));
const dataPhdr = {
p_type: 1,
p_flags: 6,
p_offset: elfGarbageSize + machineCode.length,
p_vaddr: dataStartAddr,
p_paddr: dataStartAddr,
p_filesz: data.length,
p_memsz: data.length,
p_align: 4096
};
// console.log(dataPhdr);
fs.writeSync(fd, serializeStruct(Elf64_Phdr, dataPhdr, 'LSB'));
fs.writeSync(fd, machineCode);
fs.writeSync(fd, data);
fs.closeSync(fd);
fs.chmodSync(FILE_PATH, 0o755);
}
function usage() {
console.error('Usage: node elf.js [SUBCOMMAND] [ARGUMENTS]');
console.error('SUBCOMMANDS:');
}
function main() {
const subcmd = subcmds[process.argv[2]];
if (!subcmd) {
subcmds.help.run([]);
console.error('ERROR: no subcommand is provided');
process.exit(1);
}
subcmd.run(process.argv.slice(3));
}
main();