-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpintrace.cpp
More file actions
1586 lines (1391 loc) · 54.6 KB
/
pintrace.cpp
File metadata and controls
1586 lines (1391 loc) · 54.6 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
/*
__ __ ______ _______ _______ ______ ________
/ \ / | / \ / \ / \ / \ / |
$$ \ /$$ |/$$$$$$ |$$$$$$$ |$$$$$$$ |/$$$$$$ |$$$$$$$$/
$$$ \ /$$$ |$$ | $$/ $$ |__$$ |$$ |__$$ |$$ | $$ |$$ |__
$$$$ /$$$$ |$$ | $$ $$/ $$ $$< $$ | $$ |$$ |
$$ $$ $$/$$ |$$ | __ $$$$$$$/ $$$$$$$ |$$ | $$ |$$$$$/
$$ |$$$/ $$ |$$ \__/ |$$ | $$ | $$ |$$ \__$$ |$$ |
$$ | $/ $$ |$$ $$/ $$ | $$ | $$ |$$ $$/ $$ |
$$/ $$/ $$$$$$/ $$/ $$/ $$/ $$$$$$/ $$/
A Memory and Communication Profiler
* This file is a part of MCPROF.
* https://bitbucket.org/imranashraf/mcprof
*
* Copyright (c) 2014-2016 TU Delft, The Netherlands.
* All rights reserved.
*
* MCPROF is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MCPROF 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with MCPROF. If not, see <http://www.gnu.org/licenses/>.
*
* Authors: Imran Ashraf
*
*/
#include "pin.H"
#include "markers.h"
#include "globals.h"
#include "symbols.h"
#include "pintrace.h"
#include "commatrix.h"
#include "sparsematrix.h"
#include "shadow.h"
#include "callstack.h"
#include "engine1.h"
#include "engine2.h"
#include "engine3.h"
#include "counters.h"
#include "callgraph.h"
#include <iostream>
#include <fstream>
#include <stack>
#include <set>
#include <map>
#include <deque>
#include <algorithm>
#include <cstring>
#include <cstddef>
#include <cctype>
// un-comment the following to generate read/write traces (Also in engine2.cpp)
#define GENRATE_TRACES
/* ================================================================== */
// Global variables
/* ================================================================== */
extern map <string,IDNoType> FuncName2ID;
extern Symbols symTable;
extern Matrix2D ComMatrix;
extern SparseMatrix DependMatrix;
extern map <u32,IDNoType> CallSites2ID;
std::ofstream pcout;
std::ofstream tgout;
std::ofstream traceout;
// these maps are used to record each execution of loop as dependent/independent
set<string>dependentLoopExecutions;
set<string>independentLoopExecutions;
// this map is used to record recursive functions
set<string>recursiveFunctions;
CallStackType CallStack;
CallSiteStackType CallSiteStack;
void (*WriteRecorder)(uptr, u32);
void (*ReadRecorder)(uptr, u32);
void (*InstrCounter)(ADDRINT);
VOID (*RoutineEntryRecorder)(ADDRINT);
VOID (*RoutineExitRecorder)(VOID*);
u32 Engine=0;
bool DoTrace=false;
bool TrackObjects;
bool RecordAllAllocations;
bool FlushCalls;
u32 FlushCallsLimit;
bool ShowUnknown;
bool TrackZones;
bool TrackStartStop;
bool TrackLoopDepend;
bool TrackTasks;
u32 Threshold;
static UINT64 rInstrCount = 0; // Routine instruction counter
UINT64 gInstrCount = 0; // Global running instruction counter
CallGraph callgraph;
u32 SelectedLoopNo;
extern map<IDNoType,u64> instrCounts;
extern map<IDNoType,u64> callCounts;
u32 LoopIterationCount=1;
/* ===================================================================== */
// Command line switches
/* ===================================================================== */
KNOB<string> KnobPerCallFile(KNOB_MODE_WRITEONCE, "pintool",
"PerCallFile", "percallaccesses.dat",
"specify file name for per call output file");
KNOB<BOOL> KnobRecordStack(KNOB_MODE_WRITEONCE, "pintool",
"RecordStack","0", "Include Stack Accesses");
KNOB<BOOL> KnobTrackObjects(KNOB_MODE_WRITEONCE, "pintool",
"TrackObjects", "0", "Track the objects");
KNOB<UINT32> KnobEngine(KNOB_MODE_WRITEONCE, "pintool",
"Engine", "1",
"specify engine number (1,2,3) to be used");
KNOB<BOOL> KnobSelectFunctions(KNOB_MODE_WRITEONCE, "pintool",
"SelectFunctions", "0",
"Instrument only the selected functions.\
User provides functions in <SelectFunctions.txt> file");
KNOB<BOOL> KnobSelectObjects(KNOB_MODE_WRITEONCE, "pintool",
"SelectObjects", "0",
"Instrument only the selected objects.\
User provides objects in <SelectObjects.txt> file");
KNOB<BOOL> KnobMainExecutableOnly(KNOB_MODE_WRITEONCE, "pintool",
"MainExecOnly","1",
"Trace functions that are contained only in the\
main executable image. Set it to 0 to specify library/image names\
of interest to instrument/profile in <interestingLibraryNames.dat> file \
with each name with complete path on separate line");
KNOB<BOOL> KnobRecordAllAllocations(KNOB_MODE_WRITEONCE, "pintool",
"RecordAllAllocations","1",
"Record all allocation sizes of objects");
KNOB<BOOL> KnobFlushCalls(KNOB_MODE_WRITEONCE, "pintool",
"FlushCalls","1",
"Flush calls at intermediate intervals. \
Calls to a function in Engine 3 are flushed to \
output file when they become greater than a \
certain LIMIT(for now 5000) ) ");
KNOB<UINT32> KnobFlushCallsLimit(KNOB_MODE_WRITEONCE, "pintool",
"FlushCallsLimit", "5000",
"specify LIMIT to be used for flushing calls.");
KNOB<BOOL> KnobShowUnknown(KNOB_MODE_WRITEONCE, "pintool",
"ShowUnknown", "0", "Show Unknown function in the output graphs");
KNOB<BOOL> KnobTrackStartStop(KNOB_MODE_WRITEONCE, "pintool",
"TrackStartStop", "0", "Track start/stop markers in\
the code to start/stop profiling\
instead of starting from main()");
KNOB<BOOL> KnobTrackZones(KNOB_MODE_WRITEONCE, "pintool",
"TrackZones", "0", "Track zone markers to profile per zones");
KNOB<BOOL> KnobTrackLoopDepend(KNOB_MODE_WRITEONCE, "pintool",
"TrackLoopDepend", "0", "Track markers for loop dependence");
KNOB<UINT32> KnobSelectedLoopNo(KNOB_MODE_WRITEONCE, "pintool",
"SelectedLoopNo", "0",
"Specify loop no to test of dependence.");
KNOB<BOOL> KnobReadStaticObjects(KNOB_MODE_WRITEONCE, "pintool",
"StaticSymbols", "0", "Read static symbols from the binary and show them in the graph");
KNOB<BOOL> KnobTrackTasks(KNOB_MODE_WRITEONCE, "pintool",
"TrackTasks", "0", "Each function call and loop execution for different source-code\
location will be considered as separate tasks.");
KNOB<UINT32> KnobThreshold(KNOB_MODE_WRITEONCE, "pintool",
"Threshold", "0",
"Specify Threshold, communication edge below this Threshold \
will not appear in the communication graph/matrix.");
/* ===================================================================== */
// Utilities
/* ===================================================================== */
/*!
* Print out help message.
*/
VOID Usage()
{
ECHO( "Memory and Data-Communication PROFiler.");
ECHO( KNOB_BASE::StringKnobSummary() << endl);
}
/* ===================================================================== */
// Analysis routines
/* ===================================================================== */
// This function is called for each basic block
// Use the fast linkage for calls
VOID PIN_FAST_ANALYSIS_CALL doInstrCount(ADDRINT c)
{
if(DoTrace)
{
IDNoType fid = CallStack.Top();
instrCounts[fid] += c;
rInstrCount+=c;
}
}
// used only for counting instructions for generating traces
VOID doInstrCountGlobal()
{
if(DoTrace)
++gInstrCount;
}
// used only for counting instructions for generating traces
VOID Instruction(INS ins, VOID *v)
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)doInstrCountGlobal, IARG_END);
}
void dummyRecorder(uptr a, u32 b){}
VOID dummyInstrCounter(ADDRINT c){}
void SelectAnalysisEngine()
{
InstrCounter = doInstrCount;
switch( Engine )
{
case 1:
ReadRecorder = RecordReadEngine1;
WriteRecorder = RecordWriteEngine1;
break;
case 2:
ReadRecorder = RecordReadEngine2;
WriteRecorder = RecordWriteEngine2;
break;
case 3:
ReadRecorder = RecordReadEngine3;
WriteRecorder = RecordWriteEngine3;
break;
default:
ECHO("Specify a valid Engine number to be used");
Die();
break;
}
ECHO("Selected Engine number " << Engine);
D2ECHO( ADDR((void*)RecordReadEngine1) << " and " << ADDR((void*)RecordWriteEngine1) );
D2ECHO( ADDR((void*)RecordReadEngine2) << " and " << ADDR((void*)RecordWriteEngine2) );
D2ECHO( ADDR((void*)RecordReadEngine3) << " and " << ADDR((void*)RecordWriteEngine3) );
}
void SelectDummyAnalysisEngine()
{
ReadRecorder = dummyRecorder;
WriteRecorder = dummyRecorder;
InstrCounter = dummyInstrCounter;
ECHO("Selected Engine dummy");
D2ECHO( ADDR((void*)dummyRecorder) );
}
/* ===================================================================== */
// Instrumentation callbacks
/* ===================================================================== */
/*
* This filter is used for functions which can be pushed on the call stack.
* This means that the functions in the filter will not be visible on
* the output profile.
*/
BOOL ValidFtnName(string name)
{
return
!(
name.c_str()[0]=='_' ||
name.c_str()[0]=='?' ||
!name.compare("atexit") ||
(name.find("std::") != string::npos) ||
// (name.find("::operator") != string::npos) ||
#ifdef WIN32
!name.compare("GetPdbDll") ||
!name.compare("DebuggerRuntime") ||
!name.compare("failwithmessage") ||
!name.compare("pre_c_init") ||
!name.compare("pre_cpp_init") ||
!name.compare("mainCRTStartup") ||
!name.compare("NtCurrentTeb") ||
!name.compare("check_managed_app") ||
!name.compare("DebuggerKnownHandle") ||
!name.compare("DebuggerProbe") ||
!name.compare("failwithmessage") ||
!name.compare("unnamedImageEntryPoint")
#else
!name.compare(".plt") ||
!name.compare(".gnu.version") ||
!name.compare("_start") ||
!name.compare("_init") ||
!name.compare("_fini") ||
!name.compare("__do_global_dtors_aux") ||
!name.compare("__libc_csu_init") ||
!name.compare("__gmon_start__") ||
!name.compare("__libc_csu_fini") ||
!name.compare("call_gmon_start") ||
!name.compare("register_tm_clones") ||
!name.compare("deregister_tm_clones") ||
!name.compare("frame_dummy")
#endif
);
}
/*
* This is the filter used to filter function calls only. The main difference with
* the above filter is that the calls to std::<> routines and calls to .plt
* should also not be filtered so that the last call-site is properly recorded
*/
BOOL ValidFtnCallName(string name)
{
return
!(
name.c_str()[0]=='_' ||
name.c_str()[0]=='?' ||
!name.compare("atexit") ||
#ifdef WIN32
!name.compare("GetPdbDll") ||
!name.compare("DebuggerRuntime") ||
!name.compare("failwithmessage") ||
!name.compare("pre_c_init") ||
!name.compare("pre_cpp_init") ||
!name.compare("mainCRTStartup") ||
!name.compare("NtCurrentTeb") ||
!name.compare("check_managed_app") ||
!name.compare("DebuggerKnownHandle") ||
!name.compare("DebuggerProbe") ||
!name.compare("failwithmessage") ||
!name.compare("unnamedImageEntryPoint")
#else
!name.compare(".gnu.version") ||
!name.compare("_start") ||
!name.compare("_init") ||
!name.compare("_fini") ||
!name.compare("__do_global_dtors_aux") ||
!name.compare("__libc_csu_init") ||
!name.compare("__gmon_start__") ||
!name.compare("__libc_csu_fini") ||
!name.compare("call_gmon_start") ||
!name.compare("register_tm_clones") ||
!name.compare("deregister_tm_clones") ||
!name.compare("frame_dummy")
#endif
);
}
// These are some global variables set by memory allocation functions
IDNoType currID;
u32 lastCallLocIndex=0;
u32 currSize;
uptr currStartAddress;
VOID RoutineEntryRecorder1(ADDRINT irname)
{
const char* rname = reinterpret_cast<const char *>(irname);
D1ECHO ("RoutineEntryRecorder1 : " << rname );
string calleeName(rname);
IDNoType calleeID=0;
if( !symTable.IsSeenFunctionName(calleeName) )
{
calleeID = GetNewID();
symTable.InsertFunction(calleeName, calleeID, lastCallLocIndex);
}
calleeID = FuncName2ID[calleeName];
// following is to store recursive functions
IDNoType callerID = CallStack.Top();
string callerName = symTable.GetSymName(callerID);
if(callerName != calleeName) // Non recursive function
{
CallStack.Push(calleeID);
CallSiteStack.Push(lastCallLocIndex);
}
else
{
recursiveFunctions.insert(calleeName);
}
// call count should be updated even for recursive functions
callCounts[calleeID] += 1;
callgraph.UpdateCall(calleeID, rInstrCount);
D2ECHO ("Entered Routine1 : " << calleeName << " with ID " << calleeID << " and rInstrCount " << rInstrCount);
rInstrCount=0;
#if (DEBUG>0)
CallStack.Print();
//CallSiteStack.Print();
#endif
// In engine 3, to save time, the curr call is selected only at
// func entry/exit, so that it does not need to be determined on each access
if ( Engine == 3)
{
D1ECHO ("Setting Current Call for : " << rname );
SetCurrCallOnEntry();
}
D1ECHO ("RoutineEntryRecorder1 : " << calleeName << " Done" );
}
// This recorder is used when tasks are tracked. The main differences are :
// new id is generated for each new call site
// and the way these are named (required for mcpar)
VOID RoutineEntryRecorder2(ADDRINT irname)
{
const char* rname = reinterpret_cast<const char *>(irname);
string calleeName(rname);
D1ECHO ("RoutineEntryRecorder2 : " << calleeName );
IDNoType callerID = CallStack.Top();
string callerName = symTable.GetSymName(callerID);
IDNoType tempID=0;
string callerNameSimple(callerName);
RemoveNoFromNameEnd(callerNameSimple, tempID); // remove previous id
RemoveNoFromNameEnd(callerNameSimple, tempID); // remove previous lastCallLocIndex
IDNoType calleeID=0;
D2ECHO( callerNameSimple << " -> " << calleeName);
if( callerNameSimple != calleeName ) // Non recursive case
{
// for each callsite a unique id is generated
// this will result in the generation of unique name
if( !GetAvailableORNewID(calleeID, lastCallLocIndex) ) // returns false if id is new
{
AddNoToNameEnd(calleeName, lastCallLocIndex);
AddNoToNameEnd(calleeName, calleeID);
symTable.InsertFunction(calleeName, calleeID, lastCallLocIndex);
// for taskgraph output
tgout << callerName << " FUNC " << calleeName << "\n";
}
D1ECHO ("Using ID " << calleeID);
CallStack.Push(calleeID);
CallSiteStack.Push(lastCallLocIndex);
D1ECHO ("Entered Routine2 : " << calleeName << " with ID " << calleeID);
callCounts[calleeID] += 1;
callgraph.UpdateCall(calleeID, rInstrCount);
rInstrCount=0;
}
else // recursive case
{
// call count should be updated even for recursive functions
// in this case same callerID should be used
callCounts[callerID] += 1;
callgraph.UpdateCall(callerID, rInstrCount);
rInstrCount=0;
}
#if (DEBUG>0)
CallStack.Print();
//CallSiteStack.Print();
#endif
// TODO test with updated logic later
// In engine 3, to save time, the curr call is selected only at
// func entry/exit, so that it does not need to be determined on each access
if ( Engine == 3)
{
D1ECHO ("Setting Current Call for : " << calleeName );
SetCurrCallOnEntry();
}
D1ECHO ("RoutineEntryRecorder2 : " << calleeName << " Done" );
}
VOID RoutineExitRecorder1(VOID *ip)
{
string rtnName = RTN_FindNameByAddress((ADDRINT)ip);
string rname = PIN_UndecorateSymbolName(rtnName, UNDECORATION_NAME_ONLY);
D1ECHO ("RoutineExitRecorder1 : " << rname );
// check first if map has entry for this ftn
if ( symTable.IsSeenFunctionName(rname) )
{
IDNoType lastCallID = CallStack.Top();
// check if the top ftn is the current one
if ( lastCallID == FuncName2ID[rname] )
{
D1ECHO("Leaving Routine : " << rname << " id : " << FuncName2ID[rname]);
D1ECHO("Will pop : " << symTable.GetSymName( lastCallID ) << " id : " << lastCallID );
CallStack.Pop();
CallSiteStack.Pop();
D1ECHO ("Exited Routine1 : " << rname << " rInstrCount = " << rInstrCount);
#if (DEBUG>0)
CallStack.Print();
//CallSiteStack.Print();
#endif
// In engine 3, to save time, the curr call is selected only at func entry/exit,
// so that it does not need to be determined on each access
if ( Engine == 3)
{
D1ECHO("Setting Current Call for : " << rname );
SetCurrCallOnExit(lastCallID);
}
}
// call count should be updated even for recursive functions
callgraph.UpdateReturn( lastCallID, rInstrCount );
rInstrCount = 0;
}
// un-comment the following to enable printing running count of instructions executed so far
//ECHO("Instructions executed so far : " << rInstrCount );
D1ECHO ("RoutineExitRecorder1 : " << rname << " Done");
}
// Used when tracking tasks
VOID RoutineExitRecorder2(VOID *ip)
{
string rtnName = RTN_FindNameByAddress((ADDRINT)ip);
string rname = PIN_UndecorateSymbolName(rtnName, UNDECORATION_NAME_ONLY);
D1ECHO ("RoutineExitRecorder2 : " << rname );
if( ValidFtnName(rname) )
{
string calleeName(rname); // name of routine which currently wants to exit
IDNoType tempID=0;
IDNoType topRtnID = CallStack.Top();
string topRtnName = symTable.GetSymName( topRtnID );
RemoveNoFromNameEnd(topRtnName, tempID); // remove previous id
RemoveNoFromNameEnd(topRtnName, tempID); // remove previous lastCallLocIndex
if ( calleeName == topRtnName ) // check if current == actual
{
CallStack.Pop();
CallSiteStack.Pop();
D1ECHO ("Exited2 Routine : " << rname << " rInstrCount = " << rInstrCount);
// TODO test it later with updated logic
// In engine 3, to save time, the curr call is selected only at func entry/exit,
// so that it does not need to be determined on each access
if ( Engine == 3 )
{
D1ECHO("Setting Current Call for : " << rname );
SetCurrCallOnExit(topRtnID);
}
}
// call count should be updated even for recursive functions
callgraph.UpdateReturn( topRtnID, rInstrCount );
rInstrCount = 0;
}
#if (DEBUG>0)
CallStack.Print();
//CallSiteStack.Print();
#endif
// un-comment the following to enable printing running count of instructions executed so far
//ECHO("Instructions executed so far : " << rInstrCount );
D1ECHO ("RoutineExitRecorder2 : " << rname << " Done");
}
VOID RecordZoneEntry(INT32 zoneNo)
{
IDNoType callerID = CallStack.Top();
string callerName = symTable.GetSymName(callerID);
D1ECHO("RecordZoneEntry : " << callerName);
// for each callsite a unique id is generated
// this will result in the generation of unique name
IDNoType calleeID=0;
string calleeName(callerName);
bool isNewID = !GetAvailableORNewID(calleeID, lastCallLocIndex); // returns false if id is new
if( isNewID )
{
D2ECHO(" Using new id " << calleeID << " for : " << calleeName);
if(TrackTasks || TrackLoopDepend)
{
IDNoType tempCalleeID=0;
IDNoType tempLastCallLocIndex=0;
RemoveNoFromNameEnd(calleeName, tempCalleeID); // remove previous id if there
RemoveNoFromNameEnd(calleeName, tempLastCallLocIndex); // remove previous lastCallLocIndex if there
AddNoToNameEnd(calleeName, lastCallLocIndex); // attach new lastCallLocIndex
AddNoToNameEnd(calleeName, calleeID); // attach new id
// for taskgraph output
tgout << callerName << " LOOP " << calleeName << "\n";
}
else
{
calleeName += "_Zone" + to_string(zoneNo);
}
symTable.InsertFunction(calleeName, calleeID, lastCallLocIndex);
}
CallStack.Push(calleeID);
CallSiteStack.Push(lastCallLocIndex);
D1ECHO("Entered zone : " << calleeName << " with ID " << calleeID);
callCounts[calleeID] += 1;
callgraph.UpdateCall(calleeID, rInstrCount);
rInstrCount=0;
#if (DEBUG>0)
CallStack.Print();
//CallSiteStack.Print();
#endif
// TODO test with updated logic later
// In engine 3, to save time, the curr call is selected only at
// func entry/exit, so that it does not need to be determined on each access
if ( Engine == 3 )
{
D1ECHO ("Setting Current Call for : " << calleeName );
SetCurrCallOnEntry();
}
D1ECHO ("RecordZoneEntry : " << calleeName << " Done");
}
VOID RecordZoneExit(INT32 zoneNo)
{
IDNoType lastCallID = CallStack.Top();
string zoneName = symTable.GetSymName(lastCallID);
D1ECHO ("RecordZoneExit : " << zoneName );
// check first if map has entry for this zone
if( symTable.IsSeenFunctionName(zoneName) )
{
// check if the top ftn is the current one
if ( lastCallID == FuncName2ID[zoneName] )
{
D1ECHO("Leaving Zone : " << zoneName << " id : " << FuncName2ID[zoneName] );
D1ECHO("Will pop : " << symTable.GetSymName( lastCallID ) << " id : " << lastCallID );
CallStack.Pop();
CallSiteStack.Pop();
D1ECHO("Exited zone : " << zoneName << " with ID " << lastCallID << " rInstrCount = " << rInstrCount);
callgraph.UpdateReturn( lastCallID, rInstrCount );
rInstrCount = 0;
#if (DEBUG>0)
CallStack.Print();
//CallSiteStack.Print();
#endif
// In engine 3, to save time, the curr call is selected only at func entry/exit,
// so that it does not need to be determined on each access
if ( Engine == 3 )
{
D1ECHO("Setting Current Call for : " << zoneName );
SetCurrCallOnExit(lastCallID);
}
}
}
D1ECHO ("RecordZoneExit : " << zoneName << " Done");
}
VOID SetCallSite(u32 locIndex)
{
D2ECHO("setting last callsite to : " << Locations.GetLocation(locIndex).toString() << " locIndex : " << locIndex);
lastCallLocIndex=locIndex;
}
VOID MallocBefore(u32 size)
{
D1ECHO("setting malloc size " << size );
currSize = size;
}
VOID AllocaBefore(u32 size)
{
D1ECHO("setting alloca size " << size );
currSize = size;
}
VOID CallocBefore(u32 n, u32 size)
{
D2ECHO("setting calloc size " << size );
currSize = n*size;
}
// This is used for malloc, calloc and alloca
VOID MallocCallocAllocaAfter(uptr addr)
{
D2ECHO("setting malloc/calloc/alloca start address " << ADDR(addr) << " and size " << currSize);
currStartAddress = addr;
symTable.InsertMallocCalloc(currStartAddress, lastCallLocIndex, currSize);
}
// TODO can reallocation decrease size?
VOID ReallocBefore(uptr addr, u32 size)
{
D2ECHO("reallocation at address : " << ADDR(addr) );
currStartAddress = addr;
D2ECHO("setting realloc size " << size );
currSize = size;
}
VOID ReallocAfter(uptr addr)
{
D2ECHO("Setting Realloc address " << ADDR(addr) );
uptr prevAddr = currStartAddress;
if(prevAddr == 0) //realloc behaves like malloc, supplied null address as argument
{
currStartAddress = addr;
symTable.InsertMallocCalloc(currStartAddress, lastCallLocIndex, currSize);
}
else
{
currID = GetObjectID(prevAddr);
// check if relocation has moved the object to a different address
if( addr != prevAddr )
{
D2ECHO("reallocation moved the object");
D2ECHO("setting realloc start address " << ADDR(addr) );
currStartAddress = addr;
}
symTable.UpdateRealloc(currID, prevAddr, addr, lastCallLocIndex, currSize);
}
}
VOID FreeBefore(ADDRINT addr)
{
D2ECHO("removing object with start address " << ADDR(addr) );
symTable.Remove(addr);
}
VOID StrdupBefore(uptr addr)
{
D2ECHO("setting strdup start address " << ADDR(addr) );
currStartAddress = addr;
}
VOID StrdupAfter(uptr dstAddr)
{
D2ECHO("setting strdup destination address " << ADDR(dstAddr) );
uptr srcAddr = currStartAddress;
currStartAddress = dstAddr;
u32 currSize = symTable.GetSymSize(srcAddr);
D2ECHO("strdup size: " << currSize);
symTable.InsertMallocCalloc(currStartAddress, lastCallLocIndex, currSize);
}
vector<string> InterestingLibNames;
void UpdateLibrariesOfInterestList(int argc, char **argv)
{
// parse the command line arguments for the binary name
for (int i=1; i<argc-1; i++)
{
if (!strcmp(argv[i],"--"))
{
string mainImgName( argv[i+1] );
string imgname;
GetFileName(mainImgName, imgname);
D2ECHO("Main Image Name = "<< mainImgName);
D2ECHO("Simple Image Name = "<< imgname);
InterestingLibNames.push_back(imgname);
break;
}
}
if( KnobMainExecutableOnly.Value() == false )
{
string ilfname = "interestingLibraryNames.dat";
ifstream ilfin;
OpenInFile(ilfname, ilfin);
string line;
u32 i=0;
while( getline(ilfin, line) ) // while there are function names in file
{
//the following line trims white space from the beginning of the string
line.erase(line.begin(), find_if(line.begin(), line.end(), not1(ptr_fun<int, int>(isspace))));
// ignore empty lines and lines starting with #
if (line.length() == 0 || line[0] == '#')
continue;
InterestingLibNames.push_back(line);
i++;
}
ilfin.close();
if(i==0)
{
ECHO("No library of insert found in " << ilfname );
}
}
for(auto &n : InterestingLibNames)
{
ECHO("Intersting library names : " << n);
}
}
bool IsLibOfInterest(string imgName)
{
bool isInteresting = false;
for(auto &n : InterestingLibNames)
{
if( imgName.find(n) != string::npos )
{
isInteresting = true;
break;
}
}
return isInteresting;
}
// IMG instrumentation routine - called once per image upon image load
VOID InstrumentImages(IMG img, VOID * v)
{
string imgname = IMG_Name(img);
bool isLibC = imgname.find("/libc") != string::npos;
// We should instrument malloc/free only when tracking objects !
// We should also track them when tracking tasks to report
// allocation dependencies.
if ( (TrackObjects || TrackTasks) && isLibC )
// if ( (TrackObjects || (TrackTasks && !TrackLoopDepend) ) && isLibC )
{
// instrument libc for malloc, free etc
ECHO("Instrumenting "<<imgname<<" for (re)(c)(m)alloc/free routines etc ");
RTN mallocRtn = RTN_FindByName(img, MALLOC.c_str() );
if (RTN_Valid(mallocRtn))
{
RTN_Open(mallocRtn);
D1ECHO("Instrumenting malloc");
// Instrument malloc() to print the input argument value and the return value.
RTN_InsertCall(mallocRtn, IPOINT_BEFORE, (AFUNPTR)MallocBefore,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_END);
RTN_InsertCall(mallocRtn, IPOINT_AFTER, (AFUNPTR)MallocCallocAllocaAfter,
IARG_FUNCRET_EXITPOINT_VALUE, IARG_END);
RTN_Close(mallocRtn);
}
RTN allocaRtn = RTN_FindByName(img, ALLOCA.c_str() );
if (RTN_Valid(allocaRtn))
{
RTN_Open(allocaRtn);
D1ECHO("Instrumenting alloca");
// Instrument malloc() to print the input argument value and the return value.
RTN_InsertCall(allocaRtn, IPOINT_BEFORE, (AFUNPTR)AllocaBefore,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_END);
RTN_InsertCall(allocaRtn, IPOINT_AFTER, (AFUNPTR)MallocCallocAllocaAfter,
IARG_FUNCRET_EXITPOINT_VALUE, IARG_END);
RTN_Close(allocaRtn);
}
RTN callocRtn = RTN_FindByName(img, CALLOC.c_str() );
if (RTN_Valid(callocRtn))
{
RTN_Open(callocRtn);
D1ECHO("Instrumenting calloc");
// Instrument calloc() to print the input argument value and the return value.
RTN_InsertCall(callocRtn, IPOINT_BEFORE, (AFUNPTR)CallocBefore,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_FUNCARG_ENTRYPOINT_VALUE, 1,
IARG_END);
// for now using same callback ftns as for malloc
RTN_InsertCall(callocRtn, IPOINT_AFTER, (AFUNPTR)MallocCallocAllocaAfter,
IARG_FUNCRET_EXITPOINT_VALUE, IARG_END);
RTN_Close(callocRtn);
}
RTN reallocRtn = RTN_FindByName(img, REALLOC.c_str() );
if (RTN_Valid(reallocRtn))
{
RTN_Open(reallocRtn);
D1ECHO("Instrumenting realloc");
// Instrument calloc() to print the input argument value and the return value.
// for now using same callback ftns as for malloc
RTN_InsertCall(reallocRtn, IPOINT_BEFORE, (AFUNPTR)ReallocBefore,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_FUNCARG_ENTRYPOINT_VALUE, 1,
IARG_END);
RTN_InsertCall(reallocRtn, IPOINT_AFTER, (AFUNPTR)ReallocAfter,
IARG_FUNCRET_EXITPOINT_VALUE, IARG_END);
RTN_Close(reallocRtn);
}
// Find the free() function.
RTN freeRtn = RTN_FindByName(img, FREE.c_str() );
if (RTN_Valid(freeRtn))
{
RTN_Open(freeRtn);
D1ECHO("Instrumenting free");
// Instrument free() to print the input argument value.
RTN_InsertCall(freeRtn, IPOINT_BEFORE, (AFUNPTR)FreeBefore,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_END);
RTN_Close(freeRtn);
}
// Find the strdup() function.
RTN strdupRtn = RTN_FindByName(img, STRDUP.c_str() );
if (RTN_Valid(strdupRtn))
{
RTN_Open(strdupRtn);
D1ECHO("Instrumenting strdup");
// Instrument strdup() to print the input argument value and the return value.
RTN_InsertCall(strdupRtn, IPOINT_BEFORE, (AFUNPTR)StrdupBefore,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_END);
RTN_InsertCall(strdupRtn, IPOINT_AFTER, (AFUNPTR)StrdupAfter,
IARG_FUNCRET_EXITPOINT_VALUE, IARG_END);
RTN_Close(strdupRtn);
}
}
// For simplicity, do rest of instrumentation only for images of interest
if ( !IsLibOfInterest(imgname) )
{
ECHO("Skipping Image "<< imgname<< " for function calls instrumentation as it is not image of interest");
return;
}
else
{
ECHO("Instrumenting "<<imgname<<" for function calls as it is image of interest");
}
// Traverse the sections of the image.
for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec))
{
// For each section, process all RTNs.
for (RTN rtn = SEC_RtnHead(sec); RTN_Valid(rtn); rtn = RTN_Next(rtn))
{
// Many RTN APIs require that the RTN be opened first.
RTN_Open(rtn);
// Traverse all instructions
for (INS ins = RTN_InsHead(rtn); INS_Valid(ins); ins = INS_Next(ins))
{
D2ECHO("disassembeled ins = " << INS_Disassemble(ins) );
if( INS_IsDirectCall(ins) ) //INS_IsDirectBranchOrCall OR INS_IsCall(ins)
{
ADDRINT target = INS_DirectBranchOrCallTargetAddress(ins);
string tname1 = Target2RtnName(target);
string tname = PIN_UndecorateSymbolName( tname1, UNDECORATION_NAME_ONLY);
u32 locIndex =-1;
string fileName(""); // This will hold the source file name.
INT32 line = 0; // This will hold the line number within the file
PIN_GetSourceLocation(INS_Address(ins), NULL, &line, &fileName);
// Remove the complete path of the filename
if(fileName == "") fileName = "NA";
else RemoveCurrDirFromName(fileName);
// create a temp Location loc, may be inserted in list of locations later
Location loc(line, fileName);
D2ECHO(" Routine Call found for " << tname << " at " << fileName <<":"<< line);
bool inStdHeaders = ( fileName.find("/usr/include") != string::npos );
if( (!inStdHeaders) && ( ValidFtnCallName(tname) ) )
{
bool found = Locations.GetLocIndexIfAvailable(loc, locIndex);
if( !found )
{
D2ECHO("Location " << loc.toString() << " not found, Inserting");
locIndex = Locations.Insert(loc);
}