-
Notifications
You must be signed in to change notification settings - Fork 566
/
Copy pathutils.c
4621 lines (4246 loc) · 167 KB
/
utils.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-2022 Google, Inc. All rights reserved.
* Copyright (c) 2017 ARM Limited. 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 */
/*
* utils.c - miscellaneous utilities
*/
#include "globals.h"
#include "configure_defines.h"
#include "utils.h"
#include "module_shared.h"
#include <math.h>
#ifdef PROCESS_CONTROL
# include "moduledb.h" /* for process control macros */
#endif
#ifdef UNIX
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <errno.h>
#else
# include <errno.h>
/* FIXME : remove when syslog macros fixed */
# include "events.h"
#endif
#ifdef SHARING_STUDY
# include "fragment.h" /* print_shared_stats */
#endif
#ifdef DEBUG
# include "fcache.h"
# include "synch.h" /* all_threads_synch_lock */
#endif
#include <stdarg.h> /* for varargs */
#include <stddef.h> /* for offsetof */
try_except_t global_try_except;
#ifdef UNIX
thread_id_t global_try_tid = INVALID_THREAD_ID;
#endif
int do_once_generation = 1;
#ifdef SIDELINE
extern void
sideline_exit(void);
#endif
/* use for soft errors that can handle some cleanup: assertions and apichecks
* performs some cleanup and then calls os_terminate
*/
static void
soft_terminate()
{
#ifdef SIDELINE
/* kill child threads */
if (dynamo_options.sideline) {
sideline_stop();
sideline_exit();
}
#endif
/* set exited status for shared memory watchers, other threads */
DOSTATS({
if (d_r_stats != NULL)
GLOBAL_STAT(exited) = true;
});
/* do not try to clean up */
os_terminate(NULL, TERMINATE_PROCESS);
}
#if defined(INTERNAL) || defined(DEBUG)
/* checks whether an assert statement should be ignored,
* produces a warning if so and returns true,
* otherwise returns false
*/
bool
ignore_assert(const char *assert_stmt, const char *expr)
{
bool ignore = false;
if (!IS_STRING_OPTION_EMPTY(ignore_assert_list)) {
string_option_read_lock();
ignore = check_filter(DYNAMO_OPTION(ignore_assert_list), assert_stmt);
string_option_read_unlock();
}
if (IS_LISTSTRING_OPTION_FORALL(ignore_assert_list)) {
ignore = true;
}
if (ignore) {
/* FIXME: could have passed message around */
SYSLOG_INTERNAL_WARNING("Ignoring assert %s %s", assert_stmt, expr);
}
return ignore;
}
/* Hand-made DO_ONCE used in d_r_internal_error b/c ifdefs in
* report_dynamorio_problem prevent DO_ONCE itself
*/
DECLARE_FREQPROT_VAR(static bool do_once_internal_error, false);
/* abort on internal dynamo error */
void
d_r_internal_error(const char *file, int line, const char *expr)
{
/* note that we no longer obfuscate filenames in non-internal builds
* xref PR 303817 */
/* need to produce a SYSLOG Ignore Error here and return right away */
/* to avoid adding another ?: in the ASSERT messsage
* we'll reconstruct file and line # here
*/
if (!IS_STRING_OPTION_EMPTY(ignore_assert_list)) {
char assert_stmt[MAXIMUM_PATH]; /* max unique identifier */
/* note the ignore checks are done with a possible recursive
* infinte loop if any asserts fail. Not very safe to set and
* unset a static bool either since we'll be noisy.
*/
/* Assert identifiers should be an exact match of message
* after Internal Error. Most common look like 'arch/arch.c:142',
* but could also look like 'Not implemented @arch/arch.c:142'
* or 'Bug #4809 @arch/arch.c:145;Ignore message
* @arch/arch.c:146'
*/
snprintf(assert_stmt, BUFFER_SIZE_ELEMENTS(assert_stmt), "%s:%d", file, line);
NULL_TERMINATE_BUFFER(assert_stmt);
ASSERT_CURIOSITY((strlen(assert_stmt) + 1) != BUFFER_SIZE_ELEMENTS(assert_stmt));
if (ignore_assert(assert_stmt, expr))
return;
/* we can ignore multiple asserts without triggering the do_once */
}
if (do_once_internal_error) /* recursing, bail out */
return;
else
do_once_internal_error = true;
report_dynamorio_problem(NULL, DUMPCORE_ASSERTION, NULL, NULL,
PRODUCT_NAME " debug check failure: %s:%d %s"
# if defined(DEBUG) && defined(INTERNAL)
"\n(Error occurred @%d frags in tid " TIDFMT ")"
# endif
,
file, line, expr
# if defined(DEBUG) && defined(INTERNAL)
,
d_r_stats == NULL ? -1 : GLOBAL_STAT(num_fragments),
IF_UNIX_ELSE(get_sys_thread_id(), d_r_get_thread_id())
# endif
);
soft_terminate();
}
#endif /* defined(INTERNAL) || defined(DEBUG) */
/* abort on external application created error, i.e. apicheck */
void
external_error(const char *file, int line, const char *msg)
{
DO_ONCE({
/* this syslog is before any core dump, unlike our other reports, but
* not worth fixing
*/
SYSLOG(SYSLOG_ERROR, EXTERNAL_ERROR, 4, get_application_name(),
get_application_pid(), PRODUCT_NAME, msg);
report_dynamorio_problem(NULL, DUMPCORE_FATAL_USAGE_ERROR, NULL, NULL,
"Usage error: %s (%s, line %d)", msg, file, line);
});
soft_terminate();
}
/****************************************************************************/
/* SYNCHRONIZATION */
#ifdef DEADLOCK_AVOIDANCE
/* Keeps the head of a linked list of all mutexes currently
held by a thread. We also require a LIFO lock unlock order
to keep things simpler (and stricter).
*/
struct _thread_locks_t {
mutex_t *last_lock;
};
/* These two locks are never deleted, although innermost_lock is grabbed */
DECLARE_CXTSWPROT_VAR(mutex_t outermost_lock, INIT_LOCK_FREE(outermost_lock));
DECLARE_CXTSWPROT_VAR(mutex_t innermost_lock, INIT_LOCK_FREE(innermost_lock));
/* Case 8075: For selfprot we have no way to put a local-scope mutex into
* .cspdata, and {add,remove}_process_lock need to write to the
* do_threshold_mutex when managing adjacent entries in the lock list, so
* we use a global lock instead. Could be a contention issue but it's only
* DEADLOCK_AVOIDANCE builds and there are few uses of DO_THRESHOLD_SAFE.
*/
DECLARE_CXTSWPROT_VAR(mutex_t do_threshold_mutex, INIT_LOCK_FREE(do_threshold_mutex));
/* structure field dumper for both name and value, format with %*s%d */
# define DUMP_NONZERO(v, field) \
strlen(#field) + 1, (v->field ? #field "=" : ""), v->field
# ifdef MACOS
# define DUMP_CONTENDED(v, field) \
strlen(#field) + 1, (ksynch_var_initialized(&v->field) ? #field "=" : ""), \
v->field.sem
# else
# define DUMP_CONTENDED DUMP_NONZERO
# endif
/* common format string used for different log files and loglevels */
# define DUMP_LOCK_INFO_ARGS(depth, cur_lock, prev) \
"%d lock " PFX ": name=%s\nrank=%d owner=" TIDFMT " owning_dc=" PFX " " \
"%*s" PIFX " prev=" PFX "\n" \
"lock %*s%8d %*s%8d %*s%8d %*s%8d %*s%8d+2 %s\n", \
depth, cur_lock, cur_lock->name, cur_lock->rank, cur_lock->owner, \
cur_lock->owning_dcontext, DUMP_CONTENDED(cur_lock, contended_event), prev, \
DUMP_NONZERO(cur_lock, count_times_acquired), \
DUMP_NONZERO(cur_lock, count_times_contended), \
DUMP_NONZERO(cur_lock, count_times_spin_pause), \
DUMP_NONZERO(cur_lock, count_times_spin_only), \
DUMP_NONZERO(cur_lock, max_contended_requests), cur_lock->name
# ifdef INTERNAL
static void
dump_mutex_callstack(mutex_t *lock)
{
/* from windbg proper command is
* 0:001> dds @@(&lock->callstack) L4
*/
# ifdef MUTEX_CALLSTACK
uint i;
if (INTERNAL_OPTION(mutex_callstack) == 0)
return;
LOG(GLOBAL, LOG_THREADS, 1, "dump_mutex_callstack %s\n", lock->name);
for (i = 0; i < INTERNAL_OPTION(mutex_callstack); i++) {
/* some macro's call this function, so it is easier to ifdef
* only references to callstack */
LOG(GLOBAL, LOG_THREADS, 1, " " PFX "\n", lock->callstack[i]);
}
# endif /* MUTEX_CALLSTACK */
}
# endif
void
dump_owned_locks(dcontext_t *dcontext)
{ /* LIFO order even though order in releasing doesn't matter */
mutex_t *cur_lock;
uint depth = 0;
cur_lock = dcontext->thread_owned_locks->last_lock;
LOG(THREAD, LOG_THREADS, 1, "Owned locks for thread " TIDFMT " dcontext=" PFX "\n",
dcontext->owning_thread, dcontext);
while (cur_lock != &outermost_lock) {
depth++;
LOG(THREAD, LOG_THREADS, 1,
DUMP_LOCK_INFO_ARGS(depth, cur_lock, cur_lock->prev_owned_lock));
ASSERT(cur_lock->owner == dcontext->owning_thread);
cur_lock = cur_lock->prev_owned_lock;
}
}
bool
thread_owns_no_locks(dcontext_t *dcontext)
{
ASSERT(dcontext != NULL);
if (!INTERNAL_OPTION(deadlock_avoidance))
return true; /* can't verify since we aren't keeping track of owned locks */
return (dcontext->thread_owned_locks->last_lock == &outermost_lock);
}
bool
thread_owns_one_lock(dcontext_t *dcontext, mutex_t *lock)
{
mutex_t *cur_lock;
ASSERT(dcontext != NULL);
if (!INTERNAL_OPTION(deadlock_avoidance))
return true; /* can't verify since we aren't keeping track of owned locks */
cur_lock = dcontext->thread_owned_locks->last_lock;
return (cur_lock == lock && cur_lock->prev_owned_lock == &outermost_lock);
}
/* Returns true if dcontext thread owns lock1 and lock2 and no other locks */
bool
thread_owns_two_locks(dcontext_t *dcontext, mutex_t *lock1, mutex_t *lock2)
{
mutex_t *cur_lock;
ASSERT(dcontext != NULL);
if (!INTERNAL_OPTION(deadlock_avoidance))
return true; /* can't verify since we aren't keeping track of owned locks */
cur_lock = dcontext->thread_owned_locks->last_lock;
return (cur_lock == lock1 && cur_lock->prev_owned_lock == lock2 &&
lock2->prev_owned_lock == &outermost_lock);
}
/* Returns true if dcontext thread owns lock1 and optionally lock2
* (acquired before lock1) and no other locks. */
bool
thread_owns_first_or_both_locks_only(dcontext_t *dcontext, mutex_t *lock1, mutex_t *lock2)
{
mutex_t *cur_lock;
ASSERT(dcontext != NULL);
if (!INTERNAL_OPTION(deadlock_avoidance))
return true; /* can't verify since we aren't keeping track of owned locks */
cur_lock = dcontext->thread_owned_locks->last_lock;
return (cur_lock == lock1 &&
(cur_lock->prev_owned_lock == &outermost_lock ||
(cur_lock->prev_owned_lock == lock2 &&
lock2->prev_owned_lock == &outermost_lock)));
}
/* dump process locks that have been acquired at least once */
/* FIXME: since most mutexes are global we don't have thread private lock lists */
void
dump_process_locks()
{
mutex_t *cur_lock;
uint depth = 0;
uint total_acquired = 0;
uint total_contended = 0;
LOG(GLOBAL, LOG_STATS, 2, "Currently live process locks:\n");
/* global list access needs to be synchronized */
d_r_mutex_lock(&innermost_lock);
cur_lock = &innermost_lock;
do {
depth++;
LOG(GLOBAL, LOG_STATS,
(cur_lock->count_times_contended ? 1U : 2U), /* elevate contended ones */
DUMP_LOCK_INFO_ARGS(depth, cur_lock, cur_lock->next_process_lock));
DOLOG((cur_lock->count_times_contended ? 2U : 3U), /* elevate contended ones */
LOG_THREADS, {
/* last recorded callstack, not necessarily the most contended path */
dump_mutex_callstack(cur_lock);
});
cur_lock = cur_lock->next_process_lock;
total_acquired += cur_lock->count_times_acquired;
total_contended += cur_lock->count_times_contended;
ASSERT(cur_lock);
ASSERT(cur_lock->next_process_lock->prev_process_lock == cur_lock);
ASSERT(cur_lock->prev_process_lock->next_process_lock == cur_lock);
ASSERT(cur_lock->prev_process_lock != cur_lock || cur_lock == &innermost_lock);
ASSERT(cur_lock->next_process_lock != cur_lock || cur_lock == &innermost_lock);
} while (cur_lock != &innermost_lock);
d_r_mutex_unlock(&innermost_lock);
LOG(GLOBAL, LOG_STATS, 1,
"Currently live process locks: %d, acquired %d, contended %d (current only)\n",
depth, total_acquired, total_contended);
}
uint
locks_not_closed()
{
mutex_t *cur_lock;
uint forgotten = 0;
uint ignored = 0;
/* Case 8075: we use a global do_threshold_mutex for DEADLOCK_AVOIDANCE.
* Leaving the code for a local var here via this bool in case we run
* this routine in release build while somehow avoiding the global lock.
*/
static const bool allow_do_threshold_leaks = false;
/* we assume that we would have removed them from the process list in mutex_close */
/* locks assigned with do_threshold_mutex are 'leaked' because it
* is too much hassle to find a good place to DELETE them -- though we
* now use a global mutex for DEADLOCK_AVOIDANCE so that's not the case.
*/
d_r_mutex_lock(&innermost_lock);
/* innermost will stay */
cur_lock = innermost_lock.next_process_lock;
while (cur_lock != &innermost_lock) {
if (allow_do_threshold_leaks && cur_lock->rank == LOCK_RANK(do_threshold_mutex)) {
ignored++;
} else if (cur_lock->deleted &&
(IF_WINDOWS(cur_lock->rank == LOCK_RANK(debugbox_lock) ||
cur_lock->rank == LOCK_RANK(dump_core_lock) ||)
cur_lock->rank == LOCK_RANK(report_buf_lock) ||
cur_lock->rank == LOCK_RANK(datasec_selfprot_lock) ||
cur_lock->rank == LOCK_RANK(logdir_mutex) ||
cur_lock->rank ==
LOCK_RANK(options_lock)
/* This lock can be used parallel to detach cleanup. */
IF_UNIX(|| cur_lock->rank == LOCK_RANK(detached_sigact_lock)))) {
/* i#1058: curiosities during exit re-acquire these locks. */
ignored++;
} else {
LOG(GLOBAL, LOG_STATS, 1, "missing DELETE_LOCK on lock " PFX " %s\n",
cur_lock, cur_lock->name);
forgotten++;
}
cur_lock = cur_lock->next_process_lock;
}
d_r_mutex_unlock(&innermost_lock);
LOG(GLOBAL, LOG_STATS, 3, "locks_not_closed= %d remaining, %d ignored\n", forgotten,
ignored);
return forgotten;
}
void
locks_thread_init(dcontext_t *dcontext)
{
thread_locks_t *new_thread_locks;
new_thread_locks = (thread_locks_t *)UNPROTECTED_GLOBAL_ALLOC(
sizeof(thread_locks_t) HEAPACCT(ACCT_OTHER));
LOG(THREAD, LOG_STATS, 2, "thread_locks=" PFX " size=%d\n", new_thread_locks,
sizeof(thread_locks_t));
/* initialize any thread bookkeeping fields before assigning to dcontext */
new_thread_locks->last_lock = &outermost_lock;
dcontext->thread_owned_locks = new_thread_locks;
}
void
locks_thread_exit(dcontext_t *dcontext)
{
/* using global heap and always have to clean up */
if (dcontext->thread_owned_locks) {
thread_locks_t *old_thread_locks = dcontext->thread_owned_locks;
/* when exiting, another thread may be holding the lock instead of the current,
CHECK: is this true for detaching */
ASSERT(dcontext->thread_owned_locks->last_lock == &thread_initexit_lock ||
dcontext->thread_owned_locks->last_lock == &outermost_lock
/* PR 546016: sideline client thread might hold client lock */
|| dcontext->thread_owned_locks->last_lock->rank == dr_client_mutex_rank);
/* disable thread lock checks before freeing memory */
dcontext->thread_owned_locks = NULL;
UNPROTECTED_GLOBAL_FREE(old_thread_locks,
sizeof(thread_locks_t) HEAPACCT(ACCT_OTHER));
}
}
static void
add_process_lock(mutex_t *lock)
{
/* add to global locks circular double linked list */
d_r_mutex_lock(&innermost_lock);
if (lock->prev_process_lock != NULL) {
/* race: someone already added (can only happen for read locks) */
LOG(THREAD_GET, LOG_THREADS, 2, "\talready added\n");
ASSERT(lock->next_process_lock != NULL);
d_r_mutex_unlock(&innermost_lock);
return;
}
LOG(THREAD_GET, LOG_THREADS, 2,
"add_process_lock: " DUMP_LOCK_INFO_ARGS(0, lock, lock->prev_process_lock));
ASSERT(lock->next_process_lock == NULL || lock == &innermost_lock);
ASSERT(lock->prev_process_lock == NULL || lock == &innermost_lock);
if (innermost_lock.prev_process_lock == NULL) {
innermost_lock.next_process_lock = &innermost_lock;
innermost_lock.prev_process_lock = &innermost_lock;
}
lock->next_process_lock = &innermost_lock;
innermost_lock.prev_process_lock->next_process_lock = lock;
lock->prev_process_lock = innermost_lock.prev_process_lock;
innermost_lock.prev_process_lock = lock;
ASSERT(lock->next_process_lock->prev_process_lock == lock);
ASSERT(lock->prev_process_lock->next_process_lock == lock);
ASSERT(lock->prev_process_lock != lock || lock == &innermost_lock);
ASSERT(lock->next_process_lock != lock || lock == &innermost_lock);
d_r_mutex_unlock(&innermost_lock);
}
static void
remove_process_lock(mutex_t *lock)
{
LOG(THREAD_GET, LOG_THREADS, 3,
"remove_process_lock " DUMP_LOCK_INFO_ARGS(0, lock, lock->prev_process_lock));
STATS_ADD(total_acquired, lock->count_times_acquired);
STATS_ADD(total_contended, lock->count_times_contended);
if (lock->count_times_acquired == 0) {
ASSERT(lock->prev_process_lock == NULL);
LOG(THREAD_GET, LOG_THREADS, 3, "\tnever acquired\n");
return;
}
ASSERT(lock->prev_process_lock && "if ever acquired should be on the list");
ASSERT(lock != &innermost_lock && "innermost will be 'leaked'");
/* remove from global locks list */
d_r_mutex_lock(&innermost_lock);
/* innermost should always have both fields set here */
lock->next_process_lock->prev_process_lock = lock->prev_process_lock;
lock->prev_process_lock->next_process_lock = lock->next_process_lock;
lock->next_process_lock = NULL;
lock->prev_process_lock = NULL; /* so we catch uses after closing */
d_r_mutex_unlock(&innermost_lock);
}
# ifdef MUTEX_CALLSTACK
/* FIXME: generalize and merge w/ CALL_PROFILE? */
static void
mutex_collect_callstack(mutex_t *lock)
{
uint max_depth = INTERNAL_OPTION(mutex_callstack);
uint depth = 0;
uint skip = 2; /* ignore calls from deadlock_avoidance() and d_r_mutex_lock() */
/* FIXME: write_lock could ignore one level further */
byte *fp;
dcontext_t *dcontext = get_thread_private_dcontext();
GET_FRAME_PTR(fp);
/* only interested in DR addresses which should all be readable */
while (depth < max_depth && (is_on_initstack(fp) || is_on_dstack(dcontext, fp)) &&
/* is_on_initstack() and is_on_dstack() do include the guard pages
* yet we cannot afford to call is_readable_without_exception()
*/
!is_stack_overflow(dcontext, fp)) {
app_pc our_ret = *((app_pc *)fp + 1);
fp = *(byte **)fp;
if (skip) {
skip--;
continue;
}
lock->callstack[depth] = our_ret;
depth++;
}
}
# endif /* MUTEX_CALLSTACK */
enum { LOCK_NOT_OWNABLE, LOCK_OWNABLE };
/* if not acquired only update statistics,
if not ownable (i.e. read lock) only check against previous locks,
but don't add to thread owned list
*/
static void
deadlock_avoidance_lock(mutex_t *lock, bool acquired, bool ownable)
{
if (acquired) {
lock->count_times_acquired++;
/* CHECK: everything here works without mutex_trylock's */
LOG(GLOBAL, LOG_THREADS, 6,
"acquired lock " PFX " %s rank=%d, %s dcontext, tid:%d, %d time\n", lock,
lock->name, lock->rank, get_thread_private_dcontext() ? "valid" : "not valid",
d_r_get_thread_id(), lock->count_times_acquired);
LOG(THREAD_GET, LOG_THREADS, 6, "acquired lock " PFX " %s rank=%d\n", lock,
lock->name, lock->rank);
ASSERT(lock->rank > 0 && "initialize with INIT_LOCK_FREE");
if (ownable) {
ASSERT(!lock->owner);
lock->owner = d_r_get_thread_id();
lock->owning_dcontext = get_thread_private_dcontext();
}
/* add to global list */
if (lock->prev_process_lock == NULL && lock != &innermost_lock) {
add_process_lock(lock);
}
/* cannot hold thread_initexit_lock while couldbelinking, else will
* deadlock with flushers
*/
ASSERT(lock != &thread_initexit_lock || !is_self_couldbelinking());
if (INTERNAL_OPTION(deadlock_avoidance) &&
get_thread_private_dcontext() != NULL &&
get_thread_private_dcontext() != GLOBAL_DCONTEXT) {
dcontext_t *dcontext = get_thread_private_dcontext();
if (dcontext->thread_owned_locks != NULL) {
/* PR 198871: same label used for all client locks so allow same rank.
* For now we ignore rank order when client lock is 1st, as well,
* to support decode_trace() for 0.9.6 release PR 198871 covers safer
* long-term fix.
*/
bool first_client = (dcontext->thread_owned_locks->last_lock->rank ==
dr_client_mutex_rank);
bool both_client = (first_client && lock->rank == dr_client_mutex_rank);
if (dcontext->thread_owned_locks->last_lock->rank >= lock->rank &&
!first_client /*FIXME PR 198871: remove */ && !both_client) {
/* report rank order violation */
SYSLOG_INTERNAL_NO_OPTION_SYNCH(
SYSLOG_CRITICAL,
"rank order violation %s acquired after %s in tid:%x", lock->name,
dcontext->thread_owned_locks->last_lock->name,
d_r_get_thread_id());
dump_owned_locks(dcontext);
/* like syslog don't synchronize options for dumpcore_mask */
if (TEST(DUMPCORE_DEADLOCK, DYNAMO_OPTION(dumpcore_mask)))
os_dump_core("rank order violation");
}
ASSERT((dcontext->thread_owned_locks->last_lock->rank < lock->rank ||
first_client /*FIXME PR 198871: remove */
|| both_client) &&
"rank order violation");
if (ownable) {
lock->prev_owned_lock = dcontext->thread_owned_locks->last_lock;
dcontext->thread_owned_locks->last_lock = lock;
}
DOLOG(6, LOG_THREADS, { dump_owned_locks(dcontext); });
}
}
if (INTERNAL_OPTION(mutex_callstack) != 0 && ownable &&
get_thread_private_dcontext() != NULL) {
# ifdef MUTEX_CALLSTACK
mutex_collect_callstack(lock);
# endif
}
} else {
/* NOTE check_wait_at_safe_spot makes the assumption that no system
* calls are made on the non acquired path here */
ASSERT(lock->rank > 0 && "initialize with INIT_LOCK_FREE");
if (INTERNAL_OPTION(deadlock_avoidance) && ownable) {
ASSERT(lock->owner != d_r_get_thread_id() &&
"deadlock on recursive mutex_lock");
}
lock->count_times_contended++;
}
}
/* FIXME: exported only for the linux hack -- make static once that's fixed */
void
deadlock_avoidance_unlock(mutex_t *lock, bool ownable)
{
if (INTERNAL_OPTION(simulate_contention)) {
/* with higher chances another thread will have to wait */
os_thread_yield();
}
LOG(GLOBAL, LOG_THREADS, 6,
"released lock " PFX " %s rank=%d, %s dcontext, tid:%d \n", lock, lock->name,
lock->rank, get_thread_private_dcontext() ? "valid" : "not valid",
d_r_get_thread_id());
LOG(THREAD_GET, LOG_THREADS, 6, "released lock " PFX " %s rank=%d\n", lock,
lock->name, lock->rank);
if (!ownable)
return;
ASSERT(lock->owner == d_r_get_thread_id());
if (INTERNAL_OPTION(deadlock_avoidance) && lock->owning_dcontext != NULL &&
lock->owning_dcontext != GLOBAL_DCONTEXT) {
dcontext_t *dcontext = get_thread_private_dcontext();
if (dcontext == NULL) {
# ifdef DEBUG
/* thread_initexit_lock and all_threads_synch_lock
* are unlocked after tearing down thread structures
*/
# if defined(UNIX) && !defined(HAVE_TLS)
extern mutex_t tls_lock;
# endif
bool null_ok =
(lock == &thread_initexit_lock || lock == &all_threads_synch_lock
# if defined(UNIX) && !defined(HAVE_TLS)
|| lock == &tls_lock
# endif
);
ASSERT(null_ok);
# endif
} else {
ASSERT(lock->owning_dcontext == dcontext);
if (dcontext->thread_owned_locks != NULL) {
DOLOG(6, LOG_THREADS, { dump_owned_locks(dcontext); });
/* LIFO order even though order in releasing doesn't matter */
ASSERT(dcontext->thread_owned_locks->last_lock == lock);
dcontext->thread_owned_locks->last_lock = lock->prev_owned_lock;
lock->prev_owned_lock = NULL;
}
}
}
lock->owner = INVALID_THREAD_ID;
lock->owning_dcontext = NULL;
}
# define DEADLOCK_AVOIDANCE_LOCK(lock, acquired, ownable) \
deadlock_avoidance_lock(lock, acquired, ownable)
# define DEADLOCK_AVOIDANCE_UNLOCK(lock, ownable) \
deadlock_avoidance_unlock(lock, ownable)
#else
# define DEADLOCK_AVOIDANCE_LOCK(lock, acquired, ownable) /* do nothing */
# define DEADLOCK_AVOIDANCE_UNLOCK(lock, ownable) /* do nothing */
#endif /* DEADLOCK_AVOIDANCE */
#ifdef UNIX
void
d_r_mutex_fork_reset(mutex_t *mutex)
{
/* i#239/PR 498752: need to free locks held by other threads at fork time.
* We can't call ASSIGN_INIT_LOCK_FREE as that clobbers any contention event
* (=> leak) and the debug-build lock lists (=> asserts like PR 504594).
* If the synch before fork succeeded, this is unecessary. If we encounter
* more deadlocks after fork because of synch failure, we can add more calls
* to reset locks on a case by case basis.
*/
mutex->lock_requests = LOCK_FREE_STATE;
# ifdef DEADLOCK_AVOIDANCE
mutex->owner = INVALID_THREAD_ID;
mutex->owning_dcontext = NULL;
# endif
}
#endif
static uint spinlock_count = 0; /* initialized in utils_init, but 0 is always safe */
DECLARE_FREQPROT_VAR(static uint random_seed, 1234); /* initialized in utils_init */
DEBUG_DECLARE(static uint initial_random_seed;)
void
utils_init()
{
/* FIXME: We need to find a formula (or a better constant) based on real experiments
also see comment on spinlock_count_on_SMP in optionsx.h */
/* we want to make sure it is 0 on UP, the rest is speculation */
spinlock_count = (get_num_processors() - 1) * DYNAMO_OPTION(spinlock_count_on_SMP);
/* allow reproducing PRNG sequence
* (of course, thread scheduling may still affect requests) */
random_seed =
(DYNAMO_OPTION(prng_seed) == 0) ? os_random_seed() : DYNAMO_OPTION(prng_seed);
/* logged only at end, preserved so can be looked up in a dump */
DODEBUG(initial_random_seed = random_seed;);
/* sanity check since we cast back and forth */
ASSERT(sizeof(spin_mutex_t) == sizeof(mutex_t));
ASSERT(sizeof(uint64) == 8);
ASSERT(sizeof(uint32) == 4);
ASSERT(sizeof(uint) == 4);
ASSERT(sizeof(reg_t) == sizeof(void *));
#ifdef UNIX /* after options_init(), before we open logfile or call instrument_init() */
os_file_init();
#endif
set_exception_strings(NULL, NULL); /* use defaults */
}
/* NOTE since used by spinmutex_lock_no_yield, can make no system calls before
* the lock is grabbed (required by check_wait_at_safe_spot). */
bool
spinmutex_trylock(spin_mutex_t *spin_lock)
{
mutex_t *lock = &spin_lock->lock;
int mutexval;
mutexval = atomic_swap(&lock->lock_requests, LOCK_SET_STATE);
ASSERT(mutexval == LOCK_FREE_STATE || mutexval == LOCK_SET_STATE);
DEADLOCK_AVOIDANCE_LOCK(lock, mutexval == LOCK_FREE_STATE, LOCK_OWNABLE);
return (mutexval == LOCK_FREE_STATE);
}
void
spinmutex_lock(spin_mutex_t *spin_lock)
{
/* busy-wait until mutex is locked */
while (!spinmutex_trylock(spin_lock)) {
os_thread_yield();
}
return;
}
/* special version of spinmutex_lock that makes no system calls (i.e. no yield)
* as required by check_wait_at_safe_spot */
void
spinmutex_lock_no_yield(spin_mutex_t *spin_lock)
{
/* busy-wait until mutex is locked */
while (!spinmutex_trylock(spin_lock)) {
#ifdef DEADLOCK_AVOIDANCE
mutex_t *lock = &spin_lock->lock;
/* Trylock inc'ed count_times_contended, but since we are prob. going
* to spin a lot, we'd rather attribute that to a separate counter
* count_times_spin_pause to keep the counts meaningful. */
lock->count_times_contended--;
lock->count_times_spin_pause++;
#endif
SPINLOCK_PAUSE();
}
return;
}
void
spinmutex_unlock(spin_mutex_t *spin_lock)
{
mutex_t *lock = &spin_lock->lock;
/* if this fails, it means you don't already own the lock. */
ASSERT(lock->lock_requests > LOCK_FREE_STATE && "lock not owned");
ASSERT(lock->lock_requests == LOCK_SET_STATE);
DEADLOCK_AVOIDANCE_UNLOCK(lock, LOCK_OWNABLE);
lock->lock_requests = LOCK_FREE_STATE;
/* NOTE - check_wait_at_safe_spot requires that no system calls be made
* after we release the lock */
return;
}
void
spinmutex_delete(spin_mutex_t *spin_lock)
{
ASSERT(!ksynch_var_initialized(&spin_lock->lock.contended_event));
d_r_mutex_delete(&spin_lock->lock);
}
#ifdef DEADLOCK_AVOIDANCE
static bool
mutex_ownable(mutex_t *lock)
{
bool ownable = LOCK_OWNABLE;
/* i#779: support DR locks used as app locks */
if (lock->app_lock) {
ASSERT(lock->rank == dr_client_mutex_rank);
ownable = LOCK_NOT_OWNABLE;
}
return ownable;
}
#endif
void
d_r_mutex_lock_app(mutex_t *lock, priv_mcontext_t *mc)
{
bool acquired;
#ifdef DEADLOCK_AVOIDANCE
bool ownable = mutex_ownable(lock);
#endif
/* we may want to first spin the lock for a while if we are on a multiprocessor
* machine
*/
/* option is external only so that we can set it to 0 on a uniprocessor */
if (spinlock_count) {
uint i;
/* in the common case we'll just get it */
if (d_r_mutex_trylock(lock))
return;
/* otherwise contended, we should spin for some time */
i = spinlock_count;
/* while spinning we are PAUSEing and reading without LOCKing the bus in the
* spin loop
*/
do {
/* hint we are spinning */
SPINLOCK_PAUSE();
/* We spin only while lock_requests == 0 which means that exactly one thread
holds the lock, while the current one (and possibly a few others) are
contending on who will grab it next. It doesn't make much sense to spin
when the lock->lock_requests > 0 (which means that at least one thread is
already blocked). And of course, we also break if it is LOCK_FREE_STATE.
*/
if (atomic_aligned_read_int(&lock->lock_requests) != LOCK_SET_STATE) {
#ifdef DEADLOCK_AVOIDANCE
lock->count_times_spin_only++;
#endif
break;
}
i--;
} while (i > 0);
}
/* we have strong intentions to grab this lock, increment requests */
acquired = atomic_inc_and_test(&lock->lock_requests);
DEADLOCK_AVOIDANCE_LOCK(lock, acquired, ownable);
if (!acquired) {
mutex_wait_contended_lock(lock, mc);
#ifdef DEADLOCK_AVOIDANCE
DEADLOCK_AVOIDANCE_LOCK(lock, true, ownable); /* now we got it */
/* this and previous owner are not included in lock_requests */
if (lock->max_contended_requests < (uint)lock->lock_requests)
lock->max_contended_requests = (uint)lock->lock_requests;
#endif
}
}
void
d_r_mutex_lock(mutex_t *lock)
{
d_r_mutex_lock_app(lock, NULL);
}
/* try once to grab the lock, return whether or not successful */
bool
d_r_mutex_trylock(mutex_t *lock)
{
bool acquired;
#ifdef DEADLOCK_AVOIDANCE
bool ownable = mutex_ownable(lock);
#endif
/* preserve old value in case not LOCK_FREE_STATE */
acquired =
atomic_compare_exchange(&lock->lock_requests, LOCK_FREE_STATE, LOCK_SET_STATE);
/* if old value was free, that means we just obtained lock
old value may be >=0 when several threads are trying to acquire lock,
so we should return false
*/
DEADLOCK_AVOIDANCE_LOCK(lock, acquired, ownable);
return acquired;
}
/* free the lock */
void
d_r_mutex_unlock(mutex_t *lock)
{
#ifdef DEADLOCK_AVOIDANCE
bool ownable = mutex_ownable(lock);
#endif
ASSERT(lock->lock_requests > LOCK_FREE_STATE && "lock not owned");
DEADLOCK_AVOIDANCE_UNLOCK(lock, ownable);
if (atomic_dec_and_test(&lock->lock_requests))
return;
/* if we were not the last one to hold the lock,
(i.e. final value is not LOCK_FREE_STATE)
we need to notify another waiting thread */
mutex_notify_released_lock(lock);
}
/* releases any associated kernel objects */
void
d_r_mutex_delete(mutex_t *lock)
{
LOG(GLOBAL, LOG_THREADS, 3, "mutex_delete lock " PFX "\n", lock);
/* When doing detach, application locks may be held on threads which have
* already been interrupted and will never execute lock code again. Just
* ignore the assert on the lock_requests field below in those cases.
*/
DEBUG_DECLARE(bool skip_lock_request_assert = false;)
#ifdef DEADLOCK_AVOIDANCE
LOG(THREAD_GET, LOG_THREADS, 3,
"mutex_delete " DUMP_LOCK_INFO_ARGS(0, lock, lock->prev_process_lock));
remove_process_lock(lock);
lock->deleted = true;
if (doing_detach) {
/* For possible re-attach we clear the acquired count. We leave
* deleted==true as it is not used much and we don't have a simple method for
* clearing it: we'd have to keep a special list of all locks used (appending
* as they're deleted) and then walk it from dynamo_exit_post_detach().
*/
lock->count_times_acquired = 0;
# ifdef DEBUG
skip_lock_request_assert = lock->app_lock;
# endif
}
#else
# ifdef DEBUG
/* We don't support !DEADLOCK_AVOIDANCE && DEBUG: we need to know whether to
* skip the assert lock_requests but don't know if this lock is an app lock
*/
# error DEBUG mode not supported without DEADLOCK_AVOIDANCE
# endif /* DEBUG */
#endif /* DEADLOCK_AVOIDANCE */
ASSERT(skip_lock_request_assert || lock->lock_requests == LOCK_FREE_STATE);
if (ksynch_var_initialized(&lock->contended_event)) {
mutex_free_contended_event(lock);
}
}
void
d_r_mutex_mark_as_app(mutex_t *lock)
{
#ifdef DEADLOCK_AVOIDANCE
lock->app_lock = true;
#endif
}
static inline void
own_recursive_lock(recursive_lock_t *lock)
{
#ifdef DEADLOCK_AVOIDANCE
ASSERT(!mutex_ownable(&lock->lock) || OWN_MUTEX(&lock->lock));
#endif
ASSERT(lock->owner == INVALID_THREAD_ID);
ASSERT(lock->count == 0);
lock->owner = d_r_get_thread_id();
ASSERT(lock->owner != INVALID_THREAD_ID);
lock->count = 1;
}