-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtraceclient.cpp
More file actions
1294 lines (1055 loc) · 41.5 KB
/
traceclient.cpp
File metadata and controls
1294 lines (1055 loc) · 41.5 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
/*
Trace requirements:
Every instruction of target (internal) code, in order
The first address of non-target (external) code
Need to record target of every jump in case it hits external + can check conditional completion offline
*/
#define _WIN32
//I tried to compile this using VS2015 but no matter what options or defines I used
//it wouldn't run on windows 10. these are a monument to my failure
#define _WIN32_WINNT _WIN32_WINNT_WIN7
#define WINVER _WIN32_WINNT_WIN7
#define NTDDI_VERSION _WIN32_WINNT_WIN7
#include "headers\windowstrace.h"
#include "headers\traceclient.h"
#include "headers\utilities.h"
//todo: sort crash if target buffer full (ie: paused w/debugger)
static void event_thread_init(void *drcontext);
static void event_thread_exit(void *drcontext);
void event_exit();
static bool event_pre_syscall(void *drcontext, int);
static dr_emit_flags_t event_bb_analysis(void *drcontext, void *tag,
instrlist_t *bb,
bool for_trace, bool translating,
void **user_data);
static dr_emit_flags_t event_app_instruction(void *drcontext, void *tag,
instrlist_t *bb, instr_t *inst,
bool for_trace, bool translating,
void *user_data);
static void at_cbr(app_pc pc, app_pc target, app_pc fallthrough, int taken, void *u_d);
static void at_ubr(app_pc pc, app_pc target);
static void at_mbr(app_pc pc, app_pc target);
static void at_call(app_pc pc, app_pc target);
#ifdef DEBUG_LOGGING
file_t dbgfile;
#endif
unsigned long memcount = 0;
unsigned long tmemcount = 0;
extern unsigned long *globmemcount = &memcount;
extern unsigned long * threadmemcount = &tmemcount;
std::vector<std::unordered_set<TARG_BLOCKID_PAIR>*> setAddrs;
TRACECLIENT *traceClientptr;
//quick and dirty way of reducing our time spent looking which module a given address belongs to
std::unordered_map<thread_id_t, unsigned int> threadModArr;
//write to the basic block handler thread
void TRACECLIENT::write_sync_bb(char* buf, uint strsize)
{
if(!dr_write_file(bbpipe, buf, strsize)) //fprintf truncates to internal buffer size!
{
dr_printf("[drgat]Abort called in write_sync_bb\n");
dr_abort();
}
dr_flush_file(bbpipe);
}
//write to the module_handler_thead
void TRACECLIENT::write_sync_mod(char *logText, ...)
{
char str[MAXMODMSGSIZE];
ssize_t total = 0;
va_list args;
va_start(args, logText);
total += dr_vsnprintf(str, MAXMODMSGSIZE, logText, args);
va_end(args);
DR_ASSERT_MSG(total,str);
str[total] = 0;
DR_ASSERT_MSG(total < MAXMODMSGSIZE, "MAXMODMSGSIZE too small");
total = dr_fprintf(modpipe, "%s", str);
if (total <= 0)
{
dr_printf("[drgat]Abort called in write_sync_mod\n");
dr_abort();
}
dr_flush_file(modpipe);
}
static bool event_exception(void *drcontext, dr_exception_t *excpt)
{
THREAD_STATE *thread = (THREAD_STATE *)drmgr_get_tls_field(dr_get_current_drcontext(), traceClientptr->tls_idx);
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"In exception event\n");
dr_flush_file(thread->dbgfile);
#endif
printTagCache(thread);
dr_fprintf(thread->f, "EXC,"ADDR_FMT",%lx,%lx@", excpt->record->ExceptionAddress, excpt->record->ExceptionCode, excpt->record->ExceptionFlags);
return true;
}
//take comma separated string, place in suplied string buf
void TRACECLIENT::load_modinclude_strings(char *commaSepPaths)
{
std::string pathString(commaSepPaths);
std::stringstream ss(pathString);
while (includedModuleStrings.size() < MAXINCLUDES)
{
std::string path;
std::getline(ss, path, ',');
if (path.empty()) return;
#ifdef WINDOWS
std::transform(path.begin(), path.end(), path.begin(), ::tolower);
#endif
includedModuleStrings[path] = true;
}
}
//take comma separated string, place in suplied string buf
void TRACECLIENT::load_modexclude_strings(char *commaSepPaths)
{
std::string pathString(commaSepPaths);
std::stringstream ss(pathString);
while (excludedModuleStrings.size() < MAXINCLUDES)
{
std::string path;
std::getline(ss, path, ',');
if (path.empty()) return;
#ifdef WINDOWS
std::transform(path.begin(), path.end(), path.begin(), ::tolower);
#endif
excludedModuleStrings[path] = true;
}
}
void processArgs(const char **ask_argv, int ask_argc, TRACECLIENT * client)
{
dr_printf("[drgat]Client starting with %d options: \n",ask_argc-1);
for (int x = 1; x < ask_argc; ++x)
{
dr_printf("option:%s\n", ask_argv[x]);
std::string arg(ask_argv[x]);
if (arg == "-defaultinstrument")
{
client->defaultInstrument = true;
continue;
}
//hide sleeps/shorten tick counts
if (arg == "-caffine")
{
client->hidetime = true;
continue;
}
//hide sleeps/shorten tick counts
if (arg == "-blkdebug")
{
client->processingMode = DEBUG_TRACING;
continue;
}
//instrument all libraries by default, de-instrument uwanted with exclude
if (arg == "-defaultinstrument")
{
client->defaultInstrument = true;
continue;
}
//specify libraries to instrument
if (arg == "-include")
{
client->load_modinclude_strings((char *)ask_argv[++x]);
continue;
}
//used with -defaultinstrument
if (arg == "-exclude")
{
client->load_modexclude_strings((char *)ask_argv[++x]);
continue;
}
}
}
/*
uses thread and block activity counters to decide when to unchain blocks on a sliding scale
looks something like this:
b1 b2 b3 b4 b5
1 1 1 1
2 2
3 3
2 2 2 2
3 3
4 4
3 3 3 3
4 4
5 5
1
1 1 1 1
*/
inline void process_block_chain(app_pc pc, app_pc target, BLOCKDATA *block_data)
{
THREAD_STATE *thread = (THREAD_STATE *)drmgr_get_tls_field(dr_get_current_drcontext(), traceClientptr->tls_idx);
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"<>process_block_chain: %d, block: "ADDR_FMT", blockbusy:%d, threadbusy:%d\n",
thread->tid, block_data->appc, block_data->busyCounter, thread->busyCounter);
dr_flush_file(thread->dbgfile);
#endif
//thread in an area of high workload above deinstrumentation threshold
if (thread->unchainedExist)
{
//this block (or its target) is new to the work area
//rechain everything (ie: start processing it block by block)
if((block_data->busyCounter == 0) || (thread->lastestBlockIDs.count(target) == 0))
{
#ifdef DEBUG_LOGGING
if(block_data->busyCounter == 0)
dr_fprintf(thread->dbgfile,"chain reattached by 0 activity block "ADDR_FMT", caller had executed %d times\n",
block_data->appc, thread->lastBlock->unchainedRepeats);
if (thread->lastestBlockIDs.count(target) == 0)
dr_fprintf(thread->dbgfile,"chain reattached by new target "ADDR_FMT", caller had executed %d times\n",
target, thread->lastBlock->unchainedRepeats);
#endif
printTagCache(thread);
std::vector<void *>::iterator unchainedIt = thread->unchainedBlocks.begin();
for (; unchainedIt != thread->unchainedBlocks.end(); ++unchainedIt)
{
BLOCKDATA *chainedBlock = ((BLOCKDATA *)*unchainedIt);
std::unordered_set<TARG_BLOCKID_PAIR>::iterator targetsIt = chainedBlock->targets->begin();
unsigned int outputcount = 0;
outputcount += dr_snprintf(thread->BXbuffer, TAGCACHESIZE, "BX,"ADDR_FMT",%llx,%lx",chainedBlock->appc,chainedBlock->blockID_numins,chainedBlock->unchainedRepeats);
for(; targetsIt != chainedBlock->targets->end(); ++targetsIt)
{
DR_ASSERT_MSG(outputcount < TAGCACHESIZE, "BXbuffer overflow?");
outputcount += dr_snprintf(thread->BXbuffer+outputcount,TAGCACHESIZE-outputcount,","ADDR_FMT",%lx",targetsIt->first, targetsIt->second);
}
dr_fprintf(thread->f,"%s@",thread->BXbuffer);
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"[%s@]",thread->BXbuffer);
dr_flush_file(thread->dbgfile);
#endif
dr_flush_file(thread->f);
chainedBlock->unchained = false;
chainedBlock->busyCounter = 0;
}
thread->unchainedBlocks.clear();
thread->unchainedExist = false;
//make link between unchained nodes and new appearance
//this also inserts current block onto graph
dr_fprintf(thread->f, "UL,"ADDR_FMT",%llx,"ADDR_FMT",%llx,"ADDR_FMT"@", thread->lastBlock->appc, thread->lastBlock->blockID_numins,
block_data->appc, block_data->blockID_numins, target);
dr_flush_file(thread->f);
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile, "[UL entry,"ADDR_FMT",%llx,"ADDR_FMT",%llx,"ADDR_FMT"@]", thread->lastBlock->appc, thread->lastBlock->blockID_numins,
block_data->appc, block_data->blockID_numins, target);
dr_flush_file(thread->dbgfile);
#endif
thread->busyCounter = ++block_data->busyCounter;
}
//in an area of high workload, this block is part of it so unchain it too
else
{
printTagCache(thread); //just in case
block_data->unchainedRepeats = 1;
block_data->unchained = true;
block_data->lastTarget = target;
BLOCK_IDENTIFIER targBlockID = thread->lastestBlockIDs.at(target);
block_data->lastTargetID = targBlockID;
block_data->targets->clear();
block_data->targets->insert(std::make_pair(target, targBlockID));
thread->unchainedBlocks.push_back((void *) block_data);
thread->lastBlock = block_data;
thread->lastBlock_expected_targID = targBlockID;
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"[UC0 Entry-- "ADDR_FMT",%lx,"ADDR_FMT",%lx@]",block_data->appc, block_data->blockID, target, targBlockID);
#endif
//notify visualiser that this area is going to be busy and won't report back until done
dr_fprintf(thread->f, "UC,"ADDR_FMT",%lx,"ADDR_FMT",%lx@",block_data->appc, block_data->blockID, target, targBlockID);
dr_flush_file(thread->f);
}
return;
}
//if here then thread is below unchaining threshold
//area of increased activity, increase block activity counter
if ((block_data->busyCounter == thread->busyCounter) ||
(block_data->busyCounter == (thread->busyCounter-1)))
{
//increase thread activity counter if all blocks aside from from this one
if (++block_data->busyCounter > thread->busyCounter)
++thread->busyCounter;
if(block_data->busyCounter >= DEINSTRUMENTATION_LIMIT)
{
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"Deinstrumentation limit reached at block "ADDR_FMT", unchaining\n",block_data->appc);
#endif
printTagCache(thread);
block_data->unchainedRepeats = 1;
block_data->unchained = true;
block_data->lastTarget = target;
BLOCK_IDENTIFIER targBlockID;
BLOCKIDMAP::iterator blockIDIt = thread->lastestBlockIDs.find(target);
if(blockIDIt == thread->lastestBlockIDs.end())
{
thread->unsatisfiedBlockIDs = true;
thread->unsatisfiedBlockIDAddress = target;
targBlockID = 0;
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"Unsatisfied block registered. Target: "ADDR_FMT"\n", target);
#endif
}
else
targBlockID = blockIDIt->second;
block_data->lastTargetID = targBlockID;
block_data->targets->clear();
block_data->targets->insert(std::make_pair(target, targBlockID));
thread->unchainedBlocks.push_back(((void *) block_data));
thread->unchainedExist = true;
thread->lastBlock = block_data;
thread->lastBlock_expected_targID = targBlockID;
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"[UC1 Entry-- "ADDR_FMT",%lx,"ADDR_FMT",%lx]\n",block_data->appc, block_data->blockID, target, targBlockID);
#endif
dr_fprintf(thread->f, "UC,"ADDR_FMT",%lx,"ADDR_FMT",%lx@",block_data->appc, block_data->blockID, target, targBlockID);
dr_flush_file(thread->f);
return;
}
}
else //block busier than recent thread actvity - lower block activity to match
if (block_data->busyCounter > thread->busyCounter)
block_data->busyCounter = thread->busyCounter;
else
//active block with less activity than thread - lower thread activity to match
thread->busyCounter = ++block_data->busyCounter;
thread->sourceInstruction = pc; //not set in unchained --- hasn't been a problem yet
thread->lastBlock = block_data;
unsigned int tagIdx = thread->tagIdx++;
if (tagIdx > TAGCACHESIZE-1)
{
printTagCache(thread);
tagIdx = 0;
}
if (!thread->cacheRepeats)
{
//not in loop, record new block info in cache
thread->tagCache[tagIdx] = block_data->appc;
thread->targetAddresses[tagIdx] = target;
thread->blockID_counts[tagIdx] = block_data->blockID_numins;
//not a back edge so no further processing
//ideally the processing for most blocks ends here
if ((void *)target > (void *)pc)
return;
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"\tnot in loop insaddr 0x"ADDR_FMT" bb [tagidx %d addr 0x"ADDR_FMT" targ 0x"ADDR_FMT"]\n",pc,tagIdx,block_data->appc,target);
#endif
if (thread->tagCache[0] == target)//back to start of cache
{
//record cache as first iteration of a loop
thread->loopEnd = tagIdx;
thread->cacheRepeats++;
thread->tagIdx = 0;
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"starting new loop of %d blocks from "ADDR_FMT" (cachrepeats set to %d)",thread->loopEnd, target,
thread->cacheRepeats);
#endif
}
else
{
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"\tunknown backedge idx %d, targ 0x"ADDR_FMT"!, cache[0] 0x"ADDR_FMT"\n",tagIdx,
target,thread->tagCache[0]);
#endif
//back to something else, dump cache
printTagCache(thread);
}
return;
}
if (tagIdx == thread->loopEnd) //end of loop
{
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"\tend of loop idx %d, checking targ 0x"ADDR_FMT"! = cache[0] 0x"ADDR_FMT"\n",tagIdx,
target,thread->tagCache[0]);
#endif
//back to start of loop
if (target == thread->tagCache[0])
{
//record another iteration of cache
++thread->cacheRepeats;
thread->tagIdx = 0;
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"\tback to start of loop head "ADDR_FMT", loop now %d iterations\n",target,thread->cacheRepeats);
#endif
return;
}
//leaving loop. print loops up until now + progress on current loop
--thread->tagIdx;
printTagCache(thread);
tagIdx = 0;
thread->tagCache[tagIdx] = block_data->appc;
thread->blockID_counts[tagIdx] = block_data->blockID_numins;
thread->targetAddresses[tagIdx] = target;
thread->tagIdx = 1;
return;
}
//continuing in cached loop but not at end, ensure this block matches cached block
if ((thread->tagCache[tagIdx] != block_data->appc) || //different BB?
(thread->blockID_counts[tagIdx] != block_data->blockID_numins) || //same BB start, different end?
(thread->targetAddresses[tagIdx] != target)) //leaving mid loop?
{
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"\tloop mismatch dumpcache idx %d, 0x"ADDR_FMT"!=0x"ADDR_FMT",numins:%d, 0x"ADDR_FMT"!=0x"ADDR_FMT"\n",tagIdx,
thread->tagCache[tagIdx],(uint)block_data->appc,
block_data->numInstructions,thread->targetAddresses[tagIdx], target);
dr_flush_file(thread->dbgfile);
#endif
//they don't match! print loops up til now + progress on current loop
--thread->tagIdx;
printTagCache(thread);
tagIdx = 0;
thread->tagCache[tagIdx] = block_data->appc;
thread->blockID_counts[tagIdx] = block_data->blockID_numins;
thread->targetAddresses[tagIdx] = target;
thread->tagIdx = 1;
}
}
static void at_cbr(app_pc sourceInstructionAddress, app_pc targetBlockAddress, app_pc fallthrough, int taken, void *blk_d)
{
#ifdef DEBUG_LOGGING
dr_fprintf(dbgfile,"at_cbr called\n");
#endif
app_pc actualTarget = taken ? targetBlockAddress : fallthrough;
BLOCKDATA * block_data = ((BLOCKDATA *)blk_d);
#ifdef DEBUG_LOGGING
THREAD_STATE *dbgthread = (THREAD_STATE *)drmgr_get_tls_field(dr_get_current_drcontext(), traceClientptr->tls_idx);
dr_fprintf(dbgthread->dbgfile,"at_cbr pc 0x"ADDR_FMT" target 0x"ADDR_FMT" blockhead 0x"ADDR_FMT" fallthroughaddr:0x"ADDR_FMT" taken:%d\n",
sourceInstructionAddress,targetBlockAddress,block_data->appc,fallthrough,taken);
dr_flush_file(dbgthread->dbgfile);
#endif
if (!block_data->unchained)
{
process_block_chain(sourceInstructionAddress, actualTarget, block_data);
return;
}
THREAD_STATE *thread = (THREAD_STATE *)drmgr_get_tls_field(dr_get_current_drcontext(), traceClientptr->tls_idx);
//increase count of executions for this block
++block_data->unchainedRepeats;
//check to see if this block is the expected target
if (block_data->blockID != thread->lastBlock_expected_targID)
{
//nope! add a new target to previous blocks target set so it can be added to graph
thread->lastBlock->targets->insert(std::make_pair(block_data->appc, block_data->blockID));
thread->lastBlock->lastTargetID = block_data->blockID;
}
//update state so next block can do the same check
thread->lastBlock_expected_targID = block_data->lastTargetID;
//check if the target of this jump is the one block expects
//if not then update the expected target and add it to target list
//this avoids expensive set lookup every execution
if (actualTarget != block_data->lastTarget)
{
block_data->lastTarget = actualTarget;
BLOCKIDMAP::iterator latestIDIt = thread->lastestBlockIDs.find(actualTarget);
//if not found then BB hasn't been created yet. block becomes 'unsatisfied' - value will be set when it is created
if (latestIDIt == thread->lastestBlockIDs.end())
{
thread->unsatisfiedBlockIDs = true;
thread->unsatisfiedBlockIDAddress = actualTarget;
block_data->lastTargetID = 0;
}
else
{
block_data->lastTargetID = latestIDIt->second;
block_data->targets->insert(std::make_pair(actualTarget, latestIDIt->second));
}
}
//update state so we know which member of unchained area executed an inactive block, if target is inactive
thread->lastBlock = block_data;
#ifdef DEBUG_LOGGING
dr_fprintf(dbgthread->dbgfile,"cbr done targ->0x"ADDR_FMT"\n",actualTarget);
dr_flush_file(dbgthread->dbgfile);
#endif
}
static void at_ubr(app_pc sourceInstructionAddress, app_pc targetBlockAddress)
{
#ifdef DEBUG_LOGGING
dr_fprintf(dbgfile,"at_ubr called\n");
dr_flush_file(dbgfile);
#endif
BLOCKDATA *block_data = (BLOCKDATA *)dr_read_saved_reg(dr_get_current_drcontext(), SPILL_SLOT_2);
#ifdef DEBUG_LOGGING
THREAD_STATE *dbgthread = (THREAD_STATE *)drmgr_get_tls_field(dr_get_current_drcontext(), traceClientptr->tls_idx);
dr_fprintf(dbgthread->dbgfile,"at_ubr 0x"ADDR_FMT"->0x"ADDR_FMT"\n",sourceInstructionAddress,targetBlockAddress);
dr_flush_file(dbgthread->dbgfile);
#endif
if (!block_data->unchained)
{
process_block_chain(sourceInstructionAddress, targetBlockAddress, block_data);
return;
}
THREAD_STATE *thread = (THREAD_STATE *)drmgr_get_tls_field(dr_get_current_drcontext(), traceClientptr->tls_idx);
//register 1 execution of every instruction in the block
++block_data->unchainedRepeats;
//check to see if we arrived at the expected target
if (block_data->blockID != thread->lastBlock_expected_targID)
{
//nope, add a new target to previous block so it can be added to graph
thread->lastBlock->targets->insert(std::make_pair(block_data->appc, block_data->blockID));
thread->lastBlock->lastTargetID = block_data->blockID;
}
//update state so next block can do the same check
thread->lastBlock_expected_targID = block_data->lastTargetID;
//check if the next target is the one block expects
//if not then update the expected target and add it to target list
//this avoids expensive set lookup every execution
if (targetBlockAddress != block_data->lastTarget)
{
block_data->lastTarget = targetBlockAddress;
BLOCKIDMAP::iterator blockIDit = thread->lastestBlockIDs.find(targetBlockAddress);
if (blockIDit != thread->lastestBlockIDs.end())
{
thread->unsatisfiedBlockIDs = true;
thread->unsatisfiedBlockIDAddress = targetBlockAddress;
block_data->lastTargetID = 0;
}
else
{
block_data->lastTargetID = blockIDit->second;
block_data->targets->insert(std::make_pair(targetBlockAddress, block_data->lastTargetID));
}
}
//update state so drgat knows which member of unchained area executed an inactive block
thread->lastBlock = block_data;
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"ubr done targ->0x"ADDR_FMT"\n",targetBlockAddress);
dr_flush_file(thread->dbgfile);
#endif
}
static void at_mbr(app_pc sourceInstructionAddress, app_pc targetBlockAddress)
{
BLOCKDATA *block_data = (BLOCKDATA *)dr_read_saved_reg(dr_get_current_drcontext(), SPILL_SLOT_2);
#ifdef DEBUG_LOGGING
THREAD_STATE *dbgthread = (THREAD_STATE *)drmgr_get_tls_field(dr_get_current_drcontext(), traceClientptr->tls_idx);
dr_fprintf(dbgthread->dbgfile, "at_mbr address 0x"ADDR_FMT" -> 0x"ADDR_FMT"\n", sourceInstructionAddress, targetBlockAddress);
dr_flush_file(dbgthread->dbgfile);
#endif
if (!block_data->unchained)
{
process_block_chain(sourceInstructionAddress, targetBlockAddress, block_data);
return;
}
THREAD_STATE *thread = (THREAD_STATE *)drmgr_get_tls_field(dr_get_current_drcontext(), traceClientptr->tls_idx);
++block_data->unchainedRepeats;
//check to see if we arrived at the expected target
if (block_data->blockID != thread->lastBlock_expected_targID)
{
//nope, add a new target to previous block so it can be added to graph
thread->lastBlock->targets->insert(std::make_pair(block_data->appc, block_data->blockID));
thread->lastBlock->lastTargetID = block_data->blockID;
}
//update state so next block can do the same check
thread->lastBlock_expected_targID = block_data->lastTargetID;
//check if the next target is the one block expects
//if not then update the expected target and add it to target list
//this avoids expensive set lookup every execution
if (targetBlockAddress != block_data->lastTarget)
{
BLOCKIDMAP::iterator blockIDit = thread->lastestBlockIDs.find(targetBlockAddress);
if (blockIDit != thread->lastestBlockIDs.end())
{
thread->unsatisfiedBlockIDs = true;
thread->unsatisfiedBlockIDAddress = targetBlockAddress;
block_data->lastTargetID = 0;
}
else
{
block_data->lastTargetID = blockIDit->second;
block_data->targets->insert(std::make_pair(targetBlockAddress, block_data->lastTargetID));
}
}
//update state so drgat knows which member of unchained area executed an inactive block
thread->lastBlock = block_data;
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"mbr done targ->0x"ADDR_FMT"\n",targetBlockAddress);
dr_flush_file(thread->dbgfile);
#endif
}
static void at_call(app_pc sourceInstructionAddress, app_pc targetBlockAddress)
{
BLOCKDATA *block_data = (BLOCKDATA *)dr_read_saved_reg(dr_get_current_drcontext(), SPILL_SLOT_2);
#ifdef DEBUG_LOGGING
THREAD_STATE *dbgthread = (THREAD_STATE *)drmgr_get_tls_field(dr_get_current_drcontext(), traceClientptr->tls_idx);
dr_fprintf(dbgthread->dbgfile, "at_call address 0x"ADDR_FMT" -> 0x"ADDR_FMT"\n",sourceInstructionAddress,targetBlockAddress);
dr_flush_file(dbgthread->dbgfile);
#endif
if (!block_data->unchained)
{
process_block_chain(sourceInstructionAddress, targetBlockAddress, block_data);
return;
}
THREAD_STATE *thread = (THREAD_STATE *)drmgr_get_tls_field(dr_get_current_drcontext(), traceClientptr->tls_idx);
++block_data->unchainedRepeats;
//check to see if we arrived at the expected target
if (block_data->blockID != thread->lastBlock_expected_targID)
{
//nope, add a new target to previous block so it can be added to graph
thread->lastBlock->targets->insert(std::make_pair(block_data->appc, block_data->blockID));
thread->lastBlock->lastTargetID = block_data->blockID;
}
//update state so next block can do the same check
thread->lastBlock_expected_targID = block_data->lastTargetID;
//check if the next target is the one block expects
//if not then update the expected target and add it to target list
//this avoids expensive set lookup every execution
if (targetBlockAddress != block_data->lastTarget)
{
BLOCKIDMAP::iterator blockIDit = thread->lastestBlockIDs.find(targetBlockAddress);
if (blockIDit != thread->lastestBlockIDs.end())
{
thread->unsatisfiedBlockIDs = true;
thread->unsatisfiedBlockIDAddress = targetBlockAddress;
block_data->lastTargetID = 0;
}
else
{
block_data->lastTargetID = blockIDit->second;
block_data->targets->insert(std::make_pair(targetBlockAddress, block_data->lastTargetID));
}
}
//update state so drgat knows which member of unchained area executed an inactive block
thread->lastBlock = block_data;
#ifdef DEBUG_LOGGING
dr_fprintf(thread->dbgfile,"cabr done targ->0x"ADDR_FMT"\n",targetBlockAddress);
dr_flush_file(thread->dbgfile);
#endif
}
DR_EXPORT void
dr_client_main(client_id_t id, int argc, const char *argv[])
{
dr_set_client_name("rgat instrumentation client", "https://github.com/ncatlin/rgat");
drmgr_init();
drwrap_init();
void *clientContext = dr_get_current_drcontext();
int ask_argc;
const char **ask_argv;
bool ok = dr_get_option_array(id, &ask_argc, &ask_argv);
if (argc == 0)
{
//dead code?
dr_printf("[drgat]Could not determine target path\n");
return;
}
module_data_t * mainmodule = dr_get_main_module();
std::string appPath(mainmodule->full_path);
#ifdef WINDOWS
std::transform(appPath.begin(), appPath.end(), appPath.begin(), ::tolower);
#endif
traceClientptr = new TRACECLIENT(appPath);
processArgs(ask_argv, ask_argc, traceClientptr);
traceClientptr->allocMutx = dr_mutex_create();
traceClientptr->latestAllocNode = (ALLOCLL *)dr_global_alloc(sizeof(ALLOCLL));
traceClientptr->loggedMemoryLLStart = traceClientptr->latestAllocNode;
traceClientptr->tls_idx = drmgr_register_tls_field();
DR_ASSERT(traceClientptr->tls_idx != -1);
traceClientptr->pid = dr_get_process_id();
#ifdef DEBUG_LOGGING
char filebuf[MAX_PATH];
dr_get_current_directory(filebuf, MAX_PATH);
std::string threadDbgFile = filebuf+std::string("\\")+"debuglogs\\processlog"+std::to_string(traceClientptr->pid)+".txt";
dbgfile = dr_open_file(threadDbgFile.c_str(), DR_FILE_WRITE_OVERWRITE);
dr_printf("[drgat]This is the debug drgat dll! Writing logs to %s with a *significant* performance impact\n", filebuf);
#endif
dr_printf("[drgat]Starting instrumentation of %s (PID:%d)\n",appPath.c_str(),traceClientptr->pid);
std::string pipeName = "\\\\.\\pipe\\BootstrapPipe";
traceClientptr->modpipe = dr_open_file("\\\\.\\pipe\\BootstrapPipe", DR_FILE_WRITE_OVERWRITE);
int failLimit = 30;
while (traceClientptr->modpipe == INVALID_FILE)
{
if(!--failLimit)
{
dr_printf("[drgat]ERROR: Failed on opening pipe %s\n",pipeName.c_str());
dr_close_file(traceClientptr->modpipe);
dr_abort();
return;
}
dr_sleep(1000);
traceClientptr->modpipe = dr_open_file(pipeName.c_str(), DR_FILE_WRITE_OVERWRITE);
}
uint processRandID = dr_get_random_value(INT_MAX >> 4);
//notify rgat to create threads for this process
#ifdef X86_64
dr_fprintf(traceClientptr->modpipe, "PID6%dr%dp%s", traceClientptr->pid,processRandID, mainmodule->full_path);
#else
dr_fprintf(traceClientptr->modpipe, "PID3%dr%dp%s", traceClientptr->pid, processRandID, mainmodule->full_path);
#endif
dr_sleep(600);
process_id_t pidt = traceClientptr->pid;
dr_close_file(traceClientptr->modpipe);
traceClientptr->modpipe = INVALID_FILE;
pipeName = "\\\\.\\pipe\\rioThreadMod";
pipeName.append(std::to_string(traceClientptr->pid));
pipeName.append(std::to_string(processRandID));
traceClientptr->modpipe = dr_open_file(pipeName.c_str(), DR_FILE_WRITE_OVERWRITE);
failLimit = 3;
while (traceClientptr->modpipe == INVALID_FILE)
{
if(!--failLimit)
{
dr_printf("[drgat]ERROR: Failed on opening pipe %s\n",pipeName.c_str());
dr_close_file(traceClientptr->modpipe);
dr_abort();
return;
}
dr_sleep(600);
traceClientptr->modpipe = dr_open_file(pipeName.c_str(), DR_FILE_WRITE_OVERWRITE);
}
dr_sleep(500);
pipeName = "\\\\.\\pipe\\rioThreadBB";
pipeName.append(std::to_string(traceClientptr->pid));
pipeName.append(std::to_string(processRandID));
traceClientptr->bbpipe = dr_open_file(pipeName.c_str(), DR_FILE_WRITE_OVERWRITE);
DR_ASSERT_MSG(traceClientptr->bbpipe != INVALID_FILE, "No rioThreadBB pipe!");
//load executable into module list
if(!traceClientptr->excludedModuleStrings.count(appPath))
{
traceClientptr->includedModuleStrings[appPath] = true;
traceClientptr->includedModules.push_back(true);
}
else
traceClientptr->includedModules.push_back(false);
traceClientptr->modStarts.push_back(mainmodule->start);
traceClientptr->modEnds.push_back(mainmodule->end);
char b64path[STRINGBUFMAX];
b64_string_arg(mainmodule->full_path,b64path);
traceClientptr->write_sync_mod("mn@%s@%d@"ADDR_FMT"@"ADDR_FMT"@%x", b64path, 0,
mainmodule->start, mainmodule->end, !traceClientptr->includedModules[0]);
start_sym_processing(0, mainmodule->full_path);
traceClientptr->numMods = 1;
//start instrumentation
dr_register_exit_event(event_exit);
drmgr_register_thread_init_event(event_thread_init);
drmgr_register_thread_exit_event(event_thread_exit);
drmgr_register_exception_event(event_exception);
drmgr_register_bb_instrumentation_event(event_bb_analysis, NULL, NULL);
#ifdef WINDOWS
drmgr_register_module_load_event(windows_event_module_load);
#elif LINUX
drmgr_register_module_load_event(linux_event_module_load);
#endif
dr_free_module_data(mainmodule);
#ifdef DEBUG_LOGGING
dr_fprintf(dbgfile, "dr_client_main completed\n");
#endif
}
static void event_exit()
{
#ifdef DEBUG_LOGGING
dr_fprintf(dbgfile,"event_exit called for process %d\n", dr_get_process_id());
#endif
//no real point doing this cleanup but i guess it's good practice
//the logged allocation makes new BB allocation take a bit longer but probably not meaningfully.
//try without and see if worth dropping
dr_mutex_lock(traceClientptr->allocMutx);
ALLOCLL *nextNode, *freeThisNode = (ALLOCLL *)traceClientptr->loggedMemoryLLStart->next;
while (freeThisNode)
{
dr_global_free(freeThisNode->addr, freeThisNode->size);
nextNode = (ALLOCLL *)freeThisNode->next;
dr_global_free(freeThisNode,sizeof(ALLOCLL));
freeThisNode = nextNode;
}
dr_mutex_unlock(traceClientptr->allocMutx);
dr_mutex_destroy(traceClientptr->allocMutx);
dr_global_free(traceClientptr->loggedMemoryLLStart,sizeof(ALLOCLL));
std::vector<std::unordered_set<TARG_BLOCKID_PAIR>*>::iterator setAdIt = setAddrs.begin();
for (; setAdIt!= setAddrs.end(); ++setAdIt)
delete *setAdIt;
dr_printf("[drgat]Ready to exit PID%d, waiting for writes to finish\n", dr_get_process_id());
traceClientptr->write_sync_mod("[CLIENT]EVENT: Exit\n");
dr_close_file(traceClientptr->modpipe);
dr_close_file(traceClientptr->bbpipe);
drmgr_unregister_tls_field(traceClientptr->tls_idx);
delete traceClientptr;
file_t closer = dr_open_file("\\\\.\\pipe\\riomodpipe", DR_FILE_WRITE_OVERWRITE);
dr_fprintf(closer, "DIE");
dr_flush_file(closer);
dr_close_file(closer);
drwrap_exit();
drmgr_exit();
dr_printf("[drgat]exit completed for process %d\n", dr_get_process_id());
}
static void event_thread_init(void *threadcontext)
{
thread_id_t tid = dr_get_thread_id(threadcontext);
#ifdef DEBUG_LOGGING
dr_fprintf(dbgfile,"Thread init called for thread %ld\n",tid);
#endif
traceClientptr->write_sync_mod("TI%d", tid);
char pipeName[255];
dr_snprintf(pipeName, 254, "\\\\.\\pipe\\rioThread%d", tid);
file_t threadoutpipe = INVALID_FILE;
//this has been a bottleneck in the past, be wary of it
while (threadoutpipe == INVALID_FILE)
{
dr_sleep(10);
threadoutpipe = dr_open_file(pipeName, DR_FILE_WRITE_OVERWRITE);
}
THREAD_STATE *thread = new THREAD_STATE;
thread->tid = tid;
thread->f = threadoutpipe;
thread->BBBuf = (char *)dr_thread_alloc(threadcontext, MAXBBBYTES);
thread->tagIdx = 0;
thread->cacheRepeats = 0;
thread->loopEnd = 0;
thread->lastTick = 0;
thread->busyCounter = 0;
thread->unchainedExist = false;
thread->unsatisfiedBlockIDAddress = 0;
thread->unsatisfiedBlockIDs = false;
traceClientptr->threadList.push_back(thread);
#ifdef DEBUG_LOGGING
char filebuf[MAX_PATH];
dr_get_current_directory(filebuf, MAX_PATH);
std::string threadDbgFile = filebuf+std::string("\\")+"debuglogs\\threadlog"+std::to_string(traceClientptr->pid)+"-"
+std::to_string(tid)+".txt";
dr_printf("[drgat] New thread debug logging to %s\n", threadDbgFile.c_str());
thread->dbgfile = dr_open_file(threadDbgFile.c_str(), DR_FILE_WRITE_OVERWRITE);
#endif
drmgr_set_tls_field(threadcontext, traceClientptr->tls_idx, (THREAD_STATE *)thread);
dr_flush_file(thread->f);
}
static void
event_thread_exit(void *threadcontext)
{
THREAD_STATE *thread = (THREAD_STATE *)drmgr_get_tls_field(threadcontext, traceClientptr->tls_idx);
thread_id_t tid = dr_get_thread_id(threadcontext);
#ifdef DEBUG_LOGGING
dr_fprintf(dbgfile,"Thread exit called for thread %ld\n",tid);