forked from GJDuck/e9patch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathe9api.cpp
More file actions
687 lines (651 loc) · 23.3 KB
/
e9api.cpp
File metadata and controls
687 lines (651 loc) · 23.3 KB
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/*
* e9api.cpp
* Copyright (C) 2020 National University of Singapore
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <cstring>
#include <string>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "e9elf.h"
#include "e9emit.h"
#include "e9patch.h"
#include "e9json.h"
#include "e9tactics.h"
#include "e9x86_64.h"
/*
* Insert an instruction into a binary.
*/
void insertInstruction(Binary *B, Instr *I)
{
// Insert the instruction into the index:
auto result = B->Is.insert(std::make_pair((off_t)I->offset, I));
if (!result.second)
error("failed to insert instruction at offset (+%zu), another "
"instruction already exists at that offset", I->offset);
InstrSet::iterator i = result.first;
// Find and validate successor and predecessor instructions:
++i;
if (i != B->Is.end())
{
Instr *J = i->second;
if (I->offset + I->size > J->offset)
error("failed to insert instruction at offset (+%zu), instruction "
"overlaps with another instruction at offset (+%zu)",
I->offset, J->offset);
if (I->addr + I->size > J->addr)
error("failed to insert instruction at address (%p), instruction "
"overlaps with another instruction at address (%p)",
(void *)I->addr, (void *)J->addr);
I->next = J;
J->prev = I;
}
i = result.first;
if (i != B->Is.begin())
{
--i;
Instr *J = i->second;
if (J->offset + J->size > I->offset)
error("failed to insert instruction at offset (+%zu), instruction "
"overlaps with another instruction at offset (+%zu)",
I->offset, J->offset);
if (J->addr + J->size > I->addr)
error("failed to insert instruction at address (%p), instruction "
"overlaps with another instruction at address (%p)",
(void *)I->addr, (void *)J->addr);
I->prev = J;
J->next = I;
}
// Initialize the state:
for (unsigned i = 0; i < I->size; i++)
{
switch (I->patched.state[i])
{
case STATE_UNKNOWN:
I->patched.state[i] = STATE_INSTRUCTION;
break;
case STATE_INSTRUCTION | STATE_LOCKED:
case STATE_PATCHED:
case STATE_PATCHED | STATE_LOCKED:
case STATE_FREE:
error("failed to insert instruction at address (%p), the "
"corresponding virtual memory has already been patched",
(void *)(I->addr + i));
default:
error("failed to insert instruction at address (%p), the "
"corresponding virtual memory has already been allocated "
"with state (0x%.2X)", (void *)(I->addr + i),
I->patched.state[i]);
}
}
}
/*
* Parse a binary message.
*/
static Binary *parseBinary(const Message &msg)
{
const char *filename = nullptr;
Mode mode = MODE_EXECUTABLE;
bool have_mode = false, dup = false;
for (unsigned i = 0; i < msg.num_params; i++)
{
switch (msg.params[i].name)
{
case PARAM_FILENAME:
dup = dup || (filename != nullptr);
filename = msg.params[i].value.string;
break;
case PARAM_MODE:
dup = dup || have_mode;
mode = (Mode)msg.params[i].value.integer;
have_mode = true;
break;
default:
break;
}
}
if (filename == nullptr)
error("failed to parse \"binary\" message (id=%u); missing "
"\"filename\" parameter", msg.id);
if (dup)
error("failed to parse \"binary\" message (id=%u); duplicate "
"parameters detected", msg.id);
Binary *B = new Binary;
B->filename = filename;
B->mode = mode;
// Open the binary:
int fd = open(filename, O_RDONLY);
if (fd < 0)
error("failed to open file \"%s\" for reading: %s", filename,
strerror(errno));
// Determine the binary size:
struct stat buf;
if (fstat(fd, &buf) < 0)
error("failed to get length of file \"%s\": %s", filename,
strerror(errno));
size_t size = (size_t)buf.st_size;
B->size = size;
// Allocate extra space for file extensions.
const size_t EXTEND_SIZE = 32 * (1ull << 30); // 32GB
size_t ext_size = size + EXTEND_SIZE;
void *ptr = mmap(nullptr, ext_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (ptr == MAP_FAILED)
error("failed to reserve %zu bytes for file buffer: %s",
ext_size, strerror(errno));
// Map the file (for modification):
ptr = mmap(ptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED,
fd, 0);
if (ptr == MAP_FAILED)
{
mmap_failed:
error("failed to map file \"%s\": %s", filename, strerror(errno));
}
B->patched.bytes = (uint8_t *)ptr;
B->patched.size = size;
// Parse the mmaped ELF file:
parseElf(B->allocator, B->filename, B->patched.bytes, B->size, B->mode,
B->elf);
// Map the file (unmodified):
ptr = mmap(ptr, size, PROT_READ, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED)
goto mmap_failed;
B->original.bytes = (const uint8_t *)ptr;
B->original.fd = fd;
// Create the state:
ext_size = size + PAGE_SIZE;
ext_size = (ext_size % PAGE_SIZE == 0? ext_size: ext_size + PAGE_SIZE);
ext_size = ext_size - ext_size % PAGE_SIZE;
ptr = mmap(ptr, ext_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (ptr == MAP_FAILED)
error("failed to allocate state array for file \"%s\": %s",
filename, strerror(errno));
B->patched.state = (uint8_t *)ptr;
memset(B->patched.state + size, STATE_OVERFLOW, ext_size - size);
return B;
}
/*
* Parse an instruction message.
*/
static void parseInstruction(Binary *B, const Message &msg)
{
intptr_t address = 0;
size_t length = 0;
off_t offset = 0;
Metadata *meta = nullptr;
bool have_address = false, have_length = false, have_offset = false,
dup = false;
for (unsigned i = 0; i < msg.num_params; i++)
{
switch (msg.params[i].name)
{
case PARAM_ADDRESS:
dup = dup || have_address;
address = (intptr_t)msg.params[i].value.integer;
have_address = true;
break;
case PARAM_LENGTH:
dup = dup || have_length;
length = (size_t)msg.params[i].value.integer;
have_length = true;
break;
case PARAM_OFFSET:
dup = dup || have_offset;
offset = (off_t)msg.params[i].value.integer;
have_offset = true;
break;
case PARAM_METADATA:
dup = dup || (meta != nullptr);
meta = msg.params[i].value.metadata;
break;
default:
break;
}
}
if (!have_address)
error("failed to parse \"instruction\" message (id=%u); missing "
"\"address\" parameter", msg.id);
if (!have_length)
error("failed to parse \"instruction\" message (id=%u); missing "
"\"length\" parameter", msg.id);
if (length == 0 || length > 15)
error("failed to parse \"instruction\" message (id=%u); \"length\" "
"parameter must be within the range 1..15", msg.id);
if (!have_offset)
error("failed to parse \"instruction\" message (id=%u); missing "
"\"offset\" parameter", msg.id);
if (offset < 0)
error("failed to parse \"instruction\" message (id=%u); the "
"instruction offset (%zd) is negative", msg.id, offset);
if (offset + length > B->size)
error("failed to parse \"instruction\" message (id=%u); the "
"instruction offset+length (%zd+%zu) overflows "
"the end-of-file \"%s\" (with size %zu)", msg.id, offset, length,
B->size, B->filename);
if (dup)
error("failed to parse \"instruction\" message (id=%u); duplicate "
"parameters detected", msg.id);
size_t pcrel32_idx = 0, pcrel8_idx = 0;
unsigned pcrel_idx = getInstrPCRelativeIndex(B->original.bytes + offset,
length);
if (pcrel_idx != 0)
{
if (length - pcrel_idx < sizeof(int32_t))
pcrel8_idx = pcrel_idx; // Must be pcrel8
else
pcrel32_idx = pcrel_idx; // Must be pcrel32
}
Instr *I = new Instr(offset, address, length, B->original.bytes + offset,
B->patched.bytes + offset, B->patched.state + offset, meta,
pcrel32_idx, pcrel8_idx, B->elf.pic);
insertInstruction(B, I);
}
/*
* Parse a patch message.
*/
static void parsePatch(Binary *B, const Message &msg)
{
const char *trampoline = nullptr;
off_t offset = 0;
bool have_offset = false, dup = false;
for (unsigned i = 0; i < msg.num_params; i++)
{
switch (msg.params[i].name)
{
case PARAM_TRAMPOLINE:
dup = dup || (trampoline != nullptr);
trampoline = msg.params[i].value.string;
break;
case PARAM_OFFSET:
dup = dup || have_offset;
offset = (off_t)msg.params[i].value.integer;
have_offset = true;
break;
default:
break;
}
}
if (trampoline == nullptr)
error("failed to parse \"patch\" message (id=%u); missing "
"\"trampoline\" parameter", msg.id);
if (!have_offset)
error("failed to parse \"patch\" message (id=%u); missing "
"\"offset\" parameter", msg.id);
if (dup)
error("failed to parse \"patch\" message (id=%u); duplicate "
"parameters detected", msg.id);
auto i = B->Is.find(offset);
if (i == B->Is.end())
error("failed to parse \"patch\" message (id=%u); no matching "
"instruction at offset (%zd)", msg.id, offset);
Instr *I = i->second;
auto j = B->Ts.find(trampoline);
if (j == B->Ts.end())
error("failed to parse \"patch\" message (id=%u); no matching "
"trampoline with name \"%s\"", msg.id, trampoline);
const Trampoline *T = j->second;
if (patch(*B, I, T))
stat_num_patched++;
else
stat_num_failed++;
}
/*
* Parse an emit message.
*/
static void parseEmit(Binary *B, const Message &msg)
{
size_t mapping_size = PAGE_SIZE;
const char *filename = nullptr;
Format format = FORMAT_BINARY;
bool have_format = false, have_mapping_size = false, dup = false;
for (unsigned i = 0; i < msg.num_params; i++)
{
switch (msg.params[i].name)
{
case PARAM_FILENAME:
dup = dup || (filename != nullptr);
filename = msg.params[i].value.string;
break;
case PARAM_FORMAT:
dup = dup || have_format;
format = (Format)msg.params[i].value.integer;
have_format = true;
break;
case PARAM_MAPPING_SIZE:
dup = dup || have_mapping_size;
mapping_size = (size_t)msg.params[i].value.integer;
have_mapping_size = true;
break;
default:
break;
}
}
if (filename == nullptr)
error("failed to parse \"emit\" message (id=%u); missing "
"\"filename\" parameter", msg.id);
if (mapping_size % PAGE_SIZE != 0)
error("failed to parse \"emit\" message (id=%u); mapping size "
"must be a multiple of the page size (%u), found %zu", msg.id,
PAGE_SIZE, mapping_size);
if ((mapping_size & (mapping_size - 1)) != 0)
error("failed to parse \"emit\" message (id=%u); mapping size "
"must be a power-of-two, found %zu", msg.id, mapping_size);
if (dup)
error("failed to parse \"emit\" message (id=%u); duplicate "
"parameters detected");
putchar('\n');
// Create and optimize the mappings:
MappingSet mappings;
buildMappings(B->allocator, mapping_size, mappings);
optimizeMappings(mappings);
putchar('\n');
// Create the patched binary:
B->patched.size = emitElf(B, mappings, mapping_size);
// Emit the result:
switch (format)
{
case FORMAT_BINARY:
emitBinary(filename, B->patched.bytes, B->patched.size);
break;
case FORMAT_PATCH:
emitPatch(filename, /*compress=*/nullptr, B->original.fd,
B->patched.bytes, B->patched.size);
break;
case FORMAT_PATCH_GZ:
emitPatch(filename, "gzip", B->original.fd, B->patched.bytes,
B->patched.size);
break;
case FORMAT_PATCH_BZIP2:
emitPatch(filename, "bzip2", B->original.fd, B->patched.bytes,
B->patched.size);
break;
case FORMAT_PATCH_XZ:
emitPatch(filename, "xz", B->original.fd, B->patched.bytes,
B->patched.size);
break;
default:
error("failed to parse \"emit\" message (id=%u); invalid "
"\"format\" code %u", msg.id, (unsigned)format);
}
}
/*
* Parse a reserve message.
*/
static void parseReserve(Binary *B, const Message &msg)
{
bool absolute = false;
intptr_t address = 0;
intptr_t init = 0;
intptr_t mmap = 0;
size_t length = 0;
Trampoline *bytes = nullptr;
int protection = PROT_READ | PROT_EXEC;
bool have_address = false, have_protection = false, have_init = false,
have_mmap = false, have_length = false, have_absolute = false,
dup = false;
for (unsigned i = 0; i < msg.num_params; i++)
{
switch (msg.params[i].name)
{
case PARAM_ABSOLUTE:
dup = dup || have_absolute;
absolute = msg.params[i].value.boolean;
have_absolute = true;
break;
case PARAM_ADDRESS:
dup = dup || have_address;
address = (intptr_t)msg.params[i].value.integer;
have_address = true;
break;
case PARAM_BYTES:
dup = dup || (bytes != nullptr);
bytes = msg.params[i].value.trampoline;
break;
case PARAM_INIT:
dup = dup || have_init;
init = (intptr_t)msg.params[i].value.integer;
have_init = true;
break;
case PARAM_LENGTH:
dup = dup || have_length;
length = (size_t)msg.params[i].value.integer;
have_length = true;
break;
case PARAM_MMAP:
dup = dup || have_mmap;
mmap = (intptr_t)msg.params[i].value.integer;
have_mmap = true;
break;
case PARAM_PROTECTION:
dup = dup || have_protection;
protection = (int)msg.params[i].value.integer;
have_protection = true;
break;
default:
break;
}
}
if (!have_address)
error("failed to parse \"reserve\" message (id=%u); missing "
"\"address\" parameter", msg.id);
if (bytes == nullptr && !have_length)
error("failed to parse \"reserve\" message (id=%u); missing "
"\"bytes\" parameter or \"length\" parameter", msg.id);
if (bytes != nullptr && have_length)
error("failed to parse \"reserve\" message (id=%u); only one of "
"the \"bytes\" or \"length\" parameters can be specified",
msg.id);
if (absolute && B->elf.pic)
address = ABSOLUTE_ADDRESS(address);
if (have_init)
{
if (absolute && B->elf.pic)
init = ABSOLUTE_ADDRESS(init);
if (bytes == nullptr || init < address ||
init >= address + bytes->entries[0].length)
error("failed to parse \"reserve\" message (id=%u); \"init\" "
"parameter value (" ADDRESS_FORMAT ") is out-of-bounds",
msg.id, ADDRESS(address));
B->inits.push_back(init);
}
if (have_mmap)
{
if (absolute && B->elf.pic)
mmap = ABSOLUTE_ADDRESS(mmap);
if (bytes == nullptr || mmap < address ||
mmap >= address + bytes->entries[0].length)
error("failed to parse \"reserve\" message (id=%u); \"mmap\" "
"parameter value (" ADDRESS_FORMAT ") is out-of-bounds",
msg.id, ADDRESS(address));
if (B->mmap != INTPTR_MIN)
error("failed to parse \"reserve\" message (id=%u); a mmap "
"function was previously defined", msg.id);
B->mmap = mmap;
}
if (dup)
error("failed to parse \"reserve\" message (id=%u); duplicate "
"parameters detected", msg.id);
if (have_protection && bytes != nullptr)
bytes->prot = protection;
if (bytes != nullptr)
{
bytes->preload = true;
const Alloc *A = allocate(B->allocator, address, address, bytes,
nullptr);
if (A == nullptr)
error("failed to reserve address space at address "
ADDRESS_FORMAT, ADDRESS(address));
}
if (have_length)
{
if (!reserve(B->allocator, address, address + length))
error("failed to reserve address space at address "
ADDRESS_FORMAT, ADDRESS(address));
}
}
/*
* Parse a trampoline message.
*/
static void parseTrampoline(Binary *B, const Message &msg)
{
const char *name = nullptr;
Trampoline *T = nullptr;
bool dup = false;
for (unsigned i = 0; i < msg.num_params; i++)
{
switch (msg.params[i].name)
{
case PARAM_NAME:
dup = dup || (name != nullptr);
name = msg.params[i].value.string;
break;
case PARAM_TEMPLATE:
dup = dup || (T != nullptr);
T = msg.params[i].value.trampoline;
break;
default:
break;
}
}
if (name == nullptr)
error("failed to parse \"template\" message (id=%u); missing "
"\"name\" parameter", msg.id);
if (T == nullptr)
error("failed to parse \"template\" message (id=%u); missing "
"\"template\" parameter", msg.id);
if (dup)
error("failed to parse \"template\" message (id=%u); duplicate "
"parameters detected", msg.id);
auto i = B->Ts.find(name);
if (i != B->Ts.end())
error("failed to parse \"template\" message (id=%u); a template "
"with name \"%s\" already exists", msg.id, name);
B->Ts.insert(std::make_pair(name, T));
}
/*
* Parse an option message.
*/
static void parseOptions(const Message &msg)
{
int64_t aggressiveness = 0;
bool disable_B1 = false, disable_B2 = false,
disable_T1 = false, disable_T2 = false,
disable_T3 = false;
bool have_disable_B1 = false, have_disable_B2 = false,
have_disable_T1 = false, have_disable_T2 = false,
have_disable_T3 = false;
bool have_aggressiveness = false, dup = false;
for (unsigned i = 0; i < msg.num_params; i++)
{
switch (msg.params[i].name)
{
case PARAM_OPTION_AGGRESSIVENESS:
dup = dup || have_aggressiveness;
aggressiveness = msg.params[i].value.integer;
have_aggressiveness = true;
break;
case PARAM_OPTION_DISABLE_B1:
dup = dup || have_disable_B1;
disable_B1 = msg.params[i].value.boolean;
have_disable_B1 = true;
break;
case PARAM_OPTION_DISABLE_B2:
dup = dup || have_disable_B2;
disable_B2 = msg.params[i].value.boolean;
have_disable_B2 = true;
break;
case PARAM_OPTION_DISABLE_T1:
dup = dup || have_disable_T1;
disable_T1 = msg.params[i].value.boolean;
have_disable_T1 = true;
break;
case PARAM_OPTION_DISABLE_T2:
dup = dup || have_disable_T2;
disable_T2 = msg.params[i].value.boolean;
have_disable_T2 = true;
break;
case PARAM_OPTION_DISABLE_T3:
dup = dup || have_disable_T3;
disable_T3 = msg.params[i].value.boolean;
have_disable_T3 = true;
break;
default:
break;
}
}
if (have_aggressiveness && (aggressiveness < 0 ||
aggressiveness > 100))
error("failed to parse \"option\" message (id=%u); "
"\"aggressiveness\" parameter must be within the range"
"0..100", msg.id);
if (dup)
error("failed to parse \"option\" message (id=%u); duplicate "
"parameters detected", msg.id);
if (have_aggressiveness)
option_aggressiveness = (int)aggressiveness;
if (have_disable_B1)
option_disable_B1 = disable_B1;
if (have_disable_B2)
option_disable_B2 = disable_B2;
if (have_disable_T1)
option_disable_T1 = disable_T1;
if (have_disable_T2)
option_disable_T2 = disable_T2;
if (have_disable_T3)
option_disable_T3 = disable_T3;
}
/*
* Parse the given message.
*/
Binary *parseMessage(Binary *B, Message &msg)
{
if (msg.method != METHOD_BINARY && B == nullptr)
error("failed to parse message stream; got \"%s\" message (id=%u) "
"before \"binary\" message", getMethodString(msg.method), msg.id);
switch (msg.method)
{
case METHOD_BINARY:
if (B != nullptr)
error("failed to parse message stream; got duplicate "
"\"binary\" message (id=%u)", msg.id);
return parseBinary(msg);
case METHOD_INSTRUCTION:
parseInstruction(B, msg);
return B;
case METHOD_PATCH:
parsePatch(B, msg);
return B;
case METHOD_EMIT:
parseEmit(B, msg);
return B;
case METHOD_RESERVE:
parseReserve(B, msg);
return B;
case METHOD_TRAMPOLINE:
parseTrampoline(B, msg);
return B;
case METHOD_OPTION:
parseOptions(msg);
return B;
default:
error("failed to parse message stream; got unknown message "
"method (id=%u)", msg.id);
}
}