forked from Previsou/mutrace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutrace.c
2429 lines (1825 loc) · 73.7 KB
/
mutrace.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
/*-*- Mode: C; c-basic-offset: 8 -*-*/
/***
This file is part of mutrace.
Copyright 2009 Lennart Poettering
mutrace is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
mutrace is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with mutrace. If not, see <http://www.gnu.org/licenses/>.
***/
#include "config.h"
#include <pthread.h>
#include <execinfo.h>
#include <stdlib.h>
#include <inttypes.h>
#include <assert.h>
#include <dlfcn.h>
#include <stdbool.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <sched.h>
#include <malloc.h>
#include <signal.h>
#include <math.h>
#if !defined (__linux__) || !defined(__GLIBC__)
#error "This stuff only works on Linux!"
#endif
#ifndef SCHED_RESET_ON_FORK
/* "Your libc lacks the definition of SCHED_RESET_ON_FORK. We'll now
* define it ourselves, however make sure your kernel is new
* enough! */
#define SCHED_RESET_ON_FORK 0x40000000
#endif
#if defined(__i386__) || defined(__x86_64__)
#define DEBUG_TRAP __asm__("int $3")
#else
#define DEBUG_TRAP raise(SIGTRAP)
#endif
#define LIKELY(x) (__builtin_expect(!!(x),1))
#define UNLIKELY(x) (__builtin_expect(!!(x),0))
struct stacktrace_info {
void **frames;
int nb_frame;
};
/* Used to differentiate between statistics for read-only and read-write locks
* held on rwlocks. */
typedef enum {
WRITE = 0,
READ = 1,
} LockType;
#define NUM_LOCK_TYPES READ + 1
struct mutex_info {
pthread_mutex_t *mutex;
pthread_rwlock_t *rwlock;
int type, protocol, kind;
bool broken:1;
bool realtime:1;
bool dead:1;
unsigned n_lock_level;
LockType lock_type; /* rwlocks only */
pid_t last_owner;
unsigned n_locked[NUM_LOCK_TYPES];
unsigned n_contended[NUM_LOCK_TYPES];
unsigned n_owner_changed;
uint64_t nsec_locked_total[NUM_LOCK_TYPES];
uint64_t nsec_locked_max[NUM_LOCK_TYPES];
uint64_t nsec_contended_total[NUM_LOCK_TYPES];
uint64_t nsec_timestamp[NUM_LOCK_TYPES];
struct stacktrace_info stacktrace;
unsigned id;
struct mutex_info *next;
};
struct cond_info {
pthread_cond_t *cond;
bool broken:1;
bool realtime:1;
bool dead:1;
unsigned n_wait_level;
pthread_mutex_t *mutex;
unsigned n_wait;
unsigned n_signal;
unsigned n_broadcast;
unsigned n_wait_contended; /* number of wait() calls made while another
* thread is already waiting on the cond */
unsigned n_signal_contended; /* number of signal() or broadcast() calls
* made while no thread is waiting */
uint64_t nsec_wait_total;
uint64_t nsec_wait_max;
uint64_t nsec_wait_contended_total;
uint64_t nsec_wait_contended_max;
uint64_t nsec_timestamp;
struct stacktrace_info stacktrace;
unsigned id;
struct cond_info *next;
};
static unsigned hash_size = 3371; /* probably a good idea to pick a prime here */
static unsigned frames_max = 16;
static volatile unsigned n_broken_mutexes = 0;
static volatile unsigned n_broken_conds = 0;
static volatile unsigned n_collisions = 0;
static volatile unsigned n_self_contended = 0;
static unsigned show_n_wait_min = 1;
static unsigned show_n_locked_min = 1;
static unsigned show_n_read_locked_min = 0;
static unsigned show_n_contended_min = 0;
static unsigned show_n_read_contended_min = 0;
static unsigned show_n_owner_changed_min = 2;
static unsigned show_n_max = 10;
static bool full_backtrace = false;
static bool raise_trap = false;
static bool track_rt = false;
static int (*real_pthread_mutex_init)(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr) = NULL;
static int (*real_pthread_mutex_destroy)(pthread_mutex_t *mutex) = NULL;
static int (*real_pthread_mutex_lock)(pthread_mutex_t *mutex) = NULL;
static int (*real_pthread_mutex_trylock)(pthread_mutex_t *mutex) = NULL;
static int (*real_pthread_mutex_timedlock)(pthread_mutex_t *mutex, const struct timespec *abstime) = NULL;
static int (*real_pthread_mutex_unlock)(pthread_mutex_t *mutex) = NULL;
static int (*real_pthread_cond_init)(pthread_cond_t *cond, const pthread_condattr_t *attr) = NULL;
static int (*real_pthread_cond_destroy)(pthread_cond_t *cond) = NULL;
static int (*real_pthread_cond_signal)(pthread_cond_t *cond) = NULL;
static int (*real_pthread_cond_broadcast)(pthread_cond_t *cond) = NULL;
static int (*real_pthread_cond_wait)(pthread_cond_t *cond, pthread_mutex_t *mutex) = NULL;
static int (*real_pthread_cond_timedwait)(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) = NULL;
static int (*real_pthread_create)(pthread_t *newthread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg) = NULL;
static void (*real_pthread_exit)(void *retval) __attribute__((noreturn)) = NULL;
static int (*real_pthread_rwlock_init)(pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *attr) = NULL;
static int (*real_pthread_rwlock_destroy)(pthread_rwlock_t *rwlock) = NULL;
static int (*real_pthread_rwlock_rdlock)(pthread_rwlock_t *rwlock) = NULL;
static int (*real_pthread_rwlock_tryrdlock)(pthread_rwlock_t *rwlock) = NULL;
static int (*real_pthread_rwlock_timedrdlock)(pthread_rwlock_t *rwlock, const struct timespec *abstime) = NULL;
static int (*real_pthread_rwlock_wrlock)(pthread_rwlock_t *rwlock) = NULL;
static int (*real_pthread_rwlock_trywrlock)(pthread_rwlock_t *rwlock) = NULL;
static int (*real_pthread_rwlock_timedwrlock)(pthread_rwlock_t *rwlock, const struct timespec *abstime) = NULL;
static int (*real_pthread_rwlock_unlock)(pthread_rwlock_t *rwlock);
static void (*real_exit)(int status) __attribute__((noreturn)) = NULL;
static void (*real__exit)(int status) __attribute__((noreturn)) = NULL;
static void (*real__Exit)(int status) __attribute__((noreturn)) = NULL;
static int (*real_backtrace)(void **array, int size) = NULL;
static char **(*real_backtrace_symbols)(void *const *array, int size) = NULL;
static void (*real_backtrace_symbols_fd)(void *const *array, int size, int fd) = NULL;
static struct mutex_info **alive_mutexes = NULL, **dead_mutexes = NULL;
static pthread_mutex_t *mutexes_lock = NULL;
static struct cond_info **alive_conds = NULL, **dead_conds = NULL;
static pthread_mutex_t *conds_lock = NULL;
static __thread bool recursive = false;
static volatile bool initialized = false;
static volatile bool threads_existing = false;
static uint64_t nsec_timestamp_setup;
typedef struct {
const char *command; /* as passed to --order command line argument */
const char *ui_string; /* as displayed by show_summary() */
} SummaryOrderDetails;
/* Must be kept in sync with summary_mutex_order_details. */
typedef enum {
MUTEX_ORDER_ID = 0,
MUTEX_ORDER_N_LOCKED,
MUTEX_ORDER_N_READ_LOCKED,
MUTEX_ORDER_N_CONTENDED,
MUTEX_ORDER_N_READ_CONTENDED,
MUTEX_ORDER_N_OWNER_CHANGED,
MUTEX_ORDER_NSEC_LOCKED_TOTAL,
MUTEX_ORDER_NSEC_LOCKED_MAX,
MUTEX_ORDER_NSEC_LOCKED_AVG,
MUTEX_ORDER_NSEC_READ_LOCKED_TOTAL,
MUTEX_ORDER_NSEC_READ_LOCKED_MAX,
MUTEX_ORDER_NSEC_READ_LOCKED_AVG,
MUTEX_ORDER_NSEC_CONTENDED_TOTAL,
MUTEX_ORDER_NSEC_CONTENDED_AVG,
MUTEX_ORDER_NSEC_READ_CONTENDED_TOTAL,
MUTEX_ORDER_NSEC_READ_CONTENDED_AVG,
} SummaryMutexOrder;
#define MUTEX_ORDER_INVALID MUTEX_ORDER_NSEC_READ_CONTENDED_AVG + 1 /* first invalid order */
/* Must be kept in sync with SummaryMutexOrder. */
static const SummaryOrderDetails summary_mutex_order_details[] = {
{ "id", "mutex number" },
{ "n-locked", "(write) lock count" },
{ "n-read-locked", "(read) lock count" },
{ "n-contended", "(write) contention count" },
{ "n-read-contended", "(read) contention count" },
{ "n-owner-changed", "owner change count" },
{ "nsec-locked-total", "total time (write) locked" },
{ "nsec-locked-max", "maximum time (write) locked" },
{ "nsec-locked-avg", "average time (write) locked" },
{ "nsec-read-locked-total", "total time (read) locked" },
{ "nsec-read-locked-max", "maximum time (read) locked" },
{ "nsec-read-locked-avg", "average time (read) locked" },
{ "nsec-contended-total", "total time (write) contended" },
{ "nsec-contended-avg", "average time (write) contended" },
{ "nsec-read-contended-total", "total time (read) contended" },
{ "nsec-read-contended-avg", "average time (read) contended" },
};
static SummaryMutexOrder summary_mutex_order = MUTEX_ORDER_N_CONTENDED;
static SummaryMutexOrder summary_mutex_order_from_command(const char *command);
/* Must be kept in sync with summary_cond_order_details. */
typedef enum {
COND_ORDER_ID = 0,
COND_ORDER_N_WAIT,
COND_ORDER_N_SIGNAL,
COND_ORDER_N_BROADCAST,
COND_ORDER_N_WAIT_CONTENDED,
COND_ORDER_N_SIGNAL_CONTENDED,
COND_ORDER_NSEC_WAIT_TOTAL,
COND_ORDER_NSEC_WAIT_MAX,
COND_ORDER_NSEC_WAIT_AVG,
COND_ORDER_NSEC_WAIT_CONTENDED_TOTAL,
COND_ORDER_NSEC_WAIT_CONTENDED_MAX,
COND_ORDER_NSEC_WAIT_CONTENDED_AVG,
} SummaryCondOrder;
#define COND_ORDER_INVALID COND_ORDER_NSEC_WAIT_CONTENDED_AVG + 1 /* first invalid order */
/* Must be kept in sync with SummaryCondOrder. */
static const SummaryOrderDetails summary_cond_order_details[] = {
{ "id", "condition variable number" },
{ "n-wait", "wait count" },
{ "n-signal", "signal count" },
{ "n-broadcast", "broadcast count" },
{ "n-wait-contended", "wait contention count" },
{ "n-signal-contended", "signal contention count" },
{ "nsec-wait-total", "total wait time" },
{ "nsec-wait-max", "maximum wait time" },
{ "nsec-wait-avg", "average wait time" },
{ "nsec-wait-contended-total", "total contended wait time" },
{ "nsec-wait-contended-max", "maximum contended wait time" },
{ "nsec-wait-contended-avg", "average contended wait time" },
};
static SummaryCondOrder summary_cond_order = COND_ORDER_N_WAIT_CONTENDED;
static SummaryCondOrder summary_cond_order_from_command(const char *command);
static void setup(void) __attribute ((constructor));
static void shutdown(void) __attribute ((destructor));
static char *stacktrace_to_string(struct stacktrace_info stacktrace);
static void sigusr1_cb(int sig);
static pid_t _gettid(void) {
return (pid_t) syscall(SYS_gettid);
}
static uint64_t nsec_now(void) {
struct timespec ts;
int r;
r = clock_gettime(CLOCK_MONOTONIC, &ts);
assert(r == 0);
return
(uint64_t) ts.tv_sec * 1000000000ULL +
(uint64_t) ts.tv_nsec;
}
static const char *get_prname(void) {
static char prname[17];
int r;
r = prctl(PR_GET_NAME, prname);
assert(r == 0);
prname[16] = 0;
return prname;
}
static int parse_env(const char *n, unsigned *t) {
const char *e;
char *x = NULL;
unsigned long ul;
if (!(e = getenv(n)))
return 0;
errno = 0;
ul = strtoul(e, &x, 0);
if (!x || *x || errno != 0)
return -1;
*t = (unsigned) ul;
if ((unsigned long) *t != ul)
return -1;
return 0;
}
/* Maximum tolerated relative error when comparing doubles */
#define MAX_RELATIVE_ERROR 0.001
static bool doubles_equal(double a, double b) {
/* Make sure we don't divide by zero. */
if (fpclassify(b) == FP_ZERO)
return (fpclassify(a) == FP_ZERO);
return ((a - b) / b <= MAX_RELATIVE_ERROR);
}
#define LOAD_FUNC(name) \
do { \
*(void**) (&real_##name) = dlsym(RTLD_NEXT, #name); \
assert(real_##name); \
} while (false)
#define LOAD_FUNC_VERSIONED(name, version) \
do { \
*(void**) (&real_##name) = dlvsym(RTLD_NEXT, #name, version); \
assert(real_##name); \
} while (false)
static void load_functions(void) {
static volatile bool loaded = false;
if (LIKELY(loaded))
return;
recursive = true;
/* If someone uses a shared library constructor that is called
* before ours we might not be initialized yet when the first
* lock related operation is executed. To deal with this we'll
* simply call the original implementation and do nothing
* else, but for that we do need the original function
* pointers. */
LOAD_FUNC(pthread_mutex_init);
LOAD_FUNC(pthread_mutex_destroy);
LOAD_FUNC(pthread_mutex_lock);
LOAD_FUNC(pthread_mutex_trylock);
LOAD_FUNC(pthread_mutex_timedlock);
LOAD_FUNC(pthread_mutex_unlock);
LOAD_FUNC(pthread_create);
LOAD_FUNC(pthread_exit);
LOAD_FUNC(pthread_rwlock_init);
LOAD_FUNC(pthread_rwlock_destroy);
LOAD_FUNC(pthread_rwlock_rdlock);
LOAD_FUNC(pthread_rwlock_tryrdlock);
LOAD_FUNC(pthread_rwlock_timedrdlock);
LOAD_FUNC(pthread_rwlock_wrlock);
LOAD_FUNC(pthread_rwlock_trywrlock);
LOAD_FUNC(pthread_rwlock_timedwrlock);
LOAD_FUNC(pthread_rwlock_unlock);
/* There's some kind of weird incompatibility problem causing
* pthread_cond_timedwait() to freeze if we don't ask for this
* explicit version of these functions */
LOAD_FUNC_VERSIONED(pthread_cond_init, "GLIBC_2.3.2");
LOAD_FUNC_VERSIONED(pthread_cond_destroy, "GLIBC_2.3.2");
LOAD_FUNC_VERSIONED(pthread_cond_signal, "GLIBC_2.3.2");
LOAD_FUNC_VERSIONED(pthread_cond_broadcast, "GLIBC_2.3.2");
LOAD_FUNC_VERSIONED(pthread_cond_wait, "GLIBC_2.3.2");
LOAD_FUNC_VERSIONED(pthread_cond_timedwait, "GLIBC_2.3.2");
LOAD_FUNC(exit);
LOAD_FUNC(_exit);
LOAD_FUNC(_Exit);
LOAD_FUNC(backtrace);
LOAD_FUNC(backtrace_symbols);
LOAD_FUNC(backtrace_symbols_fd);
loaded = true;
recursive = false;
}
static void setup(void) {
struct sigaction sigusr_action;
pthread_mutex_t *m, *last;
int r;
unsigned t;
const char *s;
load_functions();
if (LIKELY(initialized))
return;
if (!dlsym(NULL, "main"))
fprintf(stderr,
"mutrace: Application appears to be compiled without -rdynamic. It might be a\n"
"mutrace: good idea to recompile with -rdynamic enabled since this produces more\n"
"mutrace: useful stack traces.\n\n");
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
if (__malloc_hook) {
#pragma GCC diagnostic pop
fprintf(stderr,
"mutrace: Detected non-glibc memory allocator. Your program uses some\n"
"mutrace: alternative memory allocator (jemalloc?) which is not compatible with\n"
"mutrace: mutrace. Please rebuild your program with the standard memory\n"
"mutrace: allocator or fix mutrace to handle yours correctly.\n");
/* The reason for this is that jemalloc and other
* allocators tend to call pthread_mutex_xxx() from
* the allocator. However, we need to call malloc()
* ourselves from some mutex operations so this might
* create an endless loop eventually overflowing the
* stack. glibc's malloc() does locking too but uses
* lock routines that do not end up calling
* pthread_mutex_xxx(). */
real_exit(1);
}
t = hash_size;
if (parse_env("MUTRACE_HASH_SIZE", &t) < 0 || t <= 0)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_HASH_SIZE.\n");
else
hash_size = t;
t = frames_max;
if (parse_env("MUTRACE_FRAMES", &t) < 0 || t <= 0)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_FRAMES.\n");
else
frames_max = t;
t = show_n_wait_min;
if (parse_env("MUTRACE_WAIT_MIN", &t) < 0)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_WAIT_MIN.\n");
else
show_n_wait_min = t;
t = show_n_locked_min;
if (parse_env("MUTRACE_LOCKED_MIN", &t) < 0)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_LOCKED_MIN.\n");
else
show_n_locked_min = t;
t = show_n_read_locked_min;
if (parse_env("MUTRACE_READ_LOCKED_MIN", &t) < 0)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_READ_LOCKED_MIN.\n");
else
show_n_read_locked_min = t;
t = show_n_contended_min;
if (parse_env("MUTRACE_CONTENDED_MIN", &t) < 0)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_CONTENDED_MIN.\n");
else
show_n_contended_min = t;
t = show_n_read_contended_min;
if (parse_env("MUTRACE_READ_CONTENDED_MIN", &t) < 0)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_READ_CONTENDED_MIN.\n");
else
show_n_read_contended_min = t;
t = show_n_owner_changed_min;
if (parse_env("MUTRACE_OWNER_CHANGED_MIN", &t) < 0)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_OWNER_CHANGED_MIN.\n");
else
show_n_owner_changed_min = t;
t = show_n_max;
if (parse_env("MUTRACE_MAX", &t) < 0)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_MAX.\n");
else
show_n_max = t;
s = getenv("MUTRACE_FULL_BACKTRACE");
if (s != NULL && strncmp(s, "true", 4) == 0)
full_backtrace = true;
s = getenv("MUTRACE_SUMMARY_MUTEX_ORDER");
if (s != NULL) {
t = summary_mutex_order_from_command(s);
if (t == MUTEX_ORDER_INVALID)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_SUMMARY_MUTEX_ORDER.\n");
else
summary_mutex_order = t;
}
s = getenv("MUTRACE_SUMMARY_COND_ORDER");
if (s != NULL) {
t = summary_cond_order_from_command(s);
if (t == COND_ORDER_INVALID)
fprintf(stderr, "mutrace: WARNING: Failed to parse $MUTRACE_SUMMARY_COND_ORDER.\n");
else
summary_cond_order = t;
}
if (getenv("MUTRACE_TRAP"))
raise_trap = true;
if (getenv("MUTRACE_TRACK_RT"))
track_rt = true;
/* Set up the mutex hash table. */
alive_mutexes = calloc(hash_size, sizeof(struct mutex_info*));
assert(alive_mutexes);
dead_mutexes = calloc(hash_size, sizeof(struct mutex_info*));
assert(dead_mutexes);
mutexes_lock = malloc(hash_size * sizeof(pthread_mutex_t));
assert(mutexes_lock);
for (m = mutexes_lock, last = mutexes_lock+hash_size; m < last; m++) {
r = real_pthread_mutex_init(m, NULL);
assert(r == 0);
}
/* Set up the cond hash table. */
alive_conds = calloc(hash_size, sizeof(struct cond_info*));
assert(alive_conds);
dead_conds = calloc(hash_size, sizeof(struct cond_info*));
assert(dead_conds);
conds_lock = malloc(hash_size * sizeof(pthread_mutex_t));
assert(conds_lock);
for (m = conds_lock, last = conds_lock+hash_size; m < last; m++) {
r = real_pthread_mutex_init(m, NULL);
assert(r == 0);
}
/* Listen for SIGUSR1 and print out a summary of what's happened so far
* when we receive it. */
sigusr_action.sa_handler = sigusr1_cb;
sigemptyset(&sigusr_action.sa_mask);
sigusr_action.sa_flags = 0;
sigaction(SIGUSR1, &sigusr_action, NULL);
nsec_timestamp_setup = nsec_now();
initialized = true;
fprintf(stderr, "mutrace: "PACKAGE_VERSION" successfully initialized for process %s (PID: %lu).\n",
get_prname(), (unsigned long) getpid());
}
static unsigned long mutex_hash(pthread_mutex_t *mutex) {
unsigned long u;
u = (unsigned long) mutex;
u /= sizeof(void*);
return u % hash_size;
}
static unsigned long rwlock_hash(pthread_rwlock_t *rwlock) {
unsigned long u;
u = (unsigned long) rwlock;
u /= sizeof(void*);
return u % hash_size;
}
static unsigned long cond_hash(pthread_cond_t *cond) {
unsigned long u;
u = (unsigned long) cond;
u /= sizeof(void*);
return u % hash_size;
}
static void lock_hash(pthread_mutex_t *lock_array, unsigned u) {
int r;
r = real_pthread_mutex_trylock(lock_array + u);
if (UNLIKELY(r == EBUSY)) {
__sync_fetch_and_add(&n_self_contended, 1);
r = real_pthread_mutex_lock(lock_array + u);
}
assert(r == 0);
}
static void unlock_hash(pthread_mutex_t *lock_array, unsigned u) {
int r;
r = real_pthread_mutex_unlock(lock_array + u);
assert(r == 0);
}
#define lock_hash_mutex(u) lock_hash(mutexes_lock, u)
#define unlock_hash_mutex(u) unlock_hash(mutexes_lock, u)
#define lock_hash_cond(u) lock_hash(conds_lock, u)
#define unlock_hash_cond(u) unlock_hash(conds_lock, u)
#define _ORDER_CASE(TYPE, UCASE, lcase) \
case TYPE##_ORDER_##UCASE: \
if (a->lcase != b->lcase) \
return a->lcase - b->lcase; \
break;
#define _ORDER_CASE_AVG(TYPE, UCASE, lcase, divisor) \
case TYPE##_ORDER_##UCASE: { \
double a_avg = a->lcase / a->divisor, \
b_avg = b->lcase / b->divisor; \
if (!doubles_equal(a_avg, b_avg)) \
return ((a_avg - b_avg) < 0.0) ? -1 : 1; \
break; \
}
#define STATIC_ORDER(lcase) \
if (a->lcase != b->lcase) \
return a->lcase - b->lcase
static int mutex_info_compare(const void *_a, const void *_b) {
const struct mutex_info
*a = *(const struct mutex_info**) _a,
*b = *(const struct mutex_info**) _b;
/* Order by the user's chosen ordering first, then fall back to a static
* ordering. */
switch (summary_mutex_order) {
#define ORDER_CASE(UCASE, lcase) _ORDER_CASE(MUTEX, UCASE, lcase)
#define ORDER_CASE_AVG(UCASE, lcase, divisor) _ORDER_CASE_AVG(MUTEX, UCASE, lcase, divisor)
ORDER_CASE(ID, id)
ORDER_CASE(N_LOCKED, n_locked[WRITE])
ORDER_CASE(N_READ_LOCKED, n_locked[READ])
ORDER_CASE(N_CONTENDED, n_contended[WRITE])
ORDER_CASE(N_READ_CONTENDED, n_contended[READ])
ORDER_CASE(N_OWNER_CHANGED, n_owner_changed)
ORDER_CASE(NSEC_LOCKED_TOTAL, nsec_locked_total[WRITE])
ORDER_CASE(NSEC_LOCKED_MAX, nsec_locked_max[WRITE])
ORDER_CASE_AVG(NSEC_LOCKED_AVG, nsec_locked_total[WRITE], n_locked[WRITE])
ORDER_CASE(NSEC_READ_LOCKED_TOTAL, nsec_locked_total[READ])
ORDER_CASE(NSEC_READ_LOCKED_MAX, nsec_locked_max[READ])
ORDER_CASE_AVG(NSEC_READ_LOCKED_AVG, nsec_locked_total[READ], n_locked[READ])
ORDER_CASE(NSEC_CONTENDED_TOTAL, nsec_contended_total[WRITE])
ORDER_CASE_AVG(NSEC_CONTENDED_AVG, nsec_contended_total[WRITE], n_contended[WRITE])
ORDER_CASE(NSEC_READ_CONTENDED_TOTAL, nsec_contended_total[READ])
ORDER_CASE_AVG(NSEC_READ_CONTENDED_AVG, nsec_contended_total[READ], n_contended[READ])
default:
/* Should never be reached. */
assert(0);
#undef ORDER_CASE_AVG
#undef ORDER_CASE
}
/* Fall back to a static ordering. */
STATIC_ORDER(n_contended[WRITE]);
STATIC_ORDER(n_owner_changed);
STATIC_ORDER(n_locked[WRITE]);
STATIC_ORDER(nsec_locked_max[WRITE]);
/* Let's make the output deterministic */
return a - b;
}
static int cond_info_compare(const void *_a, const void *_b) {
const struct cond_info
*a = *(const struct cond_info**) _a,
*b = *(const struct cond_info**) _b;
/* Order by the user's chosen ordering first, then fall back to a static
* ordering. */
switch (summary_cond_order) {
#define ORDER_CASE(UCASE, lcase) _ORDER_CASE(COND, UCASE, lcase)
#define ORDER_CASE_AVG(UCASE, lcase, divisor) _ORDER_CASE_AVG(COND, UCASE, lcase, divisor)
ORDER_CASE(ID, id)
ORDER_CASE(N_WAIT, n_wait)
ORDER_CASE(N_SIGNAL, n_signal)
ORDER_CASE(N_BROADCAST, n_broadcast)
ORDER_CASE(N_WAIT_CONTENDED, n_wait_contended)
ORDER_CASE(N_SIGNAL_CONTENDED, n_signal_contended)
ORDER_CASE(NSEC_WAIT_TOTAL, nsec_wait_total)
ORDER_CASE(NSEC_WAIT_MAX, nsec_wait_max)
ORDER_CASE_AVG(NSEC_WAIT_AVG, nsec_wait_total, n_wait)
ORDER_CASE(NSEC_WAIT_CONTENDED_TOTAL, nsec_wait_contended_total)
ORDER_CASE(NSEC_WAIT_CONTENDED_MAX, nsec_wait_contended_max)
ORDER_CASE_AVG(NSEC_WAIT_CONTENDED_AVG, nsec_wait_contended_total, n_wait_contended)
default:
/* Should never be reached. */
assert(0);
#undef ORDER_CASE_AVG
#undef ORDER_CASE
}
/* Fall back to a static ordering. */
STATIC_ORDER(n_wait_contended);
STATIC_ORDER(n_wait);
STATIC_ORDER(nsec_wait_total);
STATIC_ORDER(n_signal);
/* Let's make the output deterministic */
return a - b;
}
#undef STATIC_ORDER
#undef ORDER_CASE_AVG
#undef ORDER_CASE
static bool mutex_info_show(struct mutex_info *mi) {
/* Mutexes used by real-time code are always noteworthy */
if (mi->realtime)
return true;
if (mi->n_locked[WRITE] < show_n_locked_min)
return false;
if (mi->n_locked[READ] < show_n_read_locked_min)
return false;
if (mi->n_contended[WRITE] < show_n_contended_min)
return false;
if (mi->n_contended[READ] < show_n_read_contended_min)
return false;
if (mi->n_owner_changed < show_n_owner_changed_min)
return false;
return true;
}
static bool cond_info_show(struct cond_info *ci) {
/* Condition variables used by real-time code are always noteworthy */
if (ci->realtime)
return true;
if (ci->n_wait < show_n_wait_min)
return false;
return true;
}
static bool mutex_info_dump(struct mutex_info *mi) {
char *stacktrace_str;
if (!mutex_info_show(mi))
return false;
stacktrace_str = stacktrace_to_string(mi->stacktrace);
fprintf(stderr,
"\nMutex #%u (0x%p) first referenced by:\n"
"%s", mi->id, mi->mutex ? (void*) mi->mutex : (void*) mi->rwlock, stacktrace_str);
free(stacktrace_str);
return true;
}
static bool cond_info_dump(struct cond_info *ci) {
char *stacktrace_str;
if (!cond_info_show(ci))
return false;
stacktrace_str = stacktrace_to_string(ci->stacktrace);
fprintf(stderr,
"\nCondvar #%u (0x%p) first referenced by:\n"
"%s", ci->id, ci->cond, stacktrace_str);
free(stacktrace_str);
return true;
}
static char mutex_type_name(int type) {
switch (type) {
case PTHREAD_MUTEX_NORMAL:
return '-';
case PTHREAD_MUTEX_RECURSIVE:
return 'r';
case PTHREAD_MUTEX_ERRORCHECK:
return 'e';
case PTHREAD_MUTEX_ADAPTIVE_NP:
return 'a';
default:
return '?';
}
}
static char mutex_protocol_name(int protocol) {
switch (protocol) {
case PTHREAD_PRIO_NONE:
return '-';
case PTHREAD_PRIO_INHERIT:
return 'i';
case PTHREAD_PRIO_PROTECT:
return 'p';
default:
return '?';
}
}
static char rwlock_kind_name(int kind) {
switch (kind) {
case PTHREAD_RWLOCK_PREFER_READER_NP:
return 'r';
case PTHREAD_RWLOCK_PREFER_WRITER_NP:
return 'w';
case PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP:
return 'W';
default:
return '?';
}
}
static bool mutex_info_stat(struct mutex_info *mi) {
if (!mutex_info_show(mi))
return false;
fprintf(stderr,
"%8u %8u %8u %8u %13.3f %12.3f %12.3f %c%c%c%c%c%c\n",
mi->id,
mi->n_locked[WRITE],
mi->n_owner_changed,
mi->n_contended[WRITE],
(double) mi->nsec_locked_total[WRITE] / 1000000.0,
(double) mi->nsec_contended_total[WRITE] / 1000000.0,
(double) mi->nsec_contended_total[WRITE] / mi->n_locked[WRITE] / 1000000.0,
mi->mutex ? 'M' : 'W',
mi->broken ? '!' : (mi->dead ? 'x' : '-'),
track_rt ? (mi->realtime ? 'R' : '-') : '.',
mi->mutex ? mutex_type_name(mi->type) : '.',
mi->mutex ? mutex_protocol_name(mi->protocol) : '.',
mi->rwlock ? rwlock_kind_name(mi->kind) : '.');
/* Show a second row for rwlocks, listing the statistics for read-only
* locks; the first row shows the statistics for write-only locks. */
if (mi->rwlock) {
fprintf(stderr,
" %8u %8u %13.3f %12.3f %12.3f \n",
mi->n_locked[READ],
mi->n_contended[READ],
(double) mi->nsec_locked_total[READ] / 1000000.0,
(double) mi->nsec_contended_total[READ] / 1000000.0,
(double) mi->nsec_contended_total[READ] / mi->n_locked[READ] / 1000000.0);
}
return true;
}
static bool cond_info_stat(struct cond_info *ci) {
if (!cond_info_show(ci))
return false;
fprintf(stderr,
"%8u %8u %8u %8u %12.3f %13.3f %12.3f %c%c\n",
ci->id,
ci->n_wait,
ci->n_signal + ci->n_broadcast,
ci->n_wait_contended,
(double) ci->nsec_wait_total / 1000000.0,
(double) ci->nsec_wait_contended_total / 1000000.0,
(double) ci->nsec_wait_contended_total / ci->n_wait / 1000000.0,
ci->broken ? '!' : (ci->dead ? 'x' : '-'),
track_rt ? (ci->realtime ? 'R' : '-') : '.');
return true;
}
static SummaryMutexOrder summary_mutex_order_from_command(const char *command) {
unsigned int i;
for (i = 0; i < MUTEX_ORDER_INVALID; i++) {
if (strcmp(command, summary_mutex_order_details[i].command) == 0) {
return i;
}
}
return MUTEX_ORDER_INVALID;
}
static SummaryCondOrder summary_cond_order_from_command(const char *command) {
unsigned int i;
for (i = 0; i < COND_ORDER_INVALID; i++) {
if (strcmp(command, summary_cond_order_details[i].command) == 0) {
return i;
}
}
return COND_ORDER_INVALID;
}
static void show_summary_internal(void) {
struct mutex_info *mi, **mutex_table;
struct cond_info *ci, **cond_table;
unsigned n, u, i, m;
uint64_t t;
long n_cpus;
t = nsec_now() - nsec_timestamp_setup;
fprintf(stderr,
"\n"
"mutrace: Showing statistics for process %s (PID: %lu).\n", get_prname(), (unsigned long) getpid());
/* Mutexes. */
n = 0;
for (u = 0; u < hash_size; u++) {
lock_hash_mutex(u);
for (mi = alive_mutexes[u]; mi; mi = mi->next)
n++;
for (mi = dead_mutexes[u]; mi; mi = mi->next)
n++;
}
if (n <= 0) {
fprintf(stderr,
"mutrace: No mutexes used.\n");
return;
}
fprintf(stderr,
"mutrace: %u mutexes used.\n", n);
mutex_table = malloc(sizeof(struct mutex_info*) * n);
i = 0;
for (u = 0; u < hash_size; u++) {
for (mi = alive_mutexes[u]; mi; mi = mi->next) {
mi->id = i;
mutex_table[i++] = mi;
}
for (mi = dead_mutexes[u]; mi; mi = mi->next) {