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