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