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
7 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
8 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
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.
17 #include "private/gc_pmark.h"
19 #ifndef GC_NO_FINALIZATION
20 # include "javaxfc.h" /* to get GC_finalize_all() as extern "C" */
22 /* Type of mark procedure used for marking from finalizable object. */
23 /* This procedure normally does not mark the object, only its */
25 typedef void (* finalization_mark_proc)(ptr_t /* finalizable_obj_ptr */);
27 #define HASH3(addr,size,log_size) \
28 ((((word)(addr) >> 3) ^ ((word)(addr) >> (3 + (log_size)))) \
30 #define HASH2(addr,log_size) HASH3(addr, (word)1 << (log_size), log_size)
32 struct hash_chain_entry {
34 struct hash_chain_entry * next;
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 */
48 struct disappearing_link **head;
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 };
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. */
69 word fo_object_size; /* In bytes. */
70 finalization_mark_proc fo_mark_proc; /* Mark-through procedure */
73 static signed_word log_fo_table_size = -1;
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 };
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))
87 # define SET_FINALIZE_NOW(fo) (void)(GC_fnlz_roots.finalize_now = (fo))
90 GC_API void GC_CALL GC_push_finalizer_structures(void)
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);
98 GC_PUSH_ALL_SYM(GC_dl_hashtbl.head);
99 GC_PUSH_ALL_SYM(GC_fnlz_roots);
102 /* Threshold of log_size to initiate full collection before growing */
104 #ifndef GC_ON_GROW_LOG_SIZE_MIN
105 # define GC_ON_GROW_LOG_SIZE_MIN 12
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)
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;
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 (void)GC_try_to_collect_inner(GC_never_stop_func);
129 /* GC_finalize might decrease entries value. */
130 if (*entries_ptr < ((word)1 << log_old_size) - (*entries_ptr >> 2))
134 new_table = (struct hash_chain_entry **)
135 GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
136 (size_t)new_size * sizeof(struct hash_chain_entry *),
138 if (new_table == 0) {
140 ABORT("Insufficient space for initial table allocation");
145 for (i = 0; i < old_size; i++) {
148 ptr_t real_key = (ptr_t)GC_REVEAL_POINTER(p->hidden_key);
149 struct hash_chain_entry *next = p -> next;
150 size_t new_hash = HASH3(real_key, new_size, log_new_size);
152 p -> next = new_table[new_hash];
153 new_table[new_hash] = p;
157 *log_size_ptr = log_new_size;
161 GC_API int GC_CALL GC_register_disappearing_link(void * * link)
165 base = (ptr_t)GC_base(link);
167 ABORT("Bad arg to GC_register_disappearing_link");
168 return(GC_general_register_disappearing_link(link, base));
171 STATIC int GC_register_disappearing_link_inner(
172 struct dl_hashtbl_s *dl_hashtbl, void **link,
173 const void *obj, const char *tbl_log_name)
175 struct disappearing_link *curr_dl;
177 struct disappearing_link * new_dl;
180 if (EXPECT(GC_find_leak, FALSE)) return GC_UNIMPLEMENTED;
182 GC_ASSERT(obj != NULL && GC_base_C(obj) == obj);
183 if (dl_hashtbl -> log_size == -1
184 || dl_hashtbl -> entries > ((word)1 << dl_hashtbl -> log_size)) {
185 GC_grow_table((struct hash_chain_entry ***)&dl_hashtbl -> head,
186 &dl_hashtbl -> log_size, &dl_hashtbl -> entries);
188 if (dl_hashtbl->log_size < 0) ABORT("log_size is negative");
190 GC_COND_LOG_PRINTF("Grew %s table to %u entries\n", tbl_log_name,
191 1 << (unsigned)dl_hashtbl -> log_size);
193 index = HASH2(link, dl_hashtbl -> log_size);
194 for (curr_dl = dl_hashtbl -> head[index]; curr_dl != 0;
195 curr_dl = dl_next(curr_dl)) {
196 if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
197 curr_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
202 new_dl = (struct disappearing_link *)
203 GC_INTERNAL_MALLOC(sizeof(struct disappearing_link),NORMAL);
205 GC_oom_func oom_fn = GC_oom_fn;
207 new_dl = (struct disappearing_link *)
208 (*oom_fn)(sizeof(struct disappearing_link));
212 /* It's not likely we'll make it here, but ... */
214 /* Recalculate index since the table may grow. */
215 index = HASH2(link, dl_hashtbl -> log_size);
216 /* Check again that our disappearing link not in the table. */
217 for (curr_dl = dl_hashtbl -> head[index]; curr_dl != 0;
218 curr_dl = dl_next(curr_dl)) {
219 if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
220 curr_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
222 # ifndef DBG_HDRS_ALL
223 /* Free unused new_dl returned by GC_oom_fn() */
224 GC_free((void *)new_dl);
230 new_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
231 new_dl -> dl_hidden_link = GC_HIDE_POINTER(link);
232 dl_set_next(new_dl, dl_hashtbl -> head[index]);
233 dl_hashtbl -> head[index] = new_dl;
234 dl_hashtbl -> entries++;
239 GC_API int GC_CALL GC_general_register_disappearing_link(void * * link,
242 if (((word)link & (ALIGNMENT-1)) != 0 || !NONNULL_ARG_NOT_NULL(link))
243 ABORT("Bad arg to GC_general_register_disappearing_link");
244 return GC_register_disappearing_link_inner(&GC_dl_hashtbl, link, obj,
249 # define FREE_DL_ENTRY(curr_dl) dl_set_next(curr_dl, NULL)
251 # define FREE_DL_ENTRY(curr_dl) GC_free(curr_dl)
254 /* Unregisters given link and returns the link entry to free. */
255 /* Assume the lock is held. */
256 GC_INLINE struct disappearing_link *GC_unregister_disappearing_link_inner(
257 struct dl_hashtbl_s *dl_hashtbl, void **link)
259 struct disappearing_link *curr_dl;
260 struct disappearing_link *prev_dl = NULL;
263 if (dl_hashtbl->log_size == -1)
264 return NULL; /* prevent integer shift by a negative amount */
266 index = HASH2(link, dl_hashtbl->log_size);
267 for (curr_dl = dl_hashtbl -> head[index]; curr_dl;
268 curr_dl = dl_next(curr_dl)) {
269 if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
270 /* Remove found entry from the table. */
271 if (NULL == prev_dl) {
272 dl_hashtbl -> head[index] = dl_next(curr_dl);
274 dl_set_next(prev_dl, dl_next(curr_dl));
276 dl_hashtbl -> entries--;
284 GC_API int GC_CALL GC_unregister_disappearing_link(void * * link)
286 struct disappearing_link *curr_dl;
289 if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
292 curr_dl = GC_unregister_disappearing_link_inner(&GC_dl_hashtbl, link);
294 if (NULL == curr_dl) return 0;
295 FREE_DL_ENTRY(curr_dl);
299 /* Toggle-ref support. */
300 #ifndef GC_TOGGLE_REFS_NOT_NEEDED
302 /* Lowest bit is used to distinguish between choices. */
304 GC_hidden_pointer weak_ref;
307 STATIC GC_toggleref_func GC_toggleref_callback = 0;
308 STATIC GCToggleRef *GC_toggleref_arr = NULL;
309 STATIC int GC_toggleref_array_size = 0;
310 STATIC int GC_toggleref_array_capacity = 0;
312 GC_INNER void GC_process_togglerefs(void)
317 GC_ASSERT(I_HOLD_LOCK());
318 for (i = 0; i < GC_toggleref_array_size; ++i) {
319 GCToggleRef r = GC_toggleref_arr[i];
320 void *obj = r.strong_ref;
322 if (((word)obj & 1) != 0) {
323 obj = GC_REVEAL_POINTER(r.weak_ref);
328 switch (GC_toggleref_callback(obj)) {
329 case GC_TOGGLE_REF_DROP:
331 case GC_TOGGLE_REF_STRONG:
332 GC_toggleref_arr[new_size++].strong_ref = obj;
334 case GC_TOGGLE_REF_WEAK:
335 GC_toggleref_arr[new_size++].weak_ref = GC_HIDE_POINTER(obj);
338 ABORT("Bad toggle-ref status returned by callback");
342 if (new_size < GC_toggleref_array_size) {
343 BZERO(&GC_toggleref_arr[new_size],
344 (GC_toggleref_array_size - new_size) * sizeof(GCToggleRef));
345 GC_toggleref_array_size = new_size;
349 STATIC void GC_normal_finalize_mark_proc(ptr_t);
351 static void push_and_mark_object(void *p)
353 GC_normal_finalize_mark_proc((ptr_t)p);
354 while (!GC_mark_stack_empty()) {
355 MARK_FROM_MARK_STACK();
358 if (GC_mark_state != MS_NONE) {
359 while (!GC_mark_some(0)) {
365 STATIC void GC_mark_togglerefs(void)
368 if (NULL == GC_toggleref_arr)
371 /* TODO: Hide GC_toggleref_arr to avoid its marking from roots. */
372 GC_set_mark_bit(GC_toggleref_arr);
373 for (i = 0; i < GC_toggleref_array_size; ++i) {
374 void *obj = GC_toggleref_arr[i].strong_ref;
375 if (obj != NULL && ((word)obj & 1) == 0) {
376 push_and_mark_object(obj);
381 STATIC void GC_clear_togglerefs(void)
384 for (i = 0; i < GC_toggleref_array_size; ++i) {
385 if ((GC_toggleref_arr[i].weak_ref & 1) != 0) {
386 if (!GC_is_marked(GC_REVEAL_POINTER(GC_toggleref_arr[i].weak_ref))) {
387 GC_toggleref_arr[i].weak_ref = 0;
389 /* No need to copy, BDWGC is a non-moving collector. */
395 GC_API void GC_CALL GC_set_toggleref_func(GC_toggleref_func fn)
400 GC_toggleref_callback = fn;
404 GC_API GC_toggleref_func GC_CALL GC_get_toggleref_func(void)
406 GC_toggleref_func fn;
410 fn = GC_toggleref_callback;
415 static GC_bool ensure_toggleref_capacity(int capacity_inc)
417 GC_ASSERT(capacity_inc >= 0);
418 GC_ASSERT(I_HOLD_LOCK());
419 if (NULL == GC_toggleref_arr) {
420 GC_toggleref_array_capacity = 32; /* initial capacity */
421 GC_toggleref_arr = (GCToggleRef *)GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
422 GC_toggleref_array_capacity * sizeof(GCToggleRef),
424 if (NULL == GC_toggleref_arr)
427 if ((unsigned)GC_toggleref_array_size + (unsigned)capacity_inc
428 >= (unsigned)GC_toggleref_array_capacity) {
429 GCToggleRef *new_array;
430 while ((unsigned)GC_toggleref_array_capacity
431 < (unsigned)GC_toggleref_array_size + (unsigned)capacity_inc) {
432 GC_toggleref_array_capacity *= 2;
433 if (GC_toggleref_array_capacity < 0) /* overflow */
437 new_array = (GCToggleRef *)GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
438 GC_toggleref_array_capacity * sizeof(GCToggleRef),
440 if (NULL == new_array)
442 if (EXPECT(GC_toggleref_array_size > 0, TRUE))
443 BCOPY(GC_toggleref_arr, new_array,
444 GC_toggleref_array_size * sizeof(GCToggleRef));
445 GC_INTERNAL_FREE(GC_toggleref_arr);
446 GC_toggleref_arr = new_array;
451 GC_API int GC_CALL GC_toggleref_add(void *obj, int is_strong_ref)
453 int res = GC_SUCCESS;
456 GC_ASSERT(NONNULL_ARG_NOT_NULL(obj));
458 if (GC_toggleref_callback != 0) {
459 if (!ensure_toggleref_capacity(1)) {
462 GC_toggleref_arr[GC_toggleref_array_size++].strong_ref =
463 is_strong_ref ? obj : (void *)GC_HIDE_POINTER(obj);
469 #endif /* !GC_TOGGLE_REFS_NOT_NEEDED */
471 /* Finalizer callback support. */
472 STATIC GC_await_finalize_proc GC_object_finalized_proc = 0;
474 GC_API void GC_CALL GC_set_await_finalize_proc(GC_await_finalize_proc fn)
479 GC_object_finalized_proc = fn;
483 GC_API GC_await_finalize_proc GC_CALL GC_get_await_finalize_proc(void)
485 GC_await_finalize_proc fn;
489 fn = GC_object_finalized_proc;
494 #ifndef GC_LONG_REFS_NOT_NEEDED
495 GC_API int GC_CALL GC_register_long_link(void * * link, const void * obj)
497 if (((word)link & (ALIGNMENT-1)) != 0 || !NONNULL_ARG_NOT_NULL(link))
498 ABORT("Bad arg to GC_register_long_link");
499 return GC_register_disappearing_link_inner(&GC_ll_hashtbl, link, obj,
503 GC_API int GC_CALL GC_unregister_long_link(void * * link)
505 struct disappearing_link *curr_dl;
508 if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
511 curr_dl = GC_unregister_disappearing_link_inner(&GC_ll_hashtbl, link);
513 if (NULL == curr_dl) return 0;
514 FREE_DL_ENTRY(curr_dl);
517 #endif /* !GC_LONG_REFS_NOT_NEEDED */
519 #ifndef GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED
520 /* Moves a link. Assume the lock is held. */
521 STATIC int GC_move_disappearing_link_inner(
522 struct dl_hashtbl_s *dl_hashtbl,
523 void **link, void **new_link)
525 struct disappearing_link *curr_dl, *prev_dl, *new_dl;
526 size_t curr_index, new_index;
527 word curr_hidden_link;
528 word new_hidden_link;
530 if (dl_hashtbl->log_size == -1)
531 return GC_NOT_FOUND; /* prevent integer shift by a negative amount */
533 /* Find current link. */
534 curr_index = HASH2(link, dl_hashtbl -> log_size);
535 curr_hidden_link = GC_HIDE_POINTER(link);
537 for (curr_dl = dl_hashtbl -> head[curr_index]; curr_dl;
538 curr_dl = dl_next(curr_dl)) {
539 if (curr_dl -> dl_hidden_link == curr_hidden_link)
544 if (NULL == curr_dl) {
548 if (link == new_link) {
549 return GC_SUCCESS; /* Nothing to do. */
552 /* link found; now check new_link not present. */
553 new_index = HASH2(new_link, dl_hashtbl -> log_size);
554 new_hidden_link = GC_HIDE_POINTER(new_link);
555 for (new_dl = dl_hashtbl -> head[new_index]; new_dl;
556 new_dl = dl_next(new_dl)) {
557 if (new_dl -> dl_hidden_link == new_hidden_link) {
558 /* Target already registered; bail. */
563 /* Remove from old, add to new, update link. */
564 if (NULL == prev_dl) {
565 dl_hashtbl -> head[curr_index] = dl_next(curr_dl);
567 dl_set_next(prev_dl, dl_next(curr_dl));
569 curr_dl -> dl_hidden_link = new_hidden_link;
570 dl_set_next(curr_dl, dl_hashtbl -> head[new_index]);
571 dl_hashtbl -> head[new_index] = curr_dl;
575 GC_API int GC_CALL GC_move_disappearing_link(void **link, void **new_link)
580 if (((word)new_link & (ALIGNMENT-1)) != 0
581 || !NONNULL_ARG_NOT_NULL(new_link))
582 ABORT("Bad new_link arg to GC_move_disappearing_link");
583 if (((word)link & (ALIGNMENT-1)) != 0)
584 return GC_NOT_FOUND; /* Nothing to do. */
587 result = GC_move_disappearing_link_inner(&GC_dl_hashtbl, link, new_link);
592 # ifndef GC_LONG_REFS_NOT_NEEDED
593 GC_API int GC_CALL GC_move_long_link(void **link, void **new_link)
598 if (((word)new_link & (ALIGNMENT-1)) != 0
599 || !NONNULL_ARG_NOT_NULL(new_link))
600 ABORT("Bad new_link arg to GC_move_long_link");
601 if (((word)link & (ALIGNMENT-1)) != 0)
602 return GC_NOT_FOUND; /* Nothing to do. */
605 result = GC_move_disappearing_link_inner(&GC_ll_hashtbl, link, new_link);
609 # endif /* !GC_LONG_REFS_NOT_NEEDED */
610 #endif /* !GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED */
612 /* Possible finalization_marker procedures. Note that mark stack */
613 /* overflow is handled by the caller, and is not a disaster. */
614 STATIC void GC_normal_finalize_mark_proc(ptr_t p)
618 PUSH_OBJ(p, hhdr, GC_mark_stack_top,
619 &(GC_mark_stack[GC_mark_stack_size]));
622 /* This only pays very partial attention to the mark descriptor. */
623 /* It does the right thing for normal and atomic objects, and treats */
624 /* most others as normal. */
625 STATIC void GC_ignore_self_finalize_mark_proc(ptr_t p)
628 word descr = hhdr -> hb_descr;
631 ptr_t target_limit = p + hhdr -> hb_sz - 1;
633 if ((descr & GC_DS_TAGS) == GC_DS_LENGTH) {
634 scan_limit = p + descr - sizeof(word);
636 scan_limit = target_limit + 1 - sizeof(word);
638 for (q = p; (word)q <= (word)scan_limit; q += ALIGNMENT) {
641 if (r < (word)p || r > (word)target_limit) {
642 GC_PUSH_ONE_HEAP(r, q, GC_mark_stack_top);
647 STATIC void GC_null_finalize_mark_proc(ptr_t p GC_ATTR_UNUSED) {}
649 /* Possible finalization_marker procedures. Note that mark stack */
650 /* overflow is handled by the caller, and is not a disaster. */
652 /* GC_unreachable_finalize_mark_proc is an alias for normal marking, */
653 /* but it is explicitly tested for, and triggers different */
654 /* behavior. Objects registered in this way are not finalized */
655 /* if they are reachable by other finalizable objects, even if those */
656 /* other objects specify no ordering. */
657 STATIC void GC_unreachable_finalize_mark_proc(ptr_t p)
659 GC_normal_finalize_mark_proc(p);
662 /* Register a finalization function. See gc.h for details. */
663 /* The last parameter is a procedure that determines */
664 /* marking for finalization ordering. Any objects marked */
665 /* by that procedure will be guaranteed to not have been */
666 /* finalized when this finalizer is invoked. */
667 STATIC void GC_register_finalizer_inner(void * obj,
668 GC_finalization_proc fn, void *cd,
669 GC_finalization_proc *ofn, void **ocd,
670 finalization_mark_proc mp)
672 struct finalizable_object * curr_fo;
674 struct finalizable_object *new_fo = 0;
675 hdr *hhdr = NULL; /* initialized to prevent warning. */
678 if (EXPECT(GC_find_leak, FALSE)) return;
680 if (log_fo_table_size == -1
681 || GC_fo_entries > ((word)1 << log_fo_table_size)) {
682 GC_grow_table((struct hash_chain_entry ***)&GC_fnlz_roots.fo_head,
683 &log_fo_table_size, &GC_fo_entries);
685 if (log_fo_table_size < 0) ABORT("log_size is negative");
687 GC_COND_LOG_PRINTF("Grew fo table to %u entries\n",
688 1 << (unsigned)log_fo_table_size);
690 /* in the THREADS case we hold allocation lock. */
692 struct finalizable_object *prev_fo = NULL;
695 index = HASH2(obj, log_fo_table_size);
696 curr_fo = GC_fnlz_roots.fo_head[index];
697 while (curr_fo != 0) {
698 GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
699 if (curr_fo -> fo_hidden_base == GC_HIDE_POINTER(obj)) {
700 /* Interruption by a signal in the middle of this */
701 /* should be safe. The client may see only *ocd */
702 /* updated, but we'll declare that to be his problem. */
703 if (ocd) *ocd = (void *) (curr_fo -> fo_client_data);
704 if (ofn) *ofn = curr_fo -> fo_fn;
705 /* Delete the structure for obj. */
707 GC_fnlz_roots.fo_head[index] = fo_next(curr_fo);
709 fo_set_next(prev_fo, fo_next(curr_fo));
713 /* May not happen if we get a signal. But a high */
714 /* estimate will only make the table larger than */
716 # if !defined(THREADS) && !defined(DBG_HDRS_ALL)
717 GC_free((void *)curr_fo);
720 curr_fo -> fo_fn = fn;
721 curr_fo -> fo_client_data = (ptr_t)cd;
722 curr_fo -> fo_mark_proc = mp;
723 /* Reinsert it. We deleted it first to maintain */
724 /* consistency in the event of a signal. */
726 GC_fnlz_roots.fo_head[index] = curr_fo;
728 fo_set_next(prev_fo, curr_fo);
732 # ifndef DBG_HDRS_ALL
733 if (EXPECT(new_fo != 0, FALSE)) {
734 /* Free unused new_fo returned by GC_oom_fn() */
735 GC_free((void *)new_fo);
741 curr_fo = fo_next(curr_fo);
743 if (EXPECT(new_fo != 0, FALSE)) {
744 /* new_fo is returned by GC_oom_fn(). */
747 if (NULL == hhdr) ABORT("Bad hhdr in GC_register_finalizer_inner");
758 if (EXPECT(0 == hhdr, FALSE)) {
759 /* We won't collect it, hence finalizer wouldn't be run. */
765 new_fo = (struct finalizable_object *)
766 GC_INTERNAL_MALLOC(sizeof(struct finalizable_object),NORMAL);
767 if (EXPECT(new_fo != 0, TRUE))
771 new_fo = (struct finalizable_object *)
772 (*oom_fn)(sizeof(struct finalizable_object));
774 /* No enough memory. *ocd and *ofn remains unchanged. */
777 /* It's not likely we'll make it here, but ... */
779 /* Recalculate index since the table may grow and */
780 /* check again that our finalizer is not in the table. */
782 GC_ASSERT(GC_size(new_fo) >= sizeof(struct finalizable_object));
785 new_fo -> fo_hidden_base = GC_HIDE_POINTER(obj);
786 new_fo -> fo_fn = fn;
787 new_fo -> fo_client_data = (ptr_t)cd;
788 new_fo -> fo_object_size = hhdr -> hb_sz;
789 new_fo -> fo_mark_proc = mp;
790 fo_set_next(new_fo, GC_fnlz_roots.fo_head[index]);
792 GC_fnlz_roots.fo_head[index] = new_fo;
796 GC_API void GC_CALL GC_register_finalizer(void * obj,
797 GC_finalization_proc fn, void * cd,
798 GC_finalization_proc *ofn, void ** ocd)
800 GC_register_finalizer_inner(obj, fn, cd, ofn,
801 ocd, GC_normal_finalize_mark_proc);
804 GC_API void GC_CALL GC_register_finalizer_ignore_self(void * obj,
805 GC_finalization_proc fn, void * cd,
806 GC_finalization_proc *ofn, void ** ocd)
808 GC_register_finalizer_inner(obj, fn, cd, ofn,
809 ocd, GC_ignore_self_finalize_mark_proc);
812 GC_API void GC_CALL GC_register_finalizer_no_order(void * obj,
813 GC_finalization_proc fn, void * cd,
814 GC_finalization_proc *ofn, void ** ocd)
816 GC_register_finalizer_inner(obj, fn, cd, ofn,
817 ocd, GC_null_finalize_mark_proc);
820 static GC_bool need_unreachable_finalization = FALSE;
821 /* Avoid the work if this isn't used. */
823 GC_API void GC_CALL GC_register_finalizer_unreachable(void * obj,
824 GC_finalization_proc fn, void * cd,
825 GC_finalization_proc *ofn, void ** ocd)
827 need_unreachable_finalization = TRUE;
828 GC_ASSERT(GC_java_finalization);
829 GC_register_finalizer_inner(obj, fn, cd, ofn,
830 ocd, GC_unreachable_finalize_mark_proc);
834 STATIC void GC_dump_finalization_links(
835 const struct dl_hashtbl_s *dl_hashtbl)
837 size_t dl_size = dl_hashtbl->log_size == -1 ? 0 :
838 (size_t)1 << dl_hashtbl->log_size;
841 for (i = 0; i < dl_size; i++) {
842 struct disappearing_link *curr_dl;
844 for (curr_dl = dl_hashtbl -> head[i]; curr_dl != 0;
845 curr_dl = dl_next(curr_dl)) {
846 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_obj);
847 ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_link);
849 GC_printf("Object: %p, link: %p\n",
850 (void *)real_ptr, (void *)real_link);
855 GC_API void GC_CALL GC_dump_finalization(void)
857 struct finalizable_object * curr_fo;
858 size_t fo_size = log_fo_table_size == -1 ? 0 :
859 (size_t)1 << log_fo_table_size;
862 GC_printf("Disappearing (short) links:\n");
863 GC_dump_finalization_links(&GC_dl_hashtbl);
864 # ifndef GC_LONG_REFS_NOT_NEEDED
865 GC_printf("Disappearing long links:\n");
866 GC_dump_finalization_links(&GC_ll_hashtbl);
868 GC_printf("Finalizers:\n");
869 for (i = 0; i < fo_size; i++) {
870 for (curr_fo = GC_fnlz_roots.fo_head[i];
871 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
872 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
874 GC_printf("Finalizable object: %p\n", (void *)real_ptr);
878 #endif /* !NO_DEBUGGING */
881 STATIC word GC_old_dl_entries = 0; /* for stats printing */
882 # ifndef GC_LONG_REFS_NOT_NEEDED
883 STATIC word GC_old_ll_entries = 0;
885 #endif /* !SMALL_CONFIG */
888 /* Global variables to minimize the level of recursion when a client */
889 /* finalizer allocates memory. */
890 STATIC int GC_finalizer_nested = 0;
891 /* Only the lowest byte is used, the rest is */
892 /* padding for proper global data alignment */
893 /* required for some compilers (like Watcom). */
894 STATIC unsigned GC_finalizer_skipped = 0;
896 /* Checks and updates the level of finalizers recursion. */
897 /* Returns NULL if GC_invoke_finalizers() should not be called by the */
898 /* collector (to minimize the risk of a deep finalizers recursion), */
899 /* otherwise returns a pointer to GC_finalizer_nested. */
900 STATIC unsigned char *GC_check_finalizer_nested(void)
902 unsigned nesting_level = *(unsigned char *)&GC_finalizer_nested;
904 /* We are inside another GC_invoke_finalizers(). */
905 /* Skip some implicitly-called GC_invoke_finalizers() */
906 /* depending on the nesting (recursion) level. */
907 if (++GC_finalizer_skipped < (1U << nesting_level)) return NULL;
908 GC_finalizer_skipped = 0;
910 *(char *)&GC_finalizer_nested = (char)(nesting_level + 1);
911 return (unsigned char *)&GC_finalizer_nested;
915 #define ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr_dl, prev_dl) \
918 size_t dl_size = dl_hashtbl->log_size == -1 ? 0 : \
919 (size_t)1 << dl_hashtbl->log_size; \
920 for (i = 0; i < dl_size; i++) { \
921 struct disappearing_link *prev_dl = NULL; \
922 curr_dl = dl_hashtbl -> head[i]; \
925 #define ITERATE_DL_HASHTBL_END(curr_dl, prev_dl) \
927 curr_dl = dl_next(curr_dl); \
932 #define DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr_dl, prev_dl, next_dl) \
934 next_dl = dl_next(curr_dl); \
935 if (NULL == prev_dl) { \
936 dl_hashtbl -> head[i] = next_dl; \
938 dl_set_next(prev_dl, next_dl); \
940 GC_clear_mark_bit(curr_dl); \
941 dl_hashtbl -> entries--; \
946 GC_INLINE void GC_make_disappearing_links_disappear(
947 struct dl_hashtbl_s* dl_hashtbl)
949 struct disappearing_link *curr, *next;
951 ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
952 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_obj);
953 ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_link);
955 if (!GC_is_marked(real_ptr)) {
956 *(word *)real_link = 0;
957 GC_clear_mark_bit(curr);
958 DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
960 ITERATE_DL_HASHTBL_END(curr, prev)
963 GC_INLINE void GC_remove_dangling_disappearing_links(
964 struct dl_hashtbl_s* dl_hashtbl)
966 struct disappearing_link *curr, *next;
968 ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
970 (ptr_t)GC_base(GC_REVEAL_POINTER(curr->dl_hidden_link));
972 if (NULL != real_link && !GC_is_marked(real_link)) {
973 GC_clear_mark_bit(curr);
974 DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
976 ITERATE_DL_HASHTBL_END(curr, prev)
979 /* Called with held lock (but the world is running). */
980 /* Cause disappearing links to disappear and unreachable objects to be */
981 /* enqueued for finalization. */
982 GC_INNER void GC_finalize(void)
984 struct finalizable_object * curr_fo, * prev_fo, * next_fo;
987 size_t fo_size = log_fo_table_size == -1 ? 0 :
988 (size_t)1 << log_fo_table_size;
990 # ifndef SMALL_CONFIG
991 /* Save current GC_[dl/ll]_entries value for stats printing */
992 GC_old_dl_entries = GC_dl_hashtbl.entries;
993 # ifndef GC_LONG_REFS_NOT_NEEDED
994 GC_old_ll_entries = GC_ll_hashtbl.entries;
998 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
999 GC_mark_togglerefs();
1001 GC_make_disappearing_links_disappear(&GC_dl_hashtbl);
1003 /* Mark all objects reachable via chains of 1 or more pointers */
1004 /* from finalizable objects. */
1005 GC_ASSERT(GC_mark_state == MS_NONE);
1006 for (i = 0; i < fo_size; i++) {
1007 for (curr_fo = GC_fnlz_roots.fo_head[i];
1008 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
1009 GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
1010 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1011 if (!GC_is_marked(real_ptr)) {
1012 GC_MARKED_FOR_FINALIZATION(real_ptr);
1013 GC_MARK_FO(real_ptr, curr_fo -> fo_mark_proc);
1014 if (GC_is_marked(real_ptr)) {
1015 WARN("Finalization cycle involving %p\n", real_ptr);
1020 /* Enqueue for finalization all objects that are still */
1022 GC_bytes_finalized = 0;
1023 for (i = 0; i < fo_size; i++) {
1024 curr_fo = GC_fnlz_roots.fo_head[i];
1026 while (curr_fo != 0) {
1027 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1028 if (!GC_is_marked(real_ptr)) {
1029 if (!GC_java_finalization) {
1030 GC_set_mark_bit(real_ptr);
1032 /* Delete from hash table */
1033 next_fo = fo_next(curr_fo);
1034 if (NULL == prev_fo) {
1035 GC_fnlz_roots.fo_head[i] = next_fo;
1037 fo_set_next(prev_fo, next_fo);
1040 if (GC_object_finalized_proc)
1041 GC_object_finalized_proc(real_ptr);
1043 /* Add to list of objects awaiting finalization. */
1044 fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1045 SET_FINALIZE_NOW(curr_fo);
1046 /* unhide object pointer so any future collections will */
1048 curr_fo -> fo_hidden_base =
1049 (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1050 GC_bytes_finalized +=
1051 curr_fo -> fo_object_size
1052 + sizeof(struct finalizable_object);
1053 GC_ASSERT(GC_is_marked(GC_base(curr_fo)));
1057 curr_fo = fo_next(curr_fo);
1062 if (GC_java_finalization) {
1063 /* make sure we mark everything reachable from objects finalized
1064 using the no_order mark_proc */
1065 for (curr_fo = GC_fnlz_roots.finalize_now;
1066 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
1067 real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1068 if (!GC_is_marked(real_ptr)) {
1069 if (curr_fo -> fo_mark_proc == GC_null_finalize_mark_proc) {
1070 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1072 if (curr_fo -> fo_mark_proc != GC_unreachable_finalize_mark_proc) {
1073 GC_set_mark_bit(real_ptr);
1078 /* now revive finalize-when-unreachable objects reachable from
1079 other finalizable objects */
1080 if (need_unreachable_finalization) {
1081 curr_fo = GC_fnlz_roots.finalize_now;
1082 # if defined(GC_ASSERTIONS) || defined(LINT2)
1083 if (curr_fo != NULL && log_fo_table_size < 0)
1084 ABORT("log_size is negative");
1087 while (curr_fo != NULL) {
1088 next_fo = fo_next(curr_fo);
1089 if (curr_fo -> fo_mark_proc == GC_unreachable_finalize_mark_proc) {
1090 real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1091 if (!GC_is_marked(real_ptr)) {
1092 GC_set_mark_bit(real_ptr);
1094 if (NULL == prev_fo) {
1095 SET_FINALIZE_NOW(next_fo);
1097 fo_set_next(prev_fo, next_fo);
1099 curr_fo -> fo_hidden_base =
1100 GC_HIDE_POINTER(curr_fo -> fo_hidden_base);
1101 GC_bytes_finalized -=
1102 curr_fo->fo_object_size + sizeof(struct finalizable_object);
1104 i = HASH2(real_ptr, log_fo_table_size);
1105 fo_set_next(curr_fo, GC_fnlz_roots.fo_head[i]);
1107 GC_fnlz_roots.fo_head[i] = curr_fo;
1117 GC_remove_dangling_disappearing_links(&GC_dl_hashtbl);
1118 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
1119 GC_clear_togglerefs();
1121 # ifndef GC_LONG_REFS_NOT_NEEDED
1122 GC_make_disappearing_links_disappear(&GC_ll_hashtbl);
1123 GC_remove_dangling_disappearing_links(&GC_ll_hashtbl);
1126 if (GC_fail_count) {
1127 /* Don't prevent running finalizers if there has been an allocation */
1128 /* failure recently. */
1130 GC_reset_finalizer_nested();
1132 GC_finalizer_nested = 0;
1137 #ifndef JAVA_FINALIZATION_NOT_NEEDED
1139 /* Enqueue all remaining finalizers to be run - Assumes lock is held. */
1140 STATIC void GC_enqueue_all_finalizers(void)
1142 struct finalizable_object * next_fo;
1146 fo_size = log_fo_table_size == -1 ? 0 : 1 << log_fo_table_size;
1147 GC_bytes_finalized = 0;
1148 for (i = 0; i < fo_size; i++) {
1149 struct finalizable_object * curr_fo = GC_fnlz_roots.fo_head[i];
1151 GC_fnlz_roots.fo_head[i] = NULL;
1152 while (curr_fo != NULL) {
1153 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1155 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1156 GC_set_mark_bit(real_ptr);
1158 next_fo = fo_next(curr_fo);
1160 /* Add to list of objects awaiting finalization. */
1161 fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1162 SET_FINALIZE_NOW(curr_fo);
1164 /* unhide object pointer so any future collections will */
1166 curr_fo -> fo_hidden_base =
1167 (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1168 GC_bytes_finalized +=
1169 curr_fo -> fo_object_size + sizeof(struct finalizable_object);
1173 GC_fo_entries = 0; /* all entries deleted from the hash table */
1176 /* Invoke all remaining finalizers that haven't yet been run.
1177 * This is needed for strict compliance with the Java standard,
1178 * which can make the runtime guarantee that all finalizers are run.
1179 * Unfortunately, the Java standard implies we have to keep running
1180 * finalizers until there are no more left, a potential infinite loop.
1182 * Note that this is even more dangerous than the usual Java
1183 * finalizers, in that objects reachable from static variables
1184 * may have been finalized when these finalizers are run.
1185 * Finalizers run at this point must be prepared to deal with a
1186 * mostly broken world.
1187 * This routine is externally callable, so is called without
1188 * the allocation lock.
1190 GC_API void GC_CALL GC_finalize_all(void)
1195 while (GC_fo_entries > 0) {
1196 GC_enqueue_all_finalizers();
1198 GC_invoke_finalizers();
1199 /* Running the finalizers in this thread is arguably not a good */
1200 /* idea when we should be notifying another thread to run them. */
1201 /* But otherwise we don't have a great way to wait for them to */
1208 #endif /* !JAVA_FINALIZATION_NOT_NEEDED */
1210 /* Returns true if it is worth calling GC_invoke_finalizers. (Useful if */
1211 /* finalizers can only be called from some kind of "safe state" and */
1212 /* getting into that safe state is expensive.) */
1213 GC_API int GC_CALL GC_should_invoke_finalizers(void)
1215 # ifdef AO_HAVE_load
1216 return AO_load((volatile AO_t *)&GC_fnlz_roots.finalize_now) != 0;
1218 return GC_fnlz_roots.finalize_now != NULL;
1219 # endif /* !THREADS */
1222 /* Invoke finalizers for all objects that are ready to be finalized. */
1223 /* Should be called without allocation lock. */
1224 GC_API int GC_CALL GC_invoke_finalizers(void)
1227 word bytes_freed_before = 0; /* initialized to prevent warning. */
1230 while (GC_should_invoke_finalizers()) {
1231 struct finalizable_object * curr_fo;
1237 bytes_freed_before = GC_bytes_freed;
1238 /* Don't do this outside, since we need the lock. */
1240 curr_fo = GC_fnlz_roots.finalize_now;
1242 if (curr_fo != NULL)
1243 SET_FINALIZE_NOW(fo_next(curr_fo));
1245 if (curr_fo == 0) break;
1247 GC_fnlz_roots.finalize_now = fo_next(curr_fo);
1249 fo_set_next(curr_fo, 0);
1250 (*(curr_fo -> fo_fn))((ptr_t)(curr_fo -> fo_hidden_base),
1251 curr_fo -> fo_client_data);
1252 curr_fo -> fo_client_data = 0;
1254 /* Explicit freeing of curr_fo is probably a bad idea. */
1255 /* It throws off accounting if nearly all objects are */
1256 /* finalizable. Otherwise it should not matter. */
1258 /* bytes_freed_before is initialized whenever count != 0 */
1260 # if defined(THREADS) && !defined(THREAD_SANITIZER)
1261 /* A quick check whether some memory was freed. */
1262 /* The race with GC_free() is safe to be ignored */
1263 /* because we only need to know if the current */
1264 /* thread has deallocated something. */
1265 && bytes_freed_before != GC_bytes_freed
1269 GC_finalizer_bytes_freed += (GC_bytes_freed - bytes_freed_before);
1275 static word last_finalizer_notification = 0;
1277 GC_INNER void GC_notify_or_invoke_finalizers(void)
1279 GC_finalizer_notifier_proc notifier_fn = 0;
1280 # if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1281 static word last_back_trace_gc_no = 1; /* Skip first one. */
1285 # if defined(THREADS) && !defined(KEEP_BACK_PTRS) \
1286 && !defined(MAKE_BACK_GRAPH)
1287 /* Quick check (while unlocked) for an empty finalization queue. */
1288 if (!GC_should_invoke_finalizers())
1293 /* This is a convenient place to generate backtraces if appropriate, */
1294 /* since that code is not callable with the allocation lock. */
1295 # if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1296 if (GC_gc_no > last_back_trace_gc_no) {
1297 # ifdef KEEP_BACK_PTRS
1299 /* Stops when GC_gc_no wraps; that's OK. */
1300 last_back_trace_gc_no = (word)(-1); /* disable others. */
1301 for (i = 0; i < GC_backtraces; ++i) {
1302 /* FIXME: This tolerates concurrent heap mutation, */
1303 /* which may cause occasional mysterious results. */
1304 /* We need to release the GC lock, since GC_print_callers */
1305 /* acquires it. It probably shouldn't. */
1307 GC_generate_random_backtrace_no_gc();
1310 last_back_trace_gc_no = GC_gc_no;
1312 # ifdef MAKE_BACK_GRAPH
1313 if (GC_print_back_height) {
1315 GC_print_back_graph_stats();
1321 if (NULL == GC_fnlz_roots.finalize_now) {
1326 if (!GC_finalize_on_demand) {
1327 unsigned char *pnested = GC_check_finalizer_nested();
1329 /* Skip GC_invoke_finalizers() if nested */
1330 if (pnested != NULL) {
1331 (void) GC_invoke_finalizers();
1332 *pnested = 0; /* Reset since no more finalizers. */
1334 GC_ASSERT(NULL == GC_fnlz_roots.finalize_now);
1335 # endif /* Otherwise GC can run concurrently and add more */
1340 /* These variables require synchronization to avoid data races. */
1341 if (last_finalizer_notification != GC_gc_no) {
1342 last_finalizer_notification = GC_gc_no;
1343 notifier_fn = GC_finalizer_notifier;
1346 if (notifier_fn != 0)
1347 (*notifier_fn)(); /* Invoke the notifier */
1350 #ifndef SMALL_CONFIG
1351 # ifndef GC_LONG_REFS_NOT_NEEDED
1352 # define IF_LONG_REFS_PRESENT_ELSE(x,y) (x)
1354 # define IF_LONG_REFS_PRESENT_ELSE(x,y) (y)
1357 GC_INNER void GC_print_finalization_stats(void)
1359 struct finalizable_object *fo;
1360 unsigned long ready = 0;
1362 GC_log_printf("%lu finalization entries;"
1363 " %lu/%lu short/long disappearing links alive\n",
1364 (unsigned long)GC_fo_entries,
1365 (unsigned long)GC_dl_hashtbl.entries,
1366 (unsigned long)IF_LONG_REFS_PRESENT_ELSE(
1367 GC_ll_hashtbl.entries, 0));
1369 for (fo = GC_fnlz_roots.finalize_now; fo != NULL; fo = fo_next(fo))
1371 GC_log_printf("%lu finalization-ready objects;"
1372 " %ld/%ld short/long links cleared\n",
1374 (long)GC_old_dl_entries - (long)GC_dl_hashtbl.entries,
1375 (long)IF_LONG_REFS_PRESENT_ELSE(
1376 GC_old_ll_entries - GC_ll_hashtbl.entries, 0));
1378 #endif /* !SMALL_CONFIG */
1380 #endif /* !GC_NO_FINALIZATION */