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