PR c++/31187
[official-gcc.git] / libmudflap / mf-impl.h
blob728a58bc05dd56ce1c4e02c1eec1b3b1c3fd29bc
1 /* Implementation header for mudflap runtime library.
2 Mudflap: narrow-pointer bounds-checking by tree rewriting.
3 Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
4 Contributed by Frank Ch. Eigler <fche@redhat.com>
5 and Graydon Hoare <graydon@redhat.com>
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 2, or (at your option) any later
12 version.
14 In addition to the permissions in the GNU General Public License, the
15 Free Software Foundation gives you unlimited permission to link the
16 compiled version of this file into combinations with other programs,
17 and to distribute those combinations without any restriction coming
18 from the use of this file. (The General Public License restrictions
19 do apply in other respects; for example, they cover modification of
20 the file, and distribution when not linked into a combine
21 executable.)
23 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
24 WARRANTY; without even the implied warranty of MERCHANTABILITY or
25 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
26 for more details.
28 You should have received a copy of the GNU General Public License
29 along with GCC; see the file COPYING. If not, write to the Free
30 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
31 02110-1301, USA. */
33 #ifndef __MF_IMPL_H
34 #define __MF_IMPL_H
36 #ifdef _MUDFLAP
37 #error "Do not compile this file with -fmudflap!"
38 #endif
40 #if HAVE_PTHREAD_H
41 #include <pthread.h>
42 #elif LIBMUDFLAPTH
43 #error "Cannot build libmudflapth without pthread.h."
44 #endif
46 #if HAVE_STDINT_H
47 #include <stdint.h>
48 #else
49 typedef __mf_uintptr_t uintptr_t;
50 #endif
52 /* Private definitions related to mf-runtime.h */
54 #define __MF_TYPE_MAX_CEM __MF_TYPE_STACK /* largest type# for the cemetary */
55 #define __MF_TYPE_MAX __MF_TYPE_GUESS
58 #ifndef max
59 #define max(a,b) ((a) > (b) ? (a) : (b))
60 #endif
62 #ifndef min
63 #define min(a,b) ((a) < (b) ? (a) : (b))
64 #endif
66 /* Address calculation macros. */
68 #define MINPTR ((uintptr_t) 0)
69 #define MAXPTR (~ (uintptr_t) 0)
71 /* Clamp the addition/subtraction of uintptr_t's to [MINPTR,MAXPTR] */
72 #define CLAMPSUB(ptr,offset) (((uintptr_t) ptr) >= (offset) ? ((uintptr_t) ptr)-((uintptr_t) offset) : MINPTR)
73 #define CLAMPADD(ptr,offset) (((uintptr_t) ptr) <= MAXPTR-(offset) ? ((uintptr_t) ptr)+((uintptr_t) offset) : MAXPTR)
74 #define CLAMPSZ(ptr,size) ((size) ? (((uintptr_t) ptr) <= MAXPTR-(size)+1 ? ((uintptr_t) ptr)+((uintptr_t) size) - 1 : MAXPTR) : ((uintptr_t) ptr))
76 #define __MF_CACHE_INDEX(ptr) ((((uintptr_t) (ptr)) >> __mf_lc_shift) & __mf_lc_mask)
77 #define __MF_CACHE_MISS_P(ptr,sz) ({ \
78 struct __mf_cache *elem = & __mf_lookup_cache[__MF_CACHE_INDEX((ptr))]; \
79 ((elem->low > (uintptr_t) (ptr)) || \
80 (elem->high < (CLAMPADD((uintptr_t) (ptr), (uintptr_t) CLAMPSUB(sz,1) )))); })
81 /* XXX: the above should use CLAMPSZ () */
85 /* Private functions. */
87 extern void __mf_violation (void *ptr, size_t sz,
88 uintptr_t pc, const char *location,
89 int type);
90 extern size_t __mf_backtrace (char ***, void *, unsigned);
91 extern int __mf_heuristic_check (uintptr_t, uintptr_t);
93 /* ------------------------------------------------------------------------ */
94 /* Type definitions. */
95 /* ------------------------------------------------------------------------ */
97 /* The mf_state type codes describe recursion and initialization order.
99 reentrant means we are inside a mf-runtime support routine, such as
100 __mf_register, and thus there should be no calls to any wrapped functions,
101 such as the wrapped malloc. This indicates a bug if it occurs.
102 in_malloc means we are inside a real malloc call inside a wrapped malloc
103 call, and thus there should be no calls to any wrapped functions like the
104 wrapped mmap. This happens on some systems due to how the system libraries
105 are constructed. */
107 enum __mf_state_enum { active, reentrant, in_malloc };
109 /* The __mf_options structure records optional or tunable aspects of the
110 mudflap library's behavior. There is a single global instance of this
111 structure which is populated from user input (in an environment variable)
112 when the library initializes. */
114 struct __mf_options
116 /* Emit a trace message for each call. */
117 unsigned trace_mf_calls;
119 /* Collect and emit statistics. */
120 unsigned collect_stats;
122 /* Set up a SIGUSR1 -> __mf_report handler. */
123 unsigned sigusr1_report;
125 /* Execute internal checking code. */
126 unsigned internal_checking;
128 /* Age object liveness periodically. */
129 unsigned tree_aging;
131 /* Adapt the lookup cache to working set. */
132 unsigned adapt_cache;
134 /* Print list of leaked heap objects on shutdown. */
135 unsigned print_leaks;
137 #ifdef HAVE___LIBC_FREERES
138 /* Call __libc_freeres before leak analysis. */
139 unsigned call_libc_freeres;
140 #endif
142 /* Detect reads of uninitialized objects. */
143 unsigned check_initialization;
145 /* Print verbose description of violations. */
146 unsigned verbose_violations;
148 /* Abbreviate duplicate object descriptions. */
149 unsigned abbreviate;
151 /* Emit internal tracing message. */
152 unsigned verbose_trace;
154 /* Wipe stack/heap objects upon unwind. */
155 unsigned wipe_stack;
156 unsigned wipe_heap;
158 /* Maintain a queue of this many deferred free()s,
159 to trap use of freed memory. */
160 unsigned free_queue_length;
162 /* Maintain a history of this many past unregistered objects. */
163 unsigned persistent_count;
165 /* Pad allocated extents by this many bytes on either side. */
166 unsigned crumple_zone;
168 /* Maintain this many stack frames for contexts. */
169 unsigned backtrace;
171 /* Ignore read operations even if mode_check is in effect. */
172 unsigned ignore_reads;
174 /* Collect register/unregister timestamps. */
175 unsigned timestamps;
177 #ifdef LIBMUDFLAPTH
178 /* Thread stack size. */
179 unsigned thread_stack;
180 #endif
182 /* Major operation mode */
183 #define mode_nop 0 /* Do nothing. */
184 #define mode_populate 1 /* Populate tree but do not check for violations. */
185 #define mode_check 2 /* Populate and check for violations (normal). */
186 #define mode_violate 3 /* Trigger a violation on every call (diagnostic). */
187 unsigned mudflap_mode;
189 /* How to handle a violation. */
190 #define viol_nop 0 /* Return control to application. */
191 #define viol_segv 1 /* Signal self with segv. */
192 #define viol_abort 2 /* Call abort (). */
193 #define viol_gdb 3 /* Fork a debugger on self */
194 unsigned violation_mode;
196 /* Violation heuristics selection. */
197 unsigned heur_stack_bound; /* allow current stack region */
198 unsigned heur_proc_map; /* allow & cache /proc/self/map regions. */
199 unsigned heur_start_end; /* allow _start .. _end */
200 unsigned heur_std_data; /* allow & cache stdlib data */
204 #ifdef PIC
206 /* This is a table of dynamically resolved function pointers. */
208 struct __mf_dynamic_entry
210 void *pointer;
211 char *name;
212 char *version;
215 /* The definition of the array (mf-runtime.c) must match the enums! */
216 extern struct __mf_dynamic_entry __mf_dynamic[];
217 enum __mf_dynamic_index
219 dyn_calloc, dyn_free, dyn_malloc, dyn_mmap,
220 dyn_munmap, dyn_realloc,
221 dyn_INITRESOLVE, /* Marker for last init-time resolution. */
222 #ifdef LIBMUDFLAPTH
223 dyn_pthread_create
224 #endif
227 #endif /* PIC */
229 /* ------------------------------------------------------------------------ */
230 /* Private global variables. */
231 /* ------------------------------------------------------------------------ */
233 #ifdef LIBMUDFLAPTH
234 extern pthread_mutex_t __mf_biglock;
235 #define LOCKTH() do { extern unsigned long __mf_lock_contention; \
236 int rc = pthread_mutex_trylock (& __mf_biglock); \
237 if (rc) { __mf_lock_contention ++; \
238 rc = pthread_mutex_lock (& __mf_biglock); } \
239 assert (rc==0); } while (0)
240 #define UNLOCKTH() do { int rc = pthread_mutex_unlock (& __mf_biglock); \
241 assert (rc==0); } while (0)
242 #else
243 #define LOCKTH() do {} while (0)
244 #define UNLOCKTH() do {} while (0)
245 #endif
247 #if defined(LIBMUDFLAPTH) && !defined(HAVE_TLS)
248 extern enum __mf_state_enum __mf_get_state (void);
249 extern void __mf_set_state (enum __mf_state_enum);
250 #else
251 # ifdef LIBMUDFLAPTH
252 extern __thread enum __mf_state_enum __mf_state_1;
253 # else
254 extern enum __mf_state_enum __mf_state_1;
255 # endif
256 static inline enum __mf_state_enum __mf_get_state (void)
258 return __mf_state_1;
260 static inline void __mf_set_state (enum __mf_state_enum s)
262 __mf_state_1 = s;
264 #endif
266 extern int __mf_starting_p;
267 extern struct __mf_options __mf_opts;
269 /* ------------------------------------------------------------------------ */
270 /* Utility macros. */
271 /* ------------------------------------------------------------------------ */
273 #define UNLIKELY(e) (__builtin_expect (!!(e), 0))
274 #define LIKELY(e) (__builtin_expect (!!(e), 1))
275 #define STRINGIFY2(e) #e
276 #define STRINGIFY(e) STRINGIFY2(e)
278 #ifdef LIBMUDFLAPTH
279 #define VERBOSE_TRACE(...) \
280 do { if (UNLIKELY (__mf_opts.verbose_trace)) { \
281 fprintf (stderr, "mf(%u): ", (unsigned) pthread_self ()); \
282 fprintf (stderr, __VA_ARGS__); \
283 } } while (0)
284 #define TRACE(...) \
285 do { if (UNLIKELY (__mf_opts.trace_mf_calls)) { \
286 fprintf (stderr, "mf(%u): ", (unsigned) pthread_self ()); \
287 fprintf (stderr, __VA_ARGS__); \
288 } } while (0)
289 #else
290 #define VERBOSE_TRACE(...) \
291 do { if (UNLIKELY (__mf_opts.verbose_trace)) { \
292 fprintf (stderr, "mf: "); \
293 fprintf (stderr, __VA_ARGS__); \
294 } } while (0)
295 #define TRACE(...) \
296 do { if (UNLIKELY (__mf_opts.trace_mf_calls)) { \
297 fprintf (stderr, "mf: "); \
298 fprintf (stderr, __VA_ARGS__); \
299 } } while (0)
300 #endif
303 #define __MF_PERSIST_MAX 256
304 #define __MF_FREEQ_MAX 256
307 Wrapping and redirection:
309 Mudflap redirects a number of libc functions into itself, for "cheap"
310 verification (eg. strcpy, bzero, memcpy) and also to register /
311 unregister regions of memory as they are manipulated by the program
312 (eg. malloc/free, mmap/munmap).
314 There are two methods of wrapping.
316 (1) The static method involves a list of -wrap=foo flags being passed to
317 the linker, which then links references to "foo" to the symbol
318 "__wrap_foo", and links references to "__real_foo" to the symbol "foo".
319 When compiled without -DPIC, libmudflap.a contains such __wrap_foo
320 functions which delegate to __real_foo functions in libc to get their
321 work done.
323 (2) The dynamic method involves providing a definition of symbol foo in
324 libmudflap.so and linking it earlier in the compiler command line,
325 before libc.so. The function "foo" in libmudflap must then call
326 dlsym(RTLD_NEXT, "foo") to acquire a pointer to the "real" libc foo, or
327 at least the "next" foo in the dynamic link resolution order.
329 We switch between these two techniques by the presence of the -DPIC
330 #define passed in by libtool when building libmudflap.
334 #ifdef PIC
336 extern void __mf_resolve_single_dynamic (struct __mf_dynamic_entry *);
338 #define _GNU_SOURCE
339 #include <dlfcn.h>
341 #define WRAPPER(ret, fname, ...) \
342 ret __wrap_ ## fname (__VA_ARGS__) \
343 __attribute__ (( alias (#fname) )); \
344 ret __real_ ## fname (__VA_ARGS__) \
345 __attribute__ (( alias (#fname) )); \
346 ret fname (__VA_ARGS__)
347 #define DECLARE(ty, fname, ...) \
348 typedef ty (*__mf_fn_ ## fname) (__VA_ARGS__); \
349 extern ty __mf_0fn_ ## fname (__VA_ARGS__);
350 #define CALL_REAL(fname, ...) \
351 ({__mf_starting_p \
352 ? __mf_0fn_ ## fname (__VA_ARGS__) \
353 : (__mf_resolve_single_dynamic (& __mf_dynamic[dyn_ ## fname]), \
354 (((__mf_fn_ ## fname)(__mf_dynamic[dyn_ ## fname].pointer)) (__VA_ARGS__)));})
355 #define CALL_BACKUP(fname, ...) \
356 __mf_0fn_ ## fname(__VA_ARGS__)
358 #else /* not PIC --> static library */
360 #define WRAPPER(ret, fname, ...) \
361 ret __wrap_ ## fname (__VA_ARGS__)
362 #define DECLARE(ty, fname, ...) \
363 extern ty __real_ ## fname (__VA_ARGS__)
364 #define CALL_REAL(fname, ...) \
365 __real_ ## fname (__VA_ARGS__)
366 #define CALL_BACKUP(fname, ...) \
367 __real_ ## fname(__VA_ARGS__)
369 #endif /* PIC */
371 /* WRAPPER2 is for functions intercepted via macros at compile time. */
372 #define WRAPPER2(ret, fname, ...) \
373 ret __mfwrap_ ## fname (__VA_ARGS__)
376 /* Utility macros for mf-hooks*.c */
378 #define MF_VALIDATE_EXTENT(value,size,acc,context) \
379 do { \
380 if (UNLIKELY (size > 0 && __MF_CACHE_MISS_P (value, size))) \
381 if (acc == __MF_CHECK_WRITE || ! __mf_opts.ignore_reads) \
382 __mf_check ((void *) (value), (size), acc, "(" context ")"); \
383 } while (0)
384 #define BEGIN_PROTECT(fname, ...) \
385 if (UNLIKELY (__mf_starting_p)) \
387 return CALL_BACKUP(fname, __VA_ARGS__); \
389 else if (UNLIKELY (__mf_get_state () == reentrant)) \
391 extern unsigned long __mf_reentrancy; \
392 __mf_reentrancy ++; \
393 return CALL_REAL(fname, __VA_ARGS__); \
395 else if (UNLIKELY (__mf_get_state () == in_malloc)) \
397 return CALL_REAL(fname, __VA_ARGS__); \
399 else \
401 TRACE ("%s\n", __PRETTY_FUNCTION__); \
404 /* There is an assumption here that these will only be called in routines
405 that call BEGIN_PROTECT at the start, and hence the state must always
406 be active when BEGIN_MALLOC_PROTECT is called. */
407 #define BEGIN_MALLOC_PROTECT() \
408 __mf_set_state (in_malloc)
410 #define END_MALLOC_PROTECT() \
411 __mf_set_state (active)
413 /* Unlocked variants of main entry points from mf-runtime.h. */
414 extern void __mfu_check (void *ptr, size_t sz, int type, const char *location);
415 extern void __mfu_register (void *ptr, size_t sz, int type, const char *name);
416 extern void __mfu_unregister (void *ptr, size_t sz, int type);
417 extern void __mfu_report ();
418 extern int __mfu_set_options (const char *opts);
421 #endif /* __MF_IMPL_H */