-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex4.cpp
1552 lines (1221 loc) · 50.5 KB
/
ex4.cpp
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
#include "pin.H"
extern "C" {
#include "xed-interface.h"
}
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sys/mman.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <malloc.h>
#include <errno.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <values.h>
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX_PROBE_JUMP_INSTR_BYTES 14
#define CANDIDATE_COUNT 10
/* ===================================================================== */
/* Commandline Switches */
/* ===================================================================== */
KNOB< BOOL > KnobVerbose(KNOB_MODE_WRITEONCE, "pintool", "verbose", "0", "Verbose run");
KNOB< BOOL > KnobDumpTranslatedCode(KNOB_MODE_WRITEONCE, "pintool", "dump", "0", "Dump Translated Code");
KNOB< BOOL > KnobProf(KNOB_MODE_WRITEONCE, "pintool", "prof", "0", "Run profiling mode");
KNOB< BOOL > KnobInst(KNOB_MODE_WRITEONCE, "pintool", "inst", "0", "Run instrument mode");
/* ===================================================================== */
/* Print Help Message */
/* ===================================================================== */
INT32 Usage()
{
std::cerr << "This tool prints information on RTN instruction counts.\n";
std::cerr << KNOB_BASE::StringKnobSummary();
std::cerr << std::endl;
return -1;
}
// Ex 2
struct Loop
{
ADDRINT _target_addr;
int32_t _count_seen; // backward edge execution count
int32_t _count_loop_invoked;
int32_t _diff_count = -1;
std::string _routine_name;
ADDRINT _routine_addr;
int32_t _old_iter_count;
int32_t _cur_iter_count;
};
// instruction map with an entry for each new instruction:
typedef struct {
ADDRINT orig_ins_addr;
ADDRINT new_ins_addr;
ADDRINT orig_targ_addr;
bool hasNewTargAddr;
char encoded_ins[XED_MAX_INSTRUCTION_BYTES];
xed_category_enum_t category_enum;
unsigned int size;
int new_targ_entry;
} instr_map_t;
/* ===================================================================== */
/* Global Variables */
/* ===================================================================== */
std::ifstream in_file;
std::ofstream out_file;
const char* filename = "loop-count.csv";
std::unordered_map<ADDRINT, uint32_t> routine_map; // values are default initialized to 0
std::unordered_map<ADDRINT, Loop> loops_profiler;
// Ex 3
std::unordered_map<ADDRINT, uint32_t> candidates_map;
std::vector<std::pair<ADDRINT, uint32_t>> candidates;
std::ofstream* out = 0;
// For XED:
#if defined(TARGET_IA32E)
xed_state_t dstate = {XED_MACHINE_MODE_LONG_64, XED_ADDRESS_WIDTH_64b};
#else
xed_state_t dstate = { XED_MACHINE_MODE_LEGACY_32, XED_ADDRESS_WIDTH_32b};
#endif
/* ===================================================================== */
/* From rtn-translation.cpp */
/* ===================================================================== */
//For XED: Pass in the proper length: 15 is the max. But if you do not want to
//cross pages, you can pass less than 15 bytes, of course, the
//instruction might not decode if not enough bytes are provided.
const unsigned int max_inst_len = XED_MAX_INSTRUCTION_BYTES;
ADDRINT lowest_sec_addr = 0;
ADDRINT highest_sec_addr = 0;
// tc containing the new code:
char *tc;
int tc_cursor = 0;
instr_map_t *instr_map = NULL;
int num_of_instr_map_entries = 0;
int max_ins_count = 0;
// total number of routines in the main executable module:
int max_rtn_count = 0;
// Tables of all candidate routines to be translated:
typedef struct {
ADDRINT rtn_addr;
USIZE rtn_size;
int instr_map_entry; // negative instr_map_entry means routine does not have a translation.
bool isSafeForReplacedProbe;
} translated_rtn_t;
translated_rtn_t *translated_rtn;
int translated_rtn_num = 0;
/* ===================================================================== */
VOID PIN_FAST_ANALYSIS_CALL docount(uint32_t* ptr, uint32_t c)
{
(*ptr) += c;
}
VOID PIN_FAST_ANALYSIS_CALL inc_branch(
INT32 taken,
INT32* count_seen,
INT32* count_loop_invoked,
INT32* old_iter_count,
INT32* cur_iter_count,
INT32* diff_count)
{
// Important Note: count_seen field is calculated to match the given example file.
// If only backward edges calls are required (instead of total count), it would be incremented only if BRANCH=TAKEN!
(*count_seen)++;
(*cur_iter_count)++;
if (!taken)
{
(*count_loop_invoked)++;
if (*cur_iter_count != *old_iter_count)
{
(*diff_count)++;
}
*old_iter_count = *cur_iter_count;
*cur_iter_count = 0;
}
}
/* ===================================================================== */
// Pin calls this function every time a new basic block is encountered
// It inserts a call to docount
VOID Trace(TRACE trace, VOID* v)
{
const RTN& trace_routine = TRACE_Rtn(trace);
const ADDRINT& routine_addr = RTN_Address(trace_routine);
// Visit every basic block in the trace
for (BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl = BBL_Next(bbl))
{
// Insert a call to docount for every bbl, passing the number of instructions.
// IPOINT_ANYWHERE allows Pin to schedule the call anywhere in the bbl to obtain best performance.
BBL_InsertCall(bbl, IPOINT_ANYWHERE, (AFUNPTR)docount,
IARG_FAST_ANALYSIS_CALL,
IARG_PTR, &routine_map[routine_addr], IARG_UINT32, BBL_NumIns(bbl), IARG_END);
}
}
VOID Instruction(INS ins, VOID* v)
{
if (!INS_Valid(ins)) { return; }
const ADDRINT& ins_addr = INS_Address(ins);
const RTN& ins_routine = RTN_FindByAddress(ins_addr);
if (!RTN_Valid(ins_routine)) { return; }
const IMG& routine_img = IMG_FindByAddress(ins_addr);
if (!IMG_Valid(routine_img)) { return; }
const ADDRINT& routine_addr = RTN_Address(ins_routine);
const std::string &routine_name = RTN_Name(ins_routine);
/* Ex 2 - verify this is a candidate for loop instruction
* */
if (!INS_IsDirectBranch(ins) || !INS_IsControlFlow(ins))
{
return;
}
const ADDRINT& target_addr = INS_DirectControlFlowTargetAddress(ins);
if (target_addr >= ins_addr) // not a backward edge
{
return;
}
loops_profiler[ins_addr]._target_addr = target_addr;
loops_profiler[ins_addr]._routine_addr = routine_addr;
loops_profiler[ins_addr]._routine_name = routine_name;
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)inc_branch,
IARG_FAST_ANALYSIS_CALL,
IARG_BRANCH_TAKEN,
IARG_PTR, &loops_profiler[ins_addr]._count_seen,
IARG_PTR, &loops_profiler[ins_addr]._count_loop_invoked,
IARG_PTR, &loops_profiler[ins_addr]._old_iter_count,
IARG_PTR, &loops_profiler[ins_addr]._cur_iter_count,
IARG_PTR, &loops_profiler[ins_addr]._diff_count,
IARG_END);
}
/* ============================================================= */
/* Service dump routines */
/* ============================================================= */
/*************************/
/* dump_all_image_instrs */
/*************************/
void dump_all_image_instrs(IMG img)
{
for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec))
{
for (RTN rtn = SEC_RtnHead(sec); RTN_Valid(rtn); rtn = RTN_Next(rtn))
{
// Open the RTN.
RTN_Open( rtn );
cerr << RTN_Name(rtn) << ":" << endl;
for( INS ins = RTN_InsHead(rtn); INS_Valid(ins); ins = INS_Next(ins) )
{
cerr << "0x" << hex << INS_Address(ins) << ": " << INS_Disassemble(ins) << endl;
}
// Close the RTN.
RTN_Close( rtn );
}
}
}
/*************************/
/* dump_instr_from_xedd */
/*************************/
void dump_instr_from_xedd (xed_decoded_inst_t* xedd, ADDRINT address)
{
// debug print decoded instr:
char disasm_buf[2048];
xed_uint64_t runtime_address = static_cast<UINT64>(address); // set the runtime adddress for disassembly
xed_format_context(XED_SYNTAX_INTEL, xedd, disasm_buf, sizeof(disasm_buf), static_cast<UINT64>(runtime_address), 0, 0);
cerr << hex << address << ": " << disasm_buf << endl;
}
/************************/
/* dump_instr_from_mem */
/************************/
void dump_instr_from_mem (ADDRINT *address, ADDRINT new_addr)
{
char disasm_buf[2048];
xed_decoded_inst_t new_xedd;
xed_decoded_inst_zero_set_mode(&new_xedd,&dstate);
xed_error_enum_t xed_code = xed_decode(&new_xedd, reinterpret_cast<UINT8*>(address), max_inst_len);
BOOL xed_ok = (xed_code == XED_ERROR_NONE);
if (!xed_ok){
cerr << "invalid opcode" << endl;
return;
}
xed_format_context(XED_SYNTAX_INTEL, &new_xedd, disasm_buf, 2048, static_cast<UINT64>(new_addr), 0, 0);
if (KnobVerbose)
{
cerr << "0x" << hex << new_addr << ": " << disasm_buf << endl;
}
}
/****************************/
/* dump_entire_instr_map() */
/****************************/
void dump_entire_instr_map()
{
for (int i=0; i < num_of_instr_map_entries; i++) {
for (int j=0; j < translated_rtn_num; j++) {
if (translated_rtn[j].instr_map_entry == i) {
RTN rtn = RTN_FindByAddress(translated_rtn[j].rtn_addr);
if (rtn == RTN_Invalid()) {
cerr << "Unknwon" << ":" << endl;
} else {
cerr << RTN_Name(rtn) << ":" << endl;
}
}
}
dump_instr_from_mem ((ADDRINT *)instr_map[i].new_ins_addr, instr_map[i].new_ins_addr);
}
}
/**************************/
/* dump_instr_map_entry */
/**************************/
void dump_instr_map_entry(int instr_map_entry)
{
cerr << dec << instr_map_entry << ": ";
cerr << " orig_ins_addr: " << hex << instr_map[instr_map_entry].orig_ins_addr;
cerr << " new_ins_addr: " << hex << instr_map[instr_map_entry].new_ins_addr;
cerr << " orig_targ_addr: " << hex << instr_map[instr_map_entry].orig_targ_addr;
ADDRINT new_targ_addr;
if (instr_map[instr_map_entry].new_targ_entry >= 0)
new_targ_addr = instr_map[instr_map[instr_map_entry].new_targ_entry].new_ins_addr;
else
new_targ_addr = instr_map[instr_map_entry].orig_targ_addr;
cerr << " new_targ_addr: " << hex << new_targ_addr;
cerr << " new instr:";
dump_instr_from_mem((ADDRINT *)instr_map[instr_map_entry].encoded_ins, instr_map[instr_map_entry].new_ins_addr);
}
/*************/
/* dump_tc() */
/*************/
void dump_tc()
{
char disasm_buf[2048];
xed_decoded_inst_t new_xedd;
ADDRINT address = (ADDRINT)&tc[0];
unsigned int size = 0;
while (address < (ADDRINT)&tc[tc_cursor]) {
address += size;
xed_decoded_inst_zero_set_mode(&new_xedd,&dstate);
xed_error_enum_t xed_code = xed_decode(&new_xedd, reinterpret_cast<UINT8*>(address), max_inst_len);
BOOL xed_ok = (xed_code == XED_ERROR_NONE);
if (!xed_ok){
cerr << "invalid opcode" << endl;
return;
}
xed_format_context(XED_SYNTAX_INTEL, &new_xedd, disasm_buf, 2048, static_cast<UINT64>(address), 0, 0);
cerr << "0x" << hex << address << ": " << disasm_buf << endl;
size = xed_decoded_inst_get_length (&new_xedd);
}
}
/* ============================================================= */
/* Translation routines */
/* ============================================================= */
// Ex4 - itay addition
int patched_add_new_instr_entry(xed_decoded_inst_t *xedd, ADDRINT pc, unsigned int size)
{
// copy orig instr to instr map:
ADDRINT orig_targ_addr = 0;
if (xed_decoded_inst_get_length (xedd) != size) {
cerr << "Invalid instruction decoding" << endl;
return -1;
}
xed_uint_t disp_byts = xed_decoded_inst_get_branch_displacement_width(xedd);
if (disp_byts > 0)
{
// We want to reverse the condition - so the fallthrough address is the new target address for the instructions
// The cool trick is setting the displacement value to 0, so that it will point towards the original next instr
xed_decoded_inst_set_branch_displacement(xedd, 0, disp_byts);
orig_targ_addr = pc + size;
}
// Converts the decoder request to a valid encoder request:
xed_encoder_request_init_from_decode (xedd);
unsigned int new_size = 0;
xed_error_enum_t xed_error = xed_encode (xedd, reinterpret_cast<UINT8*>(instr_map[num_of_instr_map_entries].encoded_ins), max_inst_len , &new_size);
if (xed_error != XED_ERROR_NONE) {
cerr << "ENCODE ERROR: " << xed_error_enum_t2str(xed_error) << endl;
return -1;
}
// add a new entry in the instr_map:
instr_map[num_of_instr_map_entries].orig_ins_addr = pc;
instr_map[num_of_instr_map_entries].new_ins_addr = (ADDRINT)&tc[tc_cursor]; // set an initial estimated addr in tc
instr_map[num_of_instr_map_entries].orig_targ_addr = orig_targ_addr;
instr_map[num_of_instr_map_entries].hasNewTargAddr = false;
instr_map[num_of_instr_map_entries].new_targ_entry = -1;
instr_map[num_of_instr_map_entries].size = new_size;
instr_map[num_of_instr_map_entries].category_enum = xed_decoded_inst_get_category(xedd);
num_of_instr_map_entries++;
// update expected size of tc:
tc_cursor += new_size;
if (num_of_instr_map_entries >= max_ins_count) {
cerr << "out of memory for map_instr" << endl;
return -1;
}
// debug print new encoded instr:
if (KnobVerbose) {
cerr << " new instr:";
dump_instr_from_mem((ADDRINT *)instr_map[num_of_instr_map_entries-1].encoded_ins, instr_map[num_of_instr_map_entries-1].new_ins_addr);
}
return new_size;
}
/*************************/
/* add_new_instr_entry() */
/*************************/
int add_new_instr_entry(xed_decoded_inst_t *xedd, ADDRINT pc, unsigned int size)
{
// copy orig instr to instr map:
ADDRINT orig_targ_addr = 0;
if (xed_decoded_inst_get_length (xedd) != size) {
cerr << "Invalid instruction decoding" << endl;
return -1;
}
xed_uint_t disp_byts = xed_decoded_inst_get_branch_displacement_width(xedd);
xed_int32_t disp;
if (disp_byts > 0) { // there is a branch offset.
disp = xed_decoded_inst_get_branch_displacement(xedd);
orig_targ_addr = pc + xed_decoded_inst_get_length (xedd) + disp;
}
// Converts the decoder request to a valid encoder request:
xed_encoder_request_init_from_decode (xedd);
unsigned int new_size = 0;
xed_error_enum_t xed_error = xed_encode (xedd, reinterpret_cast<UINT8*>(instr_map[num_of_instr_map_entries].encoded_ins), max_inst_len , &new_size);
if (xed_error != XED_ERROR_NONE) {
cerr << "ENCODE ERROR: " << xed_error_enum_t2str(xed_error) << endl;
return -1;
}
// add a new entry in the instr_map:
instr_map[num_of_instr_map_entries].orig_ins_addr = pc;
instr_map[num_of_instr_map_entries].new_ins_addr = (ADDRINT)&tc[tc_cursor]; // set an initial estimated addr in tc
instr_map[num_of_instr_map_entries].orig_targ_addr = orig_targ_addr;
instr_map[num_of_instr_map_entries].hasNewTargAddr = false;
instr_map[num_of_instr_map_entries].new_targ_entry = -1;
instr_map[num_of_instr_map_entries].size = new_size;
instr_map[num_of_instr_map_entries].category_enum = xed_decoded_inst_get_category(xedd);
num_of_instr_map_entries++;
// update expected size of tc:
tc_cursor += new_size;
if (num_of_instr_map_entries >= max_ins_count) {
cerr << "out of memory for map_instr" << endl;
return -1;
}
// debug print new encoded instr:
if (KnobVerbose) {
cerr << " new instr:";
dump_instr_from_mem((ADDRINT *)instr_map[num_of_instr_map_entries-1].encoded_ins, instr_map[num_of_instr_map_entries-1].new_ins_addr);
}
return new_size;
}
/*************************************************/
/* chain_all_direct_br_and_call_target_entries() */
/*************************************************/
int chain_all_direct_br_and_call_target_entries()
{
for (int i=0; i < num_of_instr_map_entries; i++) {
if (instr_map[i].orig_targ_addr == 0)
continue;
if (instr_map[i].hasNewTargAddr)
continue;
for (int j = 0; j < num_of_instr_map_entries; j++) {
if (j == i)
continue;
if (instr_map[j].orig_ins_addr == instr_map[i].orig_targ_addr) {
instr_map[i].hasNewTargAddr = true;
instr_map[i].new_targ_entry = j;
break;
}
}
}
return 0;
}
/**************************/
/* fix_rip_displacement() */
/**************************/
int fix_rip_displacement(int instr_map_entry)
{
//debug print:
//dump_instr_map_entry(instr_map_entry);
xed_decoded_inst_t xedd;
xed_decoded_inst_zero_set_mode(&xedd,&dstate);
xed_error_enum_t xed_code = xed_decode(&xedd, reinterpret_cast<UINT8*>(instr_map[instr_map_entry].encoded_ins), max_inst_len);
if (xed_code != XED_ERROR_NONE) {
cerr << "ERROR: xed decode failed for instr at: " << "0x" << hex << instr_map[instr_map_entry].new_ins_addr << endl;
return -1;
}
unsigned int memops = xed_decoded_inst_number_of_memory_operands(&xedd);
if (instr_map[instr_map_entry].orig_targ_addr != 0) // a direct jmp or call instruction.
return 0;
//cerr << "Memory Operands" << endl;
bool isRipBase = false;
xed_reg_enum_t base_reg = XED_REG_INVALID;
xed_int64_t disp = 0;
for(unsigned int i=0; i < memops ; i++) {
base_reg = xed_decoded_inst_get_base_reg(&xedd,i);
disp = xed_decoded_inst_get_memory_displacement(&xedd,i);
if (base_reg == XED_REG_RIP) {
isRipBase = true;
break;
}
}
if (!isRipBase)
return 0;
//xed_uint_t disp_byts = xed_decoded_inst_get_memory_displacement_width(xedd,i); // how many byts in disp ( disp length in byts - for example FFFFFFFF = 4
xed_int64_t new_disp = 0;
xed_uint_t new_disp_byts = 4; // set maximal num of byts for now.
unsigned int orig_size = xed_decoded_inst_get_length (&xedd);
// modify rip displacement. use direct addressing mode:
new_disp = instr_map[instr_map_entry].orig_ins_addr + disp + orig_size; // xed_decoded_inst_get_length (&xedd_orig);
xed_encoder_request_set_base0 (&xedd, XED_REG_INVALID);
//Set the memory displacement using a bit length
xed_encoder_request_set_memory_displacement (&xedd, new_disp, new_disp_byts);
unsigned int size = XED_MAX_INSTRUCTION_BYTES;
unsigned int new_size = 0;
// Converts the decoder request to a valid encoder request:
xed_encoder_request_init_from_decode (&xedd);
xed_error_enum_t xed_error = xed_encode (&xedd, reinterpret_cast<UINT8*>(instr_map[instr_map_entry].encoded_ins), size , &new_size); // &instr_map[i].size
if (xed_error != XED_ERROR_NONE) {
cerr << "ENCODE ERROR: " << xed_error_enum_t2str(xed_error) << endl;
dump_instr_map_entry(instr_map_entry);
return -1;
}
if (KnobVerbose) {
dump_instr_map_entry(instr_map_entry);
}
return new_size;
}
/************************************/
/* fix_direct_br_call_to_orig_addr */
/************************************/
int fix_direct_br_call_to_orig_addr(int instr_map_entry)
{
xed_decoded_inst_t xedd;
xed_decoded_inst_zero_set_mode(&xedd,&dstate);
xed_error_enum_t xed_code = xed_decode(&xedd, reinterpret_cast<UINT8*>(instr_map[instr_map_entry].encoded_ins), max_inst_len);
if (xed_code != XED_ERROR_NONE) {
cerr << "ERROR: xed decode failed for instr at: " << "0x" << hex << instr_map[instr_map_entry].new_ins_addr << endl;
return -1;
}
xed_category_enum_t category_enum = xed_decoded_inst_get_category(&xedd);
if (category_enum != XED_CATEGORY_CALL && category_enum != XED_CATEGORY_UNCOND_BR) {
cerr << "ERROR: Invalid direct jump from translated code to original code in rotuine: "
<< RTN_Name(RTN_FindByAddress(instr_map[instr_map_entry].orig_ins_addr)) << endl;
dump_instr_map_entry(instr_map_entry);
return -1;
}
// check for cases of direct jumps/calls back to the orginal target address:
if (instr_map[instr_map_entry].new_targ_entry >= 0) {
cerr << "ERROR: Invalid jump or call instruction" << endl;
return -1;
}
unsigned int ilen = XED_MAX_INSTRUCTION_BYTES;
unsigned int olen = 0;
xed_encoder_instruction_t enc_instr;
ADDRINT new_disp = (ADDRINT)&instr_map[instr_map_entry].orig_targ_addr -
instr_map[instr_map_entry].new_ins_addr -
xed_decoded_inst_get_length (&xedd);
if (category_enum == XED_CATEGORY_CALL)
xed_inst1(&enc_instr, dstate,
XED_ICLASS_CALL_NEAR, 64,
xed_mem_bd (XED_REG_RIP, xed_disp(new_disp, 32), 64));
if (category_enum == XED_CATEGORY_UNCOND_BR)
xed_inst1(&enc_instr, dstate,
XED_ICLASS_JMP, 64,
xed_mem_bd (XED_REG_RIP, xed_disp(new_disp, 32), 64));
xed_encoder_request_t enc_req;
xed_encoder_request_zero_set_mode(&enc_req, &dstate);
xed_bool_t convert_ok = xed_convert_to_encoder_request(&enc_req, &enc_instr);
if (!convert_ok) {
cerr << "conversion to encode request failed" << endl;
return -1;
}
xed_error_enum_t xed_error = xed_encode(&enc_req, reinterpret_cast<UINT8*>(instr_map[instr_map_entry].encoded_ins), ilen, &olen);
if (xed_error != XED_ERROR_NONE) {
cerr << "ENCODE ERROR: " << xed_error_enum_t2str(xed_error) << endl;
dump_instr_map_entry(instr_map_entry);
return -1;
}
// handle the case where the original instr size is different from new encoded instr:
if (olen != xed_decoded_inst_get_length (&xedd)) {
new_disp = (ADDRINT)&instr_map[instr_map_entry].orig_targ_addr -
instr_map[instr_map_entry].new_ins_addr - olen;
if (category_enum == XED_CATEGORY_CALL)
xed_inst1(&enc_instr, dstate,
XED_ICLASS_CALL_NEAR, 64,
xed_mem_bd (XED_REG_RIP, xed_disp(new_disp, 32), 64));
if (category_enum == XED_CATEGORY_UNCOND_BR)
xed_inst1(&enc_instr, dstate,
XED_ICLASS_JMP, 64,
xed_mem_bd (XED_REG_RIP, xed_disp(new_disp, 32), 64));
xed_encoder_request_zero_set_mode(&enc_req, &dstate);
xed_bool_t convert_ok = xed_convert_to_encoder_request(&enc_req, &enc_instr);
if (!convert_ok) {
cerr << "conversion to encode request failed" << endl;
return -1;
}
xed_error = xed_encode (&enc_req, reinterpret_cast<UINT8*>(instr_map[instr_map_entry].encoded_ins), ilen , &olen);
if (xed_error != XED_ERROR_NONE) {
cerr << "ENCODE ERROR: " << xed_error_enum_t2str(xed_error) << endl;
dump_instr_map_entry(instr_map_entry);
return -1;
}
}
// debug prints:
if (KnobVerbose) {
dump_instr_map_entry(instr_map_entry);
}
instr_map[instr_map_entry].hasNewTargAddr = true;
return olen;
}
/***********************************/
/* fix_direct_br_call_displacement */
/***********************************/
int fix_direct_br_call_displacement(int instr_map_entry)
{
xed_decoded_inst_t xedd;
xed_decoded_inst_zero_set_mode(&xedd,&dstate);
xed_error_enum_t xed_code = xed_decode(&xedd, reinterpret_cast<UINT8*>(instr_map[instr_map_entry].encoded_ins), max_inst_len);
if (xed_code != XED_ERROR_NONE) {
cerr << "ERROR: xed decode failed for instr at: " << "0x" << hex << instr_map[instr_map_entry].new_ins_addr << endl;
return -1;
}
xed_int32_t new_disp = 0;
unsigned int size = XED_MAX_INSTRUCTION_BYTES;
unsigned int new_size = 0;
xed_category_enum_t category_enum = xed_decoded_inst_get_category(&xedd);
if (category_enum != XED_CATEGORY_CALL && category_enum != XED_CATEGORY_COND_BR && category_enum != XED_CATEGORY_UNCOND_BR) {
cerr << "ERROR: unrecognized branch displacement" << endl;
return -1;
}
// fix branches/calls to original targ addresses:
if (instr_map[instr_map_entry].new_targ_entry < 0) {
int rc = fix_direct_br_call_to_orig_addr(instr_map_entry);
return rc;
}
ADDRINT new_targ_addr;
new_targ_addr = instr_map[instr_map[instr_map_entry].new_targ_entry].new_ins_addr;
new_disp = (new_targ_addr - instr_map[instr_map_entry].new_ins_addr) - instr_map[instr_map_entry].size; // orig_size;
xed_uint_t new_disp_byts = 4; // num_of_bytes(new_disp); ???
// the max displacement size of loop instructions is 1 byte:
xed_iclass_enum_t iclass_enum = xed_decoded_inst_get_iclass(&xedd);
if (iclass_enum == XED_ICLASS_LOOP || iclass_enum == XED_ICLASS_LOOPE || iclass_enum == XED_ICLASS_LOOPNE) {
new_disp_byts = 1;
}
// the max displacement size of jecxz instructions is ???:
xed_iform_enum_t iform_enum = xed_decoded_inst_get_iform_enum (&xedd);
if (iform_enum == XED_IFORM_JRCXZ_RELBRb){
new_disp_byts = 1;
}
// Converts the decoder request to a valid encoder request:
xed_encoder_request_init_from_decode (&xedd);
//Set the branch displacement:
xed_encoder_request_set_branch_displacement (&xedd, new_disp, new_disp_byts);
xed_uint8_t enc_buf[XED_MAX_INSTRUCTION_BYTES];
unsigned int max_size = XED_MAX_INSTRUCTION_BYTES;
xed_error_enum_t xed_error = xed_encode (&xedd, enc_buf, max_size , &new_size);
if (xed_error != XED_ERROR_NONE) {
cerr << "ENCODE ERROR: " << xed_error_enum_t2str(xed_error) << endl;
char buf[2048];
xed_format_context(XED_SYNTAX_INTEL, &xedd, buf, 2048, static_cast<UINT64>(instr_map[instr_map_entry].orig_ins_addr), 0, 0);
cerr << " instr: " << "0x" << hex << instr_map[instr_map_entry].orig_ins_addr << " : " << buf << endl;
return -1;
}
new_targ_addr = instr_map[instr_map[instr_map_entry].new_targ_entry].new_ins_addr;
new_disp = new_targ_addr - (instr_map[instr_map_entry].new_ins_addr + new_size); // this is the correct displacemnet.
//Set the branch displacement:
xed_encoder_request_set_branch_displacement (&xedd, new_disp, new_disp_byts);
xed_error = xed_encode (&xedd, reinterpret_cast<UINT8*>(instr_map[instr_map_entry].encoded_ins), size , &new_size); // &instr_map[i].size
if (xed_error != XED_ERROR_NONE) {
cerr << "ENCODE ERROR: " << xed_error_enum_t2str(xed_error) << endl;
dump_instr_map_entry(instr_map_entry);
return -1;
}
//debug print of new instruction in tc:
if (KnobVerbose) {
dump_instr_map_entry(instr_map_entry);
}
return new_size;
}
/************************************/
/* fix_instructions_displacements() */
/************************************/
int fix_instructions_displacements()
{
// fix displacemnets of direct branch or call instructions:
int size_diff = 0;
do {
size_diff = 0;
if (KnobVerbose) {
cerr << "starting a pass of fixing instructions displacements: " << endl;
}
for (int i=0; i < num_of_instr_map_entries; i++) {
instr_map[i].new_ins_addr += size_diff;
int rc = 0;
// fix rip displacement:
rc = fix_rip_displacement(i);
if (rc < 0)
return -1;
if (rc > 0) { // this was a rip-based instruction which was fixed.
if (instr_map[i].size != (unsigned int)rc) {
size_diff += (rc - instr_map[i].size);
instr_map[i].size = (unsigned int)rc;
}
continue;
}
// check if it is a direct branch or a direct call instr:
if (instr_map[i].orig_targ_addr == 0) {
continue; // not a direct branch or a direct call instr.
}
// fix instr displacement:
rc = fix_direct_br_call_displacement(i);
if (rc < 0)
return -1;
if (instr_map[i].size != (unsigned int)rc) {
size_diff += (rc - instr_map[i].size);
instr_map[i].size = (unsigned int)rc;
}
} // end int i=0; i ..
} while (size_diff != 0);
return 0;
}
void get_inverse_inst(INS ins, xed_decoded_inst_t* output_inst)
{
xed_decoded_inst_t *xedd = INS_XedDec(ins);
xed_category_enum_t category_enum = xed_decoded_inst_get_category(xedd);
if (category_enum != XED_CATEGORY_COND_BR)
return;
xed_iclass_enum_t iclass_enum = xed_decoded_inst_get_iclass(xedd);
if (iclass_enum == XED_ICLASS_JRCXZ)
return; // do not revert JRCXZ
xed_iclass_enum_t retverted_iclass;
switch (iclass_enum)
{
case XED_ICLASS_JB:
retverted_iclass = XED_ICLASS_JNB;
break;
case XED_ICLASS_JBE:
retverted_iclass = XED_ICLASS_JNBE;
break;
case XED_ICLASS_JL:
retverted_iclass = XED_ICLASS_JNL;
break;
case XED_ICLASS_JLE:
retverted_iclass = XED_ICLASS_JNLE;
break;
case XED_ICLASS_JNB:
retverted_iclass = XED_ICLASS_JB;
break;
case XED_ICLASS_JNBE:
retverted_iclass = XED_ICLASS_JBE;
break;
case XED_ICLASS_JNL:
retverted_iclass = XED_ICLASS_JL;
break;
case XED_ICLASS_JNLE:
retverted_iclass = XED_ICLASS_JLE;
break;
case XED_ICLASS_JNO:
retverted_iclass = XED_ICLASS_JO;
break;
case XED_ICLASS_JNP:
retverted_iclass = XED_ICLASS_JP;
break;
case XED_ICLASS_JNS:
retverted_iclass = XED_ICLASS_JS;
break;
case XED_ICLASS_JNZ:
retverted_iclass = XED_ICLASS_JZ;
break;
case XED_ICLASS_JO:
retverted_iclass = XED_ICLASS_JNO;
break;
case XED_ICLASS_JP:
retverted_iclass = XED_ICLASS_JNP;
break;
case XED_ICLASS_JS:
retverted_iclass = XED_ICLASS_JNS;
break;
case XED_ICLASS_JZ:
retverted_iclass = XED_ICLASS_JNZ;
break;
default:
return;
}
// Converts the decoder request to a valid encoder request:
xed_encoder_request_init_from_decode(xedd);
// set the reverted opcode;
xed_encoder_request_set_iclass(xedd, retverted_iclass);
xed_uint8_t enc_buf[XED_MAX_INSTRUCTION_BYTES];
unsigned int max_size = XED_MAX_INSTRUCTION_BYTES;
unsigned int new_size = 0;
xed_error_enum_t xed_error = xed_encode (xedd, enc_buf, max_size, &new_size);
if (xed_error != XED_ERROR_NONE) {
cerr << "ENCODE ERROR: " << xed_error_enum_t2str(xed_error) << endl;
return;
}
//print the original and the new reverted cond instructions:
//
cerr << "orig instr: " << hex << INS_Address(ins) << " " << INS_Disassemble(ins) << endl;
char buf[2048];
xed_decoded_inst_t new_xedd;
xed_decoded_inst_zero_set_mode(&new_xedd,&dstate);
xed_error_enum_t xed_code = xed_decode(&new_xedd, enc_buf, XED_MAX_INSTRUCTION_BYTES);
if (xed_code != XED_ERROR_NONE)
{
cerr << "ERROR: xed decode failed for instr at: " << "0x" << hex << INS_Address(ins) << endl;
return;
}
xed_format_context(XED_SYNTAX_INTEL, &new_xedd, buf, 2048, INS_Address(ins), 0, 0);
cerr << "new instr: " << hex << INS_Address(ins) << " " << buf << endl << endl;