-
Notifications
You must be signed in to change notification settings - Fork 252
/
drmemory.c
2037 lines (1901 loc) · 77.6 KB
/
drmemory.c
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) 2010-2016 Google, Inc. All rights reserved.
* Copyright (c) 2007-2010 VMware, Inc. All rights reserved.
* **********************************************************/
/* Dr. Memory: the memory debugger
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License, and no later version.
* This library 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
* Library General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/* Dr. Memory: the memory debugger
* a.k.a. DRMemory == DynamoRIO Memory checker
*/
/* Features:
* Reads of uninitialized memory
* Including register definedness tracking
* Including system call in/out params
* TODO: bit-level checking
* Heap tracking:
* Access to unaddressable memory
* Redzones to catch overflow/underflow
* Access to freed memory: delay the actual free
* Double/invalid free
* Leaks
* TODO: app custom malloc interface
* Access to un-reserved TLS slots
*/
/* TODO: Multiple threads:
*
* - Pathological races between mallocs and frees can result in Dr. Memory's
* shadow memory structures becoming mis-aligned and subsequent false
* positives. However, such a scenario will always be preceded by either
* an invalid free error or a double free error.
*
* - General races between memory accesses and Dr. Memory's shadow memory
* can occur but errors will only occur with the presence of erroneous
* race conditions in the application.
*/
/***************************************************************************/
#include "dr_api.h"
#include "drwrap.h"
#include "drx.h"
#include "drcovlib.h"
#include "drmemory.h"
#include "instru.h"
#include "slowpath.h"
#include "fastpath.h"
#include "report.h"
#include "shadow.h"
#include "syscall.h"
#include "alloc_drmem.h"
#include "alloc.h"
#include "heap.h"
#include "replace.h"
#include "leak.h"
#include "stack.h"
#include "perturb.h"
#include <stddef.h> /* for offsetof */
#include "pattern.h"
#include "frontend.h"
#include "fuzzer.h"
#ifdef WINDOWS
# include "handlecheck.h"
#endif /* WINDOWS */
#ifdef USE_DRSYMS
# include "drsyms.h" /* for pre-loading pdbs on Vista */
# include "drsymcache.h"
#endif
char logsubdir[MAXIMUM_PATH];
#ifndef USE_DRSYMS
file_t f_fork = INVALID_FILE;
#else
file_t f_results = INVALID_FILE;
file_t f_missing_symbols;
file_t f_suppress;
file_t f_potential;
#endif
static uint num_threads;
#if defined(__DATE__) && defined(__TIME__)
static const char * const build_date = __DATE__ " " __TIME__;
#else
static const char * const build_date = "unknown";
#endif
/* store pages that contain known structures so we don't blanket-define them at init */
#define KNOWN_TABLE_HASH_BITS 8
static hashtable_t known_table;
static void
set_thread_initial_structures(void *drcontext);
client_id_t client_id;
int cls_idx_drmem = -1;
int tls_idx_drmem = -1;
volatile bool go_native;
static void
event_context_init(void *drcontext, bool new_depth);
static void
event_context_exit(void *drcontext, bool thread_exit);
/***************************************************************************
* OPTIONS
*/
static void
drmem_options_init(const char *opstr)
{
options_init(opstr);
/* set globals */
op_print_stderr = options.use_stderr && !options.quiet;
op_verbose_level = options.verbose;
op_pause_at_assert = options.pause_at_assert;
op_pause_via_loop = options.pause_via_loop;
op_ignore_asserts = options.ignore_asserts;
#ifdef USE_DRSYMS
op_use_symcache = options.use_symcache;
#endif
op_prefix_style = options.prefix_style;
}
/* Returns pointer to penultimate dir separator in string or NULL if can't find */
static const char *
up_one_dir(const char *string)
{
const char *dir1 = NULL, *dir2 = NULL;
while (*string != '\0') {
if (*string == DIRSEP IF_WINDOWS(|| *string == ALT_DIRSEP)) {
dir1 = dir2;
dir2 = string;
}
string++;
}
return dir1;
}
/* Places fname into our default config file path:
* dr_get_client_path()/../fname
*/
bool
obtain_configfile_path(char *buf OUT, size_t bufsz, const char *fname)
{
const char *mypath = dr_get_client_path(client_id);
/* Windows kernel doesn't like paths with .. (0xc0000033 =
* Object Name invalid) so we can't do just strrchr and add ..
*/
const char *sep = up_one_dir(mypath);
ASSERT(sep != NULL, "client lib path not absolute?");
ASSERT(sep - mypath < bufsz, "buffer too small");
if (sep != NULL && sep - mypath < bufsz) {
int len = dr_snprintf(buf, sep - mypath, "%s", mypath);
if (len == -1) {
len = dr_snprintf(buf + (sep - mypath), bufsz - (sep - mypath),
"%c%s", DIRSEP, fname);
return (len > 0);
}
}
return false;
}
/***************************************************************************
* GLOBALS AND STATISTICS
*/
#ifdef WINDOWS
app_pc ntdll_base;
app_pc ntdll_end;
#else
static app_pc libdr_base, libdr_end;
static app_pc libdr2_base, libdr2_end;
static app_pc libdrmem_base, libdrmem_end;
#endif
static app_pc client_base;
app_pc app_base;
app_pc app_end;
char app_path[MAXIMUM_PATH];
#ifdef STATISTICS
/* statistics
* FIXME: make per-thread to avoid races (or use locked inc)
* may want some of these to be 64-bit.
* some are now split off into stack.c
*/
uint num_nudges;
static uint pcaches_loaded;
static uint pcaches_mismatch;
static uint pcaches_written;
void
dump_statistics(void)
{
int i;
dr_fprintf(f_global, "Statistics:\n");
dr_fprintf(f_global, "nudges: %d\n", num_nudges);
dr_fprintf(f_global, "basic blocks: %d\n", num_bbs);
dr_fprintf(f_global, "adjust_esp:%10u slow; %10u fast\n", adjust_esp_executions,
adjust_esp_fastpath);
dr_fprintf(f_global, "slow_path invocations: %10u\n", slowpath_executions);
#ifdef X86
dr_fprintf(f_global, "med_path invocations: %10u, fast movs: %10u, fast cmps: %10u\n",
medpath_executions, movs4_med_fast, cmps1_med_fast);
dr_fprintf(f_global, "movs4: src unalign: %10u, dst unalign: %10u, src undef: %10u\n",
movs4_src_unaligned, movs4_dst_unaligned, movs4_src_undef);
dr_fprintf(f_global, "cmps1: src undef: %10u\n",
cmps1_src_undef);
#endif
dr_fprintf(f_global, "reads: slow: %8u, fast: %8u, fast4: %8u, total: %8u\n",
read_slowpath, read_fastpath, read4_fastpath,
read_slowpath+read_fastpath+read4_fastpath);
dr_fprintf(f_global, "writes: slow: %8u, fast: %8u, fast4: %8u, total: %8u\n",
write_slowpath, write_fastpath, write4_fastpath,
write_slowpath+write_fastpath+write4_fastpath);
dr_fprintf(f_global, "pushes: slow: %8u, fast: %8u, fast4: %8u, total: %8u\n",
push_slowpath, push_fastpath, push4_fastpath,
push_slowpath+push_fastpath+push4_fastpath);
dr_fprintf(f_global, "pops: slow: %8u, fast: %8u, fast4: %8u, total: %8u\n",
pop_slowpath, pop_fastpath, pop4_fastpath,
pop_slowpath+pop_fastpath+pop4_fastpath);
dr_fprintf(f_global, "slow instead of fast: %8u, b/c unaligned: %8u, 8@border: %8u\n",
slow_instead_of_fast, slowpath_unaligned, slowpath_8_at_border);
dr_fprintf(f_global, "app instrs: fastpath: %7u, no dup: %7u, xl8: %7u\n",
app_instrs_fastpath, app_instrs_no_dup, xl8_app_for_slowpath);
dr_fprintf(f_global, "addr exceptions: header: %7u, tls: %5u, alloca: %5u\n",
heap_header_exception, tls_exception, alloca_exception);
dr_fprintf(f_global, "more addr exceptions: ld DR: %5u, cpp DR: %5u\n",
loader_DRlib_exception, cppexcept_DRlib_exception);
dr_fprintf(f_global, "addr cont'd: strlen: %5u, strcpy: %5u, str/mem: %5u\n",
strlen_exception, strcpy_exception, strmem_unaddr_exception);
dr_fprintf(f_global, "def exceptions: andor: %7u, rawmemchr: %5u, strrchr: %5u\n",
andor_exception, rawmemchr_exception, strrchr_exception);
dr_fprintf(f_global, "more def exceptions: fldfst: %5u, strlen: %5u\n",
fldfst_exception, strlen_uninit_exception);
dr_fprintf(f_global, "bitfield exceptions: const %8u, xor %5u\n",
bitfield_const_exception, bitfield_xor_exception);
dr_fprintf(f_global, "reg spills: dead:%8u, xchg:%8u, spill:%8u slow:%8u own:%8u\n",
reg_dead, reg_xchg, reg_spill, reg_spill_slow, reg_spill_own);
dr_fprintf(f_global, "bb reg spills: used %8u, unused %8u\n",
reg_spill_used_in_bb, reg_spill_unused_in_bb);
dr_fprintf(f_global, "shadow blocks allocated: %6u, freed: %6u\n",
shadow_block_alloc, shadow_block_free);
dr_fprintf(f_global, "special shadow blocks, unaddr: %6u, undef: %6u, def: %6u\n",
num_special_unaddressable, num_special_undefined, num_special_defined);
dr_fprintf(f_global, "faults writing to special shadow blocks: %6u\n",
num_faults);
dr_fprintf(f_global, "faults to transition to slowpath: %6u\n",
num_slowpath_faults);
dr_fprintf(f_global, "app mallocs: %8u, frees: %8u, large mallocs: %6u\n",
num_mallocs, num_frees, num_large_mallocs);
dr_fprintf(f_global, "unique malloc stacks: %8u\n", alloc_stack_count);
callstack_dump_statistics(f_global);
#ifdef USE_DRSYMS
dr_fprintf(f_global, "symbol lookups: %6u cached %6u, searches: %6u cached %6u\n",
symbol_lookups, symbol_lookup_cache_hits,
symbol_searches, symbol_search_cache_hits);
dr_fprintf(f_global, "symbol address lookups: %6u\n", symbol_address_lookups);
#endif
dr_fprintf(f_global, "stack swaps: %8u, triggers: %8u\n",
stack_swaps, stack_swap_triggers);
dr_fprintf(f_global, "push addr tot: %8u heap: %6u mmap: %6u\n",
push_addressable, push_addressable_heap, push_addressable_mmap);
dr_fprintf(f_global, "delayed free bytes: %8u\n", delayed_free_bytes);
dr_fprintf(f_global, "app heap regions: %8u\n", heap_regions);
dr_fprintf(f_global, "addr checks elided: %8u\n", addressable_checks_elided);
dr_fprintf(f_global, "aflags saved at top: %8u\n", aflags_saved_at_top);
dr_fprintf(f_global, "xl8 sharing: %8u shared, %6u not:conflict, %6u not:disp-sz\n",
xl8_shared, xl8_not_shared_reg_conflict, xl8_not_shared_disp_too_big);
dr_fprintf(f_global,
"\t%6u not:slowpaths, %6u not:unalign, %6u not:mem2mem, %6u not:offs\n",
xl8_not_shared_slowpaths, xl8_not_shared_unaligned,
xl8_not_shared_mem2mem, xl8_not_shared_offs);
dr_fprintf(f_global, "\t%6u not:scratch conflict\n",
xl8_not_shared_scratch_conflict);
dr_fprintf(f_global, "\t%6u instrs slowpath, %6u count slowpath\n",
xl8_shared_slowpath_instrs, xl8_shared_slowpath_count);
#ifdef WINDOWS
dr_fprintf(f_global,
"encoded pointers: total: %5u, seen during leak scan: %5u\n",
pointers_encoded, encoded_pointers_scanned);
#endif
dr_fprintf(f_global,
"midchunk legit ptrs: %5u size, %5u new, %5u inheritance, %5u string\n",
midchunk_postsize_ptrs, midchunk_postnew_ptrs,
midchunk_postinheritance_ptrs, midchunk_string_ptrs);
dr_fprintf(f_global, "strings not pointers: %5u\n", strings_not_pointers);
#ifdef WINDOWS
if (options.check_handle_leaks)
handlecheck_dump_statistics(f_global);
#endif
if (options.perturb) {
perturb_dump_statistics(f_global);
}
if (options.leaks_only) {
dr_fprintf(f_global, "zeroing loop aborts: %6u fault, %6u thresh\n",
zero_loop_aborts_fault, zero_loop_aborts_thresh);
}
dr_fprintf(f_global, "pcaches loaded: %3u, base mismatch: %3u, written: %3u\n",
pcaches_loaded, pcaches_mismatch, pcaches_written);
dr_fprintf(f_global, "\nSystem calls invoked:\n");
for (i = 0; i < MAX_SYSNUM; i++) {
if (syscall_invoked[i] > 0) {
drsys_sysnum_t num = {i, 0};
dr_fprintf(f_global, "\t0x%04x %-40s %6u%s\n",
i, get_syscall_name(num), syscall_invoked[i],
syscall_is_known(num) ? "" : " <unknown>");
}
}
dr_fprintf(f_global, "\nPer-opcode slow path executions:\n");
for (i = 0; i <= OP_LAST; i++) {
if (slowpath_count[i] > 0) {
dr_fprintf(f_global, "\t%3u %10s: %12"UINT64_FORMAT_CODE"\n",
i, decode_opcode_name(i), slowpath_count[i]);
}
}
dr_fprintf(f_global, "\nPer-size slow path executions:\n");
dr_fprintf(f_global, "\t1-byte: %12"UINT64_FORMAT_CODE"\n", slowpath_sz1);
dr_fprintf(f_global, "\t2-byte: %12"UINT64_FORMAT_CODE"\n", slowpath_sz2);
dr_fprintf(f_global, "\t4-byte: %12"UINT64_FORMAT_CODE"\n", slowpath_sz4);
dr_fprintf(f_global, "\t8-byte: %12"UINT64_FORMAT_CODE"\n", slowpath_sz8);
dr_fprintf(f_global, "\t10-byte:%12"UINT64_FORMAT_CODE"\n", slowpath_sz10);
dr_fprintf(f_global, "\t16-byte:%12"UINT64_FORMAT_CODE"\n", slowpath_sz16);
dr_fprintf(f_global, "\tOther: %12"UINT64_FORMAT_CODE"\n", slowpath_szOther);
dr_fprintf(f_global, "\n");
}
#endif /* STATISTICS */
/***************************************************************************
* PERSISTENCE SUPPORT
*/
#define PCACHE_VERSION 0
typedef struct _persist_data_t {
/* version number */
uint version;
/* we have references into our library that we want to avoid patching
* so we require the same base (we set a preferred base and /dynamicbase:no)
*/
app_pc client_base;
/* options that affect what we persist */
bool shadowing;
} persist_data_t;
static size_t
event_persist_ro_size(void *drcontext, void *perscxt, size_t file_offs,
void **user_data OUT)
{
return sizeof(persist_data_t) +
instrument_persist_ro_size(drcontext, perscxt);
}
static bool
event_persist_ro(void *drcontext, void *perscxt, file_t fd, void *user_data)
{
persist_data_t pd = {PCACHE_VERSION, client_base, options.shadowing};
ASSERT(options.persist_code, "shouldn't get here");
if (!persistence_supported())
return false;
if (dr_write_file(fd, &pd, sizeof(pd)) != (ssize_t)sizeof(pd))
return false;
if (!instrument_persist_ro(drcontext, perscxt, fd))
return false;
STATS_INC(pcaches_written);
return true;
}
static bool
event_resurrect_ro(void *drcontext, void *perscxt, byte **map INOUT)
{
persist_data_t *pd = (persist_data_t *) *map;
*map += sizeof(*pd);
if (!persistence_supported())
return false;
if (pd->version != PCACHE_VERSION) {
WARN("WARNING: persisted cache version mismatch\n");
STATS_INC(pcaches_mismatch);
return false;
}
if (pd->client_base != client_base) {
WARN("WARNING: persisted base="PFX" does not match cur base="PFX"\n",
pd->client_base, client_base);
STATS_INC(pcaches_mismatch);
return false;
}
if (pd->shadowing != options.shadowing) {
WARN("WARNING: persisted cache shadowing mode does not match current mode\n");
STATS_INC(pcaches_mismatch);
return false;
}
if (!instrument_resurrect_ro(drcontext, perscxt, map))
return false;
STATS_INC(pcaches_loaded);
return true;
}
/***************************************************************************
* DYNAMORIO EVENTS
*/
static void
close_file(file_t f)
{
/* with DRi#357, DR now isolates log files so little to do here */
dr_close_file(f);
}
#define dr_close_file DO_NOT_USE_dr_close_file
static void
event_exit(void)
{
LOGF(2, f_global, "in event_exit\n");
check_reachability(true/*at exit*/);
if (options.pause_at_exit)
wait_for_user("pausing at exit");
#ifdef STATISTICS
dump_statistics();
#endif
instrument_exit();
if (options.perturb)
perturb_exit();
syscall_exit();
alloc_drmem_exit();
/* must be called after alloc_exit() */
heap_region_exit();
if (options.pattern != 0)
pattern_exit();
if (options.fuzz)
fuzzer_exit();
if (options.shadowing) {
shadow_exit();
if (umbra_exit() != DRMF_SUCCESS)
ASSERT(false, "fail to exit Umbra");
}
hashtable_delete(&known_table);
if (!options.perturb_only)
report_exit();
#ifdef USE_DRSYMS
if (options.use_symcache)
drsymcache_exit();
#endif
utils_exit();
if (options.coverage) {
const char *covfile;
if (drcovlib_logfile(NULL, &covfile) == DRCOVLIB_SUCCESS) {
ELOGF(0, f_results, "Code coverage raw data: %s"NL, covfile);
NOTIFY_COND(options.summary, f_global, "Code coverage raw data: %s"NL,
covfile);
}
if (drcovlib_exit() != DRCOVLIB_SUCCESS)
ASSERT(false, "failed to exit drcovlib");
}
drx_exit();
drmgr_unregister_tls_field(tls_idx_drmem);
drmgr_unregister_cls_field(event_context_init, event_context_exit, cls_idx_drmem);
drwrap_exit();
drmgr_exit();
#ifdef STATISTICS
/* Dump heap stats after most cleanup is done */
heap_dump_stats(f_global);
#endif
print_timestamp_elapsed_to_file(f_global, "Exiting ");
/* To help postprocess.pl to perform sideline processing of errors, we add
* a few markers to the log files.
*/
#ifndef USE_DRSYMS
/* Note that if we exit before a child starts up, the child will
* write to f_fork after we write LOG END.
*/
dr_fprintf(f_fork, "LOG END\n");
close_file(f_fork);
#else
close_file(f_results);
close_file(f_missing_symbols);
close_file(f_suppress);
close_file(f_potential);
#endif
dr_fprintf(f_global, "LOG END\n");
close_file(f_global);
/* There's no way to set the exit code other than exiting right away, so
* we do so only after all other cleanup (xref DRi#1400).
*/
if (!options.perturb_only)
report_exit_if_errors();
}
static file_t
open_logfile(const char *name, bool pid_log, int which_thread)
{
file_t f;
char logname[MAXIMUM_PATH];
IF_DEBUG(int len;)
uint extra_flags = IF_UNIX_ELSE(DR_FILE_ALLOW_LARGE, 0);
ASSERT(logsubdir[0] != '\0', "logsubdir not set up");
if (pid_log) {
IF_DEBUG(len = )
dr_snprintf(logname, BUFFER_SIZE_ELEMENTS(logname),
"%s%c%s.%d.log", logsubdir, DIRSEP, name, dr_get_process_id());
} else if (which_thread >= 0) {
IF_DEBUG(len = )
dr_snprintf(logname, BUFFER_SIZE_ELEMENTS(logname),
"%s%c%s.%d.%d.log", logsubdir, DIRSEP, name,
which_thread, dr_get_thread_id(dr_get_current_drcontext()));
/* have DR close on fork so we don't have to track and iterate */
extra_flags |= DR_FILE_CLOSE_ON_FORK;
} else {
IF_DEBUG(len = )
dr_snprintf(logname, BUFFER_SIZE_ELEMENTS(logname),
"%s%c%s", logsubdir, DIRSEP, name);
}
ASSERT(len > 0, "logfile name buffer max reached");
NULL_TERMINATE_BUFFER(logname);
f = dr_open_file(logname, DR_FILE_WRITE_OVERWRITE | extra_flags);
if (f == INVALID_FILE) {
NOTIFY_ERROR("Unable to open log file %s"NL, logname);
dr_abort();
}
if (which_thread > 0) {
void *drcontext = dr_get_current_drcontext();
dr_log(drcontext, LOG_ALL, 1,
"DrMemory: log for thread "TIDFMT" is %s\n",
dr_get_thread_id(drcontext), logname);
NOTIFY("thread logfile is %s"NL, logname);
}
return f;
}
static void
create_thread_logfile(void *drcontext)
{
file_t f;
uint which_thread = atomic_add32_return_sum((volatile int *)&num_threads, 1) - 1;
ELOGF(0, f_global, "new thread #%d id=%d\n",
which_thread, dr_get_thread_id(drcontext));
if (!options.thread_logs) {
f = f_global;
} else {
/* we're going to dump our data to a per-thread file */
f = open_logfile("thread", false, which_thread/*tid suffix*/);
LOGPT(1, PT_GET(drcontext), "thread logfile fd=%d\n", f);
}
utils_thread_set_file(drcontext, f);
}
static void
event_thread_init(void *drcontext)
{
static volatile int thread_count;
int local_count;
static bool first_thread = true;
tls_drmem_t *pt = (tls_drmem_t *)
thread_alloc(drcontext, sizeof(*pt), HEAPSTAT_MISC);
memset(pt, 0, sizeof(*pt));
drmgr_set_tls_field(drcontext, tls_idx_drmem, (void *)pt);
utils_thread_init(drcontext);
create_thread_logfile(drcontext);
LOGPT(2, PT_GET(drcontext), "in event_thread_init()\n");
instrument_thread_init(drcontext);
if (options.shadowing && !go_native) {
/* For 1st thread we can't get mcontext so we wait for 1st bb.
* For subsequent we can. Xref i#117/PR 395156.
* FIXME: other threads injected or created early like
* we've seen on Windows could mess this up.
*/
if (options.native_until_thread > 0)
set_thread_initial_structures(drcontext);
else if (!first_thread)
set_thread_initial_structures(drcontext);
}
if (options.shadowing)
shadow_thread_init(drcontext);
syscall_thread_init(drcontext);
if (!options.perturb_only)
report_thread_init(drcontext);
if (options.perturb)
perturb_thread_init();
if (options.native_until_thread > 0 || options.show_all_threads)
local_count = dr_atomic_add32_return_sum(&thread_count, 1);
if (options.show_all_threads && !first_thread) {
dr_mcontext_t mc;
#ifdef WINDOWS
app_pc start_addr;
# ifdef USE_DRSYMS
char buf[128];
size_t sofar = 0;
ssize_t len;
# endif
#endif
IF_DEBUG(bool ok;)
mc.size = sizeof(mc);
mc.flags = DR_MC_INTEGER | DR_MC_CONTROL;
IF_DEBUG(ok = )
dr_get_mcontext(drcontext, &mc);
ASSERT(ok, "unable to get mcontext for new thread");
#ifdef WINDOWS
start_addr = (app_pc) IF_X64_ELSE(mc.rcx, mc.eax);
# ifdef USE_DRSYMS
BUFPRINT(buf, BUFFER_SIZE_ELEMENTS(buf), sofar, len,
"Thread #%d @", local_count);
print_timestamp_elapsed(buf, BUFFER_SIZE_ELEMENTS(buf), &sofar);
# ifdef STATISTICS
BUFPRINT(buf, BUFFER_SIZE_ELEMENTS(buf), sofar, len, " #bbs=%d", num_bbs);
# endif
BUFPRINT(buf, BUFFER_SIZE_ELEMENTS(buf), sofar, len,
" start="PFX" ", start_addr);
print_symbol(start_addr, buf, BUFFER_SIZE_ELEMENTS(buf), &sofar,
true, PRINT_SYMBOL_OFFSETS);
LOG(1, "%s\n", buf);
# else
LOG(1, "New thread #%d: start addr "PFX"\n", local_count, start_addr);
# endif
#else
LOG(1, "New thread #%d\n", local_count);
#endif
}
if (options.native_until_thread > 0) {
NOTIFY("@@@@@@@@@@@@@ new thread #%d %d" NL,
local_count, dr_get_thread_id(drcontext));
if (go_native && local_count == options.native_until_thread) {
void **drcontexts = NULL;
uint num_threads, i;
go_native = false;
NOTIFY("thread "TIDFMT" suspending all threads" NL,
dr_get_thread_id(drcontext));
if (dr_suspend_all_other_threads_ex(&drcontexts, &num_threads, NULL,
DR_SUSPEND_NATIVE)) {
NOTIFY("suspended %d threads" NL, num_threads);
for (i = 0; i < num_threads; i++) {
if (dr_is_thread_native(drcontexts[i])) {
NOTIFY("\txxx taking over thread #%d %d" NL,
i, dr_get_thread_id(drcontexts[i]));
dr_retakeover_suspended_native_thread(drcontexts[i]);
} else {
NOTIFY("\tthread #%d %d under DR" NL,
i, dr_get_thread_id(drcontexts[i]));
}
if (options.shadowing)
set_thread_initial_structures(drcontexts[i]);
}
set_initial_layout();
if (!dr_resume_all_other_threads(drcontexts, num_threads)) {
ASSERT(false, "failed to resume threads");
}
} else {
ASSERT(false, "failed to suspend threads");
}
}
}
if (first_thread) /* 1st thread: no lock needed */
first_thread = false;
}
static void
event_thread_exit(void *drcontext)
{
tls_drmem_t *pt = (tls_drmem_t *) drmgr_get_tls_field(drcontext, tls_idx_drmem);
LOGPT(2, PT_GET(drcontext), "in event_thread_exit() %d\n",
dr_get_thread_id(drcontext));
if (options.perturb)
perturb_thread_exit();
if (!options.perturb_only)
report_thread_exit(drcontext);
if (options.thread_logs) {
file_t f = LOGFILE_GET(drcontext);
dr_fprintf(f, "LOG END\n");
close_file(f);
}
#ifdef WINDOWS
if (options.shadowing && !go_native) {
/* the kernel de-allocs teb so we need to explicitly handle it */
/* use cached teb since can't query for some threads (i#442) */
tls_drmem_t *pt = (tls_drmem_t *) drmgr_get_tls_field(drcontext, tls_idx_drmem);
TEB *teb = pt->teb;
ASSERT(teb != NULL, "cannot determine TEB for exiting thread");
shadow_set_range((app_pc)teb, (app_pc)teb + sizeof(*teb), SHADOW_UNADDRESSABLE);
/* pass cached teb to leak scan (i#547) in place we won't free */
set_thread_tls_value(drcontext, SPILL_SLOT_1, (ptr_uint_t)teb);
}
#endif
syscall_thread_exit(drcontext);
if (options.shadowing)
shadow_thread_exit(drcontext);
instrument_thread_exit(drcontext);
utils_thread_exit(drcontext);
/* with PR 536058 we do have dcontext in exit event so indicate explicitly
* that we've cleaned up the per-thread data
*/
drmgr_set_tls_field(drcontext, tls_idx_drmem, NULL);
thread_free(drcontext, pt, sizeof(*pt), HEAPSTAT_MISC);
}
static void
event_context_init(void *drcontext, bool new_depth)
{
cls_drmem_t *data;
if (new_depth) {
data = (cls_drmem_t *) thread_alloc(drcontext, sizeof(*data), HEAPSTAT_MISC);
drmgr_set_cls_field(drcontext, cls_idx_drmem, data);
} else
data = (cls_drmem_t *) drmgr_get_cls_field(drcontext, cls_idx_drmem);
memset(data, 0, sizeof(*data));
}
static void
event_context_exit(void *drcontext, bool thread_exit)
{
if (thread_exit) {
cls_drmem_t *data = (cls_drmem_t *) drmgr_get_cls_field(drcontext, cls_idx_drmem);
thread_free(drcontext, data, sizeof(*data), HEAPSTAT_MISC);
}
/* else, nothing to do: we leave the struct for re-use on next callback */
}
#ifdef UNIX
bool
is_in_client_or_DR_lib(app_pc pc)
{
return ((pc >= libdr_base && pc < libdr_end) ||
(pc >= libdr2_base && pc < libdr2_end) ||
(pc >= libdrmem_base && pc < libdrmem_end) ||
(pc >= syscall_auxlib_start() && pc < syscall_auxlib_end()));
}
#endif
/* It's ok for start to not be the allocation base but then probably
* best to use 0 for size since start+size will be a limit if size != 0.
* Pass 0 for size to walk an entire module or allocation region.
*/
byte *
mmap_walk(app_pc start, size_t size,
IF_WINDOWS_(MEMORY_BASIC_INFORMATION *mbi_start) bool add)
{
#ifdef WINDOWS
app_pc start_base;
app_pc pc = start;
MEMORY_BASIC_INFORMATION mbi = {0};
app_pc map_base = mbi.AllocationBase;
app_pc map_end = (byte *)mbi.AllocationBase + mbi.RegionSize;
ASSERT(options.shadowing, "shadowing disabled");
if (mbi_start == NULL) {
if (dr_virtual_query(start, &mbi, sizeof(mbi)) != sizeof(mbi)) {
ASSERT(false, "error walking initial memory mappings");
return pc; /* FIXME: return error code */
}
} else
mbi = *mbi_start;
if (mbi.State == MEM_FREE)
return pc;
map_base = mbi.AllocationBase;
start_base = map_base;
map_end = (byte *)mbi.AllocationBase + mbi.RegionSize;
LOG(2, "mmap_walk %s "PFX": alloc base is "PFX"\n", add ? "add" : "remove",
start, start_base);
if (mbi.State == MEM_RESERVE)
map_end = map_base;
if (POINTER_OVERFLOW_ON_ADD(pc, mbi.RegionSize))
return NULL;
pc += mbi.RegionSize;
while (dr_virtual_query(pc, &mbi, sizeof(mbi)) == sizeof(mbi) &&
mbi.AllocationBase == start_base /*not map_base: we skip reserved pieces*/ &&
(size == 0 || pc < start+size)) {
ASSERT(mbi.State != MEM_FREE, "memory walk error");
if (mbi.State == MEM_RESERVE) {
/* set up until pc, then start accumulating again after it
* unlike Linux /proc/pid/maps the .bss is embedded inside the IMAGE region
*/
LOG(2, "\tpiece "PFX"-"PFX"\n", map_base, map_end);
shadow_set_range(map_base, map_end,
add ? SHADOW_DEFINED : SHADOW_UNADDRESSABLE);
map_base = map_end + mbi.RegionSize;
map_end = map_base;
} else {
/* best to batch adjacent committed image/data regions together */
map_end += mbi.RegionSize;
}
if (POINTER_OVERFLOW_ON_ADD(pc, mbi.RegionSize))
return NULL;
pc += mbi.RegionSize;
}
if (map_end > map_base) {
shadow_set_range(map_base, map_end, add ? SHADOW_DEFINED : SHADOW_UNADDRESSABLE);
LOG(2, "\tpiece "PFX"-"PFX"\n", map_base, map_end);
}
return pc;
#else /* WINDOWS */
dr_mem_info_t info;
module_data_t *data;
app_pc pc, module_end;
ASSERT(options.shadowing, "shadowing disabled");
/* we assume that only a module will have multiple pieces with different prots */
data = dr_lookup_module(start);
if (data != NULL) {
module_end = data->end;
} else {
module_end = start + PAGE_SIZE;
}
dr_free_module_data(data);
LOG(2, "mmap_walk %s "PFX"\n", add ? "add" : "remove", start);
pc = start;
/* Be wary of SIGBUS if we read into .bss before it's set up: PR 528744 */
while (pc < module_end && (size == 0 || pc < start+size)) {
if (!dr_query_memory_ex(pc, &info)) {
/* failed: bail */
break;
}
ASSERT(pc >= info.base_pc && pc < info.base_pc + info.size, "mem query error");
#ifdef DEBUG
/* can be data region that has a piece unmapped later, or can have
* mmaps merged together (PR 475114)
*/
if (add && pc != info.base_pc) {
LOG(1, "WARNING: mmap_walk "PFX": subsection "PFX" != query "PFX"\n",
start, pc, info.base_pc);
}
#endif
ASSERT(ALIGNED(pc, PAGE_SIZE), "memory iterator not page aligned");
if (info.prot == DR_MEMPROT_NONE) {
/* A hole in a module, probably due to alignment */
if (!add) /* just in case */
shadow_set_range(pc, pc+info.size, SHADOW_UNADDRESSABLE);
pc = info.base_pc + info.size;
continue;
}
LOG(2, "\tmmap piece "PFX"-"PFX" prot=%x\n", pc, pc+info.size, info.prot);
shadow_set_range(pc, info.base_pc + info.size,
add ? SHADOW_DEFINED : SHADOW_UNADDRESSABLE);
pc = info.base_pc + info.size;
}
return pc;
#endif /* WINDOWS */
}
static void
memory_walk(void)
{
#ifdef WINDOWS
TEB *teb = get_TEB();
app_pc pc = NULL;
MEMORY_BASIC_INFORMATION mbi;
uint type = 0;
void *drcontext = dr_get_current_drcontext();
LOG(2, "walking memory looking for images\n");
ASSERT(!dr_using_app_state(drcontext), "state error");
dr_switch_to_app_state_ex(drcontext, DR_STATE_STACK_BOUNDS);
/* Strategy: walk through every block in memory
*/
while (dr_virtual_query(pc, &mbi, sizeof(mbi)) == sizeof(mbi)) {
ASSERT(pc == mbi.BaseAddress, "memory walk error");
/* Memory mapped data or image is always addressable and defined.
* We consider heap to be unaddressable until fine-grained allocated.
*/
if (mbi.State != MEM_FREE) {
LOG(3, "mem walk: "PFX"-"PFX"\n",
mbi.BaseAddress, (app_pc)mbi.BaseAddress+mbi.RegionSize);
if (mbi.Type == MEM_IMAGE || mbi.Type == MEM_MAPPED) {
ASSERT(mbi.BaseAddress == mbi.AllocationBase, "memory walk error");
/* Due to PE section alignment there can be unaddressable regions
* inside a mapped file. Optimization: can we always
* avoid the walk for MEM_MAPPED?
*/
pc = mmap_walk(pc, 0, &mbi, true/*add*/);
if (pc == NULL)
break;
else
continue;
} else if (mbi.State == MEM_COMMIT) {
if ((app_pc)mbi.BaseAddress !=
(app_pc)teb->StackLimit - PAGE_SIZE/*guard page*/ &&
mbi.BaseAddress != teb->StackLimit &&
!is_in_heap_region(mbi.AllocationBase) &&
!dr_memory_is_dr_internal(mbi.AllocationBase) &&
!dr_memory_is_in_client(mbi.AllocationBase) &&
# ifdef X64 /* For 32-bit shadow memory will all be DR memory */
!shadow_memory_is_shadow(mbi.AllocationBase) &&
# endif
/* Avoid teb, peb, env, etc. pages where we have finer-grained
* information. We assume it's sufficient to look only at
* the start of the region.
*/
hashtable_lookup(&known_table, (void*)PAGE_START(pc)) == NULL) {
/* what can we do? we assume it's all defined */
LOG(2, "initial unknown committed region "PFX"-"PFX"\n",
mbi.BaseAddress, (app_pc)mbi.BaseAddress+mbi.RegionSize);
/* FIXME PR 406328: mark no-access regions as unaddressable,
* and watch mprotect so can shift back and forth
*/
shadow_set_range((app_pc)mbi.BaseAddress,
(app_pc)mbi.BaseAddress+mbi.RegionSize,
SHADOW_DEFINED);
/* The heap walk should have added any mmapped chunks so
* we assume we don't need to add this to the malloc table
* and it will never have free() called on it.
*/
}
}
}
if (POINTER_OVERFLOW_ON_ADD(pc, mbi.RegionSize))
break;
pc += mbi.RegionSize;
}
dr_switch_to_dr_state_ex(drcontext, DR_STATE_STACK_BOUNDS);
#else /* WINDOWS */
/* Full memory walk should cover module innards.
* If not we could do module iterator plus mmap_walk().
*/
dr_mem_info_t info;
app_pc pc = NULL, end;
app_pc pc_to_add;
uint type = 0;
# ifdef LINUX
app_pc cur_brk = get_brk(true/*pre-us*/);
LOG(2, "brk="PFX"\n", cur_brk);
# endif
while (pc < (app_pc)POINTER_MAX && dr_query_memory_ex(pc, &info)) {
end = info.base_pc+info.size;
pc_to_add = NULL;
LOG(2, " query "PFX"-"PFX" prot=%x type=%d\n",
info.base_pc, end, info.prot, info.type);
ASSERT(pc == info.base_pc ||
/* PR 424012: DR memory regions change via commit-on-demand */
dr_memory_is_dr_internal(info.base_pc), "memory iterator mismatch");
ASSERT(ALIGNED(pc, PAGE_SIZE), "memory iterator not page aligned");
if (dr_memory_is_in_client(info.base_pc)) {
/* leave client memory unaddressable */
LOG(2, " => client memory\n");
/* FIXME: Currently dr_memory_is_in_client() returns true only if
* the address argument is inside a client library, but that can
* change in future and any memory (library, bss, mmaps, heap
* alloc) used by a client can make it return true. In that case
* the fix is to identify if the address in question is inside a
* module or not and then decide whether it should be shadowed.
* This can be done by using a linker defined variable to find a
* section address and then computing the client library base from
* that.
* FIXME: If there are multiple client libraries, Derek, was
* concerned about marking a whole library as shadowable region
* because pc was in the first library. I don't that will happen
* because page protections will change between bss & image, thus
* mmap regions of two different client libraries won't get merged.
* Still check when doing multiple clients.
*/
/* PR 483720: app memory merged to the end of drmem's bss.
* XXX: i#1295 should remove the need for this on the drmem lib,
* but we leave this in place for running w/o default options.
* We still need the DR lib bss split code.
*/
if (info.base_pc >= libdrmem_base && info.base_pc < libdrmem_end &&
end > libdrmem_end) {
LOG(2, " Dr. Memory library memory ends @ "PFX", merged by kernel\n",
libdrmem_end);
pc_to_add = libdrmem_end;
type = SHADOW_DEFINED;
} else if (info.base_pc >= syscall_auxlib_start() &&
info.base_pc < syscall_auxlib_end() &&