-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlksmith.c
1380 lines (1279 loc) · 35.1 KB
/
lksmith.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
/*
* vim: ts=8:sw=8:tw=79:noet
*
* Copyright (c) 2011-2012, the Locksmith authors.
* 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.
*
* 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 THE COPYRIGHT HOLDER 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.
*/
#include "backtrace.h"
#include "config.h"
#include "error.h"
#include "handler.h"
#include "lksmith.h"
#include "platform.h"
#include "tree.h"
#include "util.h"
#include <errno.h>
#include <execinfo.h>
#include <fnmatch.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/******************************************************************
* Locksmith private data structures
*****************************************************************/
#define MAX_NLOCK 0x1fffffffffffffffULL
struct lksmith_lock_props {
/** The number of times this mutex has been locked. */
uint64_t nlock : 61;
/** 1 if we should allow recursive locks. */
uint64_t recursive : 1;
/** 1 if this mutex is a sleeping lock */
uint64_t sleeper : 1;
/** 1 if we have already warned about taking this lock while
* a spin lock is held. */
uint64_t spin_warn : 1;
};
struct lksmith_holder {
/** Name of the thread holding the lock */
char name[LKSMITH_THREAD_NAME_MAX];
/** Stack frames */
char** bt_frames;
/** Number of stack frames */
int bt_len;
/** Next in singly-linked list */
struct lksmith_holder *next;
};
struct lksmith_lock {
RB_ENTRY(lksmith_lock) entry;
/** The lock pointer */
const void *ptr;
struct lksmith_lock_props props;
/** The color that this node has been painted (used in traversal) */
uint64_t color;
/** Lock holders */
struct lksmith_holder *holders;
/** Size of the before list. */
int before_size;
/** list of locks that have been taken before this lock */
struct lksmith_lock **before;
};
struct lksmith_cond {
RB_ENTRY(lksmith_cond) entry;
/** The condition variable pointer */
const void *ptr;
/** When a pthread_cond_wait is in progress on this condition variable,
* this is the lock that is being used. */
const void *lock;
/** Number of waiters */
uint64_t refcnt;
};
struct lksmith_tls {
/** The name of this thread. */
char name[LKSMITH_THREAD_NAME_MAX];
/** Size of the held list. */
unsigned int num_held;
/** Unsorted list of locks held */
const void **held;
/** Number of spin locks currently held. */
uint64_t num_spins : 63;
/** 1 if we should intercept pthreads calls; 0 otherwise */
uint64_t intercept : 1;
/** scratch area for backtraces */
void **backtrace_scratch;
/** length of scratch area for backtraces */
int backtrace_scratch_len;
};
/******************************************************************
* Locksmith prototypes
*****************************************************************/
static int lksmith_lock_compare(const struct lksmith_lock *a,
const struct lksmith_lock *b) __attribute__((const));
RB_HEAD(lock_tree, lksmith_lock);
RB_GENERATE(lock_tree, lksmith_lock, entry, lksmith_lock_compare);
static int lksmith_cond_compare(const struct lksmith_cond *a,
const struct lksmith_cond *b) __attribute__((const));
RB_HEAD(cond_tree, lksmith_cond);
RB_GENERATE(cond_tree, lksmith_cond, entry, lksmith_cond_compare);
static void lksmith_tls_destroy(void *v);
static void lk_dump_to_stderr(struct lksmith_lock *lk) __attribute__((unused));
static void tree_print(void) __attribute__((unused));
static int compare_strings(const void *a, const void *b)
__attribute__((const));
/******************************************************************
* Locksmith globals
*****************************************************************/
/**
* 1 if the library has been initialized.
*/
static int g_initialized;
/**
* Protects the initialization state.
*/
static int g_init_state_lock;
/**
* The key that allows us to retrieve thread-local data.
* Protected by g_init_state_lock.
*/
static pthread_key_t g_tls_key;
/**
* Mutex which protects g_tree
*/
static pthread_mutex_t g_tree_lock;
/**
* Tree of mutexes sorted by pointer
*/
struct lock_tree g_tree;
/**
* Mutex which protects g_cond_tree
*/
static pthread_mutex_t g_cond_tree_lock;
/**
* Tree of condition variables sorted by pointer
*/
struct cond_tree g_cond_tree;
/**
* The latest color that has been used in graph traversal
*/
static uint64_t g_color;
/**
* A sorted list of frames to ignore.
*/
static char **g_ignored_frames;
/**
* The number of ignored frames.
*/
static int g_num_ignored_frames;
/**
* A list of frame patterns to ignore.
*/
static char **g_ignored_frame_patterns;
/**
* The number of ignored frame patterns.
*/
static int g_num_ignored_frame_patterns;
/******************************************************************
* Initialization
*****************************************************************/
static int compare_strings(const void *a, const void *b)
{
const char *sa = *(const char **)a;
const char *sb = *(const char **)b;
return strcmp(sa, sb);
}
static int lksmith_init_ignored(const char *env, char ***out, int *out_len)
{
int ret, num_ignored = 0;
const char *ignored_env;
char *ignored = NULL, **ignored_arr = 0, *saveptr = NULL;
const char *str;
ignored_env = getenv(env);
if (!ignored_env) {
ret = 0;
goto done;
}
ignored = strdup(ignored_env);
if (!ignored) {
ret = ENOMEM;
goto done;
}
for (str = strtok_r(ignored, ":", &saveptr);
str; str = strtok_r(NULL, ":", &saveptr)) {
num_ignored++;
}
strcpy(ignored, ignored_env);
ignored_arr = calloc(num_ignored, sizeof(char*));
if (!ignored_arr) {
ret = ENOMEM;
goto done;
}
num_ignored = 0;
for (str = strtok_r(ignored, ":", &saveptr);
str; str = strtok_r(NULL, ":", &saveptr)) {
ignored_arr[num_ignored] = strdup(str);
if (!ignored_arr[num_ignored]) {
ret = ENOMEM;
goto done;
}
num_ignored++;
}
qsort(ignored_arr, num_ignored, sizeof(char*), compare_strings);
ret = 0;
done:
free(ignored);
if (ret) {
if (ignored_arr) {
char **i;
for (i = ignored_arr; *i; i++) {
free(*i);
}
free(ignored_arr);
}
return ret;
}
*out = ignored_arr;
*out_len = num_ignored;
return 0;
}
/**
* Initialize the locksmith library.
*/
static void lksmith_init(void)
{
int ret;
ret = lksmith_handler_init();
if (ret) {
/* can't use lksmith_error before handler */
fprintf(stderr, "lksmith_init: lksmith_handler_init failed. "
"Can't find the real pthreads functions.\n");
abort();
}
ret = lksmith_init_ignored("LKSMITH_IGNORED_FRAMES",
&g_ignored_frames, &g_num_ignored_frames);
if (ret) {
lksmith_error(ret, "lksmith_init: lksmith_init_ignored_frames("
"frames) failed: error %d: %s\n", ret, terror(ret));
abort();
}
ret = lksmith_init_ignored("LKSMITH_IGNORED_FRAME_PATTERNS",
&g_ignored_frame_patterns,
&g_num_ignored_frame_patterns);
if (ret) {
lksmith_error(ret, "lksmith_init: lksmith_init_ignored_frames("
"patterns) failed: error %d: %s\n", ret, terror(ret));
abort();
}
ret = pthread_key_create(&g_tls_key, lksmith_tls_destroy);
if (ret) {
lksmith_error(ret, "lksmith_init: pthread_key_create("
"g_tls_key) failed: error %d: %s\n", ret, terror(ret));
abort();
}
ret = r_pthread_mutex_init(&g_tree_lock, NULL);
if (ret) {
lksmith_error(ret, "lksmith_init: pthread_mutex_init "
"g_tree_lock) failed: error %d: %s\n", ret, terror(ret));
abort();
}
ret = r_pthread_mutex_init(&g_cond_tree_lock, NULL);
if (ret) {
lksmith_error(ret, "lksmith_init: pthread_mutex_init "
"g_cond_tree_lock) failed: error %d: %s\n",
ret, terror(ret));
abort();
}
lksmith_error(0, "Locksmith has been initialized for process %lld\n",
(long long)getpid());
g_initialized = 1;
}
/******************************************************************
* Thread-local storage
*****************************************************************/
/**
* Callback which destroys thread-local storage.
*
* This callback will be invoked whenever a thread exits.
*
* @param v The TLS object.
*/
static void lksmith_tls_destroy(void *v)
{
struct lksmith_tls *tls = v;
free(tls->held);
free(tls);
}
/**
* Get or create the thread-local storage associated with this thread.
*
* The problem with POSIX thread-local storage is that in order to use it,
* you must first initialize a 'key'. But how do you initialize this key
* prior to use? There's no good way to do it.
*
* gcc provides the non-portable __attribute__((constructor)), which seems like
* it could be useful. Unfortunately, the order in which these constructor
* functions are called between shared libraries is not defined.
* If another shared library defines some constructor functions which invoke
* pthreads functions, and it gets run before we initialize, it's game over.
* C++ global constructors have the same issues.
*
* We could force Locksmith users to call an init function before calling any
* other Locksmith functions. Then, this init function could initialize the
* key. But that would be painful for many users. This is especially true
* in C++, where global constructors often make use of mutexes long before
* main() runs.
*
* The other approach, which we have taken here, is to protect the key with a
* mutex. This is somewhat slow, since it means that we have to take this
* mutex before every access to thread-local data. Luckily, on platforms
* that support the __thread keyword, we can bypass this slowness.
* Thread-local variables declared using __thread don't need to be manually
* intialized before use. They're ready to go before any code has been run.
*
* One advantage that POSIX thread-local variables have over __thread
* variables is that the former can declare "destructors" which are run when
* the thread is destroyed. (These have no relation to the C++ concept of
* the same name.) We make use of that ability here, to clean up our
* malloc()ed thread-local data when the thread in question exits.
* By combining the __thread keyword and POSIX thread-local variables, we can
* get the best of each.
*
* @return NULL on OOM, the TLS otherwise.
*/
static struct lksmith_tls *get_or_create_tls(void)
{
int ret = 0;
struct lksmith_tls *tls;
#ifdef HAVE_IMPROVED_TLS
static __thread struct lksmith_tls *t_improved_tls = NULL;
if (t_improved_tls) {
return t_improved_tls;
}
#endif
simple_spin_lock(&g_init_state_lock);
if (!g_initialized) {
lksmith_init();
}
simple_spin_unlock(&g_init_state_lock);
#ifndef HAVE_IMPROVED_TLS
tls = pthread_getspecific(g_tls_key);
if (tls) {
return tls;
}
#endif
tls = calloc(1, sizeof(*tls));
if (!tls) {
lksmith_error(ENOMEM,
"get_or_create_tls(): failed to allocate "
"memory for thread-local storage.\n");
return NULL;
}
tls->intercept = 1;
platform_create_thread_name(tls->name, LKSMITH_THREAD_NAME_MAX);
ret = pthread_setspecific(g_tls_key, tls);
if (ret) {
free(tls->held);
free(tls);
lksmith_error(ENOMEM,
"get_or_create_tls(): pthread_setspecific "
"failed with error %d: %s\n", ret, terror(ret));
return NULL;
}
#ifdef HAVE_IMPROVED_TLS
t_improved_tls = tls;
#endif
return tls;
}
int init_tls(void)
{
struct lksmith_tls *tls;
tls = get_or_create_tls();
if (!tls)
return -ENOMEM;
return 0;
}
/**
* Add a lock ID to the end of the list of lock IDs we hold.
*
* NOTE: lock IDs can be added more than once to this list!
* This is so that we can support recursive mutexes.
*
* @param tls The thread-local data.
* @param ptr the lock to add to the list.
*
* @return 0 on success; ENOMEM if we ran out of memory.
*/
static int tls_append_held(struct lksmith_tls *tls, const void *ptr)
{
const void **held;
held = realloc(tls->held, sizeof(uintptr_t) * (tls->num_held + 1));
if (!held)
return ENOMEM;
tls->held = held;
held[tls->num_held++] = ptr;
return 0;
}
/**
* Remove a lock ID from the list of lock IDs we hold.
*
* @param tls The thread-local data.
* @param ptr the lock ID to add to the list.
*
* @return 0 on success; ENOENT if we are not holding the
* lock ID.
*/
static int tls_remove_held(struct lksmith_tls *tls, const void *ptr)
{
signed int i;
const void **held;
for (i = tls->num_held - 1; i >= 0; i--) {
if (tls->held[i] == ptr)
break;
}
if (i < 0)
return ENOENT;
memmove(&tls->held[i], &tls->held[i + 1],
sizeof(struct lksmith_held*) * (tls->num_held - i - 1));
held = realloc(tls->held, sizeof(uintptr_t) * (--tls->num_held));
if (held || (tls->num_held == 0)) {
tls->held = held;
}
return 0;
}
/**
* Determine if we are holding a lock.
*
* @param tls The thread-local data.
* @param ptr The lock ID to find.
*
* @return 1 if we hold the lock; 0 otherwise.
*/
static int tls_contains_lid(struct lksmith_tls *tls, const void *ptr)
{
unsigned int i;
for (i = 0; i < tls->num_held; i++) {
if (tls->held[i] == ptr)
return 1;
}
return 0;
}
static void lksmith_error_with_ti(struct lksmith_tls *tls, int err,
const char *fmt, ...)
__attribute__((format(printf, 3, 4)));
/**
* Locksmith error with thread information (including a backtrace)
*
* @param tls Our thread-local storage object
* @param err the locksmith error code
* @param fmt printf-style format string
*/
static void lksmith_error_with_ti(struct lksmith_tls *tls, int err,
const char *fmt, ...)
{
va_list ap;
int nframes, prev_intercept;
char **frames = NULL;
if (!tls) {
tls = get_or_create_tls();
if (!tls) {
va_start(ap, fmt);
lksmith_errora(err, fmt, ap);
va_end(ap);
return;
}
}
prev_intercept = tls->intercept;
tls->intercept = 0;
nframes = bt_frames_create(&tls->backtrace_scratch,
&tls->backtrace_scratch_len, &frames);
tls->intercept = prev_intercept;
va_start(ap, fmt);
// lksmith_errora_with_bt handles nframes < 0 (the error case)
lksmith_errora_with_bt(err, frames, nframes, fmt, ap);
va_end(ap);
bt_frames_free(frames);
}
/******************************************************************
* Lock holder functions
*****************************************************************/
/**
* Dump out the contents of a lock holder structure
*
* @param holder The lock holder
* @param buf (out param) the buffer to write to
* @param off (inout param) current position in the buffer
* @param buf_len length of buf
*/
static void holder_dump(const struct lksmith_holder *holder,
char *buf, size_t *off, size_t buf_len)
{
const char *prefix = "";
int i;
fwdprintf(buf, off, buf_len, "{name=%s, "
"bt_frames=[", holder->name);
for (i = 0; i < holder->bt_len; i++) {
fwdprintf(buf, off, buf_len, "%s%s", prefix,
holder->bt_frames[i]);
prefix = ", ";
}
fwdprintf(buf, off, buf_len, "]}");
}
/**
* Create a lock holder.
*
* @param tls The thread-local storage for the current thread.
*
* @return The lock holder on success; NULL otherwise.
*/
static struct lksmith_holder* holder_create(struct lksmith_tls *tls)
{
struct lksmith_holder *holder;
int intercept, ret;
holder = calloc(1, sizeof(*holder));
if (!holder)
return NULL;
snprintf(holder->name, sizeof(holder->name), "%s", tls->name);
intercept = tls->intercept;
tls->intercept = 0;
ret = bt_frames_create(&tls->backtrace_scratch,
&tls->backtrace_scratch_len, &holder->bt_frames);
tls->intercept = intercept;
if (ret < 0) {
free(holder);
return NULL;
}
holder->bt_len = ret;
return holder;
}
/**
* Free a lock holder structure
*
* @param holder The lock holder
*/
static void holder_free(struct lksmith_holder *holder)
{
bt_frames_free(holder->bt_frames);
free(holder);
}
/******************************************************************
* Lock functions
*****************************************************************/
static int lksmith_lock_compare(const struct lksmith_lock *a,
const struct lksmith_lock *b)
{
const void *pa = a->ptr;
const void *pb = b->ptr;
if (pa < pb)
return -1;
else if (pa > pb)
return 1;
else
return 0;
}
/**
* Add an element to a sorted array, if it's not already there.
*
* @param arr (inout) the array
* @param num (inout) the array length
* @param lid The lock ID to add.
*
* @return 0 on success; ENOMEM if we ran out of memory.
*/
static int lk_add_sorted(struct lksmith_lock ** __restrict * __restrict arr,
int * __restrict num, struct lksmith_lock *lk)
{
int i;
struct lksmith_lock **narr;
for (i = 0; i < *num; i++) {
if ((*arr)[i] == lk)
return 0;
else if ((*arr)[i] > lk)
break;
}
narr = realloc(*arr, sizeof(struct lksmith_lock*) * (*num + 1));
if (!narr)
return ENOMEM;
*arr = narr;
memmove(&narr[i + 1], &narr[i], sizeof(uintptr_t) * (*num - i));
narr[i] = lk;
*num = *num + 1;
return 0;
}
/**
* Remove an element from a sorted array.
* We assume it appears only once in that array.
* TODO: be smarter here-- use bsearch
*
* @param arr (inout) the array
* @param num (inout) the array length
* @param lid The lock ID to remove.
*/
static void lk_remove_sorted(struct lksmith_lock ** __restrict * __restrict arr,
int * __restrict num, struct lksmith_lock *ak)
{
int i;
struct lksmith_lock **narr;
if (*arr == NULL)
return;
for (i = 0; i < *num; i++) {
if ((*arr)[i] == ak)
break;
else if ((*arr)[i] > ak)
return;
}
if (i == *num)
return;
if (i < (*num -1))
memmove(&(*arr)[i], &(*arr)[i + 1],
sizeof(struct lksmith_lock*) * (*num - i - 1));
narr = realloc(*arr, sizeof(struct lksmith_lock*) * (--*num));
if (narr || (*num == 0))
*arr = narr;
}
/**
* Add a lock to the 'before' set of this lock data.
* Note: you must call this function with the info->lock held.
*
* @param lk The lock data.
* @param lid The lock ID to add.
*
* @return 0 on success; ENOMEM if we ran out of memory.
*/
static int lk_add_before(struct lksmith_lock *lk, struct lksmith_lock *ak)
{
return lk_add_sorted(&lk->before, &lk->before_size, ak);
}
/**
* Remove a lock from the 'after' set of this lock data.
* Note: you must call this function with the info->lock held.
*
* @param lk The lock data.
* @param lid The lock ID to remove.
*/
static void lk_remove_before(struct lksmith_lock *lk, struct lksmith_lock *ak)
{
lk_remove_sorted(&lk->before, &lk->before_size, ak);
}
/**
* Add a lock holder to the lock.
* Note: you must call this function with the info->lock held.
*
* @param lk The lock data.
* @param holder The lock holder to add.
*/
static void lk_holder_add(struct lksmith_lock *lk,
struct lksmith_holder *holder)
{
holder->next = lk->holders;
lk->holders = holder;
}
/**
* Remove a lock holder from the lock.
* Note: you must call this function with the info->lock held.
*
* @param lk The lock data.
* @param tls The thread-local storage for the current thread.
*
* @return 0 on success; -ENOENT if the lock holder wasn't found.
*/
static int lk_holder_remove(struct lksmith_lock *lk,
struct lksmith_tls *tls)
{
struct lksmith_holder **holder, *next;
/* By iterating forward through the list, we ensure that holders are
* taken out in the reverse order that they were put in (since we also
* insert to the head of the list.) This is important when dealing
* with recursive locks, where one thread can take the same lock over
* and over. */
holder = &lk->holders;
while (*holder) {
if (!strcmp(tls->name, (*holder)->name))
break;
holder = &(*holder)->next;
}
if (!holder)
return -ENOENT;
next = (*holder)->next;
holder_free(*holder);
*holder = next;
return 0;
}
/**
* Dump out the contents of a lock data structure.
*
* @param lk The lock data
* @param buf (out param) the buffer to write to
* @param off (inout param) current position in the buffer
* @param buf_len length of buf
*/
static void lk_dump(const struct lksmith_lock *lk,
char *buf, size_t *off, size_t buf_len)
{
int i;
const char *prefix = "";
struct lksmith_holder *holder;
fwdprintf(buf, off, buf_len, "lk{ptr=%p, "
"nlock=%"PRId64", recursive=%d, sleeper=%d,"
"color=%"PRId64", before={",
(void*)lk->ptr, (uint64_t)lk->props.nlock,
lk->props.recursive, lk->props.sleeper,
lk->color);
for (i = 0; i < lk->before_size; i++) {
fwdprintf(buf, off, buf_len, "%s%p",
prefix, lk->before[i]);
prefix = " ";
}
fwdprintf(buf, off, buf_len, "}, holders=[");
prefix = "";
holder = lk->holders;
while (holder) {
fwdprintf(buf, off, buf_len, "%s", prefix);
holder_dump(holder, buf, off, buf_len);
prefix = ", ";
holder = holder->next;
}
fwdprintf(buf, off, buf_len, "]}");
}
static void lk_dump_to_stderr(struct lksmith_lock *lk)
{
char buf[16384];
size_t off = 0;
lk_dump(lk, buf, &off, sizeof(buf));
fputs(buf, stderr);
fputs("\n", stderr);
}
static void tree_print(void)
{
char buf[8196];
struct lksmith_lock *lk;
size_t off;
const char *prefix = "";
fprintf(stderr, "g_lock_tree: {");
RB_FOREACH(lk, lock_tree, &g_tree) {
off = 0;
lk_dump(lk, buf, &off, sizeof(buf));
fprintf(stderr, "%s%s", prefix, buf);
prefix = ",\n";
}
fprintf(stderr, "\n}\n");
}
static int lksmith_insert(const void *ptr, int recursive,
int sleeper, struct lksmith_lock **lk)
{
struct lksmith_lock *ak, *bk;
ak = calloc(1, sizeof(*ak));
if (!ak) {
return ENOMEM;
}
ak->ptr = ptr;
ak->props.recursive = !!recursive;
ak->props.sleeper = !!sleeper;
ak->holders = NULL;
bk = RB_INSERT(lock_tree, &g_tree, ak);
if (bk) {
free(ak);
return EEXIST;
}
*lk = ak;
return 0;
}
static struct lksmith_lock *lksmith_find(const void *ptr)
{
struct lksmith_lock exemplar;
memset(&exemplar, 0, sizeof(exemplar));
exemplar.ptr = ptr;
return RB_FIND(lock_tree, &g_tree, &exemplar);
}
/******************************************************************
* Cond functions
*****************************************************************/
static int lksmith_cond_compare(const struct lksmith_cond *a,
const struct lksmith_cond *b)
{
const void *pa = a->ptr;
const void *pb = b->ptr;
if (pa < pb)
return -1;
else if (pa > pb)
return 1;
else
return 0;
}
static struct lksmith_cond *lksmith_cond_find(const void *ptr)
{
struct lksmith_cond exemplar;
memset(&exemplar, 0, sizeof(exemplar));
exemplar.ptr = ptr;
return RB_FIND(cond_tree, &g_cond_tree, &exemplar);
}
static int lksmith_cond_insert(const void *ptr, struct lksmith_cond **cond)
{
struct lksmith_cond *cnd, *and;
cnd = calloc(1, sizeof(*cnd));
if (!cnd) {
return ENOMEM;
}
cnd->ptr = ptr;
and = RB_INSERT(cond_tree, &g_cond_tree, cnd);
if (and) {
free(cnd);
return EEXIST;
}
*cond = cnd;
return 0;
}
/******************************************************************
* API functions
*****************************************************************/
int lksmith_optional_init(const void *ptr, int recursive, int sleeper)
{
struct lksmith_tls *tls;
struct lksmith_lock *lk;
int ret;
tls = get_or_create_tls();
if (!tls) {
lksmith_error(ENOMEM, "lksmith_optional_init(lock=%p): "
"failed to allocate thread-local storage.\n", ptr);
return ENOMEM;
}
if (!tls->intercept)
return 0;
r_pthread_mutex_lock(&g_tree_lock);
ret = lksmith_insert(ptr, recursive, sleeper, &lk);
r_pthread_mutex_unlock(&g_tree_lock);
if (ret) {
lksmith_error(ret, "lksmith_optional_init(lock=%p, "
"thread=%s): failed to allocate lock data: "
"error %d: %s\n", ptr, tls->name, ret, terror(ret));
return ret;
}
return 0;
}
int lksmith_destroy(const void *ptr)
{
int ret;
struct lksmith_lock *lk, *ak;
struct lksmith_tls *tls;
tls = get_or_create_tls();
if (!tls) {
lksmith_error(ENOMEM, "lksmith_destroy(lock=%p): failed to "
"allocate thread-local storage.\n", ptr);
ret = ENOMEM;
goto done;
}
if (!tls->intercept)
return 0;
r_pthread_mutex_lock(&g_tree_lock);
lk = lksmith_find(ptr);
if (!lk) {
/* This might not be an error, if we used
* PTHREAD_MUTEX_INITIALIZER and then never did anything else
* with the lock prior to destroying it. */
ret = ENOENT;
goto done_unlock;
}
if (lk->holders != NULL) {
if (tls_contains_lid(tls, ptr) == 1) {
lksmith_error(EBUSY, "lksmith_destroy(lock=%p, "
"thread=%s): you must unlock this mutex "
"before destroying it.", ptr, tls->name);
} else {
lksmith_error(EBUSY, "lksmith_destroy(lock=%p, "
"thread=%s): this mutex is currently in use "
"and so cannot be destroyed.", ptr, tls->name);
}
ret = EBUSY;
goto done_unlock;
}
RB_REMOVE(lock_tree, &g_tree, lk);
/* TODO: could probably avoid traversing the whole tree by using both
* before and after pointers inside locks, or some such? */
RB_FOREACH(ak, lock_tree, &g_tree) {
lk_remove_before(ak, lk);
}
free(lk->before);
free(lk);
ret = 0;
done_unlock:
r_pthread_mutex_unlock(&g_tree_lock);
done:
return ret;
}
static int lksmith_search(struct lksmith_lock *lk, const void *start)
{
int ret, i;
if (lk->ptr == start)
return 1;
if (lk->color == g_color)
return 0;
lk->color = g_color;
for (i = 0; i < lk->before_size; i++) {
ret = lksmith_search(lk->before[i], start);
if (ret)
return ret;
}
return 0;
}
static void lksmith_prelock_process_depends(struct lksmith_tls *tls,
struct lksmith_lock *lk, const void *ptr)
{
unsigned int i;
const void *held;
struct lksmith_lock *ak;