-
Notifications
You must be signed in to change notification settings - Fork 9
/
gentrace.cpp
2766 lines (2145 loc) · 88.3 KB
/
gentrace.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "pin.H"
#include <cassert>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stack>
#include <vector>
#include <cstring>
#include <stdint.h>
#include <cstdlib>
#include <time.h>
//#include "pin_frame.h"
//#include "pin_trace.h"
#include "reg_mapping_pin.h"
//#include "cache.h"
/* The new trace container format */
#include <libtrace/trace.container.hpp>
#include "pivot.h"
#include "pin_taint.h"
#include "pin_misc.h"
//#define DEBUG
#ifdef DEBUG
#define dbg_printf(...) printf(__VA_ARGS__)
#else
#define dbg_printf(...)
#endif
/*
* A useful set of macros that we can customize for different
* architectures as simply as possible.
*/
#ifdef ARCH_64
#define BFD_ARCH frame_arch_i386
#define BFD_MACH frame_mach_x86_64
#define STACK_OFFSET 8
#define MAX_ADDRESS "0xffffffffffffffff"
#define MEM_ACCESS qword
#elif defined(ARCH_32)
#define BFD_ARCH frame_arch_i386
#define BFD_MACH frame_mach_i386_i386
#define STACK_OFFSET 4
#define MAX_ADDRESS "0xffffffff"
#define MEM_ACCESS dword
#endif
using namespace pintrace;
using namespace SerializedTrace;
const ADDRINT ehandler_fs_offset = 0;
const ADDRINT ehandler_nptr_offset = 0;
const ADDRINT ehandler_handler_offset = 4;
const ADDRINT ehandler_invalid_ptr = ~0x0;
const ADDRINT ehandler_size = 8;
/** The offset esp has from when the exception is initially handled to
when the handler is called. */
const ADDRINT ehandler_esp_offset = 0xe0;
const int maxSehLength = 10;
#ifdef _WIN32
const char* const windowsDll = "kernel32.dll";
const char* const wsDll = "WS2_32.dll";
const int callbackNum = 5;
const unsigned int accessViolation = 0xc0000005;
namespace WINDOWS {
#include "Winsock2.h"
#include "Windows.h"
}
#endif
/* Environment variables on windows
*
* For a program that uses getenv, Windows does the following:
*
* 1. Call GetEnvironmentStringsW and set up an environment table.
* 2. If using main (rather than wmain), WideCharToMultiByte is used
* to convert to a multibyte environment table.
*
* WideCharToMultiByte is implemented using a conversion table; we
* don't handle control-flow taint, and thus we cannot really handle
* tainting of environment variables :-/
*/
/* Networking on windows
*
* Winsock appears to communicate with a windows subsystem using a
* lightweight procedure calling interface, e.g., something we don't
* want to parse. So, we catch sockets() by instrumenting the socket
* call itself.
*/
//
// CONFIGURATION
//
// Note: since we only flush the buffer once per basic block, the number
// of instructions per block should never exceed BUFFER_SIZE.
// TODO: See if there's some way to overcome this limitation, if
// necessary.
#define BUFFER_SIZE 10240
// Leave this much extra room in the frame buffer, for some unexpected
// frames.
#define FUDGE 5
// Add a keyframe every KEYFRAME_FREQ instructions.
#define KEYFRAME_FREQ 10240
// Use value caching.
#define USE_CACHING
// Use faster functions to append to the value buffer, where possible.
//#define USE_FASTPATH
#ifdef USE_FASTPATH
#define _FASTPATH true
#else
#define _FASTPATH false
#endif
/** Set to 1 to enable lock debug information */
#ifndef DEBUG_LOCK
#define DEBUG_LOCK 0
#endif
KNOB<string> KnobOut(KNOB_MODE_WRITEONCE, "pintool",
"o", "trace.frames",
"Trace file to output to.");
KNOB<int> KnobTrigAddr(KNOB_MODE_WRITEONCE, "pintool",
"trig_addr", "",
"Address of trigger point. No logging will occur until execution reaches this address.");
KNOB<string> KnobTrigModule(KNOB_MODE_WRITEONCE, "pintool",
"trig_mod", "",
"Module that trigger point is in.");
KNOB<int> KnobTrigCount(KNOB_MODE_WRITEONCE, "pintool",
"trig_count", "0",
"Number of times trigger will be executed before activating.");
//
// NOTE: This limit is not a hard limit; the generator only stops logging
// during buffer flushes, so the actual number of instructions logged
// might exceed log_limit, but at the most by BUFFER_SIZE.
// Also note that the limit is in terms of the number of _instructions_,
// not frames; things like keyframes, LoadModuleFrames, etc. are not
// included in the count.
//
KNOB<uint64_t> KnobLogLimit(KNOB_MODE_WRITEONCE, "pintool",
"log-limit", "0",
"Number of instructions to limit logging to.");
KNOB<bool> LogAllSyscalls(KNOB_MODE_WRITEONCE, "pintool",
"log-syscalls", "false",
"Log system calls (even those unrelated to taint)");
KNOB<bool> KnobTaintTracking(KNOB_MODE_WRITEONCE, "pintool",
"taint-track", "true",
"Enable taint tracking");
KNOB<bool> LogAllAfterTaint(KNOB_MODE_WRITEONCE, "pintool",
"logall-after", "false",
"Log all (even untainted) instructions after the first tainted instruction");
KNOB<bool> LogAllBeforeTaint(KNOB_MODE_WRITEONCE, "pintool",
"logall-before", "false",
"Log all (even untainted) instructions before and after the first tainted instruction");
// This option logs one instruction. It then generates a fake
// standard frame to include operands after the instruction executed.
KNOB<bool> LogOneAfter(KNOB_MODE_WRITEONCE, "pintool",
"logone-after", "false",
"Log the first instruction outside of the log range (taint-start/end), and then exit.");
KNOB<bool> LogKeyFrames(KNOB_MODE_WRITEONCE, "pintool",
"log-key-frames", "false",
"Periodically output key frames containing important program values");
KNOB<string> TaintedFiles(KNOB_MODE_APPEND, "pintool",
"taint-files", "",
"Consider the given files as being tainted");
KNOB<bool> TaintedArgs(KNOB_MODE_WRITEONCE, "pintool",
"taint-args", "false",
"Command-line arguments will be considered tainted");
KNOB<bool> TaintedStdin(KNOB_MODE_WRITEONCE, "pintool",
"taint-stdin", "false",
"Everything read from stdin will be considered tainted");
KNOB<bool> TaintedNetwork(KNOB_MODE_WRITEONCE, "pintool",
"taint-net", "false",
"Everything read from network sockets will be considered tainted");
KNOB<bool> TaintedIndices(KNOB_MODE_WRITEONCE, "pintool",
"taint-indices", "false",
"Values loaded with tainted memory indices will be considered tainted");
// FIXME: we should be able to specify more refined tainted
// sources, e.g., that only the 5th argument should be considered
// tainted
KNOB<string> TaintedEnv(KNOB_MODE_APPEND, "pintool",
"taint-env", "",
"Environment variables to be considered tainted");
KNOB<ADDRINT> TaintStart(KNOB_MODE_WRITEONCE, "pintool",
"taint-start", "0x0",
"All logged instructions will have higher addresses");
KNOB<ADDRINT> TaintEnd(KNOB_MODE_WRITEONCE, "pintool",
"taint-end", MAX_ADDRESS,
"All logged instructions will have lower addresses");
KNOB<string> FollowProgs(KNOB_MODE_APPEND, "pintool",
"follow-progs", "",
"Follow the given program names if they are exec'd");
KNOB<string> PivotFile(KNOB_MODE_WRITEONCE, "pintool",
"pivots-file", "",
"Load file of pivot gadgets");
KNOB<bool> SEHMode(KNOB_MODE_WRITEONCE, "pintool",
"seh-mode", "false",
"Record an SEH exploits");
KNOB<int> CheckPointFreq(KNOB_MODE_WRITEONCE, "pintool",
"freq", "10000",
"Report value of eip every n instructions.");
KNOB<int> CacheLimit(KNOB_MODE_WRITEONCE, "pintool",
"cache-limit", "500000000",
"Code-cache size limit (bytes)");
KNOB<int> SkipTaints(KNOB_MODE_WRITEONCE, "pintool",
"skip-taints", "0",
"Skip this many taint introductions");
struct FrameBuf {
ADDRINT addr;
uint32_t tid;
uint32_t insn_length;
// The raw instruction bytes will be stored as 16 bytes placed over 4
// integers. The conversion is equivalent to the casting of a char[16]
// to a uint32_t[4].
// NOTE: This assumes that MAX_INSN_BYTES == 16!!!
uint32_t rawbytes0;
uint32_t rawbytes1;
uint32_t rawbytes2;
uint32_t rawbytes3;
uint32_t values_count;
ValSpecRec valspecs[MAX_VALUES_COUNT];
};
/**
* Temporary structure used during instrumentation.
*/
typedef struct TempOps_s {
uint32_t reg;
RegMem_t type;
uint32_t taint;
} TempOps_t;
/**
* Posible ways of passing a register to an analysis function
*/
enum RPassType { P_VALUE, P_REF, P_CONTEXT, P_FPX87 };
/**
* Given a register, decide how to pass it.
*/
static RPassType howPass(REG r) {
dbg_printf("howPass r=%s\n", pin_register_name(r).c_str());
if(REG_is_fr_for_get_context(r))
return P_CONTEXT;
/* XMM and floating point registers can be passed by reference */
if (REG_is_xmm(r) || REG_is_ymm(r) || REG_is_mm(r))
return P_REF;
if(REG_is_fr_or_x87(r))
return P_FPX87;
// For now, let's just use context
return P_CONTEXT;
}
/**
* Avoiding logging some addresses.
*/
static bool dontLog(ADDRINT addr) {
dbg_printf("dontLog addr=0x%lx\n", addr);
IMG i = IMG_FindByAddress(addr);
if (IMG_Valid(i)) {
char tempbuf[BUFSIZE];
char *tok = NULL;
char *lasttok = NULL;
// Fill up the temporary buffer
strncpy(tempbuf, IMG_Name(i).c_str(), BUFSIZE);
// We don't need a lock, since this is an instrumentation function (strtok is not re-entrant)
strtok(tempbuf, "\\");
while ((tok = strtok(NULL, "\\")) != NULL) {
// Just keep parsing...
lasttok = tok;
}
if (lasttok) {
if (lasttok == string("uxtheme.dll")) {
return true;
}
}
}
return false;
}
/**
* This type preserves state between a system call entry and exit.
*/
typedef struct SyscallInfo_s {
/** Frame for system call */
frame sf;
/** State shared between taintIntro and taintStart */
uint32_t state;
} SyscallInfo_t;
/**
* This type preserves state between a recv() call and return
*/
typedef struct RecvInfo_s {
/** Fd */
uint32_t fd;
/** The address */
void* addr;
/** Bytes written ptr. */
uint32_t *bytesOut;
} RecvInfo_t;
/**
* Thread local information
*/
typedef struct ThreadInfo_s {
// Stack keeping track of system calls
// Needed because windows system calls can be nested!
std::stack<SyscallInfo_t> scStack;
std::stack<RecvInfo_t> recvStack;
context delta;
} ThreadInfo_t;
int g_counter = 0;
//TraceWriter *g_tw;
TraceContainerWriter *g_twnew;
template <typename Iterator>
inline void add_frames(TraceContainerWriter* out,
Iterator first, Iterator last) {
while (first != last) {
out->add(*first++);
}
}
// A taint tracker
TaintTracker * tracker;
FrameBuf g_buffer[BUFFER_SIZE];
uint32_t g_bufidx;
// Counter to keep track of when we should add a keyframe.
uint32_t g_kfcount;
// Caches.
//RegCache g_regcache;
//MemCache g_memcache;
// Profiling timer.
clock_t g_timer;
// True if logging is activated.
// Logging should be activated if it is possible for some instruction
// to be logged. This could happen because 1) we are logging all
// instructions, or 2) taint is introduced, and so the instruction
// could be tainted.
bool g_active;
// Number of instructions logged so far.
uint64_t g_logcount;
// Number of instructions to limit logging to.
uint64_t g_loglimit;
// True if a trigger was specified.
bool g_usetrigger;
// Activate taint analysis
// bool t_active;
// Whether taint has been introduced
bool g_taint_introduced;
// True if the trigger address was resolved.
bool g_trig_resolved;
ADDRINT g_trig_addr;
// We use a signed integer because sometimes the countdown will be
// decremented past zero.
int g_trig_countdown;
// Name of our thread/process
char g_threadname[BUFFER_SIZE] = "s";
// A lock on any shared state
PIN_LOCK lock;
// An environment to keep all the values
ValSpecRec values[MAX_VALUES_COUNT];
// Address ranges
ADDRINT start_addr, end_addr;
// Pivot set
pivot_set ps;
// Exit after the next instruction
bool g_exit_next;
// Prototypes.
VOID Cleanup();
// Key for thread local system call stack
static TLS_KEY tl_key;
// Start of functions.
VOID ModLoad(IMG i, void*);
// Get Thread Info
ThreadInfo_t* GetThreadInfo(void) {
ThreadInfo_t* ti;
ti = static_cast<ThreadInfo_t*> (PIN_GetThreadData(tl_key, PIN_ThreadId()));
assert(ti);
return ti;
}
// Create a new thread information block for the current thread
ThreadInfo_t* NewThreadInfo(void) {
ThreadInfo_t* ti = NULL;
ti = new ThreadInfo_t;
assert(ti);
PIN_SetThreadData(tl_key, ti, PIN_ThreadId());
return ti;
}
/** Given a REG, return the number of bits in the reg */
static uint32_t GetBitsOfReg(REG r) {
dbg_printf("GetBitsOfReg r=%s\n", pin_register_name(r).c_str());
if (REG_is_gr8(r)) return 8;
if (REG_is_gr16(r)) return 16;
if (REG_is_gr32(r)) return 32;
if (REG_is_gr64(r)) return 64;
/* REG_is_fr_or_x87 returns true on XMM registers and other
non-x87 regs, so we can't use that. */
if (REG_ST_BASE <= r && r <= REG_ST_LAST) return 80;
string s = REG_StringShort(r);
switch (r) {
case REG_SEG_CS:
case REG_SEG_DS:
case REG_SEG_ES:
case REG_SEG_FS:
case REG_SEG_GS:
case REG_SEG_SS:
return 16;
break;
case REG_MXCSR:
return 32;
break;
case REG_MM0:
case REG_MM1:
case REG_MM2:
case REG_MM3:
case REG_MM4:
case REG_MM5:
case REG_MM6:
case REG_MM7:
return 64;
break;
case REG_XMM0:
case REG_XMM1:
case REG_XMM2:
case REG_XMM3:
case REG_XMM4:
case REG_XMM5:
case REG_XMM6:
case REG_XMM7:
return 128;
break;
case REG_YMM0:
case REG_YMM1:
case REG_YMM2:
case REG_YMM3:
case REG_YMM4:
case REG_YMM5:
case REG_YMM6:
case REG_YMM7:
return 256;
break;
/*
* Handle any extra registers specific to an architecture
* and defines any ambiguous registers
* (E.g., REG_INST_PTR can be 64 or 32 based on the architecture)
*/
#if defined(ARCH_64)
case REG_EIP:
case REG_EFLAGS:
return 32;
break;
case REG_INST_PTR:
case REG_GFLAGS:
case REG_SEG_GS_BASE:
case REG_SEG_FS_BASE:
return 64;
break;
case REG_XMM8:
case REG_XMM9:
case REG_XMM10:
case REG_XMM11:
case REG_XMM12:
case REG_XMM13:
case REG_XMM14:
case REG_XMM15:
return 128;
break;
case REG_YMM8:
case REG_YMM9:
case REG_YMM10:
case REG_YMM11:
case REG_YMM12:
case REG_YMM13:
case REG_YMM14:
case REG_YMM15:
return 256;
break;
#elif defined(ARCH_32)
case REG_INST_PTR:
case REG_GFLAGS:
case REG_SEG_GS_BASE:
case REG_SEG_FS_BASE:
return 32;
break;
#endif
default:
break;
}
// Otherwise, exit because we don't know what's up
cerr << "Warning: Unknown register size of register " << REG_StringShort(r) << endl;
assert(false);
return -1;
}
static size_t GetByteSize(RegMem_t vtype) {
return (vtype.size / 8);
}
static size_t GetBitSize(RegMem_t type) {
return type.size;
}
void LLOG(const char *str) {
#if DEBUG_LOCK
LOG(str);
#else
/* Disabled */
#endif
}
ADDRINT CheckTrigger()
{
return --g_trig_countdown <= 0;
}
VOID Activate(CONTEXT *ctx)
{
dbg_printf("Activate\n");
cerr << "Activating logging" << endl;
g_active = true;
PIN_RemoveInstrumentation();
PIN_ExecuteAt(ctx);
}
/** Activate taint analysis.
Note: It's important to NOT hold locks when calling this function.
PIN_RemoveInstrumentation obtains the VM lock, which is only possible
when no analysis functions/etc are executing. If one is waiting for
one of our locks, this will cause a deadlock.
*/
VOID TActivate()
{
dbg_printf("TActivate\n");
cerr << "Activating taint analysis " << endl;
g_active = true; /* Any instruction could be logged because taint is
introduced. */
g_taint_introduced = true; /* Taint is definitely introduced now. */
PIN_RemoveInstrumentation();
}
//
// Returns true if the buffer index with count added to it exceeds the
// maximum size of the buffer.
//
ADDRINT CheckBuffer(UINT32 count)
{
dbg_printf("CheckBuffer count=%d\n", count);
return (g_bufidx + count) >= BUFFER_SIZE - FUDGE;
}
ADDRINT CheckBufferEx(BOOL cond, UINT32 count, UINT32 count2)
{
dbg_printf("CheckBufferEx cond=%d, count=%d, count2=%d\n", cond, count, count2);
return cond && ((g_bufidx + count + count2) >= BUFFER_SIZE - FUDGE);
}
// Callers must ensure mutual exclusion
VOID FlushInstructions()
{
dbg_printf("FlushInstructions\n");
for(uint32_t i = 0; i < g_bufidx; i++) {
frame fnew;
fnew.mutable_std_frame()->set_address(g_buffer[i].addr);
fnew.mutable_std_frame()->set_thread_id(g_buffer[i].tid);
/* Ew. */
fnew.mutable_std_frame()->set_rawbytes((void*)(&(g_buffer[i].rawbytes0)), g_buffer[i].insn_length);
/* Add operands */
// Go through each value and remove the ones that are cached.
/* The operand_list is a required field, so we must access it
even if there are no operands or protobuffers will complain to
us. */
fnew.mutable_std_frame()->mutable_operand_pre_list();
for (uint32_t j = 0; j < g_buffer[i].values_count; j++) {
ValSpecRec &v = g_buffer[i].valspecs[j];
operand_info *o = fnew.mutable_std_frame()->mutable_operand_pre_list()->add_elem();
o->set_bit_length(GetBitSize(v.type));
o->mutable_operand_usage()->set_read(v.usage & RD);
o->mutable_operand_usage()->set_written(v.usage & WR);
/* XXX: Implement index and base */
o->mutable_operand_usage()->set_index(false);
o->mutable_operand_usage()->set_base(false);
switch (v.taint) {
case 0:
o->mutable_taint_info()->set_no_taint(true);
break;
case -1:
o->mutable_taint_info()->set_taint_multiple(true);
break;
default:
o->mutable_taint_info()->set_taint_id(v.taint);
break;
}
if (tracker->isMem(v.type)) {
o->mutable_operand_info_specific()->mutable_mem_operand()->set_address(v.loc);
} else {
string t = pin_register_name((REG)v.loc);
if (t == "Unknown") {
t = string("Unknown ") + REG_StringShort((REG)v.loc);
}
o->mutable_operand_info_specific()->mutable_reg_operand()->set_name(t);
}
o->set_value(&(v.value), GetByteSize(v.type));
// We're in trouble if we don't know the type.
if(v.type.type != REGISTER && v.type.type != MEM) {
cerr << "v.type = " << v.type.type << endl;
assert(false);
}
}
g_twnew->add(fnew);
}
// Update counts.
g_logcount += g_bufidx;
g_kfcount += g_bufidx;
g_bufidx = 0;
}
/* Add a PIN register to a value list. Helper function for FlushBuffer */
VOID AddRegister(tagged_value_list *tol, const CONTEXT *ctx, REG r, THREADID threadid) {
dbg_printf("AddRegister r=%d, tid=%d\n", r, threadid);
tol->mutable_value_source_tag()->set_thread_id(threadid);
value_info *v = tol->mutable_value_list()->add_elem();
v->mutable_operand_info_specific()->mutable_reg_operand()->set_name(REG_StringShort(r));
size_t s_bytes = GetBitsOfReg(r) / 8;
v->set_bit_length(s_bytes * 8);
/* Make sure this register even fits in the context. PIN would
probably throw an error, but it's good to be paranoid. */
assert (s_bytes <= sizeof(ADDRINT));
ADDRINT regv = PIN_GetContextReg(ctx, r);
v->set_value((void*)(®v), s_bytes);
//std::copy((uint8_t*) (®v), ((uint8_t*) (®v)) + s_bytes, v->
}
//
// Writes all instructions stored in the buffer to disk, and resets the
// buffer index to 0. Also checks to see if we need to insert a
// keyframe. If so, inserts the keyframe using the data in the supplied
// context.
//
VOID FlushBuffer(BOOL addKeyframe, const CONTEXT *ctx, THREADID threadid, BOOL needlock)
{
dbg_printf("FlushBuffer\n");
LLOG("Begin flushing buffer.\n");
if (needlock) {
PIN_GetLock(&lock, threadid+1);
}
FlushInstructions();
// Check to see if we should insert a keyframe here.
if (addKeyframe && (g_kfcount >= KEYFRAME_FREQ) && LogKeyFrames) {
//LOG("Inserting keyframe:\n");
//LOG(" addr: " + hexstr(PIN_GetContextReg(ctx, REG_EIP)) + "\n");
assert(ctx);
frame f;
tagged_value_list *tol = f.mutable_key_frame()->mutable_tagged_value_lists()->add_elem();
AddRegister(tol, ctx, LEVEL_BASE::REG_GAX, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_GBX, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_GCX, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_GDX, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_GSI, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_GDI, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_STACK_PTR, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_GBP, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_GFLAGS, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_SEG_CS, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_SEG_DS, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_SEG_SS, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_SEG_ES, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_SEG_FS, threadid);
AddRegister(tol, ctx, LEVEL_BASE::REG_SEG_GS, threadid);
g_twnew->add(f);
g_kfcount = 0;
}
// See if we've gotten sufficient instructions.
if ((g_loglimit != 0) && (g_logcount >= g_loglimit)) {
LOG("Logged required number of instructions, quitting.\n");
cerr << "Logged required number of instructions, quitting." << endl;
Cleanup();
//PIN_ReleaseLock(&lock);
// Never release lock
//PIN_Detach();
exit(0);
} else {
if (needlock) {
PIN_ReleaseLock(&lock);
}
}
dbg_printf("End FlushBuffer\n");
LLOG("End flushing buffer.\n");
}
#ifdef _WIN32
/** Wrapper for accept */
uint32_t AcceptWrapper(CONTEXT *ctx, AFUNPTR fp, THREADID tid, uint32_t s, void *addr, int *addrlen) {
cerr << "AcceptWrapper" << endl;
uint32_t ret;
PIN_CallApplicationFunction(ctx, tid,
CALLINGSTD_STDCALL, fp,
PIN_PARG(uint32_t), &ret,
PIN_PARG(uint32_t), s,
PIN_PARG(void*), addr,
PIN_PARG(int*), addrlen,
PIN_PARG_END());
PIN_GetLock(&lock, tid+1);
tracker->acceptHelper(ret);
PIN_ReleaseLock(&lock);
return ret;
}
/** Wrapper for WSAConnect */
uint32_t WSAConnectWrapper(CONTEXT *ctx, AFUNPTR fp, THREADID tid, uint32_t s, void *arg2, void *arg3, void *arg4, void *arg5, void *arg6, void *arg7) {
cerr << "WSAConnectWrapper" << endl;
uint32_t ret;
cerr << "Connect to socket " << s << endl;
PIN_CallApplicationFunction(ctx, tid,
CALLINGSTD_STDCALL, fp,
PIN_PARG(uint32_t), &ret,
PIN_PARG(uint32_t), s,
PIN_PARG(void*), arg2,
PIN_PARG(void*), arg3,
PIN_PARG(void*), arg4,
PIN_PARG(void*), arg5,
PIN_PARG(void*), arg6,
PIN_PARG(void*), arg7,
PIN_PARG_END());
PIN_GetLock(&lock, tid+1);
if (ret != SOCKET_ERROR) {
tracker->acceptHelper(s);
} else {
cerr << "WSAConnect error " << ret << endl;
}
PIN_ReleaseLock(&lock);
return ret;
}
/** Wrapper for connect */
uint32_t ConnectWrapper(CONTEXT *ctx, AFUNPTR fp, THREADID tid, uint32_t s, void *arg2, void *arg3) {
cerr << "ConnectWrapper" << endl;
uint32_t ret;
cerr << "Connect to socket " << s << endl;
PIN_CallApplicationFunction(ctx, tid,
CALLINGSTD_STDCALL, fp,
PIN_PARG(uint32_t), &ret,
PIN_PARG(uint32_t), s,
PIN_PARG(void*), arg2,
PIN_PARG(void*), arg3,
PIN_PARG_END());
PIN_GetLock(&lock, tid+1);
// if (ret != SOCKET_ERROR) {
// Non-blocking sockets will return an "error". However, we can't
// call GetLastError to find out what the root problem is,
// so... we'll just assume the connection was successful.
tracker->acceptHelper(s);
// } else {
// cerr << "connect error " << ret << endl;
// }
PIN_ReleaseLock(&lock);
return ret;
}
void BeforeRecv(THREADID tid, uint32_t s, char* buf) {
RecvInfo_t r;
r.fd = s;
r.addr = buf;
r.bytesOut = NULL;
ThreadInfo_t *ti = GetThreadInfo();
ti->recvStack.push(r);
}
void WSABeforeRecv(THREADID tid, uint32_t s, WINDOWS::LPWSABUF bufs, WINDOWS::LPDWORD bytesOut) {
RecvInfo_t r;
r.fd = s;
r.addr = bufs[0].buf;
r.bytesOut = (uint32_t*) bytesOut;
ThreadInfo_t *ti = GetThreadInfo();
ti->recvStack.push(r);
}
void AfterRecv(THREADID tid, int ret, char *f) {
cerr << "afterrecv called by " << f << endl;
ThreadInfo_t *ti = GetThreadInfo();
uint32_t len = 0;
if (ti->recvStack.empty()) {
cerr << "WARNING: Stack empty in AfterRecv(). Thread " << tid << endl;
} else {
RecvInfo_t ri = ti->recvStack.top();
ti->recvStack.pop();
if (ret != SOCKET_ERROR) {
PIN_GetLock(&lock, tid+1);
//cerr << "fd: " << ri.fd << endl;
uint32_t numbytes = 0;
if (ri.bytesOut) {
numbytes = *(ri.bytesOut);
} else {
numbytes = ret;
}
FrameOption_t fo = tracker->recvHelper(ri.fd, ri.addr, numbytes);
PIN_ReleaseLock(&lock);
if (fo.b) {
if (!g_taint_introduced) {
TActivate();
}
PIN_GetLock(&lock, tid+1);
g_twnew->add(fo.f);
PIN_ReleaseLock(&lock);
}
} else {
cerr << "recv() error " << endl;
}
}
}
/** Wrapper for calling GetEnvironmentStringsW() and tainting the output */
void* GetEnvWWrap(CONTEXT *ctx, AFUNPTR fp, THREADID tid) {
void *ret = NULL;
/*