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