forked from gcc-mirror/gcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmf-runtime.c
2786 lines (2350 loc) · 80.5 KB
/
mf-runtime.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
/* Mudflap: narrow-pointer bounds-checking by tree rewriting.
Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
Contributed by Frank Ch. Eigler <[email protected]>
and Graydon Hoare <[email protected]>
Splay Tree code originally by Mark Mitchell <[email protected]>,
adapted from libiberty.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2, or (at your option) any later
version.
In addition to the permissions in the GNU General Public License, the
Free Software Foundation gives you unlimited permission to link the
compiled version of this file into combinations with other programs,
and to distribute those combinations without any restriction coming
from the use of this file. (The General Public License restrictions
do apply in other respects; for example, they cover modification of
the file, and distribution when not linked into a combine
executable.)
GCC 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 General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING. If not, write to the Free
Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA. */
#include "config.h"
/* These attempt to coax various unix flavours to declare all our
needed tidbits in the system headers. */
#if !defined(__FreeBSD__) && !defined(__APPLE__)
#define _POSIX_SOURCE
#endif /* Some BSDs break <sys/socket.h> if this is defined. */
#define _GNU_SOURCE
#define _XOPEN_SOURCE
#define _BSD_TYPES
#define __EXTENSIONS__
#define _ALL_SOURCE
#define _LARGE_FILE_API
#define _XOPEN_SOURCE_EXTENDED 1
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
#include <ctype.h>
#include "mf-runtime.h"
#include "mf-impl.h"
/* ------------------------------------------------------------------------ */
/* Splay-tree implementation. */
typedef uintptr_t mfsplay_tree_key;
typedef void *mfsplay_tree_value;
/* Forward declaration for a node in the tree. */
typedef struct mfsplay_tree_node_s *mfsplay_tree_node;
/* The type of a function used to iterate over the tree. */
typedef int (*mfsplay_tree_foreach_fn) (mfsplay_tree_node, void *);
/* The nodes in the splay tree. */
struct mfsplay_tree_node_s
{
/* Data. */
mfsplay_tree_key key;
mfsplay_tree_value value;
/* Children. */
mfsplay_tree_node left;
mfsplay_tree_node right;
/* XXX: The addition of a parent pointer may eliminate some recursion. */
};
/* The splay tree itself. */
struct mfsplay_tree_s
{
/* The root of the tree. */
mfsplay_tree_node root;
/* The last key value for which the tree has been splayed, but not
since modified. */
mfsplay_tree_key last_splayed_key;
int last_splayed_key_p;
/* Statistics. */
unsigned num_keys;
/* Traversal recursion control flags. */
unsigned max_depth;
unsigned depth;
unsigned rebalance_p;
};
typedef struct mfsplay_tree_s *mfsplay_tree;
static mfsplay_tree mfsplay_tree_new (void);
static mfsplay_tree_node mfsplay_tree_insert (mfsplay_tree, mfsplay_tree_key, mfsplay_tree_value);
static void mfsplay_tree_remove (mfsplay_tree, mfsplay_tree_key);
static mfsplay_tree_node mfsplay_tree_lookup (mfsplay_tree, mfsplay_tree_key);
static mfsplay_tree_node mfsplay_tree_predecessor (mfsplay_tree, mfsplay_tree_key);
static mfsplay_tree_node mfsplay_tree_successor (mfsplay_tree, mfsplay_tree_key);
static int mfsplay_tree_foreach (mfsplay_tree, mfsplay_tree_foreach_fn, void *);
static void mfsplay_tree_rebalance (mfsplay_tree sp);
/* ------------------------------------------------------------------------ */
/* Utility macros */
#define CTOR __attribute__ ((constructor))
#define DTOR __attribute__ ((destructor))
/* Codes to describe the context in which a violation occurs. */
#define __MF_VIOL_UNKNOWN 0
#define __MF_VIOL_READ 1
#define __MF_VIOL_WRITE 2
#define __MF_VIOL_REGISTER 3
#define __MF_VIOL_UNREGISTER 4
#define __MF_VIOL_WATCH 5
/* Protect against recursive calls. */
static void
begin_recursion_protect1 (const char *pf)
{
if (__mf_get_state () == reentrant)
{
write (2, "mf: erroneous reentrancy detected in `", 38);
write (2, pf, strlen(pf));
write (2, "'\n", 2); \
abort ();
}
__mf_set_state (reentrant);
}
#define BEGIN_RECURSION_PROTECT() \
begin_recursion_protect1 (__PRETTY_FUNCTION__)
#define END_RECURSION_PROTECT() \
__mf_set_state (active)
/* ------------------------------------------------------------------------ */
/* Required globals. */
#define LOOKUP_CACHE_MASK_DFL 1023
#define LOOKUP_CACHE_SIZE_MAX 65536 /* Allows max CACHE_MASK 0xFFFF */
#define LOOKUP_CACHE_SHIFT_DFL 2
struct __mf_cache __mf_lookup_cache [LOOKUP_CACHE_SIZE_MAX];
uintptr_t __mf_lc_mask = LOOKUP_CACHE_MASK_DFL;
unsigned char __mf_lc_shift = LOOKUP_CACHE_SHIFT_DFL;
#define LOOKUP_CACHE_SIZE (__mf_lc_mask + 1)
struct __mf_options __mf_opts;
int __mf_starting_p = 1;
#ifdef LIBMUDFLAPTH
#ifdef HAVE_TLS
__thread enum __mf_state_enum __mf_state_1 = reentrant;
#endif
#else
enum __mf_state_enum __mf_state_1 = reentrant;
#endif
#ifdef LIBMUDFLAPTH
pthread_mutex_t __mf_biglock =
#ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
#else
PTHREAD_MUTEX_INITIALIZER;
#endif
#endif
/* Use HAVE_PTHREAD_H here instead of LIBMUDFLAPTH, so that even
the libmudflap.la (no threading support) can diagnose whether
the application is linked with -lpthread. See __mf_usage() below. */
#if HAVE_PTHREAD_H
#ifdef _POSIX_THREADS
#pragma weak pthread_join
#else
#define pthread_join NULL
#endif
#endif
/* ------------------------------------------------------------------------ */
/* stats-related globals. */
static unsigned long __mf_count_check;
static unsigned long __mf_lookup_cache_reusecount [LOOKUP_CACHE_SIZE_MAX];
static unsigned long __mf_count_register;
static unsigned long __mf_total_register_size [__MF_TYPE_MAX+1];
static unsigned long __mf_count_unregister;
static unsigned long __mf_total_unregister_size;
static unsigned long __mf_count_violation [__MF_VIOL_WATCH+1];
static unsigned long __mf_sigusr1_received;
static unsigned long __mf_sigusr1_handled;
/* not static */ unsigned long __mf_reentrancy;
#ifdef LIBMUDFLAPTH
/* not static */ unsigned long __mf_lock_contention;
#endif
/* ------------------------------------------------------------------------ */
/* mode-check-related globals. */
typedef struct __mf_object
{
uintptr_t low, high; /* __mf_register parameters */
const char *name;
char type; /* __MF_TYPE_something */
char watching_p; /* Trigger a VIOL_WATCH on access? */
unsigned read_count; /* Number of times __mf_check/read was called on this object. */
unsigned write_count; /* Likewise for __mf_check/write. */
unsigned liveness; /* A measure of recent checking activity. */
unsigned description_epoch; /* Last epoch __mf_describe_object printed this. */
uintptr_t alloc_pc;
struct timeval alloc_time;
char **alloc_backtrace;
size_t alloc_backtrace_size;
#ifdef LIBMUDFLAPTH
pthread_t alloc_thread;
#endif
int deallocated_p;
uintptr_t dealloc_pc;
struct timeval dealloc_time;
char **dealloc_backtrace;
size_t dealloc_backtrace_size;
#ifdef LIBMUDFLAPTH
pthread_t dealloc_thread;
#endif
} __mf_object_t;
/* Live objects: splay trees, separated by type, ordered on .low (base address). */
/* Actually stored as static vars within lookup function below. */
/* Dead objects: circular arrays; _MIN_CEM .. _MAX_CEM only */
static unsigned __mf_object_dead_head[__MF_TYPE_MAX_CEM+1]; /* next empty spot */
static __mf_object_t *__mf_object_cemetary[__MF_TYPE_MAX_CEM+1][__MF_PERSIST_MAX];
/* ------------------------------------------------------------------------ */
/* Forward function declarations */
void __mf_init () CTOR;
static void __mf_sigusr1_respond ();
static unsigned __mf_find_objects (uintptr_t ptr_low, uintptr_t ptr_high,
__mf_object_t **objs, unsigned max_objs);
static unsigned __mf_find_objects2 (uintptr_t ptr_low, uintptr_t ptr_high,
__mf_object_t **objs, unsigned max_objs, int type);
static unsigned __mf_find_dead_objects (uintptr_t ptr_low, uintptr_t ptr_high,
__mf_object_t **objs, unsigned max_objs);
static void __mf_adapt_cache ();
static void __mf_describe_object (__mf_object_t *obj);
static unsigned __mf_watch_or_not (void *ptr, size_t sz, char flag);
static mfsplay_tree __mf_object_tree (int type);
static void __mf_link_object (__mf_object_t *node);
static void __mf_unlink_object (__mf_object_t *node);
/* ------------------------------------------------------------------------ */
/* Configuration engine */
static void
__mf_set_default_options ()
{
memset (& __mf_opts, 0, sizeof (__mf_opts));
__mf_opts.adapt_cache = 1000003;
__mf_opts.abbreviate = 1;
__mf_opts.verbose_violations = 1;
__mf_opts.free_queue_length = 4;
__mf_opts.persistent_count = 100;
__mf_opts.crumple_zone = 32;
__mf_opts.backtrace = 4;
__mf_opts.timestamps = 1;
__mf_opts.mudflap_mode = mode_check;
__mf_opts.violation_mode = viol_nop;
__mf_opts.heur_std_data = 1;
#ifdef LIBMUDFLAPTH
__mf_opts.thread_stack = 0;
#endif
}
static struct option
{
char *name;
char *description;
enum
{
set_option,
read_integer_option,
} type;
unsigned value;
unsigned *target;
}
options [] =
{
{"mode-nop",
"mudflaps do nothing",
set_option, (unsigned)mode_nop, (unsigned *)&__mf_opts.mudflap_mode},
{"mode-populate",
"mudflaps populate object tree",
set_option, (unsigned)mode_populate, (unsigned *)&__mf_opts.mudflap_mode},
{"mode-check",
"mudflaps check for memory violations",
set_option, (unsigned)mode_check, (unsigned *)&__mf_opts.mudflap_mode},
{"mode-violate",
"mudflaps always cause violations (diagnostic)",
set_option, (unsigned)mode_violate, (unsigned *)&__mf_opts.mudflap_mode},
{"viol-nop",
"violations do not change program execution",
set_option, (unsigned)viol_nop, (unsigned *)&__mf_opts.violation_mode},
{"viol-abort",
"violations cause a call to abort()",
set_option, (unsigned)viol_abort, (unsigned *)&__mf_opts.violation_mode},
{"viol-segv",
"violations are promoted to SIGSEGV signals",
set_option, (unsigned)viol_segv, (unsigned *)&__mf_opts.violation_mode},
{"viol-gdb",
"violations fork a gdb process attached to current program",
set_option, (unsigned)viol_gdb, (unsigned *)&__mf_opts.violation_mode},
{"trace-calls",
"trace calls to mudflap runtime library",
set_option, 1, &__mf_opts.trace_mf_calls},
{"verbose-trace",
"trace internal events within mudflap runtime library",
set_option, 1, &__mf_opts.verbose_trace},
{"collect-stats",
"collect statistics on mudflap's operation",
set_option, 1, &__mf_opts.collect_stats},
#ifdef SIGUSR1
{"sigusr1-report",
"print report upon SIGUSR1",
set_option, 1, &__mf_opts.sigusr1_report},
#endif
{"internal-checking",
"perform more expensive internal checking",
set_option, 1, &__mf_opts.internal_checking},
{"print-leaks",
"print any memory leaks at program shutdown",
set_option, 1, &__mf_opts.print_leaks},
{"check-initialization",
"detect uninitialized object reads",
set_option, 1, &__mf_opts.check_initialization},
{"verbose-violations",
"print verbose messages when memory violations occur",
set_option, 1, &__mf_opts.verbose_violations},
{"abbreviate",
"abbreviate repetitive listings",
set_option, 1, &__mf_opts.abbreviate},
{"timestamps",
"track object lifetime timestamps",
set_option, 1, &__mf_opts.timestamps},
{"ignore-reads",
"ignore read accesses - assume okay",
set_option, 1, &__mf_opts.ignore_reads},
{"wipe-stack",
"wipe stack objects at unwind",
set_option, 1, &__mf_opts.wipe_stack},
{"wipe-heap",
"wipe heap objects at free",
set_option, 1, &__mf_opts.wipe_heap},
{"heur-proc-map",
"support /proc/self/map heuristics",
set_option, 1, &__mf_opts.heur_proc_map},
{"heur-stack-bound",
"enable a simple upper stack bound heuristic",
set_option, 1, &__mf_opts.heur_stack_bound},
{"heur-start-end",
"support _start.._end heuristics",
set_option, 1, &__mf_opts.heur_start_end},
{"heur-stdlib",
"register standard library data (argv, errno, stdin, ...)",
set_option, 1, &__mf_opts.heur_std_data},
{"free-queue-length",
"queue N deferred free() calls before performing them",
read_integer_option, 0, &__mf_opts.free_queue_length},
{"persistent-count",
"keep a history of N unregistered regions",
read_integer_option, 0, &__mf_opts.persistent_count},
{"crumple-zone",
"surround allocations with crumple zones of N bytes",
read_integer_option, 0, &__mf_opts.crumple_zone},
/* XXX: not type-safe.
{"lc-mask",
"set lookup cache size mask to N (2**M - 1)",
read_integer_option, 0, (int *)(&__mf_lc_mask)},
{"lc-shift",
"set lookup cache pointer shift",
read_integer_option, 0, (int *)(&__mf_lc_shift)},
*/
{"lc-adapt",
"adapt mask/shift parameters after N cache misses",
read_integer_option, 1, &__mf_opts.adapt_cache},
{"backtrace",
"keep an N-level stack trace of each call context",
read_integer_option, 0, &__mf_opts.backtrace},
#ifdef LIBMUDFLAPTH
{"thread-stack",
"override thread stacks allocation: N kB",
read_integer_option, 0, &__mf_opts.thread_stack},
#endif
{0, 0, set_option, 0, NULL}
};
static void
__mf_usage ()
{
struct option *opt;
fprintf (stderr,
"This is a %s%sGCC \"mudflap\" memory-checked binary.\n"
"Mudflap is Copyright (C) 2002-2004 Free Software Foundation, Inc.\n"
"\n"
"The mudflap code can be controlled by an environment variable:\n"
"\n"
"$ export MUDFLAP_OPTIONS='<options>'\n"
"$ <mudflapped_program>\n"
"\n"
"where <options> is a space-separated list of \n"
"any of the following options. Use `-no-OPTION' to disable options.\n"
"\n",
#if HAVE_PTHREAD_H
(pthread_join ? "multi-threaded " : "single-threaded "),
#else
"",
#endif
#if LIBMUDFLAPTH
"thread-aware "
#else
"thread-unaware "
#endif
);
/* XXX: The multi-threaded thread-unaware combination is bad. */
for (opt = options; opt->name; opt++)
{
int default_p = (opt->value == * opt->target);
switch (opt->type)
{
char buf[128];
case set_option:
fprintf (stderr, "-%-23.23s %s", opt->name, opt->description);
if (default_p)
fprintf (stderr, " [active]\n");
else
fprintf (stderr, "\n");
break;
case read_integer_option:
strncpy (buf, opt->name, 128);
strncpy (buf + strlen (opt->name), "=N", 2);
fprintf (stderr, "-%-23.23s %s", buf, opt->description);
fprintf (stderr, " [%d]\n", * opt->target);
break;
default: abort();
}
}
fprintf (stderr, "\n");
}
int
__mf_set_options (const char *optstr)
{
int rc;
LOCKTH ();
BEGIN_RECURSION_PROTECT ();
rc = __mfu_set_options (optstr);
/* XXX: It's not really that easy. A change to a bunch of parameters
can require updating auxiliary state or risk crashing:
free_queue_length, crumple_zone ... */
END_RECURSION_PROTECT ();
UNLOCKTH ();
return rc;
}
int
__mfu_set_options (const char *optstr)
{
struct option *opts = 0;
char *nxt = 0;
long tmp = 0;
int rc = 0;
const char *saved_optstr = optstr;
/* XXX: bounds-check for optstr! */
while (*optstr)
{
switch (*optstr) {
case ' ':
case '\t':
case '\n':
optstr++;
break;
case '-':
if (*optstr+1)
{
int negate = 0;
optstr++;
if (*optstr == '?' ||
strncmp (optstr, "help", 4) == 0)
{
/* Caller will print help and exit. */
return -1;
}
if (strncmp (optstr, "no-", 3) == 0)
{
negate = 1;
optstr = & optstr[3];
}
for (opts = options; opts->name; opts++)
{
if (strncmp (optstr, opts->name, strlen (opts->name)) == 0)
{
optstr += strlen (opts->name);
assert (opts->target);
switch (opts->type)
{
case set_option:
if (negate)
*(opts->target) = 0;
else
*(opts->target) = opts->value;
break;
case read_integer_option:
if (! negate && (*optstr == '=' && *(optstr+1)))
{
optstr++;
tmp = strtol (optstr, &nxt, 10);
if ((optstr != nxt) && (tmp != LONG_MAX))
{
optstr = nxt;
*(opts->target) = (int)tmp;
}
}
else if (negate)
* opts->target = 0;
break;
}
}
}
}
break;
default:
fprintf (stderr,
"warning: unrecognized string '%s' in mudflap options\n",
optstr);
optstr += strlen (optstr);
rc = -1;
break;
}
}
/* Special post-processing: bound __mf_lc_mask and free_queue_length for security. */
__mf_lc_mask &= (LOOKUP_CACHE_SIZE_MAX - 1);
__mf_opts.free_queue_length &= (__MF_FREEQ_MAX - 1);
/* Clear the lookup cache, in case the parameters got changed. */
/* XXX: race */
memset (__mf_lookup_cache, 0, sizeof(__mf_lookup_cache));
/* void slot 0 */
__mf_lookup_cache[0].low = MAXPTR;
TRACE ("set options from `%s'\n", saved_optstr);
/* Call this unconditionally, in case -sigusr1-report was toggled. */
__mf_sigusr1_respond ();
return rc;
}
#ifdef PIC
void
__mf_resolve_single_dynamic (struct __mf_dynamic_entry *e)
{
char *err;
assert (e);
if (e->pointer) return;
#if HAVE_DLVSYM
if (e->version != NULL && e->version[0] != '\0') /* non-null/empty */
e->pointer = dlvsym (RTLD_NEXT, e->name, e->version);
else
#endif
e->pointer = dlsym (RTLD_NEXT, e->name);
err = dlerror ();
if (err)
{
fprintf (stderr, "mf: error in dlsym(\"%s\"): %s\n",
e->name, err);
abort ();
}
if (! e->pointer)
{
fprintf (stderr, "mf: dlsym(\"%s\") = NULL\n", e->name);
abort ();
}
}
static void
__mf_resolve_dynamics ()
{
int i;
for (i = 0; i < dyn_INITRESOLVE; i++)
__mf_resolve_single_dynamic (& __mf_dynamic[i]);
}
/* NB: order must match enums in mf-impl.h */
struct __mf_dynamic_entry __mf_dynamic [] =
{
{NULL, "calloc", NULL},
{NULL, "free", NULL},
{NULL, "malloc", NULL},
{NULL, "mmap", NULL},
{NULL, "munmap", NULL},
{NULL, "realloc", NULL},
{NULL, "DUMMY", NULL}, /* dyn_INITRESOLVE */
#ifdef LIBMUDFLAPTH
{NULL, "pthread_create", PTHREAD_CREATE_VERSION},
{NULL, "pthread_join", NULL},
{NULL, "pthread_exit", NULL}
#endif
};
#endif /* PIC */
/* ------------------------------------------------------------------------ */
/* Lookup & manage automatic initialization of the five or so splay trees. */
static mfsplay_tree
__mf_object_tree (int type)
{
static mfsplay_tree trees [__MF_TYPE_MAX+1];
assert (type >= 0 && type <= __MF_TYPE_MAX);
if (UNLIKELY (trees[type] == NULL))
trees[type] = mfsplay_tree_new ();
return trees[type];
}
/* not static */void
__mf_init ()
{
char *ov = 0;
/* Return if initialization has already been done. */
if (LIKELY (__mf_starting_p == 0))
return;
/* This initial bootstrap phase requires that __mf_starting_p = 1. */
#ifdef PIC
__mf_resolve_dynamics ();
#endif
__mf_starting_p = 0;
__mf_set_state (active);
__mf_set_default_options ();
ov = getenv ("MUDFLAP_OPTIONS");
if (ov)
{
int rc = __mfu_set_options (ov);
if (rc < 0)
{
__mf_usage ();
exit (1);
}
}
/* Initialize to a non-zero description epoch. */
__mf_describe_object (NULL);
#define REG_RESERVED(obj) \
__mf_register (& obj, sizeof(obj), __MF_TYPE_NOACCESS, # obj)
REG_RESERVED (__mf_lookup_cache);
REG_RESERVED (__mf_lc_mask);
REG_RESERVED (__mf_lc_shift);
/* XXX: others of our statics? */
/* Prevent access to *NULL. */
__mf_register (MINPTR, 1, __MF_TYPE_NOACCESS, "NULL");
__mf_lookup_cache[0].low = (uintptr_t) -1;
}
int
__wrap_main (int argc, char* argv[])
{
extern char **environ;
extern int main ();
extern int __real_main ();
static int been_here = 0;
if (__mf_opts.heur_std_data && ! been_here)
{
unsigned i;
been_here = 1;
__mf_register (argv, sizeof(char *)*(argc+1), __MF_TYPE_STATIC, "argv[]");
for (i=0; i<argc; i++)
{
unsigned j = strlen (argv[i]);
__mf_register (argv[i], j+1, __MF_TYPE_STATIC, "argv element");
}
for (i=0; ; i++)
{
char *e = environ[i];
unsigned j;
if (e == NULL) break;
j = strlen (environ[i]);
__mf_register (environ[i], j+1, __MF_TYPE_STATIC, "environ element");
}
__mf_register (environ, sizeof(char *)*(i+1), __MF_TYPE_STATIC, "environ[]");
__mf_register (& errno, sizeof (errno), __MF_TYPE_STATIC, "errno area");
__mf_register (stdin, sizeof (*stdin), __MF_TYPE_STATIC, "stdin");
__mf_register (stdout, sizeof (*stdout), __MF_TYPE_STATIC, "stdout");
__mf_register (stderr, sizeof (*stderr), __MF_TYPE_STATIC, "stderr");
/* Make some effort to register ctype.h static arrays. */
/* XXX: e.g., on Solaris, may need to register __ctype, _ctype, __ctype_mask, __toupper, etc. */
/* On modern Linux GLIBC, these are thread-specific and changeable, and are dealt
with in mf-hooks2.c. */
}
#ifdef PIC
return main (argc, argv, environ);
#else
return __real_main (argc, argv, environ);
#endif
}
extern void __mf_fini () DTOR;
void __mf_fini ()
{
TRACE ("__mf_fini\n");
__mfu_report ();
#ifndef PIC
/* Since we didn't populate the tree for allocations in constructors
before __mf_init, we cannot check destructors after __mf_fini. */
__mf_opts.mudflap_mode = mode_nop;
#endif
}
/* ------------------------------------------------------------------------ */
/* __mf_check */
void __mf_check (void *ptr, size_t sz, int type, const char *location)
{
LOCKTH ();
BEGIN_RECURSION_PROTECT ();
__mfu_check (ptr, sz, type, location);
END_RECURSION_PROTECT ();
UNLOCKTH ();
}
void __mfu_check (void *ptr, size_t sz, int type, const char *location)
{
unsigned entry_idx = __MF_CACHE_INDEX (ptr);
struct __mf_cache *entry = & __mf_lookup_cache [entry_idx];
int judgement = 0; /* 0=undecided; <0=violation; >0=okay */
uintptr_t ptr_low = (uintptr_t) ptr;
uintptr_t ptr_high = CLAMPSZ (ptr, sz);
struct __mf_cache old_entry = *entry;
if (UNLIKELY (__mf_opts.sigusr1_report))
__mf_sigusr1_respond ();
if (UNLIKELY (__mf_opts.ignore_reads && type == 0))
return;
TRACE ("check ptr=%p b=%u size=%lu %s location=`%s'\n",
ptr, entry_idx, (unsigned long)sz,
(type == 0 ? "read" : "write"), location);
switch (__mf_opts.mudflap_mode)
{
case mode_nop:
/* It is tempting to poison the cache here similarly to
mode_populate. However that eliminates a valuable
distinction between these two modes. mode_nop is useful to
let a user count & trace every single check / registration
call. mode_populate is useful to let a program run fast
while unchecked.
*/
judgement = 1;
break;
case mode_populate:
entry->low = ptr_low;
entry->high = ptr_high;
judgement = 1;
break;
case mode_check:
{
unsigned heuristics = 0;
/* Advance aging/adaptation counters. */
static unsigned adapt_count;
adapt_count ++;
if (UNLIKELY (__mf_opts.adapt_cache > 0 &&
adapt_count > __mf_opts.adapt_cache))
{
adapt_count = 0;
__mf_adapt_cache ();
}
/* Looping only occurs if heuristics were triggered. */
while (judgement == 0)
{
DECLARE (void, free, void *p);
__mf_object_t* ovr_obj[1];
unsigned obj_count;
__mf_object_t** all_ovr_obj = NULL;
__mf_object_t** dealloc_me = NULL;
unsigned i;
/* Find all overlapping objects. Be optimistic that there is just one. */
obj_count = __mf_find_objects (ptr_low, ptr_high, ovr_obj, 1);
if (UNLIKELY (obj_count > 1))
{
/* Allocate a real buffer and do the search again. */
DECLARE (void *, malloc, size_t c);
unsigned n;
all_ovr_obj = CALL_REAL (malloc, (sizeof (__mf_object_t *) *
obj_count));
if (all_ovr_obj == NULL) abort ();
n = __mf_find_objects (ptr_low, ptr_high, all_ovr_obj, obj_count);
assert (n == obj_count);
dealloc_me = all_ovr_obj;
}
else
{
all_ovr_obj = ovr_obj;
dealloc_me = NULL;
}
/* Update object statistics. */
for (i = 0; i < obj_count; i++)
{
__mf_object_t *obj = all_ovr_obj[i];
assert (obj != NULL);
if (type == __MF_CHECK_READ)
obj->read_count ++;
else
obj->write_count ++;
obj->liveness ++;
}
/* Iterate over the various objects. There are a number of special cases. */
for (i = 0; i < obj_count; i++)
{
__mf_object_t *obj = all_ovr_obj[i];
/* Any __MF_TYPE_NOACCESS hit is bad. */
if (UNLIKELY (obj->type == __MF_TYPE_NOACCESS))
judgement = -1;
/* Any object with a watch flag is bad. */
if (UNLIKELY (obj->watching_p))
judgement = -2; /* trigger VIOL_WATCH */
/* A read from an uninitialized object is bad. */
if (UNLIKELY (__mf_opts.check_initialization
/* reading */
&& type == __MF_CHECK_READ
/* not written */
&& obj->write_count == 0
/* uninitialized (heap) */
&& obj->type == __MF_TYPE_HEAP))
judgement = -1;
}
/* We now know that the access spans no invalid objects. */
if (LIKELY (judgement >= 0))
for (i = 0; i < obj_count; i++)
{
__mf_object_t *obj = all_ovr_obj[i];
/* Is this access entirely contained within this object? */
if (LIKELY (ptr_low >= obj->low && ptr_high <= obj->high))
{
/* Valid access. */
entry->low = obj->low;
entry->high = obj->high;
judgement = 1;
}
}
/* This access runs off the end of one valid object. That
could be okay, if other valid objects fill in all the
holes. We allow this only for HEAP and GUESS type
objects. Accesses to STATIC and STACK variables
should not be allowed to span. */
if (UNLIKELY ((judgement == 0) && (obj_count > 1)))
{
unsigned uncovered = 0;
for (i = 0; i < obj_count; i++)
{
__mf_object_t *obj = all_ovr_obj[i];
int j, uncovered_low_p, uncovered_high_p;
uintptr_t ptr_lower, ptr_higher;
uncovered_low_p = ptr_low < obj->low;
ptr_lower = CLAMPSUB (obj->low, 1);
uncovered_high_p = ptr_high > obj->high;
ptr_higher = CLAMPADD (obj->high, 1);
for (j = 0; j < obj_count; j++)
{
__mf_object_t *obj2 = all_ovr_obj[j];
if (i == j) continue;
/* Filter out objects that cannot be spanned across. */
if (obj2->type == __MF_TYPE_STACK
|| obj2->type == __MF_TYPE_STATIC)
continue;
/* Consider a side "covered" if obj2 includes
the next byte on that side. */
if (uncovered_low_p
&& (ptr_lower >= obj2->low && ptr_lower <= obj2->high))
uncovered_low_p = 0;
if (uncovered_high_p
&& (ptr_high >= obj2->low && ptr_higher <= obj2->high))
uncovered_high_p = 0;
}
if (uncovered_low_p || uncovered_high_p)
uncovered ++;
}
/* Success if no overlapping objects are uncovered. */
if (uncovered == 0)
judgement = 1;
}
if (dealloc_me != NULL)
CALL_REAL (free, dealloc_me);
/* If the judgment is still unknown at this stage, loop
around at most one more time. */
if (judgement == 0)