Upgrade Boehm GC to 7.2alpha4.
[cacao.git] / src / mm / boehm-gc / dbg_mlc.c
1 /*
2  * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3  * Copyright (c) 1991-1995 by Xerox Corporation.  All rights reserved.
4  * Copyright (c) 1997 by Silicon Graphics.  All rights reserved.
5  * Copyright (c) 1999-2004 Hewlett-Packard Development Company, L.P.
6  * Copyright (C) 2007 Free Software Foundation, Inc
7  *
8  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
9  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
10  *
11  * Permission is hereby granted to use or copy this program
12  * for any purpose,  provided the above notices are retained on all copies.
13  * Permission to modify the code and to distribute modified code is granted,
14  * provided the above notices are retained, and a notice that the code was
15  * modified is included with the above copyright notice.
16  */
17
18 #include "private/dbg_mlc.h"
19
20 #ifndef MSWINCE
21 # include <errno.h>
22 #endif
23 #include <string.h>
24
25 GC_INNER void GC_default_print_heap_obj_proc(ptr_t p);
26
27 GC_API void GC_CALL GC_register_finalizer_no_order(void * obj,
28                                 GC_finalization_proc fn, void * cd,
29                                 GC_finalization_proc *ofn, void * *ocd);
30
31 #ifndef SHORT_DBG_HDRS
32   /* Check whether object with base pointer p has debugging info  */
33   /* p is assumed to point to a legitimate object in our part     */
34   /* of the heap.                                                 */
35   /* This excludes the check as to whether the back pointer is    */
36   /* odd, which is added by the GC_HAS_DEBUG_INFO macro.          */
37   /* Note that if DBG_HDRS_ALL is set, uncollectable objects      */
38   /* on free lists may not have debug information set.  Thus it's */
39   /* not always safe to return TRUE, even if the client does      */
40   /* its part.                                                    */
41   GC_INNER GC_bool GC_has_other_debug_info(ptr_t p)
42   {
43     oh * ohdr = (oh *)p;
44     ptr_t body = (ptr_t)(ohdr + 1);
45     word sz = GC_size((ptr_t) ohdr);
46
47     if (HBLKPTR((ptr_t)ohdr) != HBLKPTR((ptr_t)body)
48         || sz < DEBUG_BYTES + EXTRA_BYTES) {
49         return(FALSE);
50     }
51     if (ohdr -> oh_sz == sz) {
52         /* Object may have had debug info, but has been deallocated     */
53         return(FALSE);
54     }
55     if (ohdr -> oh_sf == (START_FLAG ^ (word)body)) return(TRUE);
56     if (((word *)ohdr)[BYTES_TO_WORDS(sz)-1] == (END_FLAG ^ (word)body)) {
57         return(TRUE);
58     }
59     return(FALSE);
60   }
61 #endif
62
63 #ifdef KEEP_BACK_PTRS
64
65 # include <stdlib.h>
66
67 # if defined(__GLIBC__) || defined(SOLARIS) \
68      || defined(HPUX) || defined(IRIX5) || defined(OSF1)
69 #   define RANDOM() random()
70 # else
71 #   define RANDOM() (long)rand()
72 # endif
73
74   /* Store back pointer to source in dest, if that appears to be possible. */
75   /* This is not completely safe, since we may mistakenly conclude that    */
76   /* dest has a debugging wrapper.  But the error probability is very      */
77   /* small, and this shouldn't be used in production code.                 */
78   /* We assume that dest is the real base pointer.  Source will usually    */
79   /* be a pointer to the interior of an object.                            */
80   GC_INNER void GC_store_back_pointer(ptr_t source, ptr_t dest)
81   {
82     if (GC_HAS_DEBUG_INFO(dest)) {
83       ((oh *)dest) -> oh_back_ptr = HIDE_BACK_PTR(source);
84     }
85   }
86
87   GC_INNER void GC_marked_for_finalization(ptr_t dest)
88   {
89     GC_store_back_pointer(MARKED_FOR_FINALIZATION, dest);
90   }
91
92   /* Store information about the object referencing dest in *base_p     */
93   /* and *offset_p.                                                     */
94   /*   source is root ==> *base_p = address, *offset_p = 0              */
95   /*   source is heap object ==> *base_p != 0, *offset_p = offset       */
96   /*   Returns 1 on success, 0 if source couldn't be determined.        */
97   /* Dest can be any address within a heap object.                      */
98   GC_API GC_ref_kind GC_CALL GC_get_back_ptr_info(void *dest, void **base_p,
99                                                 size_t *offset_p)
100   {
101     oh * hdr = (oh *)GC_base(dest);
102     ptr_t bp;
103     ptr_t bp_base;
104     if (!GC_HAS_DEBUG_INFO((ptr_t) hdr)) return GC_NO_SPACE;
105     bp = GC_REVEAL_POINTER(hdr -> oh_back_ptr);
106     if (MARKED_FOR_FINALIZATION == bp) return GC_FINALIZER_REFD;
107     if (MARKED_FROM_REGISTER == bp) return GC_REFD_FROM_REG;
108     if (NOT_MARKED == bp) return GC_UNREFERENCED;
109 #   if ALIGNMENT == 1
110       /* Heuristically try to fix off by 1 errors we introduced by      */
111       /* insisting on even addresses.                                   */
112       {
113         ptr_t alternate_ptr = bp + 1;
114         ptr_t target = *(ptr_t *)bp;
115         ptr_t alternate_target = *(ptr_t *)alternate_ptr;
116
117         if (alternate_target >= GC_least_plausible_heap_addr
118             && alternate_target <= GC_greatest_plausible_heap_addr
119             && (target < GC_least_plausible_heap_addr
120                 || target > GC_greatest_plausible_heap_addr)) {
121             bp = alternate_ptr;
122         }
123       }
124 #   endif
125     bp_base = GC_base(bp);
126     if (0 == bp_base) {
127       *base_p = bp;
128       *offset_p = 0;
129       return GC_REFD_FROM_ROOT;
130     } else {
131       if (GC_HAS_DEBUG_INFO(bp_base)) bp_base += sizeof(oh);
132       *base_p = bp_base;
133       *offset_p = bp - bp_base;
134       return GC_REFD_FROM_HEAP;
135     }
136   }
137
138   /* Generate a random heap address.            */
139   /* The resulting address is in the heap, but  */
140   /* not necessarily inside a valid object.     */
141   GC_API void * GC_CALL GC_generate_random_heap_address(void)
142   {
143     size_t i;
144     word heap_offset = RANDOM();
145     if (GC_heapsize > RAND_MAX) {
146         heap_offset *= RAND_MAX;
147         heap_offset += RANDOM();
148     }
149     heap_offset %= GC_heapsize;
150         /* This doesn't yield a uniform distribution, especially if     */
151         /* e.g. RAND_MAX = 1.5* GC_heapsize.  But for typical cases,    */
152         /* it's not too bad.                                            */
153     for (i = 0; i < GC_n_heap_sects; ++ i) {
154         size_t size = GC_heap_sects[i].hs_bytes;
155         if (heap_offset < size) {
156             return GC_heap_sects[i].hs_start + heap_offset;
157         } else {
158             heap_offset -= size;
159         }
160     }
161     ABORT("GC_generate_random_heap_address: size inconsistency");
162     /*NOTREACHED*/
163     return 0;
164   }
165
166   /* Generate a random address inside a valid marked heap object. */
167   GC_API void * GC_CALL GC_generate_random_valid_address(void)
168   {
169     ptr_t result;
170     ptr_t base;
171     for (;;) {
172         result = GC_generate_random_heap_address();
173         base = GC_base(result);
174         if (0 == base) continue;
175         if (!GC_is_marked(base)) continue;
176         return result;
177     }
178   }
179
180   /* Print back trace for p */
181   GC_API void GC_CALL GC_print_backtrace(void *p)
182   {
183     void *current = p;
184     int i;
185     GC_ref_kind source;
186     size_t offset;
187     void *base;
188
189     GC_print_heap_obj(GC_base(current));
190     GC_err_printf("\n");
191     for (i = 0; ; ++i) {
192       source = GC_get_back_ptr_info(current, &base, &offset);
193       if (GC_UNREFERENCED == source) {
194         GC_err_printf("Reference could not be found\n");
195         goto out;
196       }
197       if (GC_NO_SPACE == source) {
198         GC_err_printf("No debug info in object: Can't find reference\n");
199         goto out;
200       }
201       GC_err_printf("Reachable via %d levels of pointers from ", i);
202       switch(source) {
203         case GC_REFD_FROM_ROOT:
204           GC_err_printf("root at %p\n\n", base);
205           goto out;
206         case GC_REFD_FROM_REG:
207           GC_err_printf("root in register\n\n");
208           goto out;
209         case GC_FINALIZER_REFD:
210           GC_err_printf("list of finalizable objects\n\n");
211           goto out;
212         case GC_REFD_FROM_HEAP:
213           GC_err_printf("offset %ld in object:\n", (unsigned long)offset);
214           /* Take GC_base(base) to get real base, i.e. header. */
215           GC_print_heap_obj(GC_base(base));
216           GC_err_printf("\n");
217           break;
218         default:
219           GC_err_printf("INTERNAL ERROR: UNEXPECTED SOURCE!!!!\n");
220           goto out;
221       }
222       current = base;
223     }
224     out:;
225   }
226
227   /* Force a garbage collection and generate a backtrace from a */
228   /* random heap address.                                       */
229   GC_INNER void GC_generate_random_backtrace_no_gc(void)
230   {
231     void * current;
232     current = GC_generate_random_valid_address();
233     GC_printf("\n****Chose address %p in object\n", current);
234     GC_print_backtrace(current);
235   }
236
237   GC_API void GC_CALL GC_generate_random_backtrace(void)
238   {
239     if (GC_try_to_collect(GC_never_stop_func) == 0) {
240       GC_err_printf("Cannot generate a backtrace: "
241                     "garbage collection is disabled!\n");
242       return;
243     }
244     GC_generate_random_backtrace_no_gc();
245   }
246
247 #endif /* KEEP_BACK_PTRS */
248
249 # define CROSSES_HBLK(p, sz) \
250         (((word)(p + sizeof(oh) + sz - 1) ^ (word)p) >= HBLKSIZE)
251 /* Store debugging info into p.  Return displaced pointer. */
252 /* Assumes we don't hold allocation lock.                  */
253 GC_INNER ptr_t GC_store_debug_info(ptr_t p, word sz, const char *string,
254                                    word integer)
255 {
256     word * result = (word *)((oh *)p + 1);
257     DCL_LOCK_STATE;
258
259     LOCK();
260     GC_ASSERT(GC_size(p) >= sizeof(oh) + sz);
261     GC_ASSERT(!(SMALL_OBJ(sz) && CROSSES_HBLK(p, sz)));
262 #   ifdef KEEP_BACK_PTRS
263       ((oh *)p) -> oh_back_ptr = HIDE_BACK_PTR(NOT_MARKED);
264 #   endif
265 #   ifdef MAKE_BACK_GRAPH
266       ((oh *)p) -> oh_bg_ptr = HIDE_BACK_PTR((ptr_t)0);
267 #   endif
268     ((oh *)p) -> oh_string = string;
269     ((oh *)p) -> oh_int = integer;
270 #   ifndef SHORT_DBG_HDRS
271       ((oh *)p) -> oh_sz = sz;
272       ((oh *)p) -> oh_sf = START_FLAG ^ (word)result;
273       ((word *)p)[BYTES_TO_WORDS(GC_size(p))-1] =
274          result[SIMPLE_ROUNDED_UP_WORDS(sz)] = END_FLAG ^ (word)result;
275 #   endif
276     UNLOCK();
277     return((ptr_t)result);
278 }
279
280 #ifdef DBG_HDRS_ALL
281 /* Store debugging info into p.  Return displaced pointer.         */
282 /* This version assumes we do hold the allocation lock.            */
283 STATIC ptr_t GC_store_debug_info_inner(ptr_t p, word sz, char *string,
284                                        word integer)
285 {
286     word * result = (word *)((oh *)p + 1);
287
288     GC_ASSERT(GC_size(p) >= sizeof(oh) + sz);
289     GC_ASSERT(!(SMALL_OBJ(sz) && CROSSES_HBLK(p, sz)));
290 #   ifdef KEEP_BACK_PTRS
291       ((oh *)p) -> oh_back_ptr = HIDE_BACK_PTR(NOT_MARKED);
292 #   endif
293 #   ifdef MAKE_BACK_GRAPH
294       ((oh *)p) -> oh_bg_ptr = HIDE_BACK_PTR((ptr_t)0);
295 #   endif
296     ((oh *)p) -> oh_string = string;
297     ((oh *)p) -> oh_int = integer;
298 #   ifndef SHORT_DBG_HDRS
299       ((oh *)p) -> oh_sz = sz;
300       ((oh *)p) -> oh_sf = START_FLAG ^ (word)result;
301       ((word *)p)[BYTES_TO_WORDS(GC_size(p))-1] =
302          result[SIMPLE_ROUNDED_UP_WORDS(sz)] = END_FLAG ^ (word)result;
303 #   endif
304     return((ptr_t)result);
305 }
306 #endif
307
308 #ifndef SHORT_DBG_HDRS
309   /* Check the object with debugging info at ohdr       */
310   /* return NIL if it's OK.  Else return clobbered      */
311   /* address.                                           */
312   STATIC ptr_t GC_check_annotated_obj(oh *ohdr)
313   {
314     ptr_t body = (ptr_t)(ohdr + 1);
315     word gc_sz = GC_size((ptr_t)ohdr);
316     if (ohdr -> oh_sz + DEBUG_BYTES > gc_sz) {
317         return((ptr_t)(&(ohdr -> oh_sz)));
318     }
319     if (ohdr -> oh_sf != (START_FLAG ^ (word)body)) {
320         return((ptr_t)(&(ohdr -> oh_sf)));
321     }
322     if (((word *)ohdr)[BYTES_TO_WORDS(gc_sz)-1] != (END_FLAG ^ (word)body)) {
323         return((ptr_t)((word *)ohdr + BYTES_TO_WORDS(gc_sz)-1));
324     }
325     if (((word *)body)[SIMPLE_ROUNDED_UP_WORDS(ohdr -> oh_sz)]
326         != (END_FLAG ^ (word)body)) {
327         return((ptr_t)((word *)body + SIMPLE_ROUNDED_UP_WORDS(ohdr->oh_sz)));
328     }
329     return(0);
330   }
331 #endif /* !SHORT_DBG_HDRS */
332
333 STATIC GC_describe_type_fn GC_describe_type_fns[MAXOBJKINDS] = {0};
334
335 GC_API void GC_CALL GC_register_describe_type_fn(int kind,
336                                                  GC_describe_type_fn fn)
337 {
338   GC_describe_type_fns[kind] = fn;
339 }
340
341 /* Print a type description for the object whose client-visible address */
342 /* is p.                                                                */
343 STATIC void GC_print_type(ptr_t p)
344 {
345     hdr * hhdr = GC_find_header(p);
346     char buffer[GC_TYPE_DESCR_LEN + 1];
347     int kind = hhdr -> hb_obj_kind;
348
349     if (0 != GC_describe_type_fns[kind] && GC_is_marked(GC_base(p))) {
350         /* This should preclude free list objects except with   */
351         /* thread-local allocation.                             */
352         buffer[GC_TYPE_DESCR_LEN] = 0;
353         (GC_describe_type_fns[kind])(p, buffer);
354         GC_ASSERT(buffer[GC_TYPE_DESCR_LEN] == 0);
355         GC_err_puts(buffer);
356     } else {
357         switch(kind) {
358           case PTRFREE:
359             GC_err_puts("PTRFREE");
360             break;
361           case NORMAL:
362             GC_err_puts("NORMAL");
363             break;
364           case UNCOLLECTABLE:
365             GC_err_puts("UNCOLLECTABLE");
366             break;
367 #         ifdef ATOMIC_UNCOLLECTABLE
368             case AUNCOLLECTABLE:
369               GC_err_puts("ATOMIC UNCOLLECTABLE");
370               break;
371 #         endif
372           case STUBBORN:
373             GC_err_puts("STUBBORN");
374             break;
375           default:
376             GC_err_printf("kind %d, descr 0x%lx", kind,
377                           (unsigned long)(hhdr -> hb_descr));
378         }
379     }
380 }
381
382 /* Print a human-readable description of the object to stderr. p points */
383 /* to somewhere inside an object with the debugging info.               */
384 STATIC void GC_print_obj(ptr_t p)
385 {
386     oh * ohdr = (oh *)GC_base(p);
387
388     GC_ASSERT(I_DONT_HOLD_LOCK());
389     GC_err_printf("%p (", ((ptr_t)ohdr + sizeof(oh)));
390     GC_err_puts(ohdr -> oh_string);
391 #   ifdef SHORT_DBG_HDRS
392       GC_err_printf(":%ld, ", (unsigned long)(ohdr -> oh_int));
393 #   else
394       GC_err_printf(":%ld, sz=%ld, ", (unsigned long)(ohdr -> oh_int),
395                                         (unsigned long)(ohdr -> oh_sz));
396 #   endif
397     GC_print_type((ptr_t)(ohdr + 1));
398     GC_err_puts(")\n");
399     PRINT_CALL_CHAIN(ohdr);
400 }
401
402 STATIC void GC_debug_print_heap_obj_proc(ptr_t p)
403 {
404     GC_ASSERT(I_DONT_HOLD_LOCK());
405     if (GC_HAS_DEBUG_INFO(p)) {
406         GC_print_obj(p);
407     } else {
408         GC_default_print_heap_obj_proc(p);
409     }
410 }
411
412 #ifndef SHORT_DBG_HDRS
413   /* Use GC_err_printf and friends to print a description of the object */
414   /* whose client-visible address is p, and which was smashed at        */
415   /* clobbered_addr.                                                    */
416   STATIC void GC_print_smashed_obj(ptr_t p, ptr_t clobbered_addr)
417   {
418     oh * ohdr = (oh *)GC_base(p);
419
420     GC_ASSERT(I_DONT_HOLD_LOCK());
421     if (clobbered_addr <= (ptr_t)(&(ohdr -> oh_sz))
422         || ohdr -> oh_string == 0) {
423         GC_err_printf(
424                 "%p in or near object at %p(<smashed>, appr. sz = %lu)\n",
425                 clobbered_addr, p,
426                 (unsigned long)(GC_size((ptr_t)ohdr) - DEBUG_BYTES));
427     } else {
428         GC_err_printf("%p in or near object at %p(%s:%lu, sz=%lu)\n",
429                 clobbered_addr, p,
430                 (word)(ohdr -> oh_string) < HBLKSIZE ? "(smashed string)" :
431                 ohdr -> oh_string[0] == '\0' ? "EMPTY(smashed?)" :
432                                                 ohdr -> oh_string,
433                 (unsigned long)(ohdr -> oh_int),
434                 (unsigned long)(ohdr -> oh_sz));
435         PRINT_CALL_CHAIN(ohdr);
436     }
437   }
438 #endif
439
440 #ifndef SHORT_DBG_HDRS
441   STATIC void GC_check_heap_proc (void);
442   STATIC void GC_print_all_smashed_proc (void);
443 #else
444   STATIC void GC_do_nothing(void) {}
445 #endif
446
447 GC_INNER void GC_start_debugging(void)
448 {
449 #   ifndef SHORT_DBG_HDRS
450       GC_check_heap = GC_check_heap_proc;
451       GC_print_all_smashed = GC_print_all_smashed_proc;
452 #   else
453       GC_check_heap = GC_do_nothing;
454       GC_print_all_smashed = GC_do_nothing;
455 #   endif
456     GC_print_heap_obj = GC_debug_print_heap_obj_proc;
457     GC_debugging_started = TRUE;
458     GC_register_displacement((word)sizeof(oh));
459 }
460
461 size_t GC_debug_header_size = sizeof(oh);
462
463 GC_API void GC_CALL GC_debug_register_displacement(size_t offset)
464 {
465     GC_register_displacement(offset);
466     GC_register_displacement((word)sizeof(oh) + offset);
467 }
468
469 GC_API void * GC_CALL GC_debug_malloc(size_t lb, GC_EXTRA_PARAMS)
470 {
471     void * result = GC_malloc(lb + DEBUG_BYTES);
472
473     if (result == 0) {
474         GC_err_printf("GC_debug_malloc(%lu) returning NIL (",
475                       (unsigned long) lb);
476         GC_err_puts(s);
477         GC_err_printf(":%ld)\n", (unsigned long)i);
478         return(0);
479     }
480     if (!GC_debugging_started) {
481         GC_start_debugging();
482     }
483     ADD_CALL_CHAIN(result, ra);
484     return (GC_store_debug_info(result, (word)lb, s, (word)i));
485 }
486
487 GC_API void * GC_CALL GC_debug_malloc_ignore_off_page(size_t lb,
488                                                       GC_EXTRA_PARAMS)
489 {
490     void * result = GC_malloc_ignore_off_page(lb + DEBUG_BYTES);
491
492     if (result == 0) {
493         GC_err_printf("GC_debug_malloc_ignore_off_page(%lu) returning NIL (",
494                        (unsigned long) lb);
495         GC_err_puts(s);
496         GC_err_printf(":%lu)\n", (unsigned long)i);
497         return(0);
498     }
499     if (!GC_debugging_started) {
500         GC_start_debugging();
501     }
502     ADD_CALL_CHAIN(result, ra);
503     return (GC_store_debug_info(result, (word)lb, s, (word)i));
504 }
505
506 GC_API void * GC_CALL GC_debug_malloc_atomic_ignore_off_page(size_t lb,
507                                                              GC_EXTRA_PARAMS)
508 {
509     void * result = GC_malloc_atomic_ignore_off_page(lb + DEBUG_BYTES);
510
511     if (result == 0) {
512         GC_err_printf("GC_debug_malloc_atomic_ignore_off_page(%lu)"
513                        " returning NIL (", (unsigned long) lb);
514         GC_err_puts(s);
515         GC_err_printf(":%lu)\n", (unsigned long)i);
516         return(0);
517     }
518     if (!GC_debugging_started) {
519         GC_start_debugging();
520     }
521     ADD_CALL_CHAIN(result, ra);
522     return (GC_store_debug_info(result, (word)lb, s, (word)i));
523 }
524
525 #ifdef DBG_HDRS_ALL
526   /*
527    * An allocation function for internal use.
528    * Normally internally allocated objects do not have debug information.
529    * But in this case, we need to make sure that all objects have debug
530    * headers.
531    * We assume debugging was started in collector initialization,
532    * and we already hold the GC lock.
533    */
534   GC_INNER void * GC_debug_generic_malloc_inner(size_t lb, int k)
535   {
536     void * result = GC_generic_malloc_inner(lb + DEBUG_BYTES, k);
537
538     if (result == 0) {
539         GC_err_printf("GC internal allocation (%lu bytes) returning NIL\n",
540                        (unsigned long) lb);
541         return(0);
542     }
543     ADD_CALL_CHAIN(result, GC_RETURN_ADDR);
544     return (GC_store_debug_info_inner(result, (word)lb, "INTERNAL", (word)0));
545   }
546
547   GC_INNER void * GC_debug_generic_malloc_inner_ignore_off_page(size_t lb,
548                                                                 int k)
549   {
550     void * result = GC_generic_malloc_inner_ignore_off_page(
551                                                 lb + DEBUG_BYTES, k);
552
553     if (result == 0) {
554         GC_err_printf("GC internal allocation (%lu bytes) returning NIL\n",
555                        (unsigned long) lb);
556         return(0);
557     }
558     ADD_CALL_CHAIN(result, GC_RETURN_ADDR);
559     return (GC_store_debug_info_inner(result, (word)lb, "INTERNAL", (word)0));
560   }
561 #endif
562
563 #ifdef STUBBORN_ALLOC
564 GC_API void * GC_CALL GC_debug_malloc_stubborn(size_t lb, GC_EXTRA_PARAMS)
565 {
566     void * result = GC_malloc_stubborn(lb + DEBUG_BYTES);
567
568     if (result == 0) {
569         GC_err_printf("GC_debug_malloc(%lu) returning NIL (",
570                       (unsigned long) lb);
571         GC_err_puts(s);
572         GC_err_printf(":%lu)\n", (unsigned long)i);
573         return(0);
574     }
575     if (!GC_debugging_started) {
576         GC_start_debugging();
577     }
578     ADD_CALL_CHAIN(result, ra);
579     return (GC_store_debug_info(result, (word)lb, s, (word)i));
580 }
581
582 GC_API void GC_CALL GC_debug_change_stubborn(void *p)
583 {
584     void * q = GC_base(p);
585     hdr * hhdr;
586
587     if (q == 0) {
588         GC_err_printf("Bad argument: %p to GC_debug_change_stubborn\n", p);
589         ABORT("GC_debug_change_stubborn: bad arg");
590     }
591     hhdr = HDR(q);
592     if (hhdr -> hb_obj_kind != STUBBORN) {
593         GC_err_printf("GC_debug_change_stubborn arg not stubborn: %p\n", p);
594         ABORT("GC_debug_change_stubborn: arg not stubborn");
595     }
596     GC_change_stubborn(q);
597 }
598
599 GC_API void GC_CALL GC_debug_end_stubborn_change(void *p)
600 {
601     void * q = GC_base(p);
602     hdr * hhdr;
603
604     if (q == 0) {
605         GC_err_printf("Bad argument: %p to GC_debug_end_stubborn_change\n", p);
606         ABORT("GC_debug_end_stubborn_change: bad arg");
607     }
608     hhdr = HDR(q);
609     if (hhdr -> hb_obj_kind != STUBBORN) {
610         GC_err_printf("debug_end_stubborn_change arg not stubborn: %p\n", p);
611         ABORT("GC_debug_end_stubborn_change: arg not stubborn");
612     }
613     GC_end_stubborn_change(q);
614 }
615
616 #else /* !STUBBORN_ALLOC */
617
618 GC_API void * GC_CALL GC_debug_malloc_stubborn(size_t lb, GC_EXTRA_PARAMS)
619 {
620     return GC_debug_malloc(lb, OPT_RA s, i);
621 }
622
623 /*ARGSUSED*/
624 GC_API void GC_CALL GC_debug_change_stubborn(void *p) {}
625
626 /*ARGSUSED*/
627 GC_API void GC_CALL GC_debug_end_stubborn_change(void *p) {}
628
629 #endif /* !STUBBORN_ALLOC */
630
631 GC_API void * GC_CALL GC_debug_malloc_atomic(size_t lb, GC_EXTRA_PARAMS)
632 {
633     void * result = GC_malloc_atomic(lb + DEBUG_BYTES);
634
635     if (result == 0) {
636         GC_err_printf("GC_debug_malloc_atomic(%lu) returning NIL (",
637                       (unsigned long) lb);
638         GC_err_puts(s);
639         GC_err_printf(":%lu)\n", (unsigned long)i);
640         return(0);
641     }
642     if (!GC_debugging_started) {
643         GC_start_debugging();
644     }
645     ADD_CALL_CHAIN(result, ra);
646     return (GC_store_debug_info(result, (word)lb, s, (word)i));
647 }
648
649 GC_API char * GC_CALL GC_debug_strdup(const char *str, GC_EXTRA_PARAMS)
650 {
651     char *copy;
652     size_t lb;
653     if (str == NULL) return NULL;
654     lb = strlen(str) + 1;
655     copy = GC_debug_malloc_atomic(lb, OPT_RA s, i);
656     if (copy == NULL) {
657 #     ifndef MSWINCE
658         errno = ENOMEM;
659 #     endif
660       return NULL;
661     }
662 #   ifndef MSWINCE
663       strcpy(copy, str);
664 #   else
665       /* strcpy() is deprecated in WinCE */
666       memcpy(copy, str, lb);
667 #   endif
668     return copy;
669 }
670
671 GC_API void * GC_CALL GC_debug_malloc_uncollectable(size_t lb,
672                                                     GC_EXTRA_PARAMS)
673 {
674     void * result = GC_malloc_uncollectable(lb + UNCOLLECTABLE_DEBUG_BYTES);
675
676     if (result == 0) {
677         GC_err_printf("GC_debug_malloc_uncollectable(%lu) returning NIL (",
678                       (unsigned long) lb);
679         GC_err_puts(s);
680         GC_err_printf(":%lu)\n", (unsigned long)i);
681         return(0);
682     }
683     if (!GC_debugging_started) {
684         GC_start_debugging();
685     }
686     ADD_CALL_CHAIN(result, ra);
687     return (GC_store_debug_info(result, (word)lb, s, (word)i));
688 }
689
690 #ifdef ATOMIC_UNCOLLECTABLE
691   void * GC_debug_malloc_atomic_uncollectable(size_t lb, GC_EXTRA_PARAMS)
692   {
693     void * result =
694         GC_malloc_atomic_uncollectable(lb + UNCOLLECTABLE_DEBUG_BYTES);
695
696     if (result == 0) {
697         GC_err_printf(
698                 "GC_debug_malloc_atomic_uncollectable(%lu) returning NIL (",
699                 (unsigned long) lb);
700         GC_err_puts(s);
701         GC_err_printf(":%lu)\n", (unsigned long)i);
702         return(0);
703     }
704     if (!GC_debugging_started) {
705         GC_start_debugging();
706     }
707     ADD_CALL_CHAIN(result, ra);
708     return (GC_store_debug_info(result, (word)lb, s, (word)i));
709   }
710 #endif /* ATOMIC_UNCOLLECTABLE */
711
712 GC_API void GC_CALL GC_debug_free(void * p)
713 {
714     ptr_t base;
715 #   ifndef SHORT_DBG_HDRS
716       ptr_t clobbered;
717 #   endif
718
719     if (0 == p) return;
720     base = GC_base(p);
721     if (base == 0) {
722         GC_err_printf("Attempt to free invalid pointer %p\n", p);
723         ABORT("free(invalid pointer)");
724     }
725     if ((ptr_t)p - (ptr_t)base != sizeof(oh)) {
726         GC_err_printf(
727                  "GC_debug_free called on pointer %p w/o debugging info\n", p);
728     } else {
729 #     ifndef SHORT_DBG_HDRS
730         clobbered = GC_check_annotated_obj((oh *)base);
731         if (clobbered != 0) {
732           if (((oh *)base) -> oh_sz == GC_size(base)) {
733             GC_err_printf(
734                   "GC_debug_free: found previously deallocated (?) object at ");
735           } else {
736             GC_err_printf("GC_debug_free: found smashed location at ");
737           }
738           GC_print_smashed_obj(p, clobbered);
739         }
740         /* Invalidate size */
741         ((oh *)base) -> oh_sz = GC_size(base);
742 #     endif /* SHORT_DBG_HDRS */
743     }
744     if (GC_find_leak) {
745         GC_free(base);
746     } else {
747         hdr * hhdr = HDR(p);
748         GC_bool uncollectable = FALSE;
749
750         if (hhdr ->  hb_obj_kind == UNCOLLECTABLE) {
751             uncollectable = TRUE;
752         }
753 #       ifdef ATOMIC_UNCOLLECTABLE
754             if (hhdr ->  hb_obj_kind == AUNCOLLECTABLE) {
755                     uncollectable = TRUE;
756             }
757 #       endif
758         if (uncollectable) {
759             GC_free(base);
760         } else {
761             size_t i;
762             size_t obj_sz = BYTES_TO_WORDS(hhdr -> hb_sz - sizeof(oh));
763
764             for (i = 0; i < obj_sz; ++i) ((word *)p)[i] = 0xdeadbeef;
765             GC_ASSERT((word *)p + i == (word *)(base + hhdr -> hb_sz));
766         }
767     } /* !GC_find_leak */
768 }
769
770 #if defined(THREADS) && defined(DBG_HDRS_ALL)
771   /* Used internally; we assume it's called correctly.    */
772   GC_INNER void GC_debug_free_inner(void * p)
773   {
774     ptr_t base = GC_base(p);
775     GC_ASSERT((ptr_t)p - (ptr_t)base == sizeof(oh));
776 #   ifndef SHORT_DBG_HDRS
777     /* Invalidate size */
778         ((oh *)base) -> oh_sz = GC_size(base);
779 #   endif
780     GC_free_inner(base);
781   }
782 #endif
783
784 GC_API void * GC_CALL GC_debug_realloc(void * p, size_t lb, GC_EXTRA_PARAMS)
785 {
786     void * base;
787 #   ifndef SHORT_DBG_HDRS
788       ptr_t clobbered;
789 #   endif
790     void * result;
791     size_t copy_sz = lb;
792     size_t old_sz;
793     hdr * hhdr;
794
795     if (p == 0) return(GC_debug_malloc(lb, OPT_RA s, i));
796     base = GC_base(p);
797     if (base == 0) {
798         GC_err_printf("Attempt to reallocate invalid pointer %p\n", p);
799         ABORT("realloc(invalid pointer)");
800     }
801     if ((ptr_t)p - (ptr_t)base != sizeof(oh)) {
802         GC_err_printf(
803               "GC_debug_realloc called on pointer %p w/o debugging info\n", p);
804         return(GC_realloc(p, lb));
805     }
806     hhdr = HDR(base);
807     switch (hhdr -> hb_obj_kind) {
808 #    ifdef STUBBORN_ALLOC
809       case STUBBORN:
810         result = GC_debug_malloc_stubborn(lb, OPT_RA s, i);
811         break;
812 #    endif
813       case NORMAL:
814         result = GC_debug_malloc(lb, OPT_RA s, i);
815         break;
816       case PTRFREE:
817         result = GC_debug_malloc_atomic(lb, OPT_RA s, i);
818         break;
819       case UNCOLLECTABLE:
820         result = GC_debug_malloc_uncollectable(lb, OPT_RA s, i);
821         break;
822 #    ifdef ATOMIC_UNCOLLECTABLE
823       case AUNCOLLECTABLE:
824         result = GC_debug_malloc_atomic_uncollectable(lb, OPT_RA s, i);
825         break;
826 #    endif
827       default:
828         result = NULL; /* initialized to prevent warning. */
829         GC_err_printf("GC_debug_realloc: encountered bad kind\n");
830         ABORT("bad kind");
831     }
832 #   ifdef SHORT_DBG_HDRS
833       old_sz = GC_size(base) - sizeof(oh);
834 #   else
835       clobbered = GC_check_annotated_obj((oh *)base);
836       if (clobbered != 0) {
837         GC_err_printf("GC_debug_realloc: found smashed location at ");
838         GC_print_smashed_obj(p, clobbered);
839       }
840       old_sz = ((oh *)base) -> oh_sz;
841 #   endif
842     if (old_sz < copy_sz) copy_sz = old_sz;
843     if (result == 0) return(0);
844     BCOPY(p, result, copy_sz);
845     GC_debug_free(p);
846     return(result);
847 }
848
849 #ifndef SHORT_DBG_HDRS
850
851 /* List of smashed objects.  We defer printing these, since we can't    */
852 /* always print them nicely with the allocation lock held.              */
853 /* We put them here instead of in GC_arrays, since it may be useful to  */
854 /* be able to look at them with the debugger.                           */
855 #define MAX_SMASHED 20
856 STATIC ptr_t GC_smashed[MAX_SMASHED] = {0};
857 STATIC unsigned GC_n_smashed = 0;
858
859 STATIC void GC_add_smashed(ptr_t smashed)
860 {
861     GC_ASSERT(GC_is_marked(GC_base(smashed)));
862     GC_smashed[GC_n_smashed] = smashed;
863     if (GC_n_smashed < MAX_SMASHED - 1) ++GC_n_smashed;
864       /* In case of overflow, we keep the first MAX_SMASHED-1   */
865       /* entries plus the last one.                             */
866     GC_have_errors = TRUE;
867 }
868
869 /* Print all objects on the list.  Clear the list.      */
870 STATIC void GC_print_all_smashed_proc(void)
871 {
872     unsigned i;
873
874     GC_ASSERT(I_DONT_HOLD_LOCK());
875     if (GC_n_smashed == 0) return;
876     GC_err_printf("GC_check_heap_block: found smashed heap objects:\n");
877     for (i = 0; i < GC_n_smashed; ++i) {
878         GC_print_smashed_obj((ptr_t)GC_base(GC_smashed[i]) + sizeof(oh),
879                              GC_smashed[i]);
880         GC_smashed[i] = 0;
881     }
882     GC_n_smashed = 0;
883 }
884
885 /* Check all marked objects in the given block for validity     */
886 /* Avoid GC_apply_to_each_object for performance reasons.       */
887 /*ARGSUSED*/
888 STATIC void GC_check_heap_block(struct hblk *hbp, word dummy)
889 {
890     struct hblkhdr * hhdr = HDR(hbp);
891     size_t sz = hhdr -> hb_sz;
892     size_t bit_no;
893     char *p, *plim;
894
895     p = hbp->hb_body;
896     bit_no = 0;
897     if (sz > MAXOBJBYTES) {
898         plim = p;
899     } else {
900         plim = hbp->hb_body + HBLKSIZE - sz;
901     }
902     /* go through all words in block */
903         while( p <= plim ) {
904             if( mark_bit_from_hdr(hhdr, bit_no)
905                 && GC_HAS_DEBUG_INFO((ptr_t)p)) {
906                 ptr_t clobbered = GC_check_annotated_obj((oh *)p);
907
908                 if (clobbered != 0) GC_add_smashed(clobbered);
909             }
910             bit_no += MARK_BIT_OFFSET(sz);
911             p += sz;
912         }
913 }
914
915 /* This assumes that all accessible objects are marked, and that        */
916 /* I hold the allocation lock.  Normally called by collector.           */
917 STATIC void GC_check_heap_proc(void)
918 {
919 #   ifndef SMALL_CONFIG
920       GC_STATIC_ASSERT((sizeof(oh) & (GRANULE_BYTES - 1)) == 0);
921       /* FIXME: Should we check for twice that alignment?       */
922 #   endif
923     GC_apply_to_all_blocks(GC_check_heap_block, (word)0);
924 }
925
926 #endif /* !SHORT_DBG_HDRS */
927
928 struct closure {
929     GC_finalization_proc cl_fn;
930     void * cl_data;
931 };
932
933 STATIC void * GC_make_closure(GC_finalization_proc fn, void * data)
934 {
935     struct closure * result =
936 #   ifdef DBG_HDRS_ALL
937       (struct closure *) GC_debug_malloc(sizeof (struct closure),
938                                          GC_EXTRAS);
939 #   else
940       (struct closure *) GC_malloc(sizeof (struct closure));
941 #   endif
942
943     result -> cl_fn = fn;
944     result -> cl_data = data;
945     return((void *)result);
946 }
947
948 /* An auxiliary fns to make finalization work correctly with displaced  */
949 /* pointers introduced by the debugging allocators.                     */
950 STATIC void GC_CALLBACK GC_debug_invoke_finalizer(void * obj, void * data)
951 {
952     struct closure * cl = (struct closure *) data;
953     (*(cl -> cl_fn))((void *)((char *)obj + sizeof(oh)), cl -> cl_data);
954 }
955
956 /* Special finalizer_proc value to detect GC_register_finalizer() failure. */
957 #define OFN_UNSET (GC_finalization_proc)(signed_word)-1
958
959 /* Set ofn and ocd to reflect the values we got back.   */
960 static void store_old(void *obj, GC_finalization_proc my_old_fn,
961                       struct closure *my_old_cd, GC_finalization_proc *ofn,
962                       void **ocd)
963 {
964     if (0 != my_old_fn) {
965       if (my_old_fn == OFN_UNSET) {
966         /* register_finalizer() failed; (*ofn) and (*ocd) are unchanged. */
967         return;
968       }
969       if (my_old_fn != GC_debug_invoke_finalizer) {
970         GC_err_printf("Debuggable object at %p had non-debug finalizer.\n",
971                       obj);
972         /* This should probably be fatal. */
973       } else {
974         if (ofn) *ofn = my_old_cd -> cl_fn;
975         if (ocd) *ocd = my_old_cd -> cl_data;
976       }
977     } else {
978       if (ofn) *ofn = 0;
979       if (ocd) *ocd = 0;
980     }
981 }
982
983 GC_API void GC_CALL GC_debug_register_finalizer(void * obj,
984                                         GC_finalization_proc fn,
985                                         void * cd, GC_finalization_proc *ofn,
986                                         void * *ocd)
987 {
988     GC_finalization_proc my_old_fn = OFN_UNSET;
989     void * my_old_cd;
990     ptr_t base = GC_base(obj);
991     if (0 == base) {
992         /* We won't collect it, hence finalizer wouldn't be run. */
993         if (ocd) *ocd = 0;
994         if (ofn) *ofn = 0;
995         return;
996     }
997     if ((ptr_t)obj - base != sizeof(oh)) {
998         GC_err_printf(
999             "GC_debug_register_finalizer called with non-base-pointer %p\n",
1000             obj);
1001     }
1002     if (0 == fn) {
1003       GC_register_finalizer(base, 0, 0, &my_old_fn, &my_old_cd);
1004     } else {
1005       GC_register_finalizer(base, GC_debug_invoke_finalizer,
1006                             GC_make_closure(fn,cd), &my_old_fn, &my_old_cd);
1007     }
1008     store_old(obj, my_old_fn, (struct closure *)my_old_cd, ofn, ocd);
1009 }
1010
1011 GC_API void GC_CALL GC_debug_register_finalizer_no_order
1012                                     (void * obj, GC_finalization_proc fn,
1013                                      void * cd, GC_finalization_proc *ofn,
1014                                      void * *ocd)
1015 {
1016     GC_finalization_proc my_old_fn = OFN_UNSET;
1017     void * my_old_cd;
1018     ptr_t base = GC_base(obj);
1019     if (0 == base) {
1020         /* We won't collect it, hence finalizer wouldn't be run. */
1021         if (ocd) *ocd = 0;
1022         if (ofn) *ofn = 0;
1023         return;
1024     }
1025     if ((ptr_t)obj - base != sizeof(oh)) {
1026         GC_err_printf(
1027           "GC_debug_register_finalizer_no_order called with "
1028           "non-base-pointer %p\n",
1029           obj);
1030     }
1031     if (0 == fn) {
1032       GC_register_finalizer_no_order(base, 0, 0, &my_old_fn, &my_old_cd);
1033     } else {
1034       GC_register_finalizer_no_order(base, GC_debug_invoke_finalizer,
1035                                      GC_make_closure(fn,cd), &my_old_fn,
1036                                      &my_old_cd);
1037     }
1038     store_old(obj, my_old_fn, (struct closure *)my_old_cd, ofn, ocd);
1039 }
1040
1041 GC_API void GC_CALL GC_debug_register_finalizer_unreachable
1042                                     (void * obj, GC_finalization_proc fn,
1043                                      void * cd, GC_finalization_proc *ofn,
1044                                      void * *ocd)
1045 {
1046     GC_finalization_proc my_old_fn = OFN_UNSET;
1047     void * my_old_cd;
1048     ptr_t base = GC_base(obj);
1049     if (0 == base) {
1050         /* We won't collect it, hence finalizer wouldn't be run. */
1051         if (ocd) *ocd = 0;
1052         if (ofn) *ofn = 0;
1053         return;
1054     }
1055     if ((ptr_t)obj - base != sizeof(oh)) {
1056         GC_err_printf(
1057             "GC_debug_register_finalizer_unreachable called with "
1058             "non-base-pointer %p\n",
1059             obj);
1060     }
1061     if (0 == fn) {
1062       GC_register_finalizer_unreachable(base, 0, 0, &my_old_fn, &my_old_cd);
1063     } else {
1064       GC_register_finalizer_unreachable(base, GC_debug_invoke_finalizer,
1065                                         GC_make_closure(fn,cd), &my_old_fn,
1066                                         &my_old_cd);
1067     }
1068     store_old(obj, my_old_fn, (struct closure *)my_old_cd, ofn, ocd);
1069 }
1070
1071 GC_API void GC_CALL GC_debug_register_finalizer_ignore_self
1072                                     (void * obj, GC_finalization_proc fn,
1073                                      void * cd, GC_finalization_proc *ofn,
1074                                      void * *ocd)
1075 {
1076     GC_finalization_proc my_old_fn = OFN_UNSET;
1077     void * my_old_cd;
1078     ptr_t base = GC_base(obj);
1079     if (0 == base) {
1080         /* We won't collect it, hence finalizer wouldn't be run. */
1081         if (ocd) *ocd = 0;
1082         if (ofn) *ofn = 0;
1083         return;
1084     }
1085     if ((ptr_t)obj - base != sizeof(oh)) {
1086         GC_err_printf(
1087             "GC_debug_register_finalizer_ignore_self called with "
1088             "non-base-pointer %p\n", obj);
1089     }
1090     if (0 == fn) {
1091       GC_register_finalizer_ignore_self(base, 0, 0, &my_old_fn, &my_old_cd);
1092     } else {
1093       GC_register_finalizer_ignore_self(base, GC_debug_invoke_finalizer,
1094                                         GC_make_closure(fn,cd), &my_old_fn,
1095                                         &my_old_cd);
1096     }
1097     store_old(obj, my_old_fn, (struct closure *)my_old_cd, ofn, ocd);
1098 }
1099
1100 #ifdef GC_ADD_CALLER
1101 # define RA GC_RETURN_ADDR,
1102 #else
1103 # define RA
1104 #endif
1105
1106 GC_API void * GC_CALL GC_debug_malloc_replacement(size_t lb)
1107 {
1108     return GC_debug_malloc(lb, RA "unknown", 0);
1109 }
1110
1111 GC_API void * GC_CALL GC_debug_realloc_replacement(void *p, size_t lb)
1112 {
1113     return GC_debug_realloc(p, lb, RA "unknown", 0);
1114 }