Fix exporting of GC_push_finalizer_structures
[platform/upstream/libgc.git] / finalize.c
1 /*
2  * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3  * Copyright (c) 1991-1996 by Xerox Corporation.  All rights reserved.
4  * Copyright (c) 1996-1999 by Silicon Graphics.  All rights reserved.
5  * Copyright (C) 2007 Free Software Foundation, Inc
6
7  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
8  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
9  *
10  * Permission is hereby granted to use or copy this program
11  * for any purpose,  provided the above notices are retained on all copies.
12  * Permission to modify the code and to distribute modified code is granted,
13  * provided the above notices are retained, and a notice that the code was
14  * modified is included with the above copyright notice.
15  */
16
17 #include "private/gc_pmark.h"
18
19 #ifndef GC_NO_FINALIZATION
20
21 /* Type of mark procedure used for marking from finalizable object.     */
22 /* This procedure normally does not mark the object, only its           */
23 /* descendants.                                                         */
24 typedef void (* finalization_mark_proc)(ptr_t /* finalizable_obj_ptr */);
25
26 #define HASH3(addr,size,log_size) \
27         ((((word)(addr) >> 3) ^ ((word)(addr) >> (3 + (log_size)))) \
28          & ((size) - 1))
29 #define HASH2(addr,log_size) HASH3(addr, 1 << (log_size), log_size)
30
31 struct hash_chain_entry {
32     word hidden_key;
33     struct hash_chain_entry * next;
34 };
35
36 struct disappearing_link {
37     struct hash_chain_entry prolog;
38 #   define dl_hidden_link prolog.hidden_key
39                                 /* Field to be cleared.         */
40 #   define dl_next(x) (struct disappearing_link *)((x) -> prolog.next)
41 #   define dl_set_next(x, y) \
42                 (void)((x)->prolog.next = (struct hash_chain_entry *)(y))
43     word dl_hidden_obj;         /* Pointer to object base       */
44 };
45
46 struct dl_hashtbl_s {
47     struct disappearing_link **head;
48     signed_word log_size;
49     word entries;
50 };
51
52 STATIC struct dl_hashtbl_s GC_dl_hashtbl = {
53     /* head */ NULL, /* log_size */ -1, /* entries */ 0 };
54 #ifndef GC_LONG_REFS_NOT_NEEDED
55   STATIC struct dl_hashtbl_s GC_ll_hashtbl = { NULL, -1, 0 };
56 #endif
57
58 STATIC struct finalizable_object {
59     struct hash_chain_entry prolog;
60 #   define fo_hidden_base prolog.hidden_key
61                                 /* Pointer to object base.      */
62                                 /* No longer hidden once object */
63                                 /* is on finalize_now queue.    */
64 #   define fo_next(x) (struct finalizable_object *)((x) -> prolog.next)
65 #   define fo_set_next(x,y) ((x)->prolog.next = (struct hash_chain_entry *)(y))
66     GC_finalization_proc fo_fn; /* Finalizer.                   */
67     ptr_t fo_client_data;
68     word fo_object_size;        /* In bytes.                    */
69     finalization_mark_proc fo_mark_proc;        /* Mark-through procedure */
70 } **GC_fo_head = 0;
71
72 STATIC struct finalizable_object * GC_finalize_now = 0;
73         /* List of objects that should be finalized now.        */
74
75 static signed_word log_fo_table_size = -1;
76
77 GC_API void GC_CALL GC_push_finalizer_structures(void)
78 {
79     GC_ASSERT((word)&GC_dl_hashtbl.head % sizeof(word) == 0);
80     GC_ASSERT((word)&GC_fo_head % sizeof(word) == 0);
81     GC_ASSERT((word)&GC_finalize_now % sizeof(word) == 0);
82
83 # ifndef GC_LONG_REFS_NOT_NEEDED
84     GC_ASSERT((word)&GC_ll_hashtbl.head % sizeof(word) == 0);
85     GC_push_all((ptr_t)(&GC_ll_hashtbl.head),
86                 (ptr_t)(&GC_ll_hashtbl.head) + sizeof(word));
87 # endif
88
89     GC_push_all((ptr_t)(&GC_dl_hashtbl.head),
90                 (ptr_t)(&GC_dl_hashtbl.head) + sizeof(word));
91     GC_push_all((ptr_t)(&GC_fo_head), (ptr_t)(&GC_fo_head) + sizeof(word));
92     GC_push_all((ptr_t)(&GC_finalize_now),
93                 (ptr_t)(&GC_finalize_now) + sizeof(word));
94 }
95
96 /* Double the size of a hash table. *size_ptr is the log of its current */
97 /* size.  May be a no-op.                                               */
98 /* *table is a pointer to an array of hash headers.  If we succeed, we  */
99 /* update both *table and *log_size_ptr.  Lock is held.                 */
100 STATIC void GC_grow_table(struct hash_chain_entry ***table,
101                           signed_word *log_size_ptr)
102 {
103     register word i;
104     register struct hash_chain_entry *p;
105     signed_word log_old_size = *log_size_ptr;
106     signed_word log_new_size = log_old_size + 1;
107     word old_size = ((log_old_size == -1)? 0: (1 << log_old_size));
108     word new_size = (word)1 << log_new_size;
109     /* FIXME: Power of 2 size often gets rounded up to one more page. */
110     struct hash_chain_entry **new_table = (struct hash_chain_entry **)
111         GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
112                 (size_t)new_size * sizeof(struct hash_chain_entry *), NORMAL);
113
114     if (new_table == 0) {
115         if (*table == 0) {
116             ABORT("Insufficient space for initial table allocation");
117         } else {
118             return;
119         }
120     }
121     for (i = 0; i < old_size; i++) {
122       p = (*table)[i];
123       while (p != 0) {
124         ptr_t real_key = GC_REVEAL_POINTER(p -> hidden_key);
125         struct hash_chain_entry *next = p -> next;
126         size_t new_hash = HASH3(real_key, new_size, log_new_size);
127
128         p -> next = new_table[new_hash];
129         new_table[new_hash] = p;
130         p = next;
131       }
132     }
133     *log_size_ptr = log_new_size;
134     *table = new_table;
135 }
136
137 GC_API int GC_CALL GC_register_disappearing_link(void * * link)
138 {
139     ptr_t base;
140
141     base = (ptr_t)GC_base(link);
142     if (base == 0)
143         ABORT("Bad arg to GC_register_disappearing_link");
144     return(GC_general_register_disappearing_link(link, base));
145 }
146
147 STATIC int GC_register_disappearing_link_inner(
148                         struct dl_hashtbl_s *dl_hashtbl, void **link,
149                         const void *obj, const char *tbl_log_name)
150 {
151     struct disappearing_link *curr_dl;
152     size_t index;
153     struct disappearing_link * new_dl;
154     DCL_LOCK_STATE;
155
156     LOCK();
157     GC_ASSERT(obj != NULL && GC_base_C(obj) == obj);
158     if (dl_hashtbl -> log_size == -1
159         || dl_hashtbl -> entries > ((word)1 << dl_hashtbl -> log_size)) {
160         GC_grow_table((struct hash_chain_entry ***)&dl_hashtbl -> head,
161                       &dl_hashtbl -> log_size);
162         GC_COND_LOG_PRINTF("Grew %s table to %u entries\n", tbl_log_name,
163                            1 << (unsigned)dl_hashtbl -> log_size);
164     }
165     index = HASH2(link, dl_hashtbl -> log_size);
166     for (curr_dl = dl_hashtbl -> head[index]; curr_dl != 0;
167          curr_dl = dl_next(curr_dl)) {
168         if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
169             curr_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
170             UNLOCK();
171             return GC_DUPLICATE;
172         }
173     }
174     new_dl = (struct disappearing_link *)
175         GC_INTERNAL_MALLOC(sizeof(struct disappearing_link),NORMAL);
176     if (0 == new_dl) {
177       GC_oom_func oom_fn = GC_oom_fn;
178       UNLOCK();
179       new_dl = (struct disappearing_link *)
180                 (*oom_fn)(sizeof(struct disappearing_link));
181       if (0 == new_dl) {
182         return GC_NO_MEMORY;
183       }
184       /* It's not likely we'll make it here, but ... */
185       LOCK();
186       /* Recalculate index since the table may grow.    */
187       index = HASH2(link, dl_hashtbl -> log_size);
188       /* Check again that our disappearing link not in the table. */
189       for (curr_dl = dl_hashtbl -> head[index]; curr_dl != 0;
190            curr_dl = dl_next(curr_dl)) {
191         if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
192           curr_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
193           UNLOCK();
194 #         ifndef DBG_HDRS_ALL
195             /* Free unused new_dl returned by GC_oom_fn() */
196             GC_free((void *)new_dl);
197 #         endif
198           return GC_DUPLICATE;
199         }
200       }
201     }
202     new_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
203     new_dl -> dl_hidden_link = GC_HIDE_POINTER(link);
204     dl_set_next(new_dl, dl_hashtbl -> head[index]);
205     dl_hashtbl -> head[index] = new_dl;
206     dl_hashtbl -> entries++;
207     UNLOCK();
208     return GC_SUCCESS;
209 }
210
211 GC_API int GC_CALL GC_general_register_disappearing_link(void * * link,
212                                                          const void * obj)
213 {
214     if (((word)link & (ALIGNMENT-1)) != 0 || NULL == link)
215         ABORT("Bad arg to GC_general_register_disappearing_link");
216     return GC_register_disappearing_link_inner(&GC_dl_hashtbl, link, obj,
217                                                "dl");
218 }
219
220 #ifdef DBG_HDRS_ALL
221 # define FREE_DL_ENTRY(curr_dl) dl_set_next(curr_dl, NULL)
222 #else
223 # define FREE_DL_ENTRY(curr_dl) GC_free(curr_dl)
224 #endif
225
226 /* Unregisters given link and returns the link entry to free.   */
227 /* Assume the lock is held.                                     */
228 GC_INLINE struct disappearing_link *GC_unregister_disappearing_link_inner(
229                                 struct dl_hashtbl_s *dl_hashtbl, void **link)
230 {
231     struct disappearing_link *curr_dl;
232     struct disappearing_link *prev_dl = NULL;
233     size_t index = HASH2(link, dl_hashtbl->log_size);
234
235     for (curr_dl = dl_hashtbl -> head[index]; curr_dl;
236          curr_dl = dl_next(curr_dl)) {
237         if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
238             /* Remove found entry from the table. */
239             if (NULL == prev_dl) {
240                 dl_hashtbl -> head[index] = dl_next(curr_dl);
241             } else {
242                 dl_set_next(prev_dl, dl_next(curr_dl));
243             }
244             dl_hashtbl -> entries--;
245             break;
246         }
247         prev_dl = curr_dl;
248     }
249     return curr_dl;
250 }
251
252 GC_API int GC_CALL GC_unregister_disappearing_link(void * * link)
253 {
254     struct disappearing_link *curr_dl;
255     DCL_LOCK_STATE;
256
257     if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
258
259     LOCK();
260     curr_dl = GC_unregister_disappearing_link_inner(&GC_dl_hashtbl, link);
261     UNLOCK();
262     if (NULL == curr_dl) return 0;
263     FREE_DL_ENTRY(curr_dl);
264     return 1;
265 }
266
267 /* Finalizer callback support. */
268 STATIC GC_await_finalize_proc GC_object_finalized_proc = 0;
269
270 GC_API void GC_CALL GC_set_await_finalize_proc(GC_await_finalize_proc fn)
271 {
272   DCL_LOCK_STATE;
273
274   LOCK();
275   GC_object_finalized_proc = fn;
276   UNLOCK();
277 }
278
279 GC_API GC_await_finalize_proc GC_CALL GC_get_await_finalize_proc(void)
280 {
281   GC_await_finalize_proc fn;
282   DCL_LOCK_STATE;
283
284   LOCK();
285   fn = GC_object_finalized_proc;
286   UNLOCK();
287   return fn;
288 }
289
290 #ifndef GC_LONG_REFS_NOT_NEEDED
291   GC_API int GC_CALL GC_register_long_link(void * * link, const void * obj)
292   {
293     if (((word)link & (ALIGNMENT-1)) != 0 || NULL == link)
294         ABORT("Bad arg to GC_register_long_link");
295     return GC_register_disappearing_link_inner(&GC_ll_hashtbl, link, obj,
296                                                "long dl");
297   }
298
299   GC_API int GC_CALL GC_unregister_long_link(void * * link)
300   {
301     struct disappearing_link *curr_dl;
302     DCL_LOCK_STATE;
303
304     if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
305
306     LOCK();
307     curr_dl = GC_unregister_disappearing_link_inner(&GC_ll_hashtbl, link);
308     UNLOCK();
309     if (NULL == curr_dl) return 0;
310     FREE_DL_ENTRY(curr_dl);
311     return 1;
312   }
313 #endif /* !GC_LONG_REFS_NOT_NEEDED */
314
315 #ifndef GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED
316   /* Moves a link.  Assume the lock is held.    */
317   STATIC int GC_move_disappearing_link_inner(
318                                 struct dl_hashtbl_s *dl_hashtbl,
319                                 void **link, void **new_link)
320   {
321     struct disappearing_link *curr_dl, *prev_dl, *new_dl;
322     size_t curr_index, new_index;
323     word curr_hidden_link;
324     word new_hidden_link;
325
326     /* Find current link.       */
327     curr_index = HASH2(link, dl_hashtbl -> log_size);
328     curr_hidden_link = GC_HIDE_POINTER(link);
329     prev_dl = NULL;
330     for (curr_dl = dl_hashtbl -> head[curr_index]; curr_dl;
331          curr_dl = dl_next(curr_dl)) {
332       if (curr_dl -> dl_hidden_link == curr_hidden_link)
333         break;
334       prev_dl = curr_dl;
335     }
336
337     if (NULL == curr_dl) {
338       return GC_NOT_FOUND;
339     }
340
341     if (link == new_link) {
342       return GC_SUCCESS; /* Nothing to do.      */
343     }
344
345     /* link found; now check new_link not present.      */
346     new_index = HASH2(new_link, dl_hashtbl -> log_size);
347     new_hidden_link = GC_HIDE_POINTER(new_link);
348     for (new_dl = dl_hashtbl -> head[new_index]; new_dl;
349          new_dl = dl_next(new_dl)) {
350       if (new_dl -> dl_hidden_link == new_hidden_link) {
351         /* Target already registered; bail.     */
352         return GC_DUPLICATE;
353       }
354     }
355
356     /* Remove from old, add to new, update link.        */
357     if (NULL == prev_dl) {
358       dl_hashtbl -> head[curr_index] = dl_next(curr_dl);
359     } else {
360       dl_set_next(prev_dl, dl_next(curr_dl));
361     }
362     curr_dl -> dl_hidden_link = new_hidden_link;
363     dl_set_next(curr_dl, dl_hashtbl -> head[new_index]);
364     dl_hashtbl -> head[new_index] = curr_dl;
365     return GC_SUCCESS;
366   }
367
368   GC_API int GC_CALL GC_move_disappearing_link(void **link, void **new_link)
369   {
370     int result;
371     DCL_LOCK_STATE;
372
373     if (((word)new_link & (ALIGNMENT-1)) != 0 || new_link == NULL)
374       ABORT("Bad new_link arg to GC_move_disappearing_link");
375     if (((word)link & (ALIGNMENT-1)) != 0)
376       return GC_NOT_FOUND; /* Nothing to do. */
377
378     LOCK();
379     result = GC_move_disappearing_link_inner(&GC_dl_hashtbl, link, new_link);
380     UNLOCK();
381     return result;
382   }
383
384 # ifndef GC_LONG_REFS_NOT_NEEDED
385     GC_API int GC_CALL GC_move_long_link(void **link, void **new_link)
386     {
387       int result;
388       DCL_LOCK_STATE;
389
390       if (((word)new_link & (ALIGNMENT-1)) != 0 || new_link == NULL)
391         ABORT("Bad new_link arg to GC_move_disappearing_link");
392       if (((word)link & (ALIGNMENT-1)) != 0)
393         return GC_NOT_FOUND; /* Nothing to do. */
394
395       LOCK();
396       result = GC_move_disappearing_link_inner(&GC_ll_hashtbl, link, new_link);
397       UNLOCK();
398       return result;
399     }
400 # endif /* !GC_LONG_REFS_NOT_NEEDED */
401 #endif /* !GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED */
402
403 /* Possible finalization_marker procedures.  Note that mark stack       */
404 /* overflow is handled by the caller, and is not a disaster.            */
405 STATIC void GC_normal_finalize_mark_proc(ptr_t p)
406 {
407     hdr * hhdr = HDR(p);
408
409     PUSH_OBJ(p, hhdr, GC_mark_stack_top,
410              &(GC_mark_stack[GC_mark_stack_size]));
411 }
412
413 /* This only pays very partial attention to the mark descriptor.        */
414 /* It does the right thing for normal and atomic objects, and treats    */
415 /* most others as normal.                                               */
416 STATIC void GC_ignore_self_finalize_mark_proc(ptr_t p)
417 {
418     hdr * hhdr = HDR(p);
419     word descr = hhdr -> hb_descr;
420     ptr_t q;
421     word r;
422     ptr_t scan_limit;
423     ptr_t target_limit = p + hhdr -> hb_sz - 1;
424
425     if ((descr & GC_DS_TAGS) == GC_DS_LENGTH) {
426        scan_limit = p + descr - sizeof(word);
427     } else {
428        scan_limit = target_limit + 1 - sizeof(word);
429     }
430     for (q = p; (word)q <= (word)scan_limit; q += ALIGNMENT) {
431         r = *(word *)q;
432         if (r < (word)p || r > (word)target_limit) {
433             GC_PUSH_ONE_HEAP(r, q, GC_mark_stack_top);
434         }
435     }
436 }
437
438 STATIC void GC_null_finalize_mark_proc(ptr_t p GC_ATTR_UNUSED) {}
439
440 /* Possible finalization_marker procedures.  Note that mark stack       */
441 /* overflow is handled by the caller, and is not a disaster.            */
442
443 /* GC_unreachable_finalize_mark_proc is an alias for normal marking,    */
444 /* but it is explicitly tested for, and triggers different              */
445 /* behavior.  Objects registered in this way are not finalized          */
446 /* if they are reachable by other finalizable objects, even if those    */
447 /* other objects specify no ordering.                                   */
448 STATIC void GC_unreachable_finalize_mark_proc(ptr_t p)
449 {
450     GC_normal_finalize_mark_proc(p);
451 }
452
453 /* Register a finalization function.  See gc.h for details.     */
454 /* The last parameter is a procedure that determines            */
455 /* marking for finalization ordering.  Any objects marked       */
456 /* by that procedure will be guaranteed to not have been        */
457 /* finalized when this finalizer is invoked.                    */
458 STATIC void GC_register_finalizer_inner(void * obj,
459                                         GC_finalization_proc fn, void *cd,
460                                         GC_finalization_proc *ofn, void **ocd,
461                                         finalization_mark_proc mp)
462 {
463     ptr_t base;
464     struct finalizable_object * curr_fo, * prev_fo;
465     size_t index;
466     struct finalizable_object *new_fo = 0;
467     hdr *hhdr = NULL; /* initialized to prevent warning. */
468     GC_oom_func oom_fn;
469     DCL_LOCK_STATE;
470
471     LOCK();
472     if (log_fo_table_size == -1
473         || GC_fo_entries > ((word)1 << log_fo_table_size)) {
474         GC_grow_table((struct hash_chain_entry ***)&GC_fo_head,
475                       &log_fo_table_size);
476         GC_COND_LOG_PRINTF("Grew fo table to %u entries\n",
477                            1 << (unsigned)log_fo_table_size);
478     }
479     /* in the THREADS case we hold allocation lock.             */
480     base = (ptr_t)obj;
481     for (;;) {
482       index = HASH2(base, log_fo_table_size);
483       prev_fo = 0;
484       curr_fo = GC_fo_head[index];
485       while (curr_fo != 0) {
486         GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
487         if (curr_fo -> fo_hidden_base == GC_HIDE_POINTER(base)) {
488           /* Interruption by a signal in the middle of this     */
489           /* should be safe.  The client may see only *ocd      */
490           /* updated, but we'll declare that to be his problem. */
491           if (ocd) *ocd = (void *) (curr_fo -> fo_client_data);
492           if (ofn) *ofn = curr_fo -> fo_fn;
493           /* Delete the structure for base. */
494           if (prev_fo == 0) {
495             GC_fo_head[index] = fo_next(curr_fo);
496           } else {
497             fo_set_next(prev_fo, fo_next(curr_fo));
498           }
499           if (fn == 0) {
500             GC_fo_entries--;
501             /* May not happen if we get a signal.  But a high   */
502             /* estimate will only make the table larger than    */
503             /* necessary.                                       */
504 #           if !defined(THREADS) && !defined(DBG_HDRS_ALL)
505               GC_free((void *)curr_fo);
506 #           endif
507           } else {
508             curr_fo -> fo_fn = fn;
509             curr_fo -> fo_client_data = (ptr_t)cd;
510             curr_fo -> fo_mark_proc = mp;
511             /* Reinsert it.  We deleted it first to maintain    */
512             /* consistency in the event of a signal.            */
513             if (prev_fo == 0) {
514               GC_fo_head[index] = curr_fo;
515             } else {
516               fo_set_next(prev_fo, curr_fo);
517             }
518           }
519           UNLOCK();
520 #         ifndef DBG_HDRS_ALL
521             if (EXPECT(new_fo != 0, FALSE)) {
522               /* Free unused new_fo returned by GC_oom_fn() */
523               GC_free((void *)new_fo);
524             }
525 #         endif
526           return;
527         }
528         prev_fo = curr_fo;
529         curr_fo = fo_next(curr_fo);
530       }
531       if (EXPECT(new_fo != 0, FALSE)) {
532         /* new_fo is returned by GC_oom_fn(), so fn != 0 and hhdr != 0. */
533         break;
534       }
535       if (fn == 0) {
536         if (ocd) *ocd = 0;
537         if (ofn) *ofn = 0;
538         UNLOCK();
539         return;
540       }
541       GET_HDR(base, hhdr);
542       if (EXPECT(0 == hhdr, FALSE)) {
543         /* We won't collect it, hence finalizer wouldn't be run. */
544         if (ocd) *ocd = 0;
545         if (ofn) *ofn = 0;
546         UNLOCK();
547         return;
548       }
549       new_fo = (struct finalizable_object *)
550         GC_INTERNAL_MALLOC(sizeof(struct finalizable_object),NORMAL);
551       if (EXPECT(new_fo != 0, TRUE))
552         break;
553       oom_fn = GC_oom_fn;
554       UNLOCK();
555       new_fo = (struct finalizable_object *)
556                 (*oom_fn)(sizeof(struct finalizable_object));
557       if (0 == new_fo) {
558         /* No enough memory.  *ocd and *ofn remains unchanged.  */
559         return;
560       }
561       /* It's not likely we'll make it here, but ... */
562       LOCK();
563       /* Recalculate index since the table may grow and         */
564       /* check again that our finalizer is not in the table.    */
565     }
566     GC_ASSERT(GC_size(new_fo) >= sizeof(struct finalizable_object));
567     if (ocd) *ocd = 0;
568     if (ofn) *ofn = 0;
569     new_fo -> fo_hidden_base = GC_HIDE_POINTER(base);
570     new_fo -> fo_fn = fn;
571     new_fo -> fo_client_data = (ptr_t)cd;
572     new_fo -> fo_object_size = hhdr -> hb_sz;
573     new_fo -> fo_mark_proc = mp;
574     fo_set_next(new_fo, GC_fo_head[index]);
575     GC_fo_entries++;
576     GC_fo_head[index] = new_fo;
577     UNLOCK();
578 }
579
580 GC_API void GC_CALL GC_register_finalizer(void * obj,
581                                   GC_finalization_proc fn, void * cd,
582                                   GC_finalization_proc *ofn, void ** ocd)
583 {
584     GC_register_finalizer_inner(obj, fn, cd, ofn,
585                                 ocd, GC_normal_finalize_mark_proc);
586 }
587
588 GC_API void GC_CALL GC_register_finalizer_ignore_self(void * obj,
589                                GC_finalization_proc fn, void * cd,
590                                GC_finalization_proc *ofn, void ** ocd)
591 {
592     GC_register_finalizer_inner(obj, fn, cd, ofn,
593                                 ocd, GC_ignore_self_finalize_mark_proc);
594 }
595
596 GC_API void GC_CALL GC_register_finalizer_no_order(void * obj,
597                                GC_finalization_proc fn, void * cd,
598                                GC_finalization_proc *ofn, void ** ocd)
599 {
600     GC_register_finalizer_inner(obj, fn, cd, ofn,
601                                 ocd, GC_null_finalize_mark_proc);
602 }
603
604 static GC_bool need_unreachable_finalization = FALSE;
605         /* Avoid the work if this isn't used.   */
606
607 GC_API void GC_CALL GC_register_finalizer_unreachable(void * obj,
608                                GC_finalization_proc fn, void * cd,
609                                GC_finalization_proc *ofn, void ** ocd)
610 {
611     need_unreachable_finalization = TRUE;
612     GC_ASSERT(GC_java_finalization);
613     GC_register_finalizer_inner(obj, fn, cd, ofn,
614                                 ocd, GC_unreachable_finalize_mark_proc);
615 }
616
617 #ifndef NO_DEBUGGING
618   STATIC void GC_dump_finalization_links(
619                                 const struct dl_hashtbl_s *dl_hashtbl)
620   {
621     struct disappearing_link *curr_dl;
622     ptr_t real_ptr, real_link;
623     size_t dl_size = dl_hashtbl->log_size == -1 ? 0 :
624                                 1 << dl_hashtbl->log_size;
625     size_t i;
626
627     for (i = 0; i < dl_size; i++) {
628       for (curr_dl = dl_hashtbl -> head[i]; curr_dl != 0;
629            curr_dl = dl_next(curr_dl)) {
630         real_ptr = GC_REVEAL_POINTER(curr_dl -> dl_hidden_obj);
631         real_link = GC_REVEAL_POINTER(curr_dl -> dl_hidden_link);
632         GC_printf("Object: %p, link: %p\n", real_ptr, real_link);
633       }
634     }
635   }
636
637   void GC_dump_finalization(void)
638   {
639     struct finalizable_object * curr_fo;
640     size_t fo_size = log_fo_table_size == -1 ? 0 : 1 << log_fo_table_size;
641     ptr_t real_ptr;
642     size_t i;
643
644     GC_printf("Disappearing (short) links:\n");
645     GC_dump_finalization_links(&GC_dl_hashtbl);
646 #   ifndef GC_LONG_REFS_NOT_NEEDED
647       GC_printf("Disappearing long links:\n");
648       GC_dump_finalization_links(&GC_ll_hashtbl);
649 #   endif
650     GC_printf("Finalizers:\n");
651     for (i = 0; i < fo_size; i++) {
652       for (curr_fo = GC_fo_head[i]; curr_fo != 0;
653            curr_fo = fo_next(curr_fo)) {
654         real_ptr = GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
655         GC_printf("Finalizable object: %p\n", real_ptr);
656       }
657     }
658   }
659 #endif /* !NO_DEBUGGING */
660
661 #ifndef SMALL_CONFIG
662   STATIC word GC_old_dl_entries = 0; /* for stats printing */
663 # ifndef GC_LONG_REFS_NOT_NEEDED
664     STATIC word GC_old_ll_entries = 0;
665 # endif
666 #endif /* !SMALL_CONFIG */
667
668 #ifndef THREADS
669   /* Global variables to minimize the level of recursion when a client  */
670   /* finalizer allocates memory.                                        */
671   STATIC int GC_finalizer_nested = 0;
672                         /* Only the lowest byte is used, the rest is    */
673                         /* padding for proper global data alignment     */
674                         /* required for some compilers (like Watcom).   */
675   STATIC unsigned GC_finalizer_skipped = 0;
676
677   /* Checks and updates the level of finalizers recursion.              */
678   /* Returns NULL if GC_invoke_finalizers() should not be called by the */
679   /* collector (to minimize the risk of a deep finalizers recursion),   */
680   /* otherwise returns a pointer to GC_finalizer_nested.                */
681   STATIC unsigned char *GC_check_finalizer_nested(void)
682   {
683     unsigned nesting_level = *(unsigned char *)&GC_finalizer_nested;
684     if (nesting_level) {
685       /* We are inside another GC_invoke_finalizers().          */
686       /* Skip some implicitly-called GC_invoke_finalizers()     */
687       /* depending on the nesting (recursion) level.            */
688       if (++GC_finalizer_skipped < (1U << nesting_level)) return NULL;
689       GC_finalizer_skipped = 0;
690     }
691     *(char *)&GC_finalizer_nested = (char)(nesting_level + 1);
692     return (unsigned char *)&GC_finalizer_nested;
693   }
694 #endif /* THREADS */
695
696 #define ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr_dl, prev_dl) \
697   { \
698     size_t i; \
699     size_t dl_size = dl_hashtbl->log_size == -1 ? 0 : \
700                                 1 << dl_hashtbl->log_size; \
701     for (i = 0; i < dl_size; i++) { \
702       curr_dl = dl_hashtbl -> head[i]; \
703       prev_dl = NULL; \
704       while (curr_dl) {
705
706 #define ITERATE_DL_HASHTBL_END(curr_dl, prev_dl) \
707         prev_dl = curr_dl; \
708         curr_dl = dl_next(curr_dl); \
709       } \
710     } \
711   }
712
713 #define DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr_dl, prev_dl, next_dl) \
714   { \
715     next_dl = dl_next(curr_dl); \
716     if (NULL == prev_dl) { \
717         dl_hashtbl -> head[i] = next_dl; \
718     } else { \
719         dl_set_next(prev_dl, next_dl); \
720     } \
721     GC_clear_mark_bit(curr_dl); \
722     dl_hashtbl -> entries--; \
723     curr_dl = next_dl; \
724     continue; \
725   }
726
727 GC_INLINE void GC_make_disappearing_links_disappear(
728                                 struct dl_hashtbl_s* dl_hashtbl)
729 {
730     struct disappearing_link *curr, *prev, *next;
731     ptr_t real_ptr, real_link;
732
733     ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
734         real_ptr = GC_REVEAL_POINTER(curr -> dl_hidden_obj);
735         real_link = GC_REVEAL_POINTER(curr -> dl_hidden_link);
736         if (!GC_is_marked(real_ptr)) {
737             *(word *)real_link = 0;
738             GC_clear_mark_bit(curr);
739             DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
740         }
741     ITERATE_DL_HASHTBL_END(curr, prev)
742 }
743
744 GC_INLINE void GC_remove_dangling_disappearing_links(
745                                 struct dl_hashtbl_s* dl_hashtbl)
746 {
747     struct disappearing_link *curr, *prev, *next;
748     ptr_t real_link;
749
750     ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
751         real_link = GC_base(GC_REVEAL_POINTER(curr -> dl_hidden_link));
752         if (NULL != real_link && !GC_is_marked(real_link)) {
753             GC_clear_mark_bit(curr);
754             DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
755         }
756     ITERATE_DL_HASHTBL_END(curr, prev)
757 }
758
759 /* Called with held lock (but the world is running).                    */
760 /* Cause disappearing links to disappear and unreachable objects to be  */
761 /* enqueued for finalization.                                           */
762 GC_INNER void GC_finalize(void)
763 {
764     struct finalizable_object * curr_fo, * prev_fo, * next_fo;
765     ptr_t real_ptr;
766     size_t i;
767     size_t fo_size = log_fo_table_size == -1 ? 0 : 1 << log_fo_table_size;
768
769 #   ifndef SMALL_CONFIG
770       /* Save current GC_[dl/ll]_entries value for stats printing */
771       GC_old_dl_entries = GC_dl_hashtbl.entries;
772 #     ifndef GC_LONG_REFS_NOT_NEEDED
773         GC_old_ll_entries = GC_ll_hashtbl.entries;
774 #     endif
775 #   endif
776
777     GC_make_disappearing_links_disappear(&GC_dl_hashtbl);
778
779   /* Mark all objects reachable via chains of 1 or more pointers        */
780   /* from finalizable objects.                                          */
781     GC_ASSERT(GC_mark_state == MS_NONE);
782     for (i = 0; i < fo_size; i++) {
783       for (curr_fo = GC_fo_head[i]; curr_fo != 0;
784            curr_fo = fo_next(curr_fo)) {
785         GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
786         real_ptr = GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
787         if (!GC_is_marked(real_ptr)) {
788             GC_MARKED_FOR_FINALIZATION(real_ptr);
789             GC_MARK_FO(real_ptr, curr_fo -> fo_mark_proc);
790             if (GC_is_marked(real_ptr)) {
791                 WARN("Finalization cycle involving %p\n", real_ptr);
792             }
793         }
794       }
795     }
796   /* Enqueue for finalization all objects that are still                */
797   /* unreachable.                                                       */
798     GC_bytes_finalized = 0;
799     for (i = 0; i < fo_size; i++) {
800       curr_fo = GC_fo_head[i];
801       prev_fo = 0;
802       while (curr_fo != 0) {
803         real_ptr = GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
804         if (!GC_is_marked(real_ptr)) {
805             if (!GC_java_finalization) {
806               GC_set_mark_bit(real_ptr);
807             }
808             /* Delete from hash table */
809               next_fo = fo_next(curr_fo);
810               if (prev_fo == 0) {
811                 GC_fo_head[i] = next_fo;
812               } else {
813                 fo_set_next(prev_fo, next_fo);
814               }
815               GC_fo_entries--;
816               if (GC_object_finalized_proc)
817                 GC_object_finalized_proc(real_ptr);
818
819             /* Add to list of objects awaiting finalization.    */
820               fo_set_next(curr_fo, GC_finalize_now);
821               GC_finalize_now = curr_fo;
822               /* unhide object pointer so any future collections will   */
823               /* see it.                                                */
824               curr_fo -> fo_hidden_base =
825                         (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
826               GC_bytes_finalized +=
827                         curr_fo -> fo_object_size
828                         + sizeof(struct finalizable_object);
829             GC_ASSERT(GC_is_marked(GC_base(curr_fo)));
830             curr_fo = next_fo;
831         } else {
832             prev_fo = curr_fo;
833             curr_fo = fo_next(curr_fo);
834         }
835       }
836     }
837
838   if (GC_java_finalization) {
839     /* make sure we mark everything reachable from objects finalized
840        using the no_order mark_proc */
841       for (curr_fo = GC_finalize_now;
842          curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
843         real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
844         if (!GC_is_marked(real_ptr)) {
845             if (curr_fo -> fo_mark_proc == GC_null_finalize_mark_proc) {
846                 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
847             }
848             if (curr_fo -> fo_mark_proc != GC_unreachable_finalize_mark_proc) {
849                 GC_set_mark_bit(real_ptr);
850             }
851         }
852       }
853
854     /* now revive finalize-when-unreachable objects reachable from
855        other finalizable objects */
856       if (need_unreachable_finalization) {
857         curr_fo = GC_finalize_now;
858         prev_fo = 0;
859         while (curr_fo != 0) {
860           next_fo = fo_next(curr_fo);
861           if (curr_fo -> fo_mark_proc == GC_unreachable_finalize_mark_proc) {
862             real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
863             if (!GC_is_marked(real_ptr)) {
864               GC_set_mark_bit(real_ptr);
865             } else {
866               if (prev_fo == 0)
867                 GC_finalize_now = next_fo;
868               else
869                 fo_set_next(prev_fo, next_fo);
870
871               curr_fo -> fo_hidden_base =
872                                 GC_HIDE_POINTER(curr_fo -> fo_hidden_base);
873               GC_bytes_finalized -=
874                   curr_fo->fo_object_size + sizeof(struct finalizable_object);
875
876               i = HASH2(real_ptr, log_fo_table_size);
877               fo_set_next (curr_fo, GC_fo_head[i]);
878               GC_fo_entries++;
879               GC_fo_head[i] = curr_fo;
880               curr_fo = prev_fo;
881             }
882           }
883           prev_fo = curr_fo;
884           curr_fo = next_fo;
885         }
886       }
887   }
888
889   GC_remove_dangling_disappearing_links(&GC_dl_hashtbl);
890 # ifndef GC_LONG_REFS_NOT_NEEDED
891     GC_make_disappearing_links_disappear(&GC_ll_hashtbl);
892     GC_remove_dangling_disappearing_links(&GC_ll_hashtbl);
893 # endif
894
895   if (GC_fail_count) {
896     /* Don't prevent running finalizers if there has been an allocation */
897     /* failure recently.                                                */
898 #   ifdef THREADS
899       GC_reset_finalizer_nested();
900 #   else
901       GC_finalizer_nested = 0;
902 #   endif
903   }
904 }
905
906 #ifndef JAVA_FINALIZATION_NOT_NEEDED
907
908   /* Enqueue all remaining finalizers to be run - Assumes lock is held. */
909   STATIC void GC_enqueue_all_finalizers(void)
910   {
911     struct finalizable_object * curr_fo, * prev_fo, * next_fo;
912     ptr_t real_ptr;
913     register int i;
914     int fo_size;
915
916     fo_size = log_fo_table_size == -1 ? 0 : 1 << log_fo_table_size;
917     GC_bytes_finalized = 0;
918     for (i = 0; i < fo_size; i++) {
919         curr_fo = GC_fo_head[i];
920         prev_fo = 0;
921       while (curr_fo != 0) {
922           real_ptr = GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
923           GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
924           GC_set_mark_bit(real_ptr);
925
926           /* Delete from hash table */
927           next_fo = fo_next(curr_fo);
928           if (prev_fo == 0) {
929               GC_fo_head[i] = next_fo;
930           } else {
931               fo_set_next(prev_fo, next_fo);
932           }
933           GC_fo_entries--;
934
935           /* Add to list of objects awaiting finalization.      */
936           fo_set_next(curr_fo, GC_finalize_now);
937           GC_finalize_now = curr_fo;
938
939           /* unhide object pointer so any future collections will       */
940           /* see it.                                                    */
941           curr_fo -> fo_hidden_base =
942                         (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
943           GC_bytes_finalized +=
944                 curr_fo -> fo_object_size + sizeof(struct finalizable_object);
945           curr_fo = next_fo;
946         }
947     }
948   }
949
950   /* Invoke all remaining finalizers that haven't yet been run.
951    * This is needed for strict compliance with the Java standard,
952    * which can make the runtime guarantee that all finalizers are run.
953    * Unfortunately, the Java standard implies we have to keep running
954    * finalizers until there are no more left, a potential infinite loop.
955    * YUCK.
956    * Note that this is even more dangerous than the usual Java
957    * finalizers, in that objects reachable from static variables
958    * may have been finalized when these finalizers are run.
959    * Finalizers run at this point must be prepared to deal with a
960    * mostly broken world.
961    * This routine is externally callable, so is called without
962    * the allocation lock.
963    */
964   GC_API void GC_CALL GC_finalize_all(void)
965   {
966     DCL_LOCK_STATE;
967
968     LOCK();
969     while (GC_fo_entries > 0) {
970       GC_enqueue_all_finalizers();
971       UNLOCK();
972       GC_invoke_finalizers();
973       /* Running the finalizers in this thread is arguably not a good   */
974       /* idea when we should be notifying another thread to run them.   */
975       /* But otherwise we don't have a great way to wait for them to    */
976       /* run.                                                           */
977       LOCK();
978     }
979     UNLOCK();
980   }
981
982 #endif /* !JAVA_FINALIZATION_NOT_NEEDED */
983
984 /* Returns true if it is worth calling GC_invoke_finalizers. (Useful if */
985 /* finalizers can only be called from some kind of "safe state" and     */
986 /* getting into that safe state is expensive.)                          */
987 GC_API int GC_CALL GC_should_invoke_finalizers(void)
988 {
989     return GC_finalize_now != 0;
990 }
991
992 /* Invoke finalizers for all objects that are ready to be finalized.    */
993 /* Should be called without allocation lock.                            */
994 GC_API int GC_CALL GC_invoke_finalizers(void)
995 {
996     struct finalizable_object * curr_fo;
997     int count = 0;
998     word bytes_freed_before = 0; /* initialized to prevent warning. */
999     DCL_LOCK_STATE;
1000
1001     while (GC_finalize_now != 0) {
1002 #       ifdef THREADS
1003             LOCK();
1004 #       endif
1005         if (count == 0) {
1006             bytes_freed_before = GC_bytes_freed;
1007             /* Don't do this outside, since we need the lock. */
1008         }
1009         curr_fo = GC_finalize_now;
1010 #       ifdef THREADS
1011             if (curr_fo != 0) GC_finalize_now = fo_next(curr_fo);
1012             UNLOCK();
1013             if (curr_fo == 0) break;
1014 #       else
1015             GC_finalize_now = fo_next(curr_fo);
1016 #       endif
1017         fo_set_next(curr_fo, 0);
1018         (*(curr_fo -> fo_fn))((ptr_t)(curr_fo -> fo_hidden_base),
1019                               curr_fo -> fo_client_data);
1020         curr_fo -> fo_client_data = 0;
1021         ++count;
1022 #       ifdef UNDEFINED
1023             /* This is probably a bad idea.  It throws off accounting if */
1024             /* nearly all objects are finalizable.  O.w. it shouldn't    */
1025             /* matter.                                                   */
1026             GC_free((void *)curr_fo);
1027 #       endif
1028     }
1029     /* bytes_freed_before is initialized whenever count != 0 */
1030     if (count != 0 && bytes_freed_before != GC_bytes_freed) {
1031         LOCK();
1032         GC_finalizer_bytes_freed += (GC_bytes_freed - bytes_freed_before);
1033         UNLOCK();
1034     }
1035     return count;
1036 }
1037
1038 static word last_finalizer_notification = 0;
1039
1040 GC_INNER void GC_notify_or_invoke_finalizers(void)
1041 {
1042     GC_finalizer_notifier_proc notifier_fn = 0;
1043 #   if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1044       static word last_back_trace_gc_no = 1;    /* Skip first one. */
1045 #   endif
1046     DCL_LOCK_STATE;
1047
1048 #   if defined(THREADS) && !defined(KEEP_BACK_PTRS) \
1049        && !defined(MAKE_BACK_GRAPH)
1050       /* Quick check (while unlocked) for an empty finalization queue.  */
1051       if (GC_finalize_now == 0) return;
1052 #   endif
1053     LOCK();
1054
1055     /* This is a convenient place to generate backtraces if appropriate, */
1056     /* since that code is not callable with the allocation lock.         */
1057 #   if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1058       if (GC_gc_no > last_back_trace_gc_no) {
1059 #       ifdef KEEP_BACK_PTRS
1060           long i;
1061           /* Stops when GC_gc_no wraps; that's OK.      */
1062           last_back_trace_gc_no = (word)(-1);  /* disable others. */
1063           for (i = 0; i < GC_backtraces; ++i) {
1064               /* FIXME: This tolerates concurrent heap mutation,        */
1065               /* which may cause occasional mysterious results.         */
1066               /* We need to release the GC lock, since GC_print_callers */
1067               /* acquires it.  It probably shouldn't.                   */
1068               UNLOCK();
1069               GC_generate_random_backtrace_no_gc();
1070               LOCK();
1071           }
1072           last_back_trace_gc_no = GC_gc_no;
1073 #       endif
1074 #       ifdef MAKE_BACK_GRAPH
1075           if (GC_print_back_height) {
1076             UNLOCK();
1077             GC_print_back_graph_stats();
1078             LOCK();
1079           }
1080 #       endif
1081       }
1082 #   endif
1083     if (GC_finalize_now == 0) {
1084       UNLOCK();
1085       return;
1086     }
1087
1088     if (!GC_finalize_on_demand) {
1089       unsigned char *pnested = GC_check_finalizer_nested();
1090       UNLOCK();
1091       /* Skip GC_invoke_finalizers() if nested */
1092       if (pnested != NULL) {
1093         (void) GC_invoke_finalizers();
1094         *pnested = 0; /* Reset since no more finalizers. */
1095 #       ifndef THREADS
1096           GC_ASSERT(GC_finalize_now == 0);
1097 #       endif   /* Otherwise GC can run concurrently and add more */
1098       }
1099       return;
1100     }
1101
1102     /* These variables require synchronization to avoid data races.     */
1103     if (last_finalizer_notification != GC_gc_no) {
1104         last_finalizer_notification = GC_gc_no;
1105         notifier_fn = GC_finalizer_notifier;
1106     }
1107     UNLOCK();
1108     if (notifier_fn != 0)
1109         (*notifier_fn)(); /* Invoke the notifier */
1110 }
1111
1112 #ifndef SMALL_CONFIG
1113 # ifndef GC_LONG_REFS_NOT_NEEDED
1114 #   define IF_LONG_REFS_PRESENT_ELSE(x,y) (x)
1115 # else
1116 #   define IF_LONG_REFS_PRESENT_ELSE(x,y) (y)
1117 # endif
1118
1119   GC_INNER void GC_print_finalization_stats(void)
1120   {
1121     struct finalizable_object *fo;
1122     unsigned long ready = 0;
1123
1124     GC_log_printf("%lu finalization entries;"
1125                   " %lu/%lu short/long disappearing links alive\n",
1126                   (unsigned long)GC_fo_entries,
1127                   (unsigned long)GC_dl_hashtbl.entries,
1128                   (unsigned long)IF_LONG_REFS_PRESENT_ELSE(
1129                                                 GC_ll_hashtbl.entries, 0));
1130
1131     for (fo = GC_finalize_now; 0 != fo; fo = fo_next(fo))
1132       ++ready;
1133     GC_log_printf("%lu finalization-ready objects;"
1134                   " %ld/%ld short/long links cleared\n",
1135                   ready,
1136                   (long)GC_old_dl_entries - (long)GC_dl_hashtbl.entries,
1137                   (long)IF_LONG_REFS_PRESENT_ELSE(
1138                               GC_old_ll_entries - GC_ll_hashtbl.entries, 0));
1139   }
1140 #endif /* !SMALL_CONFIG */
1141
1142 #endif /* !GC_NO_FINALIZATION */