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 CPP_LOG_HBLKSIZE
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 IF_CANCEL(int cancel_state;)
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))
138 new_table = (struct hash_chain_entry **)
139 GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
140 (size_t)new_size * sizeof(struct hash_chain_entry *),
142 if (new_table == 0) {
144 ABORT("Insufficient space for initial table allocation");
149 for (i = 0; i < old_size; i++) {
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);
156 p -> next = new_table[new_hash];
157 new_table[new_hash] = p;
161 *log_size_ptr = log_new_size;
165 GC_API int GC_CALL GC_register_disappearing_link(void * * link)
169 base = (ptr_t)GC_base(link);
171 ABORT("Bad arg to GC_register_disappearing_link");
172 return(GC_general_register_disappearing_link(link, base));
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)
179 struct disappearing_link *curr_dl;
181 struct disappearing_link * new_dl;
184 if (EXPECT(GC_find_leak, FALSE)) return GC_UNIMPLEMENTED;
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);
192 if (dl_hashtbl->log_size < 0) ABORT("log_size is negative");
194 GC_COND_LOG_PRINTF("Grew %s table to %u entries\n", tbl_log_name,
195 1 << (unsigned)dl_hashtbl -> log_size);
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);
206 new_dl = (struct disappearing_link *)
207 GC_INTERNAL_MALLOC(sizeof(struct disappearing_link),NORMAL);
209 GC_oom_func oom_fn = GC_oom_fn;
211 new_dl = (struct disappearing_link *)
212 (*oom_fn)(sizeof(struct disappearing_link));
216 /* It's not likely we'll make it here, but ... */
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);
226 # ifndef DBG_HDRS_ALL
227 /* Free unused new_dl returned by GC_oom_fn() */
228 GC_free((void *)new_dl);
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++;
243 GC_API int GC_CALL GC_general_register_disappearing_link(void * * link,
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,
253 # define FREE_DL_ENTRY(curr_dl) dl_set_next(curr_dl, NULL)
255 # define FREE_DL_ENTRY(curr_dl) GC_free(curr_dl)
258 /* Unregisters given link and returns the link entry to free. */
259 GC_INLINE struct disappearing_link *GC_unregister_disappearing_link_inner(
260 struct dl_hashtbl_s *dl_hashtbl, void **link)
262 struct disappearing_link *curr_dl;
263 struct disappearing_link *prev_dl = NULL;
266 GC_ASSERT(I_HOLD_LOCK());
267 if (dl_hashtbl->log_size == -1)
268 return NULL; /* prevent integer shift by a negative amount */
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);
278 dl_set_next(prev_dl, dl_next(curr_dl));
280 dl_hashtbl -> entries--;
288 GC_API int GC_CALL GC_unregister_disappearing_link(void * * link)
290 struct disappearing_link *curr_dl;
293 if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
296 curr_dl = GC_unregister_disappearing_link_inner(&GC_dl_hashtbl, link);
298 if (NULL == curr_dl) return 0;
299 FREE_DL_ENTRY(curr_dl);
303 /* Toggle-ref support. */
304 #ifndef GC_TOGGLE_REFS_NOT_NEEDED
306 /* Lowest bit is used to distinguish between choices. */
308 GC_hidden_pointer weak_ref;
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;
316 GC_INNER void GC_process_togglerefs(void)
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;
326 if (((word)obj & 1) != 0) {
327 obj = GC_REVEAL_POINTER(r.weak_ref);
332 switch (GC_toggleref_callback(obj)) {
333 case GC_TOGGLE_REF_DROP:
335 case GC_TOGGLE_REF_STRONG:
336 GC_toggleref_arr[new_size++].strong_ref = obj;
338 case GC_TOGGLE_REF_WEAK:
339 GC_toggleref_arr[new_size++].weak_ref = GC_HIDE_POINTER(obj);
342 ABORT("Bad toggle-ref status returned by callback");
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;
353 STATIC void GC_normal_finalize_mark_proc(ptr_t);
355 static void push_and_mark_object(void *p)
357 GC_normal_finalize_mark_proc((ptr_t)p);
358 while (!GC_mark_stack_empty()) {
359 MARK_FROM_MARK_STACK();
362 if (GC_mark_state != MS_NONE) {
363 while (!GC_mark_some(0)) {
369 STATIC void GC_mark_togglerefs(void)
372 if (NULL == GC_toggleref_arr)
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);
385 STATIC void GC_clear_togglerefs(void)
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;
393 /* No need to copy, BDWGC is a non-moving collector. */
399 GC_API void GC_CALL GC_set_toggleref_func(GC_toggleref_func fn)
404 GC_toggleref_callback = fn;
408 GC_API GC_toggleref_func GC_CALL GC_get_toggleref_func(void)
410 GC_toggleref_func fn;
414 fn = GC_toggleref_callback;
419 static GC_bool ensure_toggleref_capacity(int capacity_inc)
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),
428 if (NULL == GC_toggleref_arr)
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 */
441 new_array = (GCToggleRef *)GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
442 GC_toggleref_array_capacity * sizeof(GCToggleRef),
444 if (NULL == new_array)
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;
455 GC_API int GC_CALL GC_toggleref_add(void *obj, int is_strong_ref)
457 int res = GC_SUCCESS;
460 GC_ASSERT(NONNULL_ARG_NOT_NULL(obj));
462 if (GC_toggleref_callback != 0) {
463 if (!ensure_toggleref_capacity(1)) {
466 GC_toggleref_arr[GC_toggleref_array_size++].strong_ref =
467 is_strong_ref ? obj : (void *)GC_HIDE_POINTER(obj);
473 #endif /* !GC_TOGGLE_REFS_NOT_NEEDED */
475 /* Finalizer callback support. */
476 STATIC GC_await_finalize_proc GC_object_finalized_proc = 0;
478 GC_API void GC_CALL GC_set_await_finalize_proc(GC_await_finalize_proc fn)
483 GC_object_finalized_proc = fn;
487 GC_API GC_await_finalize_proc GC_CALL GC_get_await_finalize_proc(void)
489 GC_await_finalize_proc fn;
493 fn = GC_object_finalized_proc;
498 #ifndef GC_LONG_REFS_NOT_NEEDED
499 GC_API int GC_CALL GC_register_long_link(void * * link, const void * obj)
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,
507 GC_API int GC_CALL GC_unregister_long_link(void * * link)
509 struct disappearing_link *curr_dl;
512 if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
515 curr_dl = GC_unregister_disappearing_link_inner(&GC_ll_hashtbl, link);
517 if (NULL == curr_dl) return 0;
518 FREE_DL_ENTRY(curr_dl);
521 #endif /* !GC_LONG_REFS_NOT_NEEDED */
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)
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;
534 GC_ASSERT(I_HOLD_LOCK());
535 if (dl_hashtbl->log_size == -1)
536 return GC_NOT_FOUND; /* prevent integer shift by a negative amount */
538 /* Find current link. */
539 curr_index = HASH2(link, dl_hashtbl -> log_size);
540 curr_hidden_link = GC_HIDE_POINTER(link);
542 for (curr_dl = dl_hashtbl -> head[curr_index]; curr_dl;
543 curr_dl = dl_next(curr_dl)) {
544 if (curr_dl -> dl_hidden_link == curr_hidden_link)
549 if (NULL == curr_dl) {
553 if (link == new_link) {
554 return GC_SUCCESS; /* Nothing to do. */
557 /* link found; now check new_link not present. */
558 new_index = HASH2(new_link, dl_hashtbl -> log_size);
559 new_hidden_link = GC_HIDE_POINTER(new_link);
560 for (new_dl = dl_hashtbl -> head[new_index]; new_dl;
561 new_dl = dl_next(new_dl)) {
562 if (new_dl -> dl_hidden_link == new_hidden_link) {
563 /* Target already registered; bail. */
568 /* Remove from old, add to new, update link. */
569 if (NULL == prev_dl) {
570 dl_hashtbl -> head[curr_index] = dl_next(curr_dl);
572 dl_set_next(prev_dl, dl_next(curr_dl));
574 curr_dl -> dl_hidden_link = new_hidden_link;
575 dl_set_next(curr_dl, dl_hashtbl -> head[new_index]);
576 dl_hashtbl -> head[new_index] = curr_dl;
580 GC_API int GC_CALL GC_move_disappearing_link(void **link, void **new_link)
585 if (((word)new_link & (ALIGNMENT-1)) != 0
586 || !NONNULL_ARG_NOT_NULL(new_link))
587 ABORT("Bad new_link arg to GC_move_disappearing_link");
588 if (((word)link & (ALIGNMENT-1)) != 0)
589 return GC_NOT_FOUND; /* Nothing to do. */
592 result = GC_move_disappearing_link_inner(&GC_dl_hashtbl, link, new_link);
597 # ifndef GC_LONG_REFS_NOT_NEEDED
598 GC_API int GC_CALL GC_move_long_link(void **link, void **new_link)
603 if (((word)new_link & (ALIGNMENT-1)) != 0
604 || !NONNULL_ARG_NOT_NULL(new_link))
605 ABORT("Bad new_link arg to GC_move_long_link");
606 if (((word)link & (ALIGNMENT-1)) != 0)
607 return GC_NOT_FOUND; /* Nothing to do. */
610 result = GC_move_disappearing_link_inner(&GC_ll_hashtbl, link, new_link);
614 # endif /* !GC_LONG_REFS_NOT_NEEDED */
615 #endif /* !GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED */
617 /* Possible finalization_marker procedures. Note that mark stack */
618 /* overflow is handled by the caller, and is not a disaster. */
619 STATIC void GC_normal_finalize_mark_proc(ptr_t p)
623 PUSH_OBJ(p, hhdr, GC_mark_stack_top,
624 &(GC_mark_stack[GC_mark_stack_size]));
627 /* This only pays very partial attention to the mark descriptor. */
628 /* It does the right thing for normal and atomic objects, and treats */
629 /* most others as normal. */
630 STATIC void GC_ignore_self_finalize_mark_proc(ptr_t p)
633 word descr = hhdr -> hb_descr;
636 ptr_t target_limit = p + hhdr -> hb_sz - 1;
638 if ((descr & GC_DS_TAGS) == GC_DS_LENGTH) {
639 scan_limit = p + descr - sizeof(word);
641 scan_limit = target_limit + 1 - sizeof(word);
643 for (q = p; (word)q <= (word)scan_limit; q += ALIGNMENT) {
646 if (r < (word)p || r > (word)target_limit) {
647 GC_PUSH_ONE_HEAP(r, q, GC_mark_stack_top);
652 STATIC void GC_null_finalize_mark_proc(ptr_t p GC_ATTR_UNUSED) {}
654 /* Possible finalization_marker procedures. Note that mark stack */
655 /* overflow is handled by the caller, and is not a disaster. */
657 /* GC_unreachable_finalize_mark_proc is an alias for normal marking, */
658 /* but it is explicitly tested for, and triggers different */
659 /* behavior. Objects registered in this way are not finalized */
660 /* if they are reachable by other finalizable objects, even if those */
661 /* other objects specify no ordering. */
662 STATIC void GC_unreachable_finalize_mark_proc(ptr_t p)
664 GC_normal_finalize_mark_proc(p);
667 /* Register a finalization function. See gc.h for details. */
668 /* The last parameter is a procedure that determines */
669 /* marking for finalization ordering. Any objects marked */
670 /* by that procedure will be guaranteed to not have been */
671 /* finalized when this finalizer is invoked. */
672 STATIC void GC_register_finalizer_inner(void * obj,
673 GC_finalization_proc fn, void *cd,
674 GC_finalization_proc *ofn, void **ocd,
675 finalization_mark_proc mp)
677 struct finalizable_object * curr_fo;
679 struct finalizable_object *new_fo = 0;
680 hdr *hhdr = NULL; /* initialized to prevent warning. */
683 if (EXPECT(GC_find_leak, FALSE)) return;
685 if (log_fo_table_size == -1
686 || GC_fo_entries > ((word)1 << log_fo_table_size)) {
687 GC_grow_table((struct hash_chain_entry ***)&GC_fnlz_roots.fo_head,
688 &log_fo_table_size, &GC_fo_entries);
690 if (log_fo_table_size < 0) ABORT("log_size is negative");
692 GC_COND_LOG_PRINTF("Grew fo table to %u entries\n",
693 1 << (unsigned)log_fo_table_size);
695 /* in the THREADS case we hold allocation lock. */
697 struct finalizable_object *prev_fo = NULL;
700 index = HASH2(obj, log_fo_table_size);
701 curr_fo = GC_fnlz_roots.fo_head[index];
702 while (curr_fo != 0) {
703 GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
704 if (curr_fo -> fo_hidden_base == GC_HIDE_POINTER(obj)) {
705 /* Interruption by a signal in the middle of this */
706 /* should be safe. The client may see only *ocd */
707 /* updated, but we'll declare that to be his problem. */
708 if (ocd) *ocd = (void *) (curr_fo -> fo_client_data);
709 if (ofn) *ofn = curr_fo -> fo_fn;
710 /* Delete the structure for obj. */
712 GC_fnlz_roots.fo_head[index] = fo_next(curr_fo);
714 fo_set_next(prev_fo, fo_next(curr_fo));
718 /* May not happen if we get a signal. But a high */
719 /* estimate will only make the table larger than */
721 # if !defined(THREADS) && !defined(DBG_HDRS_ALL)
722 GC_free((void *)curr_fo);
725 curr_fo -> fo_fn = fn;
726 curr_fo -> fo_client_data = (ptr_t)cd;
727 curr_fo -> fo_mark_proc = mp;
728 /* Reinsert it. We deleted it first to maintain */
729 /* consistency in the event of a signal. */
731 GC_fnlz_roots.fo_head[index] = curr_fo;
733 fo_set_next(prev_fo, curr_fo);
737 # ifndef DBG_HDRS_ALL
738 if (EXPECT(new_fo != 0, FALSE)) {
739 /* Free unused new_fo returned by GC_oom_fn() */
740 GC_free((void *)new_fo);
746 curr_fo = fo_next(curr_fo);
748 if (EXPECT(new_fo != 0, FALSE)) {
749 /* new_fo is returned by GC_oom_fn(). */
752 if (NULL == hhdr) ABORT("Bad hhdr in GC_register_finalizer_inner");
763 if (EXPECT(0 == hhdr, FALSE)) {
764 /* We won't collect it, hence finalizer wouldn't be run. */
770 new_fo = (struct finalizable_object *)
771 GC_INTERNAL_MALLOC(sizeof(struct finalizable_object),NORMAL);
772 if (EXPECT(new_fo != 0, TRUE))
776 new_fo = (struct finalizable_object *)
777 (*oom_fn)(sizeof(struct finalizable_object));
779 /* No enough memory. *ocd and *ofn remains unchanged. */
782 /* It's not likely we'll make it here, but ... */
784 /* Recalculate index since the table may grow and */
785 /* check again that our finalizer is not in the table. */
787 GC_ASSERT(GC_size(new_fo) >= sizeof(struct finalizable_object));
790 new_fo -> fo_hidden_base = GC_HIDE_POINTER(obj);
791 new_fo -> fo_fn = fn;
792 new_fo -> fo_client_data = (ptr_t)cd;
793 new_fo -> fo_object_size = hhdr -> hb_sz;
794 new_fo -> fo_mark_proc = mp;
795 fo_set_next(new_fo, GC_fnlz_roots.fo_head[index]);
797 GC_fnlz_roots.fo_head[index] = new_fo;
801 GC_API void GC_CALL GC_register_finalizer(void * obj,
802 GC_finalization_proc fn, void * cd,
803 GC_finalization_proc *ofn, void ** ocd)
805 GC_register_finalizer_inner(obj, fn, cd, ofn,
806 ocd, GC_normal_finalize_mark_proc);
809 GC_API void GC_CALL GC_register_finalizer_ignore_self(void * obj,
810 GC_finalization_proc fn, void * cd,
811 GC_finalization_proc *ofn, void ** ocd)
813 GC_register_finalizer_inner(obj, fn, cd, ofn,
814 ocd, GC_ignore_self_finalize_mark_proc);
817 GC_API void GC_CALL GC_register_finalizer_no_order(void * obj,
818 GC_finalization_proc fn, void * cd,
819 GC_finalization_proc *ofn, void ** ocd)
821 GC_register_finalizer_inner(obj, fn, cd, ofn,
822 ocd, GC_null_finalize_mark_proc);
825 static GC_bool need_unreachable_finalization = FALSE;
826 /* Avoid the work if this isn't used. */
828 GC_API void GC_CALL GC_register_finalizer_unreachable(void * obj,
829 GC_finalization_proc fn, void * cd,
830 GC_finalization_proc *ofn, void ** ocd)
832 need_unreachable_finalization = TRUE;
833 GC_ASSERT(GC_java_finalization);
834 GC_register_finalizer_inner(obj, fn, cd, ofn,
835 ocd, GC_unreachable_finalize_mark_proc);
839 STATIC void GC_dump_finalization_links(
840 const struct dl_hashtbl_s *dl_hashtbl)
842 size_t dl_size = dl_hashtbl->log_size == -1 ? 0 :
843 (size_t)1 << dl_hashtbl->log_size;
846 for (i = 0; i < dl_size; i++) {
847 struct disappearing_link *curr_dl;
849 for (curr_dl = dl_hashtbl -> head[i]; curr_dl != 0;
850 curr_dl = dl_next(curr_dl)) {
851 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_obj);
852 ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_link);
854 GC_printf("Object: %p, link: %p\n",
855 (void *)real_ptr, (void *)real_link);
860 GC_API void GC_CALL GC_dump_finalization(void)
862 struct finalizable_object * curr_fo;
863 size_t fo_size = log_fo_table_size == -1 ? 0 :
864 (size_t)1 << log_fo_table_size;
867 GC_printf("Disappearing (short) links:\n");
868 GC_dump_finalization_links(&GC_dl_hashtbl);
869 # ifndef GC_LONG_REFS_NOT_NEEDED
870 GC_printf("Disappearing long links:\n");
871 GC_dump_finalization_links(&GC_ll_hashtbl);
873 GC_printf("Finalizers:\n");
874 for (i = 0; i < fo_size; i++) {
875 for (curr_fo = GC_fnlz_roots.fo_head[i];
876 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
877 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
879 GC_printf("Finalizable object: %p\n", (void *)real_ptr);
883 #endif /* !NO_DEBUGGING */
886 STATIC word GC_old_dl_entries = 0; /* for stats printing */
887 # ifndef GC_LONG_REFS_NOT_NEEDED
888 STATIC word GC_old_ll_entries = 0;
890 #endif /* !SMALL_CONFIG */
893 /* Global variables to minimize the level of recursion when a client */
894 /* finalizer allocates memory. */
895 STATIC int GC_finalizer_nested = 0;
896 /* Only the lowest byte is used, the rest is */
897 /* padding for proper global data alignment */
898 /* required for some compilers (like Watcom). */
899 STATIC unsigned GC_finalizer_skipped = 0;
901 /* Checks and updates the level of finalizers recursion. */
902 /* Returns NULL if GC_invoke_finalizers() should not be called by the */
903 /* collector (to minimize the risk of a deep finalizers recursion), */
904 /* otherwise returns a pointer to GC_finalizer_nested. */
905 STATIC unsigned char *GC_check_finalizer_nested(void)
907 unsigned nesting_level = *(unsigned char *)&GC_finalizer_nested;
909 /* We are inside another GC_invoke_finalizers(). */
910 /* Skip some implicitly-called GC_invoke_finalizers() */
911 /* depending on the nesting (recursion) level. */
912 if (++GC_finalizer_skipped < (1U << nesting_level)) return NULL;
913 GC_finalizer_skipped = 0;
915 *(char *)&GC_finalizer_nested = (char)(nesting_level + 1);
916 return (unsigned char *)&GC_finalizer_nested;
920 #define ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr_dl, prev_dl) \
923 size_t dl_size = dl_hashtbl->log_size == -1 ? 0 : \
924 (size_t)1 << dl_hashtbl->log_size; \
925 GC_ASSERT(I_HOLD_LOCK()); \
926 for (i = 0; i < dl_size; i++) { \
927 struct disappearing_link *prev_dl = NULL; \
928 curr_dl = dl_hashtbl -> head[i]; \
931 #define ITERATE_DL_HASHTBL_END(curr_dl, prev_dl) \
933 curr_dl = dl_next(curr_dl); \
938 #define DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr_dl, prev_dl, next_dl) \
940 next_dl = dl_next(curr_dl); \
941 if (NULL == prev_dl) { \
942 dl_hashtbl -> head[i] = next_dl; \
944 dl_set_next(prev_dl, next_dl); \
946 GC_clear_mark_bit(curr_dl); \
947 dl_hashtbl -> entries--; \
952 GC_INLINE void GC_make_disappearing_links_disappear(
953 struct dl_hashtbl_s* dl_hashtbl)
955 struct disappearing_link *curr, *next;
957 ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
958 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_obj);
959 ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_link);
961 if (!GC_is_marked(real_ptr)) {
962 *(word *)real_link = 0;
963 GC_clear_mark_bit(curr);
964 DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
966 ITERATE_DL_HASHTBL_END(curr, prev)
969 GC_INLINE void GC_remove_dangling_disappearing_links(
970 struct dl_hashtbl_s* dl_hashtbl)
972 struct disappearing_link *curr, *next;
974 ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
976 (ptr_t)GC_base(GC_REVEAL_POINTER(curr->dl_hidden_link));
978 if (NULL != real_link && !GC_is_marked(real_link)) {
979 GC_clear_mark_bit(curr);
980 DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
982 ITERATE_DL_HASHTBL_END(curr, prev)
985 /* Called with held lock (but the world is running). */
986 /* Cause disappearing links to disappear and unreachable objects to be */
987 /* enqueued for finalization. */
988 GC_INNER void GC_finalize(void)
990 struct finalizable_object * curr_fo, * prev_fo, * next_fo;
993 size_t fo_size = log_fo_table_size == -1 ? 0 :
994 (size_t)1 << log_fo_table_size;
996 GC_ASSERT(I_HOLD_LOCK());
997 # ifndef SMALL_CONFIG
998 /* Save current GC_[dl/ll]_entries value for stats printing */
999 GC_old_dl_entries = GC_dl_hashtbl.entries;
1000 # ifndef GC_LONG_REFS_NOT_NEEDED
1001 GC_old_ll_entries = GC_ll_hashtbl.entries;
1005 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
1006 GC_mark_togglerefs();
1008 GC_make_disappearing_links_disappear(&GC_dl_hashtbl);
1010 /* Mark all objects reachable via chains of 1 or more pointers */
1011 /* from finalizable objects. */
1012 GC_ASSERT(GC_mark_state == MS_NONE);
1013 for (i = 0; i < fo_size; i++) {
1014 for (curr_fo = GC_fnlz_roots.fo_head[i];
1015 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
1016 GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
1017 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1018 if (!GC_is_marked(real_ptr)) {
1019 GC_MARKED_FOR_FINALIZATION(real_ptr);
1020 GC_MARK_FO(real_ptr, curr_fo -> fo_mark_proc);
1021 if (GC_is_marked(real_ptr)) {
1022 WARN("Finalization cycle involving %p\n", real_ptr);
1027 /* Enqueue for finalization all objects that are still */
1029 GC_bytes_finalized = 0;
1030 for (i = 0; i < fo_size; i++) {
1031 curr_fo = GC_fnlz_roots.fo_head[i];
1033 while (curr_fo != 0) {
1034 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1035 if (!GC_is_marked(real_ptr)) {
1036 if (!GC_java_finalization) {
1037 GC_set_mark_bit(real_ptr);
1039 /* Delete from hash table */
1040 next_fo = fo_next(curr_fo);
1041 if (NULL == prev_fo) {
1042 GC_fnlz_roots.fo_head[i] = next_fo;
1044 fo_set_next(prev_fo, next_fo);
1047 if (GC_object_finalized_proc)
1048 GC_object_finalized_proc(real_ptr);
1050 /* Add to list of objects awaiting finalization. */
1051 fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1052 SET_FINALIZE_NOW(curr_fo);
1053 /* unhide object pointer so any future collections will */
1055 curr_fo -> fo_hidden_base =
1056 (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1057 GC_bytes_finalized +=
1058 curr_fo -> fo_object_size
1059 + sizeof(struct finalizable_object);
1060 GC_ASSERT(GC_is_marked(GC_base(curr_fo)));
1064 curr_fo = fo_next(curr_fo);
1069 if (GC_java_finalization) {
1070 /* make sure we mark everything reachable from objects finalized
1071 using the no_order mark_proc */
1072 for (curr_fo = GC_fnlz_roots.finalize_now;
1073 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
1074 real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1075 if (!GC_is_marked(real_ptr)) {
1076 if (curr_fo -> fo_mark_proc == GC_null_finalize_mark_proc) {
1077 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1079 if (curr_fo -> fo_mark_proc != GC_unreachable_finalize_mark_proc) {
1080 GC_set_mark_bit(real_ptr);
1085 /* now revive finalize-when-unreachable objects reachable from
1086 other finalizable objects */
1087 if (need_unreachable_finalization) {
1088 curr_fo = GC_fnlz_roots.finalize_now;
1089 # if defined(GC_ASSERTIONS) || defined(LINT2)
1090 if (curr_fo != NULL && log_fo_table_size < 0)
1091 ABORT("log_size is negative");
1094 while (curr_fo != NULL) {
1095 next_fo = fo_next(curr_fo);
1096 if (curr_fo -> fo_mark_proc == GC_unreachable_finalize_mark_proc) {
1097 real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1098 if (!GC_is_marked(real_ptr)) {
1099 GC_set_mark_bit(real_ptr);
1101 if (NULL == prev_fo) {
1102 SET_FINALIZE_NOW(next_fo);
1104 fo_set_next(prev_fo, next_fo);
1106 curr_fo -> fo_hidden_base =
1107 GC_HIDE_POINTER(curr_fo -> fo_hidden_base);
1108 GC_bytes_finalized -=
1109 curr_fo->fo_object_size + sizeof(struct finalizable_object);
1111 i = HASH2(real_ptr, log_fo_table_size);
1112 fo_set_next(curr_fo, GC_fnlz_roots.fo_head[i]);
1114 GC_fnlz_roots.fo_head[i] = curr_fo;
1124 GC_remove_dangling_disappearing_links(&GC_dl_hashtbl);
1125 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
1126 GC_clear_togglerefs();
1128 # ifndef GC_LONG_REFS_NOT_NEEDED
1129 GC_make_disappearing_links_disappear(&GC_ll_hashtbl);
1130 GC_remove_dangling_disappearing_links(&GC_ll_hashtbl);
1133 if (GC_fail_count) {
1134 /* Don't prevent running finalizers if there has been an allocation */
1135 /* failure recently. */
1137 GC_reset_finalizer_nested();
1139 GC_finalizer_nested = 0;
1144 #ifndef JAVA_FINALIZATION_NOT_NEEDED
1146 /* Enqueue all remaining finalizers to be run. */
1147 STATIC void GC_enqueue_all_finalizers(void)
1149 struct finalizable_object * next_fo;
1153 GC_ASSERT(I_HOLD_LOCK());
1154 fo_size = log_fo_table_size == -1 ? 0 : 1 << log_fo_table_size;
1155 GC_bytes_finalized = 0;
1156 for (i = 0; i < fo_size; i++) {
1157 struct finalizable_object * curr_fo = GC_fnlz_roots.fo_head[i];
1159 GC_fnlz_roots.fo_head[i] = NULL;
1160 while (curr_fo != NULL) {
1161 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1163 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1164 GC_set_mark_bit(real_ptr);
1166 next_fo = fo_next(curr_fo);
1168 /* Add to list of objects awaiting finalization. */
1169 fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1170 SET_FINALIZE_NOW(curr_fo);
1172 /* unhide object pointer so any future collections will */
1174 curr_fo -> fo_hidden_base =
1175 (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1176 GC_bytes_finalized +=
1177 curr_fo -> fo_object_size + sizeof(struct finalizable_object);
1181 GC_fo_entries = 0; /* all entries deleted from the hash table */
1184 /* Invoke all remaining finalizers that haven't yet been run.
1185 * This is needed for strict compliance with the Java standard,
1186 * which can make the runtime guarantee that all finalizers are run.
1187 * Unfortunately, the Java standard implies we have to keep running
1188 * finalizers until there are no more left, a potential infinite loop.
1190 * Note that this is even more dangerous than the usual Java
1191 * finalizers, in that objects reachable from static variables
1192 * may have been finalized when these finalizers are run.
1193 * Finalizers run at this point must be prepared to deal with a
1194 * mostly broken world.
1195 * This routine is externally callable, so is called without
1196 * the allocation lock.
1198 GC_API void GC_CALL GC_finalize_all(void)
1203 while (GC_fo_entries > 0) {
1204 GC_enqueue_all_finalizers();
1206 GC_invoke_finalizers();
1207 /* Running the finalizers in this thread is arguably not a good */
1208 /* idea when we should be notifying another thread to run them. */
1209 /* But otherwise we don't have a great way to wait for them to */
1216 #endif /* !JAVA_FINALIZATION_NOT_NEEDED */
1218 /* Returns true if it is worth calling GC_invoke_finalizers. (Useful if */
1219 /* finalizers can only be called from some kind of "safe state" and */
1220 /* getting into that safe state is expensive.) */
1221 GC_API int GC_CALL GC_should_invoke_finalizers(void)
1223 # ifdef AO_HAVE_load
1224 return AO_load((volatile AO_t *)&GC_fnlz_roots.finalize_now) != 0;
1226 return GC_fnlz_roots.finalize_now != NULL;
1227 # endif /* !THREADS */
1230 /* Invoke finalizers for all objects that are ready to be finalized. */
1231 /* Should be called without allocation lock. */
1232 GC_API int GC_CALL GC_invoke_finalizers(void)
1235 word bytes_freed_before = 0; /* initialized to prevent warning. */
1238 while (GC_should_invoke_finalizers()) {
1239 struct finalizable_object * curr_fo;
1245 bytes_freed_before = GC_bytes_freed;
1246 /* Don't do this outside, since we need the lock. */
1248 curr_fo = GC_fnlz_roots.finalize_now;
1250 if (curr_fo != NULL)
1251 SET_FINALIZE_NOW(fo_next(curr_fo));
1253 if (curr_fo == 0) break;
1255 GC_fnlz_roots.finalize_now = fo_next(curr_fo);
1257 fo_set_next(curr_fo, 0);
1258 (*(curr_fo -> fo_fn))((ptr_t)(curr_fo -> fo_hidden_base),
1259 curr_fo -> fo_client_data);
1260 curr_fo -> fo_client_data = 0;
1262 /* Explicit freeing of curr_fo is probably a bad idea. */
1263 /* It throws off accounting if nearly all objects are */
1264 /* finalizable. Otherwise it should not matter. */
1266 /* bytes_freed_before is initialized whenever count != 0 */
1268 # if defined(THREADS) && !defined(THREAD_SANITIZER)
1269 /* A quick check whether some memory was freed. */
1270 /* The race with GC_free() is safe to be ignored */
1271 /* because we only need to know if the current */
1272 /* thread has deallocated something. */
1273 && bytes_freed_before != GC_bytes_freed
1277 GC_finalizer_bytes_freed += (GC_bytes_freed - bytes_freed_before);
1283 static word last_finalizer_notification = 0;
1285 GC_INNER void GC_notify_or_invoke_finalizers(void)
1287 GC_finalizer_notifier_proc notifier_fn = 0;
1288 # if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1289 static word last_back_trace_gc_no = 1; /* Skip first one. */
1293 # if defined(THREADS) && !defined(KEEP_BACK_PTRS) \
1294 && !defined(MAKE_BACK_GRAPH)
1295 /* Quick check (while unlocked) for an empty finalization queue. */
1296 if (!GC_should_invoke_finalizers())
1301 /* This is a convenient place to generate backtraces if appropriate, */
1302 /* since that code is not callable with the allocation lock. */
1303 # if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1304 if (GC_gc_no > last_back_trace_gc_no) {
1305 # ifdef KEEP_BACK_PTRS
1307 /* Stops when GC_gc_no wraps; that's OK. */
1308 last_back_trace_gc_no = (word)(-1); /* disable others. */
1309 for (i = 0; i < GC_backtraces; ++i) {
1310 /* FIXME: This tolerates concurrent heap mutation, */
1311 /* which may cause occasional mysterious results. */
1312 /* We need to release the GC lock, since GC_print_callers */
1313 /* acquires it. It probably shouldn't. */
1315 GC_generate_random_backtrace_no_gc();
1318 last_back_trace_gc_no = GC_gc_no;
1320 # ifdef MAKE_BACK_GRAPH
1321 if (GC_print_back_height) {
1322 GC_print_back_graph_stats();
1327 if (NULL == GC_fnlz_roots.finalize_now) {
1332 if (!GC_finalize_on_demand) {
1333 unsigned char *pnested = GC_check_finalizer_nested();
1335 /* Skip GC_invoke_finalizers() if nested */
1336 if (pnested != NULL) {
1337 (void) GC_invoke_finalizers();
1338 *pnested = 0; /* Reset since no more finalizers. */
1340 GC_ASSERT(NULL == GC_fnlz_roots.finalize_now);
1341 # endif /* Otherwise GC can run concurrently and add more */
1346 /* These variables require synchronization to avoid data races. */
1347 if (last_finalizer_notification != GC_gc_no) {
1348 last_finalizer_notification = GC_gc_no;
1349 notifier_fn = GC_finalizer_notifier;
1352 if (notifier_fn != 0)
1353 (*notifier_fn)(); /* Invoke the notifier */
1356 #ifndef SMALL_CONFIG
1357 # ifndef GC_LONG_REFS_NOT_NEEDED
1358 # define IF_LONG_REFS_PRESENT_ELSE(x,y) (x)
1360 # define IF_LONG_REFS_PRESENT_ELSE(x,y) (y)
1363 GC_INNER void GC_print_finalization_stats(void)
1365 struct finalizable_object *fo;
1366 unsigned long ready = 0;
1368 GC_log_printf("%lu finalization entries;"
1369 " %lu/%lu short/long disappearing links alive\n",
1370 (unsigned long)GC_fo_entries,
1371 (unsigned long)GC_dl_hashtbl.entries,
1372 (unsigned long)IF_LONG_REFS_PRESENT_ELSE(
1373 GC_ll_hashtbl.entries, 0));
1375 for (fo = GC_fnlz_roots.finalize_now; fo != NULL; fo = fo_next(fo))
1377 GC_log_printf("%lu finalization-ready objects;"
1378 " %ld/%ld short/long links cleared\n",
1380 (long)GC_old_dl_entries - (long)GC_dl_hashtbl.entries,
1381 (long)IF_LONG_REFS_PRESENT_ELSE(
1382 GC_old_ll_entries - GC_ll_hashtbl.entries, 0));
1384 #endif /* !SMALL_CONFIG */
1386 #endif /* !GC_NO_FINALIZATION */