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