forked from GJDuck/e9patch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathe9tool.cpp
More file actions
1718 lines (1634 loc) · 53 KB
/
e9tool.cpp
File metadata and controls
1718 lines (1634 loc) · 53 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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ___ _ _
* ___ / _ \| |_ ___ ___ | |
* / _ \ (_) | __/ _ \ / _ \| |
* | __/\__, | || (_) | (_) | |
* \___| /_/ \__\___/ \___/|_|
*
* Copyright (C) 2022 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 <cassert>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <regex>
#include <set>
#include <string>
#include <dlfcn.h>
#include <fcntl.h>
#include <getopt.h>
#include <libgen.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
#include <elf.h>
#define PAGE_SIZE 4096
#define MAX_ACTIONS (1 << 16)
/*
* Options.
*/
static std::string option_format("binary");
static std::string option_output("");
static std::vector<std::pair<const char *, char *>> option_plugin;
#include "e9action.h"
#include "e9csv.h"
#include "e9elf.h"
#include "e9metadata.h"
#include "e9misc.h"
#include "e9parser.h"
#include "e9plugin.h"
#include "e9tool.h"
#include "e9x86_64.h"
using namespace e9tool;
/*
* Backend info.
*/
struct Backend
{
FILE *out; // JSON RPC output.
pid_t pid; // Backend process ID.
};
/*
* Excluded locations.
*/
struct Exclude
{
intptr_t lo;
intptr_t hi;
};
/*
* Disassembler desync information.
*/
struct Desync
{
intptr_t lo;
intptr_t hi;
intptr_t addr;
const char *section;
uint8_t byte;
};
/*
* Spawn e9patch backend instance.
*/
static void spawnBackend(const char *prog,
const std::vector<const char *> &options, Backend &backend)
{
int fds[2];
if (pipe(fds) != 0)
error("failed to open pipe to backend process: %s", strerror(errno));
pid_t pid = fork();
if (pid == 0)
{
close(fds[1]);
if (dup2(fds[0], STDIN_FILENO) < 0)
error("failed to dup backend process pipe file descriptor "
"(%d): %s", fds[0], strerror(errno));
close(fds[0]);
const char *argv[options.size() + 2];
prog = findBinary(prog, /*exe=*/true, /*dot=*/true);
argv[0] = "e9patch";
unsigned i = 1;
for (const char *option: options)
argv[i++] = option;
argv[i] = nullptr;
execvp(prog, (char * const *)argv);
error("failed to execute backend process \"%s\": %s", argv[0],
strerror(errno));
}
else if (pid < 0)
error("failed to fork backend process: %s", strerror(errno));
close(fds[0]);
FILE *out = fdopen(fds[1], "w");
if (out == nullptr)
error("failed to open backend process stream: %s", strerror(errno));
backend.out = out;
backend.pid = pid;
}
/*
* Wait for e9patch instance to terminate.
*/
static void waitBackend(const Backend &backend)
{
fclose(backend.out);
if (backend.pid == 0)
return;
int status;
do
{
if (waitpid(backend.pid, &status, WUNTRACED | WCONTINUED) < 0)
error("failed to wait for backend process (%d): %s",
backend.pid, strerror(errno));
}
while (!WIFEXITED(status) && !WIFSIGNALED(status));
if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
error("backend process (%d) exitted with a non-zero status (%d)",
backend.pid, WEXITSTATUS(status));
else if (WIFSIGNALED(status))
error("backend process (%d) killed by signal (%s)", backend.pid,
strsignal(WTERMSIG(status)));
}
/*
* Open a new plugin object.
*/
static std::map<const char *, Plugin *, CStrCmp> plugins;
Plugin *openPlugin(const char *basename)
{
std::string filename(basename);
if (!hasSuffix(filename, ".so"))
filename += ".so";
const char *pathname = realpath(filename.c_str(), nullptr);
if (pathname == nullptr)
error("failed to create path for plugin \"%s\"; %s", basename,
strerror(errno));
auto i = plugins.find(pathname);
if (i != plugins.end())
{
free((char *)pathname);
return i->second;
}
void *handle = dlopen(pathname, RTLD_LOCAL | RTLD_LAZY);
if (handle == nullptr)
error("failed to load plugin \"%s\": %s", pathname, dlerror());
Plugin *plugin = new Plugin;
plugin->filename = pathname;
plugin->handle = handle;
plugin->context = nullptr;
plugin->result = 0;
plugin->initFunc = (PluginInit)dlsym(handle, "e9_plugin_init");
plugin->eventFunc = (PluginEvent)dlsym(handle, "e9_plugin_event");
plugin->matchFunc = (PluginMatch)dlsym(handle, "e9_plugin_match");
plugin->codeFunc = (PluginCode)dlsym(handle, "e9_plugin_code");
plugin->dataFunc = (PluginData)dlsym(handle, "e9_plugin_data");
plugin->patchFunc = (PluginPatch)dlsym(handle, "e9_plugin_patch");
plugin->finiFunc = (PluginFini)dlsym(handle, "e9_plugin_fini");
if (plugin->initFunc == nullptr && plugin->eventFunc == nullptr &&
plugin->codeFunc == nullptr && plugin->dataFunc == nullptr &&
plugin->matchFunc == nullptr && plugin->patchFunc == nullptr &&
plugin->finiFunc == nullptr)
error("failed to load plugin \"%s\"; the shared "
"object does not export any plugin API functions",
plugin->filename);
plugin->argv.push_back(strDup(basename));
for (auto &entry: option_plugin)
{
if (entry.first == nullptr)
continue;
if (strcmp(entry.first, basename) != 0)
continue;
if (entry.second != nullptr)
plugin->argv.push_back(entry.second);
delete entry.first;
entry.first = entry.second = nullptr;
}
plugin->argv.shrink_to_fit();
plugins.insert({plugin->filename, plugin});
return plugin;
}
/*
* Notify all plugins of a new instruction.
*/
static void notifyPlugins(FILE *out, const ELF *elf,
const std::vector<Instr> &Is, Event event)
{
for (auto i: plugins)
{
Plugin *plugin = i.second;
if (plugin->eventFunc == nullptr)
continue;
Context cxt = {API_VERSION, STRING(VERSION), out, &plugin->argv,
plugin->context, elf, &Is, -1, nullptr, -1};
plugin->eventFunc(&cxt, event);
}
}
/*
* Get the match value for all plugins.
*/
static void matchPlugins(FILE *out, const ELF *elf,
const std::vector<Instr> &Is, size_t idx, const InstrInfo *I)
{
for (auto i: plugins)
{
Plugin *plugin = i.second;
if (plugin->matchFunc == nullptr)
continue;
Context cxt = {API_VERSION, STRING(VERSION), out, &plugin->argv,
plugin->context, elf, &Is, (ssize_t)idx, I, -1};
plugin->result = plugin->matchFunc(&cxt);
}
}
/*
* Initialize all plugins.
*/
static void initPlugins(FILE *out, const ELF *elf)
{
for (auto i: plugins)
{
Plugin *plugin = i.second;
if (plugin->initFunc == nullptr)
continue;
Context cxt = {API_VERSION, STRING(VERSION), out, &plugin->argv,
nullptr, elf, nullptr, -1, nullptr, -1};
plugin->context = plugin->initFunc(&cxt);
}
}
/*
* Finalize all plugins.
*/
static void finiPlugins(FILE *out, const ELF *elf)
{
for (auto i: plugins)
{
Plugin *plugin = i.second;
if (plugin->finiFunc == nullptr)
continue;
Context cxt = {API_VERSION, STRING(VERSION), out, &plugin->argv,
plugin->context, elf, nullptr, -1, nullptr, -1};
plugin->finiFunc(&cxt);
}
}
/*
* Parse an exclusion.
*/
static Exclude parseExcludeBound(Parser &parser, const char *str,
const ELF &elf)
{
Exclude bound = {INTPTR_MAX, INTPTR_MIN};
int t = parser.getToken();
bool neg = false;
switch (t)
{
case '-':
neg = true;
// Fallthrough:
case '+':
parser.expectToken(TOKEN_INTEGER);
// Fallthrough:
case TOKEN_INTEGER:
{
intptr_t b = (neg? -parser.i: parser.i);
bound = {b, b};
break;
}
case '&':
t = parser.getToken();
// Fallthrough:
default:
{
std::string name;
if (t == '.')
{
t = parser.getToken();
name += '.';
}
if (t != TOKEN_STRING && t != TOKEN_NAME)
parser.unexpectedToken();
name += parser.s;
const Elf64_Shdr *shdr = getELFSection(&elf, name.c_str());
if (shdr != nullptr)
{
bound = {elf.base + (intptr_t)shdr->sh_addr,
elf.base + (intptr_t)shdr->sh_addr +
(intptr_t)shdr->sh_size};
break;
}
const Elf64_Sym *sym = getELFDynSym(&elf, name.c_str());
if (sym == nullptr)
sym = getELFSym(&elf, name.c_str());
if (sym != nullptr && sym->st_shndx != SHN_UNDEF)
{
bound = {elf.base + (intptr_t)sym->st_value,
elf.base + (intptr_t)sym->st_value};
break;
}
intptr_t val = getELFPLTEntry(&elf, name.c_str());
if (val != INTPTR_MIN)
{
bound = {val, val};
break;
}
warning("ignoring exclusion \"%s\"; no such symbol or "
"section \"%s\" in \"%s\"", str, name.c_str(), elf.filename);
return bound;
}
}
if (parser.peekToken() == '.')
{
parser.getToken();
switch (parser.getToken())
{
case TOKEN_START:
bound.hi = bound.lo;
break;
case TOKEN_END:
bound.lo = bound.hi;
break;
default:
parser.unexpectedToken();
}
}
neg = false;
intptr_t offset = 0;
switch (parser.peekToken())
{
case '-':
neg = true;
// Fallthrough
case '+':
parser.getToken();
parser.expectToken(TOKEN_INTEGER);
offset = parser.i;
if (offset < INT32_MIN || offset > INT32_MAX)
error("failed to parse exclusion \"%s\"; offset %ld is "
"out-of-range %zd..%zd", str, offset, INT32_MIN,
INT32_MAX);
offset = (neg? -offset: offset);
bound.lo += offset;
bound.hi += offset;
break;
default:
break;
}
return bound;
}
static Exclude parseExclude(const ELF &elf, const char *str)
{
Parser parser(str, "exclusion", elf);
Exclude lb = parseExcludeBound(parser, str, elf);
if (lb.lo == INTPTR_MAX && lb.hi == INTPTR_MIN)
return lb;
Exclude ub = lb;
if (parser.peekToken() == TOKEN_DOTDOT)
{
parser.getToken();
ub = parseExcludeBound(parser, str, elf);
if (ub.lo == INTPTR_MAX && lb.hi == INTPTR_MIN)
return ub;
}
parser.expectToken(TOKEN_EOF);
Exclude exclude = {std::min(lb.lo, ub.hi), std::max(lb.lo, ub.hi)};
if (exclude.lo == exclude.hi)
warning("ignoring empty exclusion \"%s\" (0x%lx..0x%lx)",
str, exclude.lo, exclude.hi);
else
debug("excluding \"%s\" (0x%lx..0x%lx)", str, exclude.lo, exclude.hi);
return exclude;
}
/*
* Matching.
*/
struct Matching
{
std::vector<Action *> actions;
Matching(std::vector<Action *> &&actions) : actions(std::move(actions))
{
;
}
};
struct MatchingCmp
{
bool operator()(const Matching *m1, const Matching *m2)
{
for (size_t i = 0; ; i++)
{
if (i >= m1->actions.size())
return (i < m2->actions.size());
else if (i >= m2->actions.size())
return false;
if (m1->actions[i] < m2->actions[i])
return true;
if (m1->actions[i] > m2->actions[i])
return false;
}
}
};
struct MatchingCache
{
std::map<const Matching *, size_t, MatchingCmp> cache;
std::vector<const Matching *> matchings;
};
/*
* Matching.
*/
static void match(const std::vector<Action *> &actions, const ELF &elf,
const std::vector<Instr> &Is, size_t idx, const InstrInfo *I,
std::vector<Action *> &matching)
{
for (auto *action: actions)
{
if (!matchEval(action->match, elf, Is, idx, I))
continue;
matching.push_back(action);
}
}
/*
* Save matching.
*/
static size_t saveMatching(std::vector<Action *> &matching, const InstrInfo *I,
MatchingCache &Ms)
{
// Check for existing:
Matching M(std::move(matching));
auto i = Ms.cache.find(&M);
if (i != Ms.cache.end())
return i->second;
// Check if valid (at most one replace):
bool seen_replace = false, seen_break = false;
for (const auto *action: matching)
for (const auto *patch: action->patch)
seen_break = seen_break ||
(patch->kind == PATCH_BREAK && patch->pos == POS_BEFORE);
for (const auto *action: matching)
{
for (const auto *patch: action->patch)
{
if (patch->pos != POS_REPLACE)
continue;
if (seen_replace && !seen_break)
error("multiple matching \"replace\" trampolines detected "
"for instruction \"%s\" at address 0x%lx", I->string.instr,
I->address);
seen_replace = true;
seen_break = seen_break || (patch->kind == PATCH_BREAK);
}
}
// Add to cache:
size_t idx = Ms.matchings.size();
Matching *N = new Matching(std::move(M.actions));
Ms.cache.insert({N, idx});
Ms.matchings.push_back(N);
return idx;
}
/*
* Exclusion.
*/
static size_t exclude(const std::vector<Exclude> &excludes, intptr_t addr)
{
if (excludes.size() == 0)
return 0;
ssize_t lo = 0, hi = (ssize_t)excludes.size()-1;
while (lo <= hi)
{
ssize_t mid = (lo + hi) / 2;
const Exclude &exclude = excludes[mid];
if (addr < exclude.lo)
hi = mid-1;
else if (addr > exclude.hi)
lo = mid+1;
else
return exclude.hi - addr;
}
return 0;
}
/*
* Next instruction.
*/
static size_t nextInstr(const std::vector<intptr_t> &disasm, intptr_t addr)
{
ssize_t max = (ssize_t)disasm.size() - 1;
if (disasm.size() == 0 || addr > disasm[max])
return INT32_MAX;
ssize_t lo = 0, hi = max;
while (lo <= hi)
{
ssize_t mid = (lo + hi) / 2;
intptr_t i = disasm[mid];
if (addr < i)
hi = mid-1;
else if (addr > i)
lo = mid+1;
else
return 0;
}
return disasm[lo] - addr;
}
/*
* Metadata.
*/
struct Metadata
{
const Action * const action;
size_t idx;
};
/*
* Send a trampoline.
*/
static bool sendTrampoline(FILE *out, const Action *action, size_t idx,
Context *cxt, std::vector<Metadata> &metadata)
{
const Patch *patch = action->patch[idx];
const Plugin *plugin = nullptr;
if (patch->kind == PATCH_PLUGIN)
{
plugin = patch->plugin;
if (plugin->codeFunc != nullptr)
{
cxt->argv = &plugin->argv;
cxt->context = plugin->context;
plugin->codeFunc(cxt);
}
}
else
{
sendString(out, patch->name);
sendSeparator(out);
if (patch->kind == PATCH_BREAK)
return true;
}
bool found = false;
switch (patch->kind)
{
case PATCH_PLUGIN:
plugin = patch->plugin;
if (plugin->patchFunc == nullptr)
break;
// Fallthrough
case PATCH_PRINT: case PATCH_CALL:
for (const auto &entry: metadata)
{
const Patch *prev = entry.action->patch[entry.idx];
if (strcmp(prev->name, patch->name) == 0)
{
found = true;
break;
}
}
if (found)
break;
metadata.push_back({action, idx});
break;
default:
break;
}
return false;
}
/*
* Options.
*/
enum Option
{
OPTION_100,
OPTION_BACKEND,
OPTION_CFR,
OPTION_COMPRESSION,
OPTION_DSYNC,
OPTION_DTHRESHOLD,
OPTION_DEBUG,
OPTION_DUMP_ALL,
OPTION_EXCLUDE,
OPTION_EXECUTABLE,
OPTION_FORMAT,
OPTION_HELP,
OPTION_MATCH,
OPTION_NO_WARNINGS,
OPTION_PATCH,
OPTION_PLT,
OPTION_PLUGIN,
OPTION_OPTION,
OPTION_OUTPUT,
OPTION_SEED,
OPTION_SHARED,
OPTION_STATIC_LOADER,
OPTION_SYNTAX,
OPTION_TRAP,
OPTION_TRAP_ALL,
OPTION_USE_DISASM,
OPTION_USE_TARGETS,
OPTION_VERSION,
};
/*
* Action parsing.
*/
struct ActionEntry
{
std::vector<std::string> match;
std::vector<std::string> patch;
};
/*
* Parse an integer from an optarg.
*/
static intptr_t parseIntOptArg(const char *option, const char *optarg,
intptr_t lb, intptr_t ub)
{
const char *optarg_0 = optarg;
bool neg = (optarg[0] == '-');
if (neg)
optarg++;
int base = 10;
if (optarg[0] == '0' && optarg[1] == 'x')
base = 16;
errno = 0;
char *end = nullptr;
intptr_t r = (intptr_t)strtoul(optarg, &end, base);
r = (neg? -r: r);
if (errno != 0 || end == optarg ||
(end != nullptr && *end != '\0') || r < lb || r > ub)
{
error("failed to parse argument \"%s\" for the `%s' option; "
"expected a number within the range %zd..%zd", option,
optarg_0, lb, ub);
}
return r;
}
/*
* Entry.
*/
int main_2(int argc, char **argv)
{
/*
* Parse options.
*/
(void)atexit(flushWarnings);
const int req_arg = required_argument, /*opt_arg = optional_argument,*/
no_arg = no_argument;
static const struct option long_options[] =
{
{"100", no_arg, nullptr, OPTION_100},
{"backend", req_arg, nullptr, OPTION_BACKEND},
{"CFR", no_arg, nullptr, OPTION_CFR},
{"compression", req_arg, nullptr, OPTION_COMPRESSION},
{"Dsync", req_arg, nullptr, OPTION_DSYNC},
{"Dthreshold", req_arg, nullptr, OPTION_DTHRESHOLD},
{"debug", no_arg, nullptr, OPTION_DEBUG},
{"dump-all", no_arg, nullptr, OPTION_DUMP_ALL},
{"exclude", req_arg, nullptr, OPTION_EXCLUDE},
{"executable", no_arg, nullptr, OPTION_EXECUTABLE},
{"format", req_arg, nullptr, OPTION_FORMAT},
{"help", no_arg, nullptr, OPTION_HELP},
{"match", req_arg, nullptr, OPTION_MATCH},
{"no-warnings", no_arg, nullptr, OPTION_NO_WARNINGS},
{"patch", req_arg, nullptr, OPTION_PATCH},
{"plt", no_arg, nullptr, OPTION_PLT},
{"plugin", req_arg, nullptr, OPTION_PLUGIN},
{"option", req_arg, nullptr, OPTION_OPTION},
{"output", req_arg, nullptr, OPTION_OUTPUT},
{"seed", req_arg, nullptr, OPTION_SEED},
{"shared", no_arg, nullptr, OPTION_SHARED},
{"static-loader", no_arg, nullptr, OPTION_STATIC_LOADER},
{"syntax", req_arg, nullptr, OPTION_SYNTAX},
{"trap", req_arg, nullptr, OPTION_TRAP},
{"trap-all", no_arg, nullptr, OPTION_TRAP_ALL},
{"use-disasm", req_arg, nullptr, OPTION_USE_DISASM},
{"use-targets", req_arg, nullptr, OPTION_USE_TARGETS},
{"version", no_arg, nullptr, OPTION_VERSION},
{nullptr, no_arg, nullptr, 0}
};
option_is_tty = isatty(STDERR_FILENO);
std::vector<const char *> option_options;
unsigned option_compression_level = 9;
bool option_plt = false;
char option_optimization_level = '2';
bool option_executable = false, option_shared = false,
option_static_loader = false;
std::string option_backend("");
std::set<intptr_t> option_trap;
std::vector<std::string> option_match;
std::vector<std::string> option_patch;
std::vector<ActionEntry> option_actions;
std::vector<std::string> option_exclude;
std::string option_use_disasm("");
std::string option_use_targets("");
std::string option_use_funcs("");
bool option_dump_all = false;
int option_sync = 64, option_threshold = 2;
bool option_100 = false, option_CFR = false;
srand(0xe9e9e9e9);
while (true)
{
int idx;
int opt = getopt_long_only(argc, argv, "A:c:E:hM:o:O:P:sX",
long_options, &idx);
if (opt < 0)
break;
switch (opt)
{
case OPTION_100:
option_100 = true;
break;
case OPTION_BACKEND:
option_backend = optarg;
break;
case OPTION_CFR:
case 'X':
option_CFR = true;
break;
case OPTION_COMPRESSION:
case 'c':
option_compression_level = (unsigned)parseIntOptArg(
"--compression/-c", optarg, 0, 9);
break;
case OPTION_DSYNC:
option_sync = (int)parseIntOptArg("--Dsync", optarg,
0, UINT16_MAX);
break;
case OPTION_DTHRESHOLD:
option_threshold = (int)parseIntOptArg("--Dthreshold", optarg,
0, 10);
break;
case OPTION_DEBUG:
option_debug = true;
break;
case OPTION_DUMP_ALL:
option_targets = option_bbs = option_fs =
option_dump_all = true;
break;
case OPTION_EXCLUDE:
case 'E':
option_exclude.push_back(optarg);
break;
case OPTION_EXECUTABLE:
option_executable = true;
break;
case OPTION_FORMAT:
option_format = optarg;
if (option_format != "binary" &&
option_format != "json" &&
option_format != "patch" &&
option_format != "patch.gz" &&
option_format != "patch.bz2" &&
option_format != "patch.xz")
error("bad value \"%s\" for `--format' option; "
"expected one of \"binary\", \"json\", \"patch\", "
"\"patch.gz\", \"patch.bz2\", or \"patch.xz\"",
optarg);
break;
case OPTION_HELP:
case 'h':
usage(stdout, argv[0]);
return EXIT_SUCCESS;
case OPTION_OPTION:
option_options.push_back(optarg);
break;
case OPTION_MATCH:
case 'M':
{
if (option_patch.size() > 0)
{
ActionEntry entry;
entry.match.swap(option_match);
entry.patch.swap(option_patch);
option_actions.emplace_back(entry);
}
std::string match(optarg);
option_match.emplace_back(match);
break;
}
case OPTION_PATCH:
case 'P':
{
if (option_match.size() == 0)
error("failed to parse command-line arguments; "
"the `--patch'/`-P' option must be preceded by "
"one or more `--match'/`-M' options");
std::string patch(optarg);
option_patch.emplace_back(patch);
break;
}
case OPTION_PLT:
option_plt = true;
break;
case OPTION_PLUGIN:
{
size_t i;
for (i = 0; optarg[i] != '\0' && optarg[i] != ':'; i++)
;
if (optarg[i] != ':')
error("bad value \"%s\" for `--plugin'; "
"expected a plugin:option pair", optarg);
char *key = strDup(optarg, i);
char *val = strDup(optarg+i+1);
option_plugin.push_back({key, val});
break;
}
case OPTION_OUTPUT:
case 'o':
option_output = optarg;
break;
case 'O':
option_optimization_level = -1;
switch (optarg[0])
{
case '0': case '1': case '2': case '3': case 's':
option_optimization_level = optarg[0];
break;
}
if (option_optimization_level < 0 || optarg[1] != '\0')
error("bad value \"%s\" for `-O' option; "
"expected one of -O0,-O1,-O2,-O3,-Os", optarg);
break;
case OPTION_NO_WARNINGS:
option_no_warnings = true;
break;
case OPTION_SEED:
{
unsigned long r = (unsigned long)parseIntOptArg("--seed",
optarg, 0, RAND_MAX);
if (r == 0)
syscall(/*SYS_getrandom=*/318, &r, sizeof(unsigned), 0);
srand((unsigned)r);
break;
}
case OPTION_SHARED:
option_shared = true;
break;
case OPTION_STATIC_LOADER:
case 's':
option_static_loader = true;
break;
case OPTION_SYNTAX:
if (strcmp(optarg, "ATT") == 0)
option_intel_syntax = false;
else if (strcmp(optarg, "intel") == 0)
option_intel_syntax = true;
else
error("bad value \"%s\" for `--syntax' option; "
"expected \"ATT\" or \"intel\"", optarg);
break;
case OPTION_TRAP:
{
errno = 0;
char *end = nullptr;
unsigned long r = strtoul(optarg, &end, 0);
if (errno != 0 || end == optarg ||
(end != nullptr && *end != '\0') || r > INTPTR_MAX)
error("bad value \"%s\" for `--trap' option; "
"expected an address", optarg);
option_trap.insert(r);
break;
}
case OPTION_TRAP_ALL:
option_trap_all = true;
break;
case OPTION_USE_DISASM:
option_use_disasm = optarg;
break;
case OPTION_USE_TARGETS:
option_use_targets = optarg;
break;
case OPTION_VERSION:
puts("E9Tool " STRING(VERSION));
return EXIT_SUCCESS;
default:
error("failed to parse command-line options; try `--help' "
"for more information");
return EXIT_FAILURE;
}
}
if (optind != argc-1)
{
error("missing input file; try `--help' for more information");
return EXIT_FAILURE;
}
if (option_match.size() > 0)
{
if (option_patch.size() == 0)
error("failed to parse command-line arguments; the `--match'/`-M' "
"option must be followed by one or more `--patch'/`-P' "
"options");
ActionEntry entry;
entry.match.swap(option_match);
entry.patch.swap(option_patch);
option_actions.emplace_back(entry);
}
if (option_actions.size() > MAX_ACTIONS)
error("failed to parse command-line arguments; the total number of "
"match/patch pairs (%zu) exceeds the maximum (%zu)",
option_actions.size(), MAX_ACTIONS);
if (option_shared && option_executable)
error("failed to parse command-line arguments; both the `--shared' "
"and `--executable' options cannot be used at the same time");
/*
* Parse the ELF file.
*/
const char *filename = argv[optind];
bool exe = (option_executable? true:
(option_shared? false: !isLibraryFilename(filename)));
filename = findBinary(filename, exe, /*dot=*/true);
ELF &elf = *parseBinary(filename);
/*
* Patch the match/action pairs.
*/
std::vector<Action *> actions;
for (const auto &entry: option_actions)
{
if (entry.match.size() == 0)
error("failed to parse action; the `--action' or `-A' option "
"must be preceded by one or more `--match' or `-M' options");
MatchExpr *match = nullptr;
for (const auto &str: entry.match)
{
MatchExpr *expr = parseMatch(elf, str.c_str());
match = (match == nullptr? expr:
new MatchExpr(MATCH_OP_AND, match, expr));
}
std::vector<const Patch *> patch;
for (const auto &str: entry.patch)
{
const Patch *P = parsePatch(elf, str.c_str());
patch.push_back(P);
if (P->kind == PATCH_BREAK)
break;
}
Action *action = new Action(match, std::move(patch));
actions.push_back(action);
}
option_actions.clear();
for (auto &entry: option_plugin)
{
if (entry.first != nullptr)