-
Notifications
You must be signed in to change notification settings - Fork 8
/
idadbg.cpp
5459 lines (4993 loc) · 177 KB
/
idadbg.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
/*
IDA trace: PIN tool to communicate with IDA's debugger
Last supported linux version: 3.30-98830
Last supported windows version: 3.30-98830
*/
#if defined(__NT__) && defined(__LINT__)
//lint -e40 -e1055 -e64 -e92
#endif
#include <pin.H>
// PIN_PRODUCT_VERSION_MAJOR is not defined in pin-3.10
#ifndef PIN_PRODUCT_VERSION_MAJOR
#define PIN_PRODUCT_VERSION_MAJOR 3
#define PIN_PRODUCT_VERSION_MINOR 10
#define PIN_BUILD_NUMBER 97971
#endif
#ifndef PIN_BUILD_NUMBER
#error PIN_BUILD_NUMBER undefined
#endif
#if PIN_BUILD_NUMBER >= 97971
#define PIN_3_10_OR_HIGHER
#endif
//--------------------------------------------------------------------------
#if PIN_PRODUCT_VERSION_MAJOR < 3 || PIN_PRODUCT_VERSION_MAJOR == 3 && PIN_PRODUCT_VERSION_MINOR < 7
#define PIN_NUMERIC_BUILD PIN_BUILD_NUMBER
#endif
#include "idadbg.h"
#include "idadbg_local.h"
#include <time.h>
//--------------------------------------------------------------------------
#if defined(__GNUC__) && __GNUC__ >= 7
#pragma GCC diagnostic warning "-Waligned-new=all"
#endif
//--------------------------------------------------------------------------
#define PIN_STR_TO_BUF(buf, s) \
pin_strncpy(buf, s.c_str(), sizeof(buf)-1); \
buf[sizeof(buf)-1] = '\0';
//--------------------------------------------------------------------------
// PIN build 71313 cannot load WinSock library
#if defined(_WIN32) && defined(PIN_NUMERIC_BUILD) && PIN_NUMERIC_BUILD == 71313
# error "IDA does not support PIN build #71313. Please use a newer one instead"
#endif
#if !defined(PIN_NUMERIC_BUILD) || PIN_NUMERIC_BUILD >= 76991
#ifndef _WIN32
#include <sys/syscall.h>
#endif
// Since build 76991 PIN does not have PIN_IsProcessExiting, Get/ReleaseVmLock
#define PIN_IsProcessExiting() process_exiting()
#define GetVmLock()
#define ReleaseVmLock()
#define PIN_SetExiting() (process_state = APP_STATE_EXITING)
#elif !defined(_WIN32)
#define PIN_SetExiting()
#endif
// avoid deprecated functions
#ifdef PIN_3_10_OR_HIGHER
#define pin_IMG_Entry IMG_EntryAddress
#define pin_INS_IsBranchOrCall(i) (INS_IsBranch(i) || INS_IsCall(i))
#else
#define pin_IMG_Entry IMG_Entry
#define pin_INS_IsBranchOrCall(i) INS_IsBranchOrCall(i)
#endif
//--------------------------------------------------------------------------
// By default we use a separate internal thread for reinstrumentation
// (PIN_RemoveInstrumentation) as there is a a danger of deadlock
// when calling it from listener thread while an application thread is
// waiting on the semaphore.
// There is another issue: breakpoints, thread suspends, pausing and
// waiting for resume on events are implemented by stopping all application
// threads from a separate thread 'suspender'. Suspending on EXCEPTION events
// is implemented by waiting on semaphore in the corresponding callbacks and
// analysis routines. In this case all threads are considered to be
// suspended when an event has been emited and application semaphore cleared:
// we assume that soon thereafter each running thread will be suspended
// on the semaphore inside one of analysis routines. But some threads may be
// waiting somewhere else (system calls and so on). For such threads we can't
// provide the client correct registers as we don't have valid thread contexts
// stored for them.
// For all threads stopped by suspender we can provide valid contexts.
#define SEPARATE_THREAD_FOR_REINSTR
//--------------------------------------------------------------------------
// Command line switches
//lint -esym(843, knob_ida_port, knob_connect_timeout, knob_debug_mode) could be made const
KNOB<int> knob_ida_port(
KNOB_MODE_WRITEONCE,
"pintool",
"p",
"23946",
"Port where IDA Pro is listening for incoming PIN tool's connections");
KNOB<int> knob_connect_timeout(
KNOB_MODE_WRITEONCE,
"pintool",
"T",
"0",
"How many seconds wait for client connection (in seconds, 0 - wait for forever)");
KNOB<int> knob_debug_mode(
KNOB_MODE_WRITEONCE,
"pintool",
"idadbg",
"0",
"Debug mode");
//--------------------------------------------------------------------------
int pin_client_version; // client version (from 'HELLO' packet)
//--------------------------------------------------------------------------
// IDA listener (runs in a separate thread)
static VOID ida_pin_listener(VOID *);
// sockets
static PIN_SOCKET srv_socket, cli_socket;
// internal thread identifier
static PIN_THREAD_UID listener_uid;
// this lock prevents listener thread to start serving of requests
static PIN_LOCK start_listener_lock;
// flag: has internal listener thread really started?
static bool listener_ready = false;
// this lock protects 'listener_ready' flag: a thread should acquire it
// when is going to communicate with IDA
static PIN_LOCK listener_ready_lock;
//--------------------------------------------------------------------------
// Handle IDA requests
static bool handle_packets(int total, pin_event_id_t until_ev = NO_EVENT);
static bool read_handle_packet(idapin_packet_t *res = nullptr);
static bool handle_packet(const idapin_packet_t *res);
//lint -esym(551, last_packet) not accessed
static const char *last_packet = "NONE"; // for debug purposes
// We use this function to communicate with IDA synchronously
// while the listener thread is not active
static bool serve_sync(void);
//--------------------------------------------------------------------------
inline void get_context_regs(const CONTEXT *ctx, idapin_registers_t *regs);
inline void get_phys_context_regs(const PHYSICAL_CONTEXT *ctx, idapin_registers_t *regs);
//--------------------------------------------------------------------------
#if PIN_BUILD_NUMBER >= 98425
// REG_FPTAG_FULL is removed since 3.19-98425, define original index for it here
#define NONSTD_FPTAG_FULL
#define REG_FPTAG_FULL (REG_LAST+1)
typedef int PINTOOL_REG;
#else
typedef REG PINTOOL_REG;
#endif
static int get_pinreg_size(PINTOOL_REG regid);
static PINTOOL_REG regidx_pintool2pin(pin_regid_t pintool_reg);
inline const char *regname_by_idx(pin_regid_t pintool_reg);
struct PINTOOL_REGISTER
{
UINT8 *byte = nullptr;
UINT8 buf[256];
PINTOOL_REGISTER(PINTOOL_REG regno)
{
int size = get_pinreg_size(regno);
int bufsize = sizeof(buf);
// dynamically allocate memory if the size exceeds sizeof(buf)
byte = size <= bufsize ? buf : (UINT8 *)malloc(size);
}
~PINTOOL_REGISTER()
{
if ( byte != buf )
free(byte);
byte = nullptr;
}
};
//--------------------------------------------------------------------------
// application process state
enum process_state_t
{
APP_STATE_NONE, // not started yet -> don't report any event
// until the PROCESS_STARTED packet is added
// to the events queue
APP_STATE_RUNNING, // process thread is running
APP_STATE_PAUSE, // pause request received
APP_STATE_SUSPENDED, // process suspended - wait for resume
APP_STATE_WAIT_FLUSH, // process suspended due to tracebuf is full
APP_STATE_EXITING, // process thread is exiting
APP_STATE_EXITED, // process exited
APP_STATE_DETACHED, // detached
};
// global process state variable and lock for it
static process_state_t process_state = APP_STATE_NONE;
static PIN_LOCK process_state_lock;
//--------------------------------------------------------------------------
struct pin_local_event_t
{
pin_local_event_t(uint32 evid = NO_EVENT,
THREADID ltid = INVALID_THREADID, uint64 addr = BADADDR)
: debev(evid, addr), tid_local(ltid)
{
}
// The following fields must be filled for all events:
pin_debug_event_t debev;
THREADID tid_local; // local thread id
};
//--------------------------------------------------------------------------
// break at the very next instruction?
static bool break_at_next_inst = false;
// semaphore used for pausing the whole application
static PIN_SEMAPHORE run_app_sem;
// main thread id: we don't emit THREAD_STARTED event for it
// as IDA registers main thread when handles PROCESS_STARTED event
static THREADID main_thread = INVALID_THREADID;
static bool main_thread_started = false;
// PROCESS_STARTED event prepared by app_start_cb
static pin_local_event_t start_ev;
//--------------------------------------------------------------------------
// thread-local data
class thread_data_t
{
public:
// to get PIN_StopApplicationThreads() chance to catch safe points
// we periodically call ExecuteAt() from analysis routines.
// the following type denotes whether restart is requested and
// where restart has been issued from (if it has)
enum restart_mode_t
{
RESTART_REQ = 0x01, // restart is requested
RESTART_FROM_CTRL = 0x02, // restarted from do_ctrl
RESTART_FROM_BPT = 0x04, // restarted from do_bpt
};
inline thread_data_t();
~thread_data_t();
bool is_started() const { return started; }
inline void set_started();
inline void set_finished() const;
bool ctx_ok() const { return ctx != nullptr; }
CONTEXT *get_ctx() { create_ctx(); return ctx; } //lint !e1535 !e1536 exposes lower access member
bool is_phys_ctx() const { return is_phys; }
bool is_ctx_changed() const { return ctx_changed; }
bool is_ctx_valid() const { return ctx_valid; }
void discard_ctx() { ctx_valid = false; }
inline void suspend();
inline void wait();
inline void resume();
inline void set_excp_handled(bool val);
bool suspended() const { return susp; }
bool excp_handled() const { return ev_handled; }
inline pin_thid get_ext_tid() const { return ext_tid; }
inline bool save_curr_thread_ctx(const CONTEXT *src_ctx);
inline void save_ctx(const CONTEXT *src_ctx, bool can_change = true);
inline void save_phys_ctx(const PHYSICAL_CONTEXT *phys_ctx);
inline void set_ctx_reg(REG pinreg, ADDRINT regval);
inline void export_ctx(idapin_registers_t *regs);
inline bool change_regval(PINTOOL_REG regno, const UINT8 *regval);
inline void continue_execution(int restarted_from);
inline bool can_break(ADDRINT addr) const;
int available_regs(int clsmask) const;
inline bool add_thread_areas(pin_meminfo_vec_t *miv);
static inline int n_active_threads();
static inline bool have_suspended_threads();
static inline bool all_threads_suspended();
void set_restart_ea(ADDRINT ea) { restarted_at = ea; }
inline void set_restart_ctx(const CONTEXT *context);
static inline thread_data_t *get_thread_data();
static inline thread_data_t *get_thread_data(THREADID tid);
static thread_data_t *find_thread_data(THREADID tid, bool create = false);
static inline bool release_thread_data(THREADID tid);
static inline THREADID get_thread_id();
static inline pin_thid get_ext_thread_id(THREADID locat_tid);
static inline THREADID get_local_thread_id(pin_thid tid_ext);
static inline void restart_threads_for_suspend();
static inline void resume_threads_after_suspend();
static inline bool has_stoppable_threads();
static inline thread_data_t *get_any_stopped_thread(THREADID *tid);
static inline void add_all_thread_areas(pin_meminfo_vec_t *miv);
static inline ssize_t read_memory(void *dst, ADDRINT ea, size_t size);
static inline ssize_t write_memory(ADDRINT ea, const void *src, size_t size);
private:
void create_ctx() { if ( !ctx_ok() ) ctx = new CONTEXT; }
inline void try_init_ext_tid(THREADID locat_tid);
inline void set_ext_tid(THREADID locat_tid, pin_thid tid);
inline void save_ctx_nolock(const CONTEXT *src_ctx, bool can_change = true);
inline void restart_for_suspend();
inline void resume_after_suspend();
inline void reexecute_thread(restart_mode_t restart_bit);
#ifdef _WIN32
void *tibbase;
WINDOWS::_NT_TIB nt_tib;
ADDRINT stack_top() const { return ADDRINT(nt_tib.StackBase); }
ADDRINT stack_bottom() const { return ADDRINT(nt_tib.StackLimit); }
ADDRINT tibstart() const { return ADDRINT(tibbase); }
ADDRINT tibend() const { return tibstart() + sizeof(nt_tib); }
inline void read_tibmem(char *dst, ADDRINT ea, size_t size) const;
#endif
CONTEXT *ctx;
ADDRINT restarted_at;
PIN_SEMAPHORE thr_sem;
PIN_LOCK ctx_lock;
pin_thid ext_tid;
int state_bits;
bool ctx_valid;
bool ctx_changed;
bool can_change_regs;
bool susp;
bool ev_handled; // true if the last exception was hanlded by debugger
bool started;
bool is_phys;
bool is_stoppable; // can be stopped by PIN_StopApplicationThreads
static int thread_cnt; // number of thread_data_t objects
static int active_threads_cnt; // number of active threads
static int suspeded_cnt;
typedef std::map <THREADID, thread_data_t *> thrdata_map_t;
static thrdata_map_t thr_data;
static std::map <pin_thid, THREADID> local_tids;
static PIN_LOCK thr_data_lock;
static bool thr_data_lock_inited;
static PIN_LOCK meminfo_lock;
};
//--------------------------------------------------------------------------
typedef std::deque<pin_local_event_t> event_list_t;
//--------------------------------------------------------------------------
// Event queue
//-V:ev_queue_t:730 Not all members of a class are initialized inside the constructor: lock
class ev_queue_t
{
public:
ev_queue_t();
~ev_queue_t();
//lint -sem(ev_queue_t::init,initializer)
void init();
inline void push_back(const pin_local_event_t &ev);
inline void push_front(const pin_local_event_t &ev);
inline void add_ev(const pin_local_event_t &ev, bool front);
inline bool pop_front(pin_local_event_t *out_ev, bool *can_resume);
inline bool back(pin_local_event_t *out_ev);
inline size_t size();
inline bool empty();
inline void last_ev(pin_local_event_t *out_ev);
bool send_event(bool *can_resume);
inline bool can_send_event() const;
inline void add_symbol(const std::string &name, ea_t ea);
inline char *export_symbols(int *bufsize); // return value should be freed
private:
event_list_t queue;
PIN_LOCK lock;
pin_local_event_t last_retrieved_ev;
std::vector<pin_symdef_t> symbols;
int sym_size;
};
//--------------------------------------------------------------------------
// Manager of breakpoints, pausing, stepping, thread susending
//-V:bpt_mgr_t:730 Not all members of a class are initialized inside the constructor: bpt_lock
class bpt_mgr_t
{
public:
bpt_mgr_t();
~bpt_mgr_t();
//lint -sem(bpt_mgr_t::cleanup,initializer)
inline void cleanup();
// return values: true - bpt really added/removed, false - else
inline void add_soft_bpt(ADDRINT at);
inline void del_soft_bpt(ADDRINT at);
// have bpt at given address?
inline bool have_bpt_at(ADDRINT addr);
// set stepping thread ID
inline void set_step(THREADID stepping_tid);
// inform bpt_mgr that we are about to suspend/resume
// return value:
// true - need reinstrumentation
inline bool prepare_resume();
inline void prepare_suspend();
// instrumentation callback: add analysis routines
inline void add_rtns(INS ins, ADDRINT ins_addr);
// IfCall callback for ctrl_rtn (should be inlined by PIN; run tool with
// -log_inline command line option to check what routines PIN really inlines)
static ADDRINT ctrl_rtn_enabled();
bool need_control_cb() const;
inline void update_ctrl_flag() const;
private:
enum ev_id_t
{
EV_PAUSED = 0,
EV_SINGLE_STEP = 1,
EV_BPT = 2,
EV_INITIAL_STOP = 3,
EV_NO_EVENT = 4
};
typedef std::set<ADDRINT> addrset_t;
inline bool have_bpt_at_nolock(ADDRINT addr);
// analysis routines
static void PIN_FAST_ANALYSIS_CALL bpt_rtn(ADDRINT addr, const CONTEXT *ctx);
static void PIN_FAST_ANALYSIS_CALL ctrl_rtn(ADDRINT addr, const CONTEXT *ctx);
inline void do_bpt(ADDRINT addr, const CONTEXT *ctx);
inline void do_ctrl(ADDRINT addr, const CONTEXT *ctx);
void emit_event(ev_id_t eid, ADDRINT addr, THREADID tid);
static bool control_enabled;
addrset_t bpts;
// Sometimes PIN starts reinstrumenting not immediately but after some period.
// So during this period we keep newly added bpts in the special set
// (pending_bpts) and handle them in ctrl_rtn until we detect
// reinstrumentation really started. Note that using ctrl_rtn for breakpoints
// can dramatically slow down the execution so we will try to get rid
// of such pending breakpoints as soon as possible
addrset_t pending_bpts;
// this lock controls access to breakpoints
PIN_LOCK bpt_lock;
// thread ID of the last dbg_set_resume_mode request
THREADID stepping_thread;
// true if we need to reinstrument just after resume
bool need_reinst;
};
//--------------------------------------------------------------------------
// Application suspender (runs in a separate thread)
// This thread waits on the semaphore and tries to suspend the application
// with PIN_StopApplicationThreads if the application should be paused
class suspender_t
{
public:
suspender_t();
bool start();
bool finish();
bool wait_termination();
inline void stop_threads(const pin_local_event_t &ev);
inline void pause_threads();
bool resume_threads();
inline void copy_pending_events(THREADID curr_tid = INVALID_THREADID);
inline void wakeup();
private:
enum state_t
{
IDLE,
RUNNING,
STOPPING,
PAUSING,
STOPPED,
RESUMING,
EXITING,
};
void copy_pending_events_nolock(THREADID curr_tid);
void suspend_threads(state_t new_susp_state, const pin_local_event_t &ev);
inline void add_pending_event(const pin_local_event_t &ev);
void thread_worker();
static VOID thread_hnd(VOID *ud);
inline bool can_stop_app_threads() const;
event_list_t pending_events;
PIN_LOCK lock;
PIN_SEMAPHORE sem;
PIN_THREAD_UID thread_uid;
std::vector<CONTEXT *> contexts;
process_state_t next_process_state;
state_t state;
};
//--------------------------------------------------------------------------
// This class implements analysis routines, instrumentation callbacks,
// init/update instrumentation according to client's requests
class instrumenter_t
{
public:
static bool init();
static bool finish();
static bool wait_termination();
static void init_instrumentations();
static void update_instrumentation(uint32 trace_types);
static inline void reinit_instrumentations();
static inline void remove_instrumentations();
static inline void resume();
static inline size_t tracebuf_size();
static inline bool tracebuf_is_full();
static inline void clear_trace();
static int get_trace_events(idatrace_events_t *out_trc_events);
static bool set_limits(bool only_new, uint32 enq_size, const char *imgname);
static void process_image(const IMG &img, bool as_default);
static inline void add_trace_intervals(int cnt, const mem_interval_t *ivs);
static inline bool write_regs(pin_thid tid, int cnt, const pin_regval_t *values);
enum instr_state_t
{
INSTR_STATE_INITIAL,
INSTR_STATE_NEED_REINIT,
INSTR_STATE_REINIT_STARTED,
INSTR_STATE_OK,
};
static inline bool instr_state_ok();
private:
static void add_instrumentation(trace_flags_t inst);
// logic IF-routines (should be inlined by PIN; run tool with -log_inline
// command line option to check what routines PIN does really inline)
static ADDRINT ins_enabled(VOID *);
static ADDRINT trc_enabled(VOID *);
static ADDRINT rtn_enabled(VOID *);
// logic THEN-routines
static VOID PIN_FAST_ANALYSIS_CALL ins_logic_cb(
const CONTEXT *ctx,
VOID *ip,
pin_tev_type_t tev_type);
static VOID PIN_FAST_ANALYSIS_CALL rtn_logic_cb(
ADDRINT ins_ip,
ADDRINT target_ip,
BOOL is_indirect,
BOOL is_ret);
static inline void store_trace_entry(
const CONTEXT *ctx,
ADDRINT ea,
pin_tev_type_t tev_type);
static inline void add_to_trace(
const CONTEXT *ctx,
ADDRINT ea,
pin_tev_type_t tev_type);
static inline void add_to_trace(ADDRINT ea, pin_tev_type_t tev_type);
static inline void prepare_and_wait_trace_flush();
static inline void register_recorded_insn(ADDRINT addr);
static inline bool insn_is_registered(ADDRINT addr);
static inline bool check_address(ADDRINT addr);
static inline bool check_address(ADDRINT addr, pin_tev_type_t type);
static inline bool addrok(ADDRINT ea);// does addr belong to set of intervals?
static inline void add_interval(ADDRINT start, ADDRINT end);
// instrumentation callbacks: insert logic routines
static VOID instruction_cb(INS ins, VOID *);
static VOID trace_cb(TRACE trace, VOID *);
static VOID routine_cb(TRACE trace, VOID *);
static bool add_bbl_logic_cb(INS ins, bool first);
static bool add_rtn_logic_cb(INS ins);
static uint32 curr_trace_types();
// recorded instructions
typedef std::deque<trc_element_t> trc_deque_t;
static PIN_LOCK tracebuf_lock;
static trc_deque_t trace_addrs;
// semaphore used for pausing when trace buffer is full
static PIN_SEMAPHORE tracebuf_sem;
// Already recorded instructions, those should be skipped if
// only_new_instructions flag is true.
// NOTE: as we have limited memory in the PIN tool we cannot let it grow
// without limit, we need to remember a maximum number of "skip_limit"
// element(s), or the PIN tool would die because it runs out of memory
typedef std::deque<ADDRINT> addr_deque_t;
static addr_deque_t all_addrs;
// only record new instructions?
static bool only_new_instructions;
// acceptable intervals: if excluding debugger segments and/or library functions
struct intv_t
{
intv_t(ADDRINT s = BADADDR, ADDRINT e = BADADDR): start(s), end(e) {}
ADDRINT start;
ADDRINT end;
};
typedef std::vector<intv_t> intvlist_t;
struct ea_checker_t
{
intvlist_t intervals;
intvlist_t::const_iterator curr_iv;
bool trace_everything; // do not limit tracing addrs by segments/libs
};
static ea_checker_t ea_checker;
// max trace buffer size (max number of events in the buffer)
static uint32 enqueue_limit;
// remember only the last 1 million instructions
static const uint32 skip_limit;
// name of the image to trace
static string image_name;
static instr_state_t state;
// trace mode switches
static bool tracing_instruction;
static bool tracing_bblock;
static bool tracing_routine;
static bool tracing_registers;
static bool log_ret_isns;
static uchar instrumentations;
#ifdef SEPARATE_THREAD_FOR_REINSTR
static VOID reinstrumenter(VOID *);
static bool reinstr_started;
static PIN_SEMAPHORE reinstr_sem;
static PIN_THREAD_UID reinstr_uid;
#endif
};
//--------------------------------------------------------------------------
// Logging/debug
static int debug_level = 0;
//#debug MUTEX_DEBUG
/*
#ifdef MUTEX_DEBUG
//--------------------------------------------------------------------------
class dbg_janitor_for_pinlock_t: public janitor_for_pinlock_t
{
protected:
const char *lname;
int lline;
public:
dbg_janitor_for_pinlock_t(int line, const char *name, PIN_LOCK *lock)
: janitor_for_pinlock_t(lock), lname(name), lline(line)
{
MSG("LOCK %s at %d\n", name, line);
}
~dbg_janitor_for_pinlock_t()
{
MSG("UNLOCK %s/%d\n", lname, lline);
}
};
#define MUTEX_GUARD(n, x) dbg_janitor_for_pinlock_t n(__LINE__, #x, &x)
#else
#define MUTEX_GUARD(n, x) janitor_for_pinlock_t n(&x)
#endif
*/
//--------------------------------------------------------------------------
// Avoid a possible bug in PIN 76991: suspender calls PIN_StopApplicationThreads()
// and then PIN_GetStoppedThreadId which can crash If between these calls a new thread
// is created. We introduce a thread counter and do not call PIN_GetStoppedThreadId -
// just resume threads instead. In this case we know for sure that the last
// thread start/finish callback incremented 'thr_age' also issued suspend request
// which should cause one more suspender iteration.
// (the bug was revealed by pc_linux_pin_threads64.elf)
static int thr_age = 0; //lint !e843 could be made const
inline void inc_thr_age(const char *from) //lint !e715 'from' not subsequently referenced
{
DEBUG(2, "%s: inc_thr_age -> %d\n", from, thr_age+1);
#ifndef _WIN32
janitor_for_pinlock_t process_state_guard(&process_state_lock);
++thr_age;
#endif
}
//--------------------------------------------------------------------------
// PIN address to void *
inline void *pvoid(ADDRINT addr)
{
return (void *)addr;
}
//--------------------------------------------------------------------------
// queued events
static ev_queue_t events;
// The folowing object manages bpt/pausing/single step/thread suspend
static bpt_mgr_t breakpoints;
// The folowing object suspends/resumes application threads
static suspender_t suspender;
//--------------------------------------------------------------------------
// the following functions access process state; they don't acquire
// process_state_lock, it MUST be acquired by caller
inline bool process_started()
{
return process_state != APP_STATE_NONE;
}
//--------------------------------------------------------------------------
inline bool process_exited()
{
return process_state == APP_STATE_EXITED;
}
//--------------------------------------------------------------------------
inline bool process_exiting()
{
return process_state == APP_STATE_EXITING || process_exited();
}
//--------------------------------------------------------------------------
inline bool process_detached()
{
return process_state == APP_STATE_DETACHED;
}
//--------------------------------------------------------------------------
inline bool process_pause()
{
return process_state == APP_STATE_PAUSE;
}
//--------------------------------------------------------------------------
inline bool process_suspended()
{
return process_state == APP_STATE_SUSPENDED
|| process_state == APP_STATE_WAIT_FLUSH;
}
//--------------------------------------------------------------------------
inline char *tail(char *in_str) { return strchr(in_str, '\0'); } //lint !e818 parameter could be pointer to const
inline const char *tail(const char *in_str) { return strchr(in_str, '\0'); }
//--------------------------------------------------------------------------
inline ADDRINT get_ctx_ip(const CONTEXT *ctx)
{
return ctx == nullptr ? BADADDR : (ADDRINT)PIN_GetContextReg(ctx, REG_INST_PTR);
}
//--------------------------------------------------------------------------
inline void get_context_regs(const CONTEXT *ctx, idapin_registers_t *regs)
{
regs->eax = (ADDRINT)PIN_GetContextReg(ctx, REG_GAX);
regs->ebx = (ADDRINT)PIN_GetContextReg(ctx, REG_GBX);
regs->ecx = (ADDRINT)PIN_GetContextReg(ctx, REG_GCX);
regs->edx = (ADDRINT)PIN_GetContextReg(ctx, REG_GDX);
regs->esi = (ADDRINT)PIN_GetContextReg(ctx, REG_GSI);
regs->edi = (ADDRINT)PIN_GetContextReg(ctx, REG_GDI);
regs->ebp = (ADDRINT)PIN_GetContextReg(ctx, REG_GBP);
regs->esp = (ADDRINT)PIN_GetContextReg(ctx, REG_STACK_PTR);
regs->eip = (ADDRINT)PIN_GetContextReg(ctx, REG_INST_PTR);
#if defined(PIN_64)
regs->r8 = (ADDRINT)PIN_GetContextReg(ctx, REG_R8);
regs->r9 = (ADDRINT)PIN_GetContextReg(ctx, REG_R9);
regs->r10 = (ADDRINT)PIN_GetContextReg(ctx, REG_R10);
regs->r11 = (ADDRINT)PIN_GetContextReg(ctx, REG_R11);
regs->r12 = (ADDRINT)PIN_GetContextReg(ctx, REG_R12);
regs->r13 = (ADDRINT)PIN_GetContextReg(ctx, REG_R13);
regs->r14 = (ADDRINT)PIN_GetContextReg(ctx, REG_R14);
regs->r15 = (ADDRINT)PIN_GetContextReg(ctx, REG_R15);
regs->eflags = (ADDRINT)PIN_GetContextReg(ctx, REG_RFLAGS);
#else
regs->eflags = (ADDRINT)PIN_GetContextReg(ctx, REG_EFLAGS);
#endif
regs->cs = (ADDRINT)PIN_GetContextReg(ctx, REG_SEG_CS);
regs->ds = (ADDRINT)PIN_GetContextReg(ctx, REG_SEG_DS);
regs->es = (ADDRINT)PIN_GetContextReg(ctx, REG_SEG_ES);
regs->fs = (ADDRINT)PIN_GetContextReg(ctx, REG_SEG_FS);
regs->gs = (ADDRINT)PIN_GetContextReg(ctx, REG_SEG_GS);
regs->ss = (ADDRINT)PIN_GetContextReg(ctx, REG_SEG_SS);
}
//--------------------------------------------------------------------------
inline void get_phys_context_regs(const PHYSICAL_CONTEXT *ctx, idapin_registers_t *regs)
{
regs->eax = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_GAX);
regs->ebx = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_GBX);
regs->ecx = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_GCX);
regs->edx = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_GDX);
regs->esi = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_GSI);
regs->edi = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_GDI);
regs->ebp = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_GBP);
regs->esp = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_STACK_PTR);
regs->eip = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_INST_PTR);
#if defined(PIN_64)
regs->r8 = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_R8);
regs->r9 = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_R9);
regs->r10 = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_R10);
regs->r11 = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_R11);
regs->r12 = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_R12);
regs->r13 = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_R13);
regs->r14 = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_R14);
regs->r15 = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_R15);
regs->eflags = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_RFLAGS);
#else
regs->eflags = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_EFLAGS);
#endif
regs->cs = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_SEG_CS);
regs->ds = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_SEG_DS);
regs->es = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_SEG_ES);
regs->fs = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_SEG_FS);
regs->gs = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_SEG_GS);
regs->ss = (ADDRINT)PIN_GetPhysicalContextReg(ctx, REG_SEG_SS);
}
//--------------------------------------------------------------------------
// fill some common fields of event and add it to the queue
inline void enqueue_event(pin_local_event_t &ev)
{
ev.debev.pid = PIN_GetPid();
ev.debev.handled = false;
// put PROCESS_STARTED event into the front of the queue to be sent to IDA
// before any LIB_LOADED event because IDA needs
// existing main thread context when suspends execution on LIB_LOADED
// (in case 'Suspend on library load/unload' option is enabled)
events.add_ev(ev, ev.debev.eid == PROCESS_STARTED);
}
//--------------------------------------------------------------------------
inline bool pop_debug_event(pin_local_event_t *out_ev, bool *can_resume)
{
if ( !events.pop_front(out_ev, can_resume) )
return false;
if ( out_ev->tid_local != INVALID_THREADID )
{
out_ev->debev.tid = thread_data_t::get_ext_thread_id(out_ev->tid_local);
}
else if ( out_ev->debev.eid != NO_EVENT )
{
thread_data_t *td = thread_data_t::get_any_stopped_thread(&out_ev->tid_local);
if ( td == nullptr )
{
MSG("PINtool error: undefined event TID and no stopped thread found\n");
}
else
{
out_ev->debev.tid = td->get_ext_tid();
CONTEXT *ctx = td->get_ctx();
out_ev->debev.ea = get_ctx_ip(ctx);
DEBUG(2, "pop event->correct tid(%d)/ea(%p)\n", out_ev->debev.tid, pvoid(out_ev->debev.ea));
}
}
out_ev->debev.flags |= PIN_DEBEV_REFRESH_MEMINFO;
return true;
}
//--------------------------------------------------------------------------
// prepare suspend (don't acquire process_state_lock, it must be done by caller)
inline void suspend_on_semaphore(pin_local_event_t &ev)
{
enqueue_event(ev);
if ( !process_suspended() )
{
sema_clear(&run_app_sem);
process_state = APP_STATE_SUSPENDED;
DEBUG(2, "suspend_on_semaphore\n");
breakpoints.prepare_suspend();
}
}
//--------------------------------------------------------------------------
// prepare suspend (don't acquire process_state_lock, it must be done by caller)
inline void do_suspend(pin_local_event_t &ev)
{
if ( !listener_ready )
{
suspend_on_semaphore(ev);
return;
}
if ( process_suspended() )
{ // process already suspended - just add event to the queue
enqueue_event(ev);
}
else
{
DEBUG(3, "do_suspend\n");
breakpoints.prepare_suspend();
suspender.stop_threads(ev);
}
}
//--------------------------------------------------------------------------
// fill some common fields of event, add it to the queue and suspend process
inline bool suspend_at_event(pin_local_event_t &ev, bool use_sem)
{
janitor_for_pinlock_t process_state_guard(&process_state_lock);
if ( !process_detached() && !process_exiting() )
{
if ( use_sem )
suspend_on_semaphore(ev);
else
do_suspend(ev);
return true;
}
return false;
}
//--------------------------------------------------------------------------
inline bool wait_for_thread_termination(PIN_THREAD_UID tuid)
{
return PIN_WaitForThreadTermination(tuid, 10000, nullptr);
}
//--------------------------------------------------------------------------
// This function is called when the application exits
static VOID fini_cb(INT32 code, VOID *)
{
#ifndef _WIN32
// generate and send PROCESS_EXITED event
// (on Windows it was sent earlier by prepare_fini_cb)
pin_local_event_t evt(PROCESS_EXITED, thread_data_t::get_thread_id());
evt.debev.exit_code = code;
enqueue_event(evt);
PIN_SetExiting(); // terminate listener
#else
qnotused(code);
#endif
MSG("Waiting for internal threads to exit...\n");
instrumenter_t::finish();
bool ok = suspender.wait_termination();
if ( !ok )
MSG("Cannot stop suspender thread\n");
if ( !instrumenter_t::wait_termination() )
{
MSG("Cannot stop instrumenter thread\n");
ok = false;
}
if ( listener_uid != INVALID_PIN_THREAD_UID
&& !wait_for_thread_termination(listener_uid) )
{
MSG("Cannot stop listener thread\n");
ok = false;
}
if ( ok )
DEBUG(2, "FINI: Everything OK\n");
}
#if !defined(PIN_NUMERIC_BUILD) || PIN_NUMERIC_BUILD >= 76991
//--------------------------------------------------------------------------
// This function is called when the application exits
static VOID prepare_fini_cb(VOID *)
{
THREADID thr = thread_data_t::get_thread_id();
DEBUG(2, "PREPARE_FINI (thread = %d/main=%d)\n", thr, main_thread);
// THREAD_EXITED, PROCESS_EXITED events should be sent after all other ones -
// move them from suspender to the listener queue
suspender.copy_pending_events();
suspender.finish();
DEBUG(2, "PREPARE_FINI: Everything OK\n");
// on Windows ws2_32.dll can be unloaded before fini_cb and main thread's
// thread_fini_cb, so we cannot send events to IDA from them, the better
// place seems to be here. The problem is we do not have yet correct exit code
// here - just pass 0.
// Also we should terminate listener thread and send all remaining events here
#ifdef _WIN32
// terminate listener and wait for its termination
PIN_SetExiting();
for ( int i = 0; i <= RCV_TIMEOUT && listener_uid != INVALID_PIN_THREAD_UID; ++i )
PIN_Sleep(1);
// generate artifical THREAD_EXITED and PROCESS_EXITED events
int fake_code = 0;
pin_local_event_t exit_thr_ev(THREAD_EXITED, thr);
exit_thr_ev.debev.exit_code = fake_code;
enqueue_event(exit_thr_ev);
pin_local_event_t exit_ev(PROCESS_EXITED, thr);
exit_ev.debev.exit_code = fake_code;
enqueue_event(exit_ev);
// add the last empty event for read_handle_packet to be able to send ACK for
// the last event (PROCESS_EXITED), otherwise we can hang on Win10
pin_local_event_t last_empty_ev(NO_EVENT, INVALID_THREADID);
enqueue_event(last_empty_ev);
// send remaining events
while ( !events.empty() )
if ( !read_handle_packet() )
break;
#endif
}
#endif
//--------------------------------------------------------------------------