-
Notifications
You must be signed in to change notification settings - Fork 19
/
addrtrace.cpp
1916 lines (1736 loc) · 62.4 KB
/
addrtrace.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
/************************************************************************
* Copyright (C) 2017-2018 IAIK TU Graz and Fraunhofer AISEC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
***********************************************************************/
/**
* @file addrtrace.cpp
* @brief DATA tracing tool for Pin.
* @license This project is released under the GNU GPLv3+ License.
* @author See AUTHORS file.
* @version 0.3
*/
/***********************************************************************/
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <map>
#include <set>
#include <sys/types.h>
#include <unistd.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <getopt.h>
#include "pin.H"
/**
* Pin 3.11 Documentation:
* https://software.intel.com/sites/landingpage/pintool/docs/97998/Pin/html
*/
// Pin above 3.7.97720 deprecates some functions
#if (PIN_PRODUCT_VERSION_MAJOR > 3) || \
(PIN_PRODUCT_VERSION_MAJOR == 3 && PIN_PRODUCT_VERSION_MINOR > 7) || \
(PIN_PRODUCT_VERSION_MAJOR == 3 && PIN_PRODUCT_VERSION_MINOR == 7 && PIN_BUILD_NUMBER > 97720)
#define INS_IS_INDIRECT INS_IsIndirectControlFlow
#define INS_HAS_TAKEN_BRANCH INS_IsValidForIpointTakenBranch
#define INS_HAS_IPOINT_AFTER INS_IsValidForIpointAfter
#else
#define INS_IS_INDIRECT INS_IsIndirectBranchOrCall
#define INS_HAS_TAKEN_BRANCH INS_IsBranchOrCall
#define INS_HAS_IPOINT_AFTER INS_HasFallThrough
#endif
using namespace std;
/***********************************************************************/
VOID RecordFunctionEntry(THREADID threadid, ADDRINT bbl, ADDRINT bp, BOOL indirect, ADDRINT target, bool report_as_cfleak);
VOID RecordFunctionExit(THREADID threadid, ADDRINT bbl, ADDRINT bp, const CONTEXT* ctxt, bool report_as_cfleak);
/***********************************************************************/
KNOB<string> KnobRawFile(KNOB_MODE_WRITEONCE, "pintool",
"raw", "", "Raw output file.");
KNOB<bool> KnobFunc(KNOB_MODE_WRITEONCE, "pintool",
"func", "0", "Trace function calls and returns.");
KNOB<bool> KnobBbl(KNOB_MODE_WRITEONCE, "pintool",
"bbl", "0", "Trace basic blocks.");
KNOB<bool> KnobMem(KNOB_MODE_WRITEONCE, "pintool",
"mem", "0", "Trace data memory accesses.");
KNOB<bool> KnobTrackHeap(KNOB_MODE_WRITEONCE, "pintool",
"heap", "0", "Track heap usage (malloc, free).");
KNOB<string> KnobSyms(KNOB_MODE_WRITEONCE, "pintool",
"syms", "", "Output file for image information.");
KNOB<string> KnobVDSO(KNOB_MODE_WRITEONCE, "pintool",
"vdso", "vdso.so", "Output file for the vdso shared library.");
KNOB<bool> KnobLeaks(KNOB_MODE_WRITEONCE, "pintool",
"leaks", "0", "Enable fast recording of leaks, provided via leakin.");
KNOB<string> KnobLeakIn(KNOB_MODE_WRITEONCE, "pintool",
"leakin", "", "Binary input file containing all leaks to trace."
"If empty, all selected instructions are traced. "
"In any case specify -func, -bbl, -mem -heap accordingly!"
"This means that instructions in the -bin file are only traced,"
"if also the corresponding flag (e.g. -mem, -bbl) is set");
KNOB<string> KnobLeakOut(KNOB_MODE_WRITEONCE, "pintool",
"leakout", "", "Hierarchical output file of all leaks. Only useful with -bin option.");
KNOB<bool> KnobCallstack(KNOB_MODE_WRITEONCE, "pintool",
"cs", "0", "Take callstack into account and trace leaks only in the correct calling context. Only useful with -bin option.");
KNOB<string> KnobMain(KNOB_MODE_WRITEONCE, "pintool",
"main", "main", "Main method to start tracing. Defaults to 'main'. Provide ALL to trace from the beginning.");
KNOB<int> KnobDebug(KNOB_MODE_WRITEONCE, "pintool",
"debug", "0", "Enable debugging output.");
/***********************************************************************/
/** Recording */
/***********************************************************************/
// TODO: instrument strdup
#define MALLOC "malloc"
#define REALLOC "realloc"
#define CALLOC "calloc"
#define FREE "free"
#define DEBUG(x) if(KnobDebug.Value() >= x)
int alloc_instrumented = 0;
/* When using '-main ALL', ensures recording starts at function call */
bool WaitForFirstFunction = false;
bool Record = false;
bool use_callstack = false;
/**
* Traces are stored in a binary format, containing a sequence of
* entry_t entries.
*/
typedef struct __attribute__((packed))
{
uint8_t type; /* holds values of entry_type_t */
uint64_t ip; /* instruction pointer */
uint64_t data; /* additional data, depending on type */
}
entry_t;
/**
* Entry types.
*/
enum entry_type_t {
/* Dummy types */
A = 0,
B = 1,
C = 2,
D = 3,
MASK_NONE = 0,
/* Instructions doing memory reads/writes */
READ = MASK_NONE | A,
WRITE = MASK_NONE | B,
MASK_BRANCH = 4,
/* Branching instructions */
BRANCH = MASK_BRANCH | A,
FUNC_ENTRY = MASK_BRANCH | B,
FUNC_EXIT = MASK_BRANCH | C,
FUNC_BBL = MASK_BRANCH | D,
MASK_HEAP = 8,
/* Instructions doing memory reads/writes on heap objects */
HREAD = MASK_HEAP | READ,
HWRITE = MASK_HEAP | WRITE,
/* Heap alloc/free calls */
HALLOC = MASK_HEAP | C,
HFREE = MASK_HEAP | D,
MASK_LEAK = 16,
/* Dataleaks and Controlflow leaks, used for fast recording */
DLEAK = MASK_LEAK | A,
CFLEAK = MASK_LEAK | B,
};
std::vector<entry_t> trace; /* Contains all traced instructions */
ofstream imgfile; /* Holds memory layout with function symbols */
ofstream vdsofile; /* Holds vdso shared library */
/***********************************************************************/
/* Heap tracking */
typedef struct {
uint32_t id;
size_t size;
uint64_t base;
bool used;
} memobj_t;
uint32_t nextheapid = 1;
memobj_t* heapcache;
typedef std::vector<memobj_t> HEAPVEC;
HEAPVEC heap;
/***********************************************************************/
/* Multithreading */
/* Global lock to protect trace buffer */
//PIN_MUTEX lock;
typedef struct {
ADDRINT size;
} alloc_state_t;
typedef struct {
ADDRINT old;
ADDRINT size;
} realloc_state_t;
typedef struct {
/* allocation routines sometimes call themselves in a nested way during initialization */
std::vector<alloc_state_t> malloc_state;
std::vector<alloc_state_t> calloc_state;
std::vector<realloc_state_t> realloc_state;
ADDRINT RetIP;
int newbbl;
} thread_state_t;
std::vector<thread_state_t> thread_state;
/***********************************************************************
* FAST RECORDING
*
* In contrast to normal recording, fast recording only traces those
* instructions which were identified as leaks. The leaks to trace are
* provided via a binary file via -leakin. This file can be created via
* analyze.py --leakout.
*
* The -leakin binary format is as follows:
* 1B 8B 1B len * 8B
* [Type] [ip] [len] [val1, val2, ...]
*
* Type is one of FUNC_ENTRY, FUNC_EXIT, DLEAK, CFLEAK. Each type is
* followed by the instruction and the length of subsequent optional
* values.
*
* FUNC_ENTRY ip-caller 1 ip-callee
* FUNC_EXIT 0 0
* DLEAK ip 0
* CFLEAK ip n mergepoint 1 ... mergepoint n
*
* Fast recording results are exported to the file, specified via
* pintool argument -leakout. The binary format is as follows:
*
* DLEAK (1B) IP (8B) len [evidence] (len*8B)
* CFEAK (1B) IP (8B) len [evidence] (len*8B)
* FUNC_ENTRY (1B) IP-Caller (8B) IP-Callee (8B)
* FUNC_EXIT (1B)
*
* FUNC_ENTRY and FUNC_EXIT are only written if flag '-cs' is provided.
***********************************************************************/
/***********************************************************************/
/** Leaks, CallStack, Contexts */
/***********************************************************************/
/**
* Collect evidence for a specific data leak
*/
class DataLeak {
private:
std::vector<uint64_t> data; /* Holds evidences */
uint64_t ip; /* The leaking instruction */
public:
DataLeak(uint64_t ip = 0) : ip(ip) {
}
/**
* Add evidence
* @param d The evidence to add
*/
void append(uint64_t d) {
ASSERT(ip, "[pintool] Error: IP not set");
DEBUG(1) printf("[pintool] DLEAK@%" PRIx64 ": %" PRIx64 " appended\n", ip, d);
data.push_back(d);
}
void print() {
for (std::vector<uint64_t>::iterator it = data.begin(); it != data.end(); it++) {
printf(" %" PRIx64 " ", *it);
}
printf("\n");
}
/**
* Export evidence to binary format
* @param f The file to export to
*/
void doexport(FILE* f) {
uint8_t type = DLEAK;
uint64_t len = data.size();
uint8_t res = 0;
res += fwrite(&type, sizeof(type), 1, f) != 1;
res += fwrite(&ip, sizeof(ip), 1, f) != 1;
res += fwrite(&len, sizeof(len), 1, f) != 1;
res += fwrite(&data[0], sizeof(uint64_t), len, f) != len;
ASSERT(!res, "[pintool] Error: Unable to write file");
}
};
/**
* Collect evidence for a specific control-flow leak
*/
class CFLeak {
private:
std::vector<uint64_t> targets; /* Holds evidences */
std::vector<uint64_t> mergepoints; /* unused */
uint64_t bp; /* The leaking instruction */
public:
CFLeak(uint64_t bp = 0) : bp(bp) {
}
/**
* Add evidence
* @param ip The evidence to add
*/
void append(uint64_t ip) {
ASSERT(bp, "[pintool] Error: BP not set");
DEBUG(1) printf("[pintool] CFLEAK@%" PRIx64 ": %" PRIx64 " appended\n", bp, ip);
targets.push_back(ip);
}
void print() {
for (std::vector<uint64_t>::iterator it = targets.begin(); it != targets.end(); it++) {
printf(" %" PRIx64 " ", *it);
}
printf("\n");
}
/**
* Export evidence to binary format
* @param f The file to export to
*/
void doexport(FILE* f) {
uint8_t type = CFLEAK;
uint64_t len = targets.size();
uint8_t res = 0;
res += fwrite(&type, sizeof(type), 1, f) != 1;
res += fwrite(&bp, sizeof(bp), 1, f) != 1;
res += fwrite(&len, sizeof(len), 1, f) != 1;
res += fwrite(&targets[0], sizeof(uint64_t), len, f) != len;
ASSERT(!res, "[pintool] Error: Unable to write file");
}
};
typedef std::map<uint64_t, DataLeak> dleaks_t;
typedef std::map<uint64_t, CFLeak> cfleaks_t;
/**
* Holds a single context of the call hierarchy,
* holding leaks which shall be recorded at precisely this context.
*/
class Context {
private:
dleaks_t dleaks;
cfleaks_t cfleaks;
public:
Context() {
}
/**
* Add a new dataleak to trace during execution
* @param ip The instruction to trace
*/
virtual void dleak_create(uint64_t ip) {
if (dleaks.find(ip) == dleaks.end()) {
dleaks.insert(std::pair<uint64_t, DataLeak>(ip, DataLeak(ip)));
} else {
DEBUG(1) printf("[pintool] Warning: DLEAK: %" PRIx64 " not created\n", ip);
}
}
/**
* Add a new cfleak to trace during execution
* @param ip The instruction to trace (branch point)
* @param mp The merge point (unused)
* @param len The length of the branch (branch point-> merge point) (unused)
*/
virtual void cfleak_create(uint64_t ip, uint64_t* mp, uint8_t len) {
if (cfleaks.find(ip) == cfleaks.end()) {
cfleaks.insert(std::pair<uint64_t, CFLeak>(ip, CFLeak(ip)));
} else {
DEBUG(1) printf("[pintool] Warning: CFLEAK: %" PRIx64 " not created\n", ip);
}
}
/**
* Record evidence for a data leak
* @param ip The leaking instruction
* @param data The accessed memory (the evidence).
* We do not (need to) distinguish between read and write here.
*/
virtual void dleak_append(uint64_t ip, uint64_t data) {
if (dleaks.find(ip) == dleaks.end()) {
DEBUG(1) printf("[pintool] Warning: DLEAK: %" PRIx64 " not appended\n", ip);
} else {
dleaks[ip].append(data);
}
}
/**
* Record evidence for a control-flow leak
* @param bbl The basic block which contains the cf-leak
* @param target The taken branch target (the evidence)
*/
virtual void cfleak_append(uint64_t bbl, uint64_t target) {
if (cfleaks.find(bbl) == cfleaks.end()) {
DEBUG(1) printf("[pintool] Warning: CFLEAK: %" PRIx64 " not appended\n", bbl);
} else {
cfleaks[bbl].append(target);
}
}
virtual void print() {
for (dleaks_t::iterator it = dleaks.begin(); it != dleaks.end(); it++) {
printf("[pintool] DLEAK %" PRIx64 ": ", it->first);
it->second.print();
}
for (cfleaks_t::iterator it = cfleaks.begin(); it != cfleaks.end(); it++) {
printf("[pintool] CFLEAK %" PRIx64 ": ", it->first);
it->second.print();
}
}
/**
* Export evidence to binary format
* @param f The file to export to
*/
virtual void doexport(FILE* f) {
for (dleaks_t::iterator it = dleaks.begin(); it != dleaks.end(); it++) {
it->second.doexport(f);
}
for (cfleaks_t::iterator it = cfleaks.begin(); it != cfleaks.end(); it++) {
it->second.doexport(f);
}
}
};
class CallContext;
class CallStack;
typedef std::map<uint64_t, CallContext*> children_t;
/**
* Wraps class Context for use in class CallStack
*/
class CallContext : public Context {
friend class CallStack;
private:
uint64_t caller;
uint64_t callee;
CallContext* parent;
children_t children;
int unknown_child_depth;
bool used;
public:
CallContext(uint64_t caller = 0, uint64_t callee = 0)
: Context(), caller(caller), callee(callee), parent(NULL), unknown_child_depth(0), used(false) {
}
virtual void dleak_append(uint64_t ip, uint64_t data) {
if (used == false || unknown_child_depth) {
DEBUG(1) printf("[pintool] Warning: DLEAK %" PRIx64 ": skipping due to %d %d\n", ip, used, unknown_child_depth);
} else {
Context::dleak_append(ip, data);
}
}
virtual void cfleak_append(uint64_t bbl, uint64_t target) {
if (used == false || unknown_child_depth) {
DEBUG(1) printf("[pintool] Warning: CFLEAK %" PRIx64 ": skipping due to %d %d\n", bbl, used, unknown_child_depth);
} else {
Context::cfleak_append(bbl, target);
}
}
virtual void print(Context* currentContext = NULL) {
if (this == currentContext) {
printf("*");
}
printf("%" PRIx64 "-->%" PRIx64 " (%d)(%d)\n", this->caller, this->callee, this->unknown_child_depth, this->used);
Context::print();
for (children_t::iterator it = children.begin(); it != children.end(); it++) {
it->second->print(currentContext);
}
printf("<\n");
}
/**
* Export evidence to binary format
* @param f The file to export to
*/
virtual void doexport(FILE* f) {
uint8_t type = FUNC_ENTRY;
uint8_t res = 0;
res += fwrite(&type, sizeof(type), 1, f) != 1;
res += fwrite(&caller, sizeof(caller), 1, f) != 1;
res += fwrite(&callee, sizeof(callee), 1, f) != 1;
ASSERT(!res, "[pintool] Error: Unable to write file");
Context::doexport(f);
for (children_t::iterator it = children.begin(); it != children.end(); it++) {
it->second->doexport(f);
}
type = FUNC_EXIT;
res = fwrite(&type, sizeof(type), 1, f) != 1;
ASSERT(!res, "[pintool] Error: Unable to write file");
}
};
/**
* Container for managing fast-recording
*/
class AbstractLeakContainer {
protected:
std::set<uint64_t> traced_dataleaks; /* List of data leaks which shall be instrumented */
std::set<uint64_t> traced_cfleaks; /* List of control-flow leaks which shall be instrumented */
std::set<uint64_t> erased_dataleaks; /* List of data leaks which are already instrumented */
std::set<uint64_t> erased_cfleaks; /* List of control-flow leaks which are already instrumented */
Context* currentContext;
public:
size_t get_uninstrumented_dleak_size() {
return traced_dataleaks.size();
}
size_t get_uninstrumented_cfleak_size() {
return traced_cfleaks.size();
}
/**
* Checks whether an instruction shall be instrumented and if yes,
* removes it from the list of uninstrumented instructions.
* @param ip The instruction to test
* @return a value != 0 if successful
*/
size_t get_erase_dleak(uint64_t ip) {
size_t er = traced_dataleaks.erase(ip);
if (er) {
erased_dataleaks.insert(ip);
}
return er;
}
/**
* Returns whether an instruction was previously
* instrumented and, thus, erased.
*/
bool was_erased_dleak(uint64_t ip) {
return erased_dataleaks.count(ip);
}
/**
* Checks whether an instruction shall be instrumented and if yes,
* removes it from the list of uninstrumented instructions.
* @param ip The instruction to test
* @return a value != 0 if successful
*/
size_t get_erase_cfleak(uint64_t ip) {
size_t er = traced_cfleaks.erase(ip);
if (er) {
erased_cfleaks.insert(ip);
}
return er;
}
/**
* Returns whether an instruction was previously
* instrumented and, thus, erased.
*/
bool was_erased_cfleak(uint64_t ip) {
return erased_cfleaks.count(ip);
}
void print_uninstrumented_leaks() {
if (traced_dataleaks.size() > 0) {
printf("[pintool] Uninstrumented DLEAKS:\n");
for (std::set<uint64_t>::iterator it = traced_dataleaks.begin(); it != traced_dataleaks.end(); it++) {
printf(" %" PRIx64 "\n", *it);
}
}
if (traced_cfleaks.size() > 0) {
printf("[pintool] Uninstrumented CFLEAKS:\n");
for (std::set<uint64_t>::iterator it = traced_cfleaks.begin(); it != traced_cfleaks.end(); it++) {
printf(" %" PRIx64 "\n", *it);
}
}
}
/**
* Can be used to build a call stack. Is called for every function
* call in the leakage file
* @param caller The caller
* @param callee The callee
*/
virtual void call_create(uint64_t caller, uint64_t callee) = 0;
/**
* Can be used to build a call stack. Is called for every function
* return in the leakage file
* @param ip The return instruction
*/
virtual void ret_create(uint64_t ip) = 0;
/**
* Can be used to traverse the call stack during recording.
* Is called for every function call during recording.
* @param caller The caller
* @param callee The callee
*/
virtual void call_consume(uint64_t caller, uint64_t callee) = 0;
/**
* Can be used to traverse the call stack during recording.
* Is called for every function return during recording.
* @param ip The return instruction
*/
virtual void ret_consume(uint64_t ip) = 0;
/**
* Add a new dataleak to trace during execution
* @param ip The instruction to trace
*/
virtual void dleak_create(uint64_t ip) {
ASSERT(currentContext, "[pintool] Error: Context not initialized");
traced_dataleaks.insert(ip);
currentContext->dleak_create(ip);
}
/**
* Add a new cfleak to trace during execution
* @param ip The instruction to trace (branch point)
* @param mp The merge point (unused)
* @param len The length of the branch (branch point-> merge point) (unused)
*/
virtual void cfleak_create(uint64_t bp, uint64_t* mp, uint8_t len) {
ASSERT(currentContext, "[pintool] Error: Context not initialized");
traced_cfleaks.insert(bp);
currentContext->cfleak_create(bp, mp, len);
}
/**
* Record evidence for a data leak
* @param ip The leaking instruction
* @param data The accessed memory (the evidence).
* We do not (need to) distinguish between read and write here.
*/
virtual void dleak_consume(uint64_t ip, uint64_t data) {
ASSERT(currentContext, "[pintool] Error: Context not initialized");
DEBUG(1) printf("[pintool] Consuming DLEAK %" PRIx64 "\n", ip);
currentContext->dleak_append(ip, data);
}
/**
* Record evidence for a control-flow leak
* @param bbl The basic block which contains the cf-leak
* @param target The taken branch target (the evidence)
*/
virtual void cfleak_consume(uint64_t bbl, uint64_t target) {
ASSERT(currentContext, "[pintool] Error: Context not initialized");
DEBUG(1) printf("[pintool] Consuming CFLEAK %" PRIx64 "\n", bbl);
currentContext->cfleak_append(bbl, target);
}
virtual void print_all() = 0;
/**
* Export evidence to binary format
* @param f The file to export to
*/
virtual void doexport(FILE* f) {
ASSERT(currentContext, "[pintool] Error: Context not initialized");
currentContext->doexport(f);
}
};
/**
* This class is used to report leaks.
* It does not keep track of the actual calling context.
* It is used to trace leaking instructions at any calling context.
*/
class Flat : public AbstractLeakContainer {
public:
Flat() {
currentContext = new Context();
}
virtual void call_create(uint64_t caller, uint64_t callee) {
}
virtual void ret_create(uint64_t ip) {
}
virtual void call_consume(uint64_t caller, uint64_t callee) {
}
virtual void ret_consume(uint64_t ip) {
}
virtual void print_all() {
currentContext->print();
}
};
/**
* This class is used to report leaks at certain instructions only.
* It keeps track of the call-stack. It is used to trace leaking
* instructions only in the calling context where the leakage
* occured.
*
* To initially build the callstack, sequentially traverse the leakage
* bin-file and use call_create and ret_consume as well as dleak_create
* and cfleak_create.
*
* During binary instrumentation, use call_consume and ret_consume to
* move to the current calling context. Then, use isdleaking and
* iscfleaking to determine whether the current instruction shall be
* traced or not.
*/
class CallStack : public AbstractLeakContainer {
protected:
/* Generate a hash of caller and callee by swapping callee's DWORDS and XORING both. */
uint64_t get_call_id(uint64_t caller, uint64_t callee) {
uint64_t id = caller;
uint32_t lower = callee & 0x00000000FFFFFFFFULL;
uint32_t upper = callee >> 32ULL;
id ^= upper | ((uint64_t)lower << 32ULL);
return id;
}
public:
CallStack() {
}
void call_create(uint64_t caller, uint64_t callee) {
ASSERT(use_callstack, "[pintool] Error: Wrong usage of callstack");
DEBUG(2) printf("[pintool] Building callstack %" PRIx64 " --> %" PRIx64 "\n", caller, callee);
uint64_t id = get_call_id(caller, callee);
if (currentContext == NULL) {
currentContext = new CallContext(caller, callee);
} else {
CallContext* top = static_cast<CallContext*>(currentContext);
if (top->children.find(id) == top->children.end()) {
CallContext* newcs = new CallContext(caller, callee);
newcs->used = true;
newcs->parent = top;
top->children[id] = newcs;
}
CallContext* move = top->children[id];
currentContext = top = move;
}
}
void call_consume(uint64_t caller, uint64_t callee) {
ASSERT(use_callstack, "[pintool] Error: Wrong usage of callstack");
ASSERT(currentContext, "[pintool] Error: Callstack is not initialized");
DEBUG(3) print_all();
DEBUG(2) printf("[pintool] Calling %" PRIx64 " --> %" PRIx64 "\n", caller, callee);
uint64_t id = get_call_id(caller, callee);
CallContext* top = static_cast<CallContext*>(currentContext);
if (!top->used) {
if (top->caller == caller && top->callee == callee) {
DEBUG(2) printf("[pintool] Entered first leaking callstack\n");
top->used = true;
}
} else {
if (top->unknown_child_depth || top->children.find(id) == top->children.end()) {
top->unknown_child_depth++;
} else {
CallContext* move = top->children[id];
currentContext = top = move;
}
}
DEBUG(3) print_all();
}
void ret_consume(uint64_t ip) {
ASSERT(use_callstack, "[pintool] Error: Wrong usage of callstack");
ASSERT(currentContext, "[pintool] Error: Callstack is not initialized");
DEBUG(2) printf("[pintool] Returning %" PRIx64 "\n", ip);
CallContext* top = static_cast<CallContext*>(currentContext);
if (top->unknown_child_depth) {
top->unknown_child_depth--;
} else {
if (top->parent) {
ASSERT(top->parent, "[pintool] Error: Callstack parent is empty");
currentContext = top = top->parent;
} else {
DEBUG(2) printf("[pintool] Warning: Ignoring return\n");
}
}
}
void ret_create(uint64_t ip) {
ret_consume(ip);
}
bool empty() {
ASSERT(use_callstack, "[pintool] Error: Wrong usage of callstack");
CallContext* top = static_cast<CallContext*>(currentContext);
return top == NULL || top->used == false;
}
CallContext* get_begin() {
ASSERT(use_callstack, "[pintool] Error: Wrong usage of callstack");
CallContext* c = static_cast<CallContext*>(currentContext);
while(c && c->parent) {
c = c->parent;
}
return c;
}
/**
* After loading leakage file, use this function to rewind to the
* initial context
*/
void rewind() {
ASSERT(use_callstack, "[pintool] Error: Wrong usage of callstack");
CallContext* top = get_begin();
ASSERT(top, "[pintool] Error: Leaks not initialized");
top->used = false;
currentContext = top;
}
void print_all() {
ASSERT(use_callstack, "[pintool] Error: Wrong usage of callstack");
CallContext* top = get_begin();
if (top) {
printf("[pintool] Callstack:\n");
top->print(currentContext);
}
}
};
AbstractLeakContainer* leaks = NULL;
/***********************************************************************/
/** Thread/Main recording and initialization */
/***********************************************************************/
void init() {
//ASSERT(PIN_MutexInit(&lock), "[pintool] Error: Mutex init failed");
}
/**
* Add an entry to the trace
* This function is not thread-safe. Lock first.
*/
VOID record_entry(entry_t entry)
{
trace.push_back(entry);
}
/**
* Start recording.
* @param threadid The thread
* @param ins The first recorded instruction
*/
VOID RecordMainBegin(THREADID threadid, ADDRINT ins) {
Record = true;
DEBUG(1) printf("[pintool] Start main() %lx\n", (long unsigned int)ins);
RecordFunctionEntry(threadid, 0, 0, false, ins, false);
}
/**
* Stop recording.
* @param threadid The thread
* @param ins The last recorded instruction
*/
VOID RecordMainEnd(THREADID threadid, ADDRINT ins) {
Record = false;
DEBUG(1) printf("[pintool] End main()\n");
RecordFunctionExit(threadid, ins, ins, NULL, false);
}
/**
* Track thread creation.
* Creates a separate recording context per thread.
* Note: currently all threads report to the same trace
* @param threadid The thread
* @param ctxt Unused
* @param flags Unused
* @param v Unused
*/
VOID ThreadStart(THREADID threadid, CONTEXT *ctxt, INT32 flags, VOID *v)
{
ASSERT(threadid == 0, "[pintool] Error: Multithreading detected but not supported!");
DEBUG(1) printf("[pintool] Thread begin %d\n",threadid);
//PIN_MutexLock(&lock);
if (thread_state.size() <= threadid) {
thread_state_t newstate;
newstate.RetIP = 0;
newstate.newbbl = 0;
thread_state.push_back(newstate);
} else {
thread_state[threadid].RetIP = 0;
thread_state[threadid].newbbl = 0;
}
ASSERT(thread_state.size() > threadid, "[pintool] Error: thread_state corrupted");
//PIN_MutexUnlock(&lock);
}
/**
* Track thread destruction.
* @param threadid The thread
* @param ctxt Unused
* @param code Unused
* @param v Unused
*/
VOID ThreadFini(THREADID threadid, const CONTEXT *ctxt, INT32 code, VOID *v)
{
//PIN_MutexLock(&lock);
DEBUG(1) printf("[pintool] Thread end %d code %d\n",threadid, code);
//PIN_MutexUnlock(&lock);
}
/***********************************************************************/
/** Heap recording */
/***********************************************************************/
void printheap() {
std::cout << "[pintool] Heap:" << std::endl;
for(HEAPVEC::iterator it = heap.begin(); it != heap.end(); ++it) {
std::cout << std::hex << it->id << ":" << it->base << "-" << it->size << " used:" << it->used << std::endl;
}
}
memobj_t* lookup_heap(uint64_t addr) {
uint64_t paddr = addr;
if (heapcache) {
ASSERT(heapcache->used, "[pintool] Error: Heapcache corrupt");
if (paddr >= heapcache->base && paddr < heapcache->base + heapcache->size) {
return heapcache;
}
}
for(HEAPVEC::reverse_iterator it = heap.rbegin(); it != heap.rend(); ++it) {
if (!it->used) {
continue;
}
if (paddr >= it->base) {
if (paddr < it->base + it->size) {
return heapcache = &(*it);
} else {
break;
}
}
}
return NULL;
}
VOID test_mem_heap(entry_t* pentry) {
memobj_t* obj = lookup_heap(pentry->data);
if (obj) {
uint64_t pdata = pentry->data;
pdata -= obj->base;
ASSERT((pdata & 0xFFFFFFFF00000000ULL) == 0, "[pintool] Error: Heap object too big");
pdata |= (uint64_t)obj->id << 32ULL;
pentry->data = pdata;
pentry->type |= MASK_HEAP;
}
}
/**
* Add alloc/free to the trace
* This function is not thread-safe. Lock first.
*/
void record_heap_op(memobj_t *obj, ADDRINT addr) {
entry_t entry;
entry.type = obj->used ? HALLOC : HFREE;
entry.ip = (((uint64_t)obj->id << 32ULL) | obj->size);
entry.data = addr;
record_entry(entry);
}
/**
* Handle calls to [m|re|c]alloc by keeping a list of all heap objects
* This function is not thread-safe. Lock first.
*/
void domalloc(ADDRINT addr, ADDRINT size, uint32_t objid) {
heapcache = NULL;
memobj_t obj;
if (objid) {
obj.id = objid;
} else {
obj.id = nextheapid++;
}
obj.base = addr;
obj.size = size;