-
Notifications
You must be signed in to change notification settings - Fork 570
/
Copy pathdynamo.c
3523 lines (3208 loc) · 128 KB
/
dynamo.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-2024 Google, Inc. All rights reserved.
* Copyright (c) 2000-2010 VMware, Inc. All rights reserved.
* **********************************************************/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of VMware, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/* Copyright (c) 2003-2007 Determina Corp. */
/* Copyright (c) 2001-2003 Massachusetts Institute of Technology */
/* Copyright (c) 2000-2001 Hewlett-Packard Company */
/*
* dynamo.c -- initialization and cleanup routines for DynamoRIO
*/
#include "globals.h"
#include "configure_defines.h"
#include "link.h"
#include "fragment.h"
#include "fcache.h"
#include "emit.h"
#include "dispatch.h"
#include "utils.h"
#include "monitor.h"
#include "vmareas.h"
#ifdef SIDELINE
# include "sideline.h"
#endif
#ifdef PAPI
# include "perfctr.h"
#endif
#include "instrument.h"
#include "hotpatch.h"
#include "moduledb.h"
#include "module_shared.h"
#include "synch.h"
#include "native_exec.h"
#include "jit_opt.h"
#ifdef ANNOTATIONS
# include "annotations.h"
#endif
#ifdef WINDOWS
/* for close handle, duplicate handle, free memory and constants associated with them
*/
/* also for nt_terminate_process_for_app() */
# include "ntdll.h"
# include "nudge.h" /* to get generic_nudge_target() address for an assert */
#endif
#ifdef RCT_IND_BRANCH
# include "rct.h"
#endif
#include "perscache.h"
#ifdef VMX86_SERVER
# include "vmkuw.h"
#endif
#ifndef STANDALONE_UNIT_TEST
# ifdef __AVX512F__
# error "DynamoRIO core should run without AVX-512 instructions to remain \
portable and to avoid frequency scaling."
# endif
#endif
/* global thread-shared variables */
bool dynamo_initialized = false;
static bool dynamo_options_initialized = false;
bool dynamo_heap_initialized = false;
bool dynamo_started = false;
bool automatic_startup = false;
bool control_all_threads = false;
/* On Windows we can't really tell attach apart from our default late
* injection, and we do see early threads in place which is the point of
* this flag: so we always set it.
*/
bool dynamo_control_via_attach = IF_WINDOWS_ELSE(true, false);
#ifdef WINDOWS
bool dr_early_injected = false;
int dr_early_injected_location = INJECT_LOCATION_Invalid;
bool dr_earliest_injected = false;
static void *dr_earliest_inject_args;
/* should be set if we are controlling the primary thread, either by
* injecting initially (!dr_injected_secondary_thread), or by retaking
* over (dr_late_injected_primary_thread). Used only for debugging
* purposes, yet can't rely on !dr_injected_secondary_thread very
* early in the process
*/
bool dr_injected_primary_thread = false;
bool dr_injected_secondary_thread = false;
/* should be set once we retakeover the primary thread for -inject_primary */
bool dr_late_injected_primary_thread = false;
#endif /* WINDOWS */
/* flags to indicate when DR is being initialized / exited using the API */
bool dr_api_entry = false;
bool dr_api_exit = false;
#ifdef RETURN_AFTER_CALL
bool dr_preinjected = false;
#endif /* RETURN_AFTER_CALL */
#ifdef UNIX
static bool dynamo_exiting = false;
#endif
bool dynamo_exited = false;
bool dynamo_exited_all_other_threads = false;
bool dynamo_exited_and_cleaned = false;
#ifdef DEBUG
bool dynamo_exited_log_and_stats = false;
#endif
/* Only used in release build to decide whether synch is needed, justifying
* its placement in .nspdata. If we use it for more we should protect it.
*/
DECLARE_NEVERPROT_VAR(bool dynamo_all_threads_synched, false);
bool dynamo_resetting = false;
bool standalone_library = false;
static int standalone_init_count;
#ifdef UNIX
bool post_execve = false;
#endif
/* initial stack so we don't have to use app's */
byte *d_r_initstack;
event_t dr_app_started;
event_t dr_attach_finished;
#ifdef WINDOWS
/* PR203701: separate stack for error reporting when the dstack is exhausted */
# define EXCEPTION_STACK_SIZE (2 * PAGE_SIZE)
DECLARE_NEVERPROT_VAR(byte *exception_stack, NULL);
#endif
/*******************************************************/
/* separate segment of Non-Self-Protected data to avoid data section
* protection issues -- we need to write to these vars in bootstrapping
* spots where we cannot unprotect first
*/
START_DATA_SECTION(NEVER_PROTECTED_SECTION, "w");
/* spinlock used in assembly trampolines when we can't spare registers for more */
mutex_t initstack_mutex IF_AARCH64(__attribute__((aligned(8))))
VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = INIT_SPINLOCK_FREE(initstack_mutex);
byte *initstack_app_xsp VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = 0;
/* keeps track of how many threads are in cleanup_and_terminate */
volatile int exiting_thread_count VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = 0;
/* Tracks newly created threads not yet on the all_threads list. */
volatile int uninit_thread_count VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = 0;
/* This is unprotected to allow stats to be written while the data
* segment is still protected (right now the only ones are selfmod stats)
*/
static dr_statistics_t nonshared_stats VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = {
{ 0 },
};
/* Each lock protects its corresponding datasec_start, datasec_end, and
* datasec_writable variables.
*/
static mutex_t
datasec_lock[DATASEC_NUM] VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = { { 0 } };
/* back to normal section */
END_DATA_SECTION()
/*******************************************************/
/* Like a recursive lock: 0==readonly, 1+=writable.
* This would be a simple array, but we need each in its own protected
* section, as this could be exploited.
*/
const uint datasec_writable_neverprot = 1; /* always writable */
uint datasec_writable_rareprot = 1;
DECLARE_FREQPROT_VAR(uint datasec_writable_freqprot, 1);
DECLARE_CXTSWPROT_VAR(uint datasec_writable_cxtswprot, 1);
static app_pc datasec_start[DATASEC_NUM];
static app_pc datasec_end[DATASEC_NUM];
const uint DATASEC_SELFPROT[] = {
0,
SELFPROT_DATA_RARE,
SELFPROT_DATA_FREQ,
SELFPROT_DATA_CXTSW,
};
const char *const DATASEC_NAMES[] = {
NEVER_PROTECTED_SECTION,
RARELY_PROTECTED_SECTION,
FREQ_PROTECTED_SECTION,
CXTSW_PROTECTED_SECTION,
};
/* kept in unprotected heap to avoid issues w/ data segment being RO */
typedef struct _protect_info_t {
/* FIXME: this needs to be a recursive lock to handle signals
* and exceptions!
*/
mutex_t lock;
int num_threads_unprot; /* # threads in DR code */
int num_threads_suspended;
} protect_info_t;
static protect_info_t *protect_info;
static void
data_section_init(void);
static void
data_section_exit(void);
#ifdef DEBUG /*************************/
# include <time.h>
/* FIXME: not all dynamo_options references are #ifdef DEBUG
* are we trying to hardcode the options for a release build?
*/
# ifdef UNIX
/* linux include files for mmap stuff*/
# include <sys/ipc.h>
# include <sys/types.h>
# include <unistd.h>
# endif
static uint starttime;
file_t main_logfile = INVALID_FILE;
#endif /* DEBUG ****************************/
dr_statistics_t *d_r_stats = NULL;
DECLARE_FREQPROT_VAR(static int num_known_threads, 0);
#ifdef UNIX
/* i#237/PR 498284: vfork threads that execve need to be separately delay-freed */
DECLARE_FREQPROT_VAR(int num_execve_threads, 0);
#endif
DECLARE_FREQPROT_VAR(static uint threads_ever_count, 0);
/* FIXME : not static so os.c can hand walk it for dump core */
/* FIXME: use new generic_table_t and generic_hash_* routines */
thread_record_t **all_threads; /* ALL_THREADS_HASH_BITS-bit addressed hash table */
/* these locks are used often enough that we put them in .cspdata: */
/* not static so can be referenced in win32/os.c for SuspendThread handling,
* FIXME : is almost completely redundant in usage with thread_initexit_lock
* maybe replace this lock with thread_initexit_lock? */
DECLARE_CXTSWPROT_VAR(mutex_t all_threads_lock, INIT_LOCK_FREE(all_threads_lock));
/* used for synch to prevent thread creation/deletion in critical periods
* due to its use for flushing, this lock cannot be held while couldbelinking!
*/
DECLARE_CXTSWPROT_VAR(mutex_t thread_initexit_lock, INIT_LOCK_FREE(thread_initexit_lock));
/* recursive to handle signals/exceptions while in DR code */
DECLARE_CXTSWPROT_VAR(static recursive_lock_t thread_in_DR_exclusion,
INIT_RECURSIVE_LOCK(thread_in_DR_exclusion));
static thread_synch_state_t
exit_synch_state(void);
static void
synch_with_threads_at_exit(thread_synch_state_t synch_res, bool pre_exit);
static void
delete_dynamo_context(dcontext_t *dcontext, bool free_stack);
/****************************************************************************/
#ifdef DEBUG
static const char *
main_logfile_name(void)
{
return get_app_name_for_path();
}
static const char *
thread_logfile_name(void)
{
return "log";
}
#endif /* DEBUG */
/****************************************************************************/
static void
statistics_pre_init(void)
{
/* until it's set up for real, point at static var
* really only logmask and loglevel are meaningful, so be careful!
* statistics_init and create_log_directory are the only routines that
* use stats before it's set up for real, currently
*/
/* The indirection here is left over from when we used to allow alternative
* locations for stats (namely shared memory for the old MIT gui). */
d_r_stats = &nonshared_stats;
d_r_stats->process_id = get_process_id();
strncpy(d_r_stats->process_name, get_application_name(), MAXIMUM_PATH);
d_r_stats->process_name[MAXIMUM_PATH - 1] = '\0';
ASSERT(strlen(d_r_stats->process_name) > 0);
d_r_stats->num_stats = 0;
}
static void
statistics_init(void)
{
/* should have called statistics_pre_init() first */
ASSERT(d_r_stats == &nonshared_stats);
ASSERT(d_r_stats->num_stats == 0);
#ifndef DEBUG
if (!DYNAMO_OPTION(global_rstats)) {
/* references to stat values should return 0 (static var) */
return;
}
#endif
d_r_stats->num_stats = 0
#ifdef DEBUG
# define STATS_DEF(desc, name) +1
#else
# define RSTATS_DEF(desc, name) +1
#endif
#include "statsx.h"
#undef STATS_DEF
#undef RSTATS_DEF
;
/* We inline the stat description to make it easy for external processes
* to view our stats: they don't have to chase pointers, and we could put
* this in shared memory easily. However, we do waste some memory, but
* not much in release build.
*/
#ifdef DEBUG
# define STATS_DEF(desc, statname) \
strncpy(d_r_stats->statname##_pair.name, desc, \
BUFFER_SIZE_ELEMENTS(d_r_stats->statname##_pair.name)); \
NULL_TERMINATE_BUFFER(d_r_stats->statname##_pair.name);
#else
# define RSTATS_DEF(desc, statname) \
strncpy(d_r_stats->statname##_pair.name, desc, \
BUFFER_SIZE_ELEMENTS(d_r_stats->statname##_pair.name)); \
NULL_TERMINATE_BUFFER(d_r_stats->statname##_pair.name);
#endif
#include "statsx.h"
#undef STATS_DEF
#undef RSTATS_DEF
}
static void
statistics_exit(void)
{
if (doing_detach)
memset(d_r_stats, 0, sizeof(*d_r_stats)); /* for possible re-attach */
d_r_stats = NULL;
}
dr_statistics_t *
get_dr_stats(void)
{
return d_r_stats;
}
/* initialize per-process dynamo state; this must be called before any
* threads are created and before any other API calls are made;
* returns zero on success, non-zero on failure
*/
DYNAMORIO_EXPORT int
dynamorio_app_init(void)
{
dynamorio_app_init_part_one_options();
return dynamorio_app_init_part_two_finalize();
}
void
dynamorio_app_init_part_one_options(void)
{
if (dynamo_initialized || dynamo_options_initialized) {
if (standalone_library) {
REPORT_FATAL_ERROR_AND_EXIT(STANDALONE_ALREADY, 2, get_application_name(),
get_application_pid());
}
} else /* we do enter if nullcalls is on */ {
#ifdef UNIX
os_page_size_init((const char **)our_environ, is_our_environ_followed_by_auxv());
#endif
#ifdef WINDOWS
/* MUST do this before making any system calls */
syscalls_init();
#endif
/* avoid time() for libc independence */
DODEBUG(starttime = query_time_seconds(););
#ifdef UNIX
if (getenv(DYNAMORIO_VAR_EXECVE) != NULL) {
post_execve = true;
# ifdef VMX86_SERVER
/* PR 458917: our gdt slot was not cleared on exec so we need to
* clear it now to ensure we don't leak it and eventually run out of
* slots. We could alternatively call os_tls_exit() prior to
* execve, since syscalls use thread-private fcache_enter, but
* complex to recover from execve failure, so instead we pass which
* TLS index we had.
*/
os_tls_pre_init(atoi(getenv(DYNAMORIO_VAR_EXECVE)));
# endif
/* important to remove it, don't want to propagate to forked children, etc. */
/* i#909: unsetenv is unsafe as it messes up auxv access, so we disable */
disable_env(DYNAMORIO_VAR_EXECVE);
/* check that it's gone: we've had problems with unsetenv */
ASSERT(getenv(DYNAMORIO_VAR_EXECVE) == NULL);
} else
post_execve = false;
#endif
/* default non-zero dynamo settings (options structure is
* initialized to 0 automatically)
*/
#ifdef DEBUG
# ifndef INTERNAL
nonshared_stats.logmask = LOG_ALL_RELEASE;
# else
nonshared_stats.logmask = LOG_ALL;
# endif
statistics_pre_init();
#endif
d_r_config_init();
options_init();
#ifdef WINDOWS
syscalls_init_options_read(); /* must be called after options_init
* but before init_syscall_trampolines */
#endif
utils_init();
data_section_init();
#ifdef DEBUG
/* decision: nullcalls WILL create a dynamorio.log file and
* fill it with perfctr stats!
*/
if (d_r_stats->loglevel > 0) {
main_logfile = open_log_file(main_logfile_name(), NULL, 0);
LOG(GLOBAL, LOG_TOP, 1, "global log file fd=%d\n", main_logfile);
} else {
/* loglevel 0 means we don't create a log file!
* if the loglevel is later raised, too bad! it all goes to stderr!
* N.B.: when checking for no logdir, we check for empty string or
* first char '<'!
*/
strncpy(d_r_stats->logdir, "<none (loglevel was 0 on startup)>",
MAXIMUM_PATH - 1);
d_r_stats->logdir[MAXIMUM_PATH - 1] = '\0'; /* if max no null */
main_logfile = INVALID_FILE;
}
# ifdef PAPI
/* setup hardware performance counting */
hardware_perfctr_init();
# endif
DOLOG(1, LOG_TOP, { print_version_and_app_info(GLOBAL); });
/* now exit if nullcalls, now that perfctrs are set up */
if (INTERNAL_OPTION(nullcalls)) {
return;
}
LOG(GLOBAL, LOG_TOP, 1, PRODUCT_NAME "'s stack size: %d Kb\n",
DYNAMORIO_STACK_SIZE / 1024);
#endif /* !DEBUG */
/* set up exported statistics struct */
#ifndef DEBUG
statistics_pre_init();
#endif
statistics_init();
dynamo_options_initialized = true;
}
}
int
dynamorio_app_init_part_two_finalize(void)
{
if (!dynamo_options_initialized) {
/* Part one was never called. */
return FAILURE;
} else if (dynamo_initialized) {
if (standalone_library) {
REPORT_FATAL_ERROR_AND_EXIT(STANDALONE_ALREADY, 2, get_application_name(),
get_application_pid());
}
/* Nop. */
} else if (INTERNAL_OPTION(nullcalls)) {
print_file(main_logfile, "** nullcalls is set, NOT taking over execution **\n\n");
return SUCCESS;
} else {
#ifdef VMX86_SERVER
/* Must be before {vmm,d_r}_heap_init() */
vmk_init_lib();
#endif
/* initialize components (CAUTION: order is important here) */
vmm_heap_init(); /* must be called even if not using vmm heap */
/* PR 200207: load the client lib before callback_interception_init
* since the client library load would hit our own hooks (xref hotpatch
* cases about that) -- though -private_loader removes that issue.
*/
instrument_load_client_libs();
d_r_heap_init();
dynamo_heap_initialized = true;
/* The process start event should be done after d_r_os_init() but before
* process_control_int() because the former initializes event logging
* and the latter can kill the process if a violation occurs.
*/
SYSLOG(SYSLOG_INFORMATION, INFO_PROCESS_START_CLIENT, 2, get_application_name(),
get_application_pid());
#ifdef PROCESS_CONTROL
if (IS_PROCESS_CONTROL_ON()) /* Case 8594. */
process_control_init();
#endif
#ifdef WINDOWS
/* Now that DR is set up, perform any final clean-up, before
* we do our address space scans.
*/
if (dr_earliest_injected)
earliest_inject_cleanup(dr_earliest_inject_args);
#endif
dynamo_vm_areas_init();
d_r_decode_init();
proc_init();
modules_init(); /* before vm_areas_init() */
d_r_os_init();
config_heap_init(); /* after heap_init */
/* Setup for handling faults in loader_init() */
/* initial stack so we don't have to use app's
* N.B.: we never de-allocate d_r_initstack (see comments in app_exit)
*/
d_r_initstack = (byte *)stack_alloc(DYNAMORIO_STACK_SIZE, NULL);
LOG(GLOBAL, LOG_SYNCH, 2, "d_r_initstack is " PFX "-" PFX "\n",
d_r_initstack - DYNAMORIO_STACK_SIZE, d_r_initstack);
#ifdef WINDOWS
/* PR203701: separate stack for error reporting when the
* dstack is exhausted
*/
exception_stack = (byte *)stack_alloc(EXCEPTION_STACK_SIZE, NULL);
#endif
#ifdef WINDOWS
if (!INTERNAL_OPTION(noasynch)) {
/* We split the hooks up: first we put in just Ki* to catch
* exceptions in client init routines (PR 200207), but we don't want
* syscall hooks so client init can scan syscalls.
* Xref PR 216934 where this was originally down below 1st thread init,
* before we had GLOBAL_DCONTEXT.
*/
callback_interception_init_start();
}
#endif /* WINDOWS */
/* Set up any private-loader-related data we need before generating any
* code, such as the private PEB on Windows.
*/
loader_init_prologue();
d_r_arch_init();
synch_init();
#ifdef KSTATS
kstat_init();
#endif
d_r_monitor_init();
fcache_init();
d_r_link_init();
fragment_init();
moduledb_init(); /* before vm_areas_init, after heap_init */
perscache_init(); /* before vm_areas_init */
native_exec_init(); /* before vm_areas_init, after arch_init */
if (!DYNAMO_OPTION(thin_client)) {
#ifdef HOT_PATCHING_INTERFACE
/* must init hotp before vm_areas_init() calls find_executable_vm_areas() */
if (DYNAMO_OPTION(hot_patching))
hotp_init();
#endif
}
#ifdef INTERNAL
{
char initial_options[MAX_OPTIONS_STRING];
get_dynamo_options_string(&dynamo_options, initial_options,
sizeof(initial_options), true);
SYSLOG_INTERNAL_INFO("Initial options = %s", initial_options);
DOLOG(1, LOG_TOP, {
get_pcache_dynamo_options_string(&dynamo_options, initial_options,
sizeof(initial_options),
OP_PCACHE_LOCAL);
LOG(GLOBAL, LOG_TOP, 1, "Initial pcache-affecting options = %s\n",
initial_options);
});
}
#endif /* INTERNAL */
LOG(GLOBAL, LOG_TOP, 1, "\n");
/* initialize thread hashtable */
/* Note: for thin_client, this isn't needed if it is only going to
* look for spawned processes; however, if we plan to promote from
* thin_client to hotp_only mode (highly likely), this would be needed.
* For now, leave it in there unless thin_client footprint becomes an
* issue.
*/
int size = HASHTABLE_SIZE(ALL_THREADS_HASH_BITS) * sizeof(thread_record_t *);
all_threads =
(thread_record_t **)global_heap_alloc(size HEAPACCT(ACCT_THREAD_MGT));
memset(all_threads, 0, size);
if (!INTERNAL_OPTION(nop_initial_bblock) IF_WINDOWS(
|| !check_sole_thread())) /* some other thread is already here! */
bb_lock_start = true;
#ifdef SIDELINE
/* initialize sideline thread after thread table is set up */
if (dynamo_options.sideline)
sideline_init();
#endif
/* We can't clear this on detach like other vars b/c we need native threads
* to continue to avoid safe_read_tls_magic() in is_thread_tls_initialized().
* So we clear it on (re-)init in dynamorio_take_over_threads().
* From now until then, we avoid races where another thread invokes a
* safe_read during native signal delivery but we remove DR's handler before
* it reaches there and it is delivered to the app's handler instead, kind
* of like i#3535, by re-using the i#3535 mechanism of pointing at the only
* thread who could possibly have a dcontext.
* XXX: Should we rename this s/detacher_/singleton_/ or something?
*/
detacher_tid = IF_UNIX_ELSE(get_sys_thread_id(), INVALID_THREAD_ID);
/* thread-specific initialization for the first thread we inject in
* (in a race with injected threads, sometimes it is not the primary thread)
*/
/* i#117/PR 395156: it'd be nice to have mc here but would
* require changing start/stop API
*/
dynamo_thread_init(NULL, NULL, NULL, false);
/* i#2751: we need TLS to be set up to relocate and call init funcs. */
loader_init_epilogue(get_thread_private_dcontext());
/* We move vm_areas_init() below dynamo_thread_init() so we can have
* two things: 1) a dcontext and 2) a SIGSEGV handler, for TRY/EXCEPT
* inside vm_areas_init() for PR 361594's probes and for d_r_safe_read().
* This means vm_areas_thread_init() runs before vm_areas_init().
*/
if (!DYNAMO_OPTION(thin_client)) {
vm_areas_init();
#ifdef RCT_IND_BRANCH
/* relies on is_in_dynamo_dll() which needs vm_areas_init */
rct_init();
#endif
} else {
/* This is needed to handle exceptions in thin_client mode, mostly
* internal ones, but can be app ones too. */
dynamo_vm_areas_lock();
find_dynamo_library_vm_areas();
dynamo_vm_areas_unlock();
}
#ifdef ANNOTATIONS
annotation_init();
#endif
jitopt_init();
dr_attach_finished = create_broadcast_event();
/* New client threads rely on dr_app_started being initialized, so do
* that before initializing clients.
*/
dr_app_started = create_broadcast_event();
/* client last, in case it depends on other inits: must be after
* dynamo_thread_init so the client can use a dcontext (PR 216936).
* Note that we *load* the client library before installing our hooks,
* but call the client's init routine afterward so that we correctly
* report crashes (PR 200207).
* Note: DllMain in client libraries can crash and we still won't
* report; better document that client libraries shouldn't have
* DllMain.
*/
instrument_init();
/* To give clients a chance to process pcaches as we load them, we
* delay the loading until we've initialized the clients.
*/
vm_area_delay_load_coarse_units();
#ifdef WINDOWS
if (!INTERNAL_OPTION(noasynch))
callback_interception_init_finish(); /* split for PR 200207: see above */
#endif
if (SELF_PROTECT_ON_CXT_SWITCH) {
protect_info = (protect_info_t *)global_unprotected_heap_alloc(
sizeof(protect_info_t) HEAPACCT(ACCT_OTHER));
ASSIGN_INIT_LOCK_FREE(protect_info->lock, protect_info);
protect_info->num_threads_unprot = 0; /* ENTERING_DR() below will inc to 1 */
protect_info->num_threads_suspended = 0;
if (INTERNAL_OPTION(single_privileged_thread)) {
/* FIXME: thread_initexit_lock must be a recursive lock! */
ASSERT_NOT_IMPLEMENTED(false);
/* grab the lock now -- the thread that is in dynamo must be holding
* the lock, and we are the initial thread in dynamo!
*/
d_r_mutex_lock(&thread_initexit_lock);
}
/* ENTERING_DR will increment, so decrement first
* FIXME: waste of protection change since will nop-unprotect!
*/
if (TEST(SELFPROT_DATA_CXTSW, DYNAMO_OPTION(protect_mask)))
datasec_writable_cxtswprot = 0;
/* FIXME case 8073: remove once freqprot not every cxt sw */
if (TEST(SELFPROT_DATA_FREQ, DYNAMO_OPTION(protect_mask)))
datasec_writable_freqprot = 0;
}
/* this thread is now entering DR */
ENTERING_DR();
#ifdef WINDOWS
if (DYNAMO_OPTION(early_inject)) {
/* AFTER callback_interception_init and self protect init and
* ENTERING_DR() */
early_inject_init();
}
#endif
}
dynamo_initialized = true;
/* Protect .data, assuming all vars there have been initialized. */
SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT);
/* internal-only options for testing run-once (case 3990) */
if (INTERNAL_OPTION(unsafe_crash_process)) {
SYSLOG_INTERNAL_ERROR("Crashing the process deliberately!");
*((int *)PTR_UINT_MINUS_1) = 0;
}
if (INTERNAL_OPTION(unsafe_hang_process)) {
event_t never_signaled = create_event();
SYSLOG_INTERNAL_ERROR("Hanging the process deliberately!");
wait_for_event(never_signaled, 0);
destroy_event(never_signaled);
}
return SUCCESS;
}
#ifdef UNIX
void
dynamorio_fork_init(dcontext_t *dcontext)
{
/* on a fork we want to re-initialize some data structures, especially
* log files, which we want a separate directory for
*/
thread_record_t **threads;
int i, num_threads;
# ifdef DEBUG
char parent_logdir[MAXIMUM_PATH];
# endif
/* re-cache app name, etc. that are using parent pid before we
* create log dirs (xref i#189/PR 452168)
*/
os_fork_init(dcontext);
/* sanity check, plus need to set this for statistics_init:
* even if parent did an execve, env var should be reset by now
*/
post_execve = (getenv(DYNAMORIO_VAR_EXECVE) != NULL);
ASSERT(!post_execve);
# ifdef DEBUG
/* copy d_r_stats->logdir
* d_r_stats->logdir is static, so current copy is fine, don't need
* frozen copy
*/
strncpy(parent_logdir, d_r_stats->logdir, MAXIMUM_PATH - 1);
d_r_stats->logdir[MAXIMUM_PATH - 1] = '\0'; /* if max no null */
# endif
if (get_log_dir(PROCESS_DIR, NULL, NULL)) {
/* we want brand new log dir */
enable_new_log_dir();
create_log_dir(PROCESS_DIR);
}
# ifdef DEBUG
/* just like dynamorio_app_init, create main_logfile before stats */
if (d_r_stats->loglevel > 0) {
/* we want brand new log files. os_fork_init() closed inherited files. */
main_logfile = open_log_file(main_logfile_name(), NULL, 0);
print_file(main_logfile, "%s\n", dynamorio_version_string);
print_file(main_logfile, "New log file for child %d forked by parent %d\n",
d_r_get_thread_id(), get_parent_id());
print_file(main_logfile, "Parent's log dir: %s\n", parent_logdir);
}
d_r_stats->process_id = get_process_id();
if (d_r_stats->loglevel > 0) {
/* FIXME: share these few lines of code w/ dynamorio_app_init? */
LOG(GLOBAL, LOG_TOP, 1, "Running: %s\n", d_r_stats->process_name);
# ifndef _WIN32_WCE
LOG(GLOBAL, LOG_TOP, 1, "DYNAMORIO_OPTIONS: %s\n", d_r_option_string);
# endif
}
# endif /* DEBUG */
vmm_heap_fork_init(dcontext);
/* must re-hash parent entry in threads table, plus no longer have any
* other threads (fork -> we're alone in address space), so clear
* out entire thread table, then add child
*/
d_r_mutex_lock(&thread_initexit_lock);
get_list_of_threads_ex(&threads, &num_threads, true /*include execve*/);
for (i = 0; i < num_threads; i++) {
if (threads[i] == dcontext->thread_record)
remove_thread(threads[i]->id);
else
dynamo_other_thread_exit(threads[i]);
}
d_r_mutex_unlock(&thread_initexit_lock);
global_heap_free(threads,
num_threads * sizeof(thread_record_t *) HEAPACCT(ACCT_THREAD_MGT));
add_thread(get_process_id(), d_r_get_thread_id(), true /*under dynamo control*/,
dcontext);
GLOBAL_STAT(num_threads) = 1;
# ifdef DEBUG
if (d_r_stats->loglevel > 0) {
/* need a new thread-local logfile */
dcontext->logfile = open_log_file(thread_logfile_name(), NULL, 0);
print_file(dcontext->logfile, "%s\n", dynamorio_version_string);
print_file(dcontext->logfile, "New log file for child %d forked by parent %d\n",
d_r_get_thread_id(), get_parent_id());
LOG(THREAD, LOG_TOP | LOG_THREADS, 1, "THREAD %d (dcontext " PFX ")\n\n",
d_r_get_thread_id(), dcontext);
}
# endif
num_threads = 1;
/* FIXME: maybe should have a callback list for who wants to be notified
* on a fork -- probably everyone who makes a log file on init.
*/
fragment_fork_init(dcontext);
/* this must be called after dynamo_other_thread_exit() above */
signal_fork_init(dcontext);
if (CLIENTS_EXIST()) {
instrument_fork_init(dcontext);
}
}
#endif /* UNIX */
/* To make DynamoRIO useful as a library for a standalone client
* application (as opposed to a client library that works with
* DynamoRIO in executing a target application). This makes DynamoRIO
* useful as an IA-32 disassembly library, etc.
*/
dcontext_t *
standalone_init(void)
{
dcontext_t *dcontext;
int count = atomic_add_exchange_int(&standalone_init_count, 1);
if (count > 1 || dynamo_initialized)
return GLOBAL_DCONTEXT;
standalone_library = true;
/* We have release-build stats now so this is not just DEBUG */
d_r_stats = &nonshared_stats;
/* No reason to limit heap size when there's no code cache. */
IF_X64(dynamo_options.reachable_heap = false;)
dynamo_options.vm_base_near_app = false;
#if defined(INTERNAL) && defined(DEADLOCK_AVOIDANCE)
/* avoid issues w/ GLOBAL_DCONTEXT instead of thread dcontext */
dynamo_options.deadlock_avoidance = false;
#endif
#ifdef UNIX
os_page_size_init((const char **)our_environ, is_our_environ_followed_by_auxv());
#endif
#ifdef WINDOWS
/* MUST do this before making any system calls */
if (!syscalls_init())
return NULL; /* typically b/c of unsupported OS version */
#endif
d_r_config_init();
options_init();
vmm_heap_init();
d_r_heap_init();
dynamo_heap_initialized = true;
dynamo_vm_areas_init();
d_r_decode_init();
proc_init();
d_r_os_init();
config_heap_init();
#ifdef STANDALONE_UNIT_TEST
os_tls_init();
dcontext = create_new_dynamo_context(true /*initial*/, NULL, NULL);
set_thread_private_dcontext(dcontext);
/* sanity check */
ASSERT(get_thread_private_dcontext() == dcontext);
heap_thread_init(dcontext);
# ifdef DEBUG
/* XXX: share code w/ main init routine? */
nonshared_stats.logmask = LOG_ALL;
options_init();
if (d_r_stats->loglevel > 0) {
char initial_options[MAX_OPTIONS_STRING];
main_logfile = open_log_file(main_logfile_name(), NULL, 0);
print_file(main_logfile, "%s\n", dynamorio_version_string);
print_file(main_logfile, "Log file for standalone unit test\n");
get_dynamo_options_string(&dynamo_options, initial_options,
sizeof(initial_options), true);
SYSLOG_INTERNAL_INFO("Initial options = %s", initial_options);
print_file(main_logfile, "\n");
}
# endif /* DEBUG */
#else
/* rather than ask the user to call some thread-init routine in
* every thread, we just use global dcontext everywhere (i#548)
*/
dcontext = GLOBAL_DCONTEXT;
#endif
/* In case standalone_exit() is omitted or there's a crash, we clean up any .1config
* file right now. the only loss if that we can't synch options: but that
* should be less important for standalone. We disabling synching.
*/
/* options are never made read-only for standalone */
dynamo_options.dynamic_options = false;
dynamo_initialized = true;
return dcontext;
}
void
standalone_exit(void)
{
int count = atomic_add_exchange_int(&standalone_init_count, -1);
if (count != 0)
return;
/* We support re-attach by setting doing_detach. */
doing_detach = true;
#ifdef STANDALONE_UNIT_TEST
dcontext_t *dcontext = get_thread_private_dcontext();
set_thread_private_dcontext(NULL);
heap_thread_exit(dcontext);
delete_dynamo_context(dcontext, true);
/* We can't call os_tls_exit() b/c we don't have safe_read support for
* the TLS magic read on Linux.
*/
#endif
config_heap_exit();
os_fast_exit();
os_slow_exit();
#if !defined(STANDALONE_UNIT_TEST) || !defined(AARCH64)
/* XXX: The lock setup is somehow messed up on AArch64. Disabling cleanup. */
dynamo_vm_areas_exit();
#endif
#ifndef STANDALONE_UNIT_TEST
/* We have a leak b/c we can't call os_tls_exit(). For now we simplify