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 /* Assume the lock is held. */
260 GC_INLINE struct disappearing_link *GC_unregister_disappearing_link_inner(
261 struct dl_hashtbl_s *dl_hashtbl, void **link)
263 struct disappearing_link *curr_dl;
264 struct disappearing_link *prev_dl = NULL;
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 if (dl_hashtbl->log_size == -1)
535 return GC_NOT_FOUND; /* prevent integer shift by a negative amount */
537 /* Find current link. */
538 curr_index = HASH2(link, dl_hashtbl -> log_size);
539 curr_hidden_link = GC_HIDE_POINTER(link);
541 for (curr_dl = dl_hashtbl -> head[curr_index]; curr_dl;
542 curr_dl = dl_next(curr_dl)) {
543 if (curr_dl -> dl_hidden_link == curr_hidden_link)
548 if (NULL == curr_dl) {
552 if (link == new_link) {
553 return GC_SUCCESS; /* Nothing to do. */
556 /* link found; now check new_link not present. */
557 new_index = HASH2(new_link, dl_hashtbl -> log_size);
558 new_hidden_link = GC_HIDE_POINTER(new_link);
559 for (new_dl = dl_hashtbl -> head[new_index]; new_dl;
560 new_dl = dl_next(new_dl)) {
561 if (new_dl -> dl_hidden_link == new_hidden_link) {
562 /* Target already registered; bail. */
567 /* Remove from old, add to new, update link. */
568 if (NULL == prev_dl) {
569 dl_hashtbl -> head[curr_index] = dl_next(curr_dl);
571 dl_set_next(prev_dl, dl_next(curr_dl));
573 curr_dl -> dl_hidden_link = new_hidden_link;
574 dl_set_next(curr_dl, dl_hashtbl -> head[new_index]);
575 dl_hashtbl -> head[new_index] = curr_dl;
579 GC_API int GC_CALL GC_move_disappearing_link(void **link, void **new_link)
584 if (((word)new_link & (ALIGNMENT-1)) != 0
585 || !NONNULL_ARG_NOT_NULL(new_link))
586 ABORT("Bad new_link arg to GC_move_disappearing_link");
587 if (((word)link & (ALIGNMENT-1)) != 0)
588 return GC_NOT_FOUND; /* Nothing to do. */
591 result = GC_move_disappearing_link_inner(&GC_dl_hashtbl, link, new_link);
596 # ifndef GC_LONG_REFS_NOT_NEEDED
597 GC_API int GC_CALL GC_move_long_link(void **link, void **new_link)
602 if (((word)new_link & (ALIGNMENT-1)) != 0
603 || !NONNULL_ARG_NOT_NULL(new_link))
604 ABORT("Bad new_link arg to GC_move_long_link");
605 if (((word)link & (ALIGNMENT-1)) != 0)
606 return GC_NOT_FOUND; /* Nothing to do. */
609 result = GC_move_disappearing_link_inner(&GC_ll_hashtbl, link, new_link);
613 # endif /* !GC_LONG_REFS_NOT_NEEDED */
614 #endif /* !GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED */
616 /* Possible finalization_marker procedures. Note that mark stack */
617 /* overflow is handled by the caller, and is not a disaster. */
618 STATIC void GC_normal_finalize_mark_proc(ptr_t p)
622 PUSH_OBJ(p, hhdr, GC_mark_stack_top,
623 &(GC_mark_stack[GC_mark_stack_size]));
626 /* This only pays very partial attention to the mark descriptor. */
627 /* It does the right thing for normal and atomic objects, and treats */
628 /* most others as normal. */
629 STATIC void GC_ignore_self_finalize_mark_proc(ptr_t p)
632 word descr = hhdr -> hb_descr;
635 ptr_t target_limit = p + hhdr -> hb_sz - 1;
637 if ((descr & GC_DS_TAGS) == GC_DS_LENGTH) {
638 scan_limit = p + descr - sizeof(word);
640 scan_limit = target_limit + 1 - sizeof(word);
642 for (q = p; (word)q <= (word)scan_limit; q += ALIGNMENT) {
645 if (r < (word)p || r > (word)target_limit) {
646 GC_PUSH_ONE_HEAP(r, q, GC_mark_stack_top);
651 STATIC void GC_null_finalize_mark_proc(ptr_t p GC_ATTR_UNUSED) {}
653 /* Possible finalization_marker procedures. Note that mark stack */
654 /* overflow is handled by the caller, and is not a disaster. */
656 /* GC_unreachable_finalize_mark_proc is an alias for normal marking, */
657 /* but it is explicitly tested for, and triggers different */
658 /* behavior. Objects registered in this way are not finalized */
659 /* if they are reachable by other finalizable objects, even if those */
660 /* other objects specify no ordering. */
661 STATIC void GC_unreachable_finalize_mark_proc(ptr_t p)
663 GC_normal_finalize_mark_proc(p);
666 /* Register a finalization function. See gc.h for details. */
667 /* The last parameter is a procedure that determines */
668 /* marking for finalization ordering. Any objects marked */
669 /* by that procedure will be guaranteed to not have been */
670 /* finalized when this finalizer is invoked. */
671 STATIC void GC_register_finalizer_inner(void * obj,
672 GC_finalization_proc fn, void *cd,
673 GC_finalization_proc *ofn, void **ocd,
674 finalization_mark_proc mp)
676 struct finalizable_object * curr_fo;
678 struct finalizable_object *new_fo = 0;
679 hdr *hhdr = NULL; /* initialized to prevent warning. */
682 if (EXPECT(GC_find_leak, FALSE)) return;
684 if (log_fo_table_size == -1
685 || GC_fo_entries > ((word)1 << log_fo_table_size)) {
686 GC_grow_table((struct hash_chain_entry ***)&GC_fnlz_roots.fo_head,
687 &log_fo_table_size, &GC_fo_entries);
689 if (log_fo_table_size < 0) ABORT("log_size is negative");
691 GC_COND_LOG_PRINTF("Grew fo table to %u entries\n",
692 1 << (unsigned)log_fo_table_size);
694 /* in the THREADS case we hold allocation lock. */
696 struct finalizable_object *prev_fo = NULL;
699 index = HASH2(obj, log_fo_table_size);
700 curr_fo = GC_fnlz_roots.fo_head[index];
701 while (curr_fo != 0) {
702 GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
703 if (curr_fo -> fo_hidden_base == GC_HIDE_POINTER(obj)) {
704 /* Interruption by a signal in the middle of this */
705 /* should be safe. The client may see only *ocd */
706 /* updated, but we'll declare that to be his problem. */
707 if (ocd) *ocd = (void *) (curr_fo -> fo_client_data);
708 if (ofn) *ofn = curr_fo -> fo_fn;
709 /* Delete the structure for obj. */
711 GC_fnlz_roots.fo_head[index] = fo_next(curr_fo);
713 fo_set_next(prev_fo, fo_next(curr_fo));
717 /* May not happen if we get a signal. But a high */
718 /* estimate will only make the table larger than */
720 # if !defined(THREADS) && !defined(DBG_HDRS_ALL)
721 GC_free((void *)curr_fo);
724 curr_fo -> fo_fn = fn;
725 curr_fo -> fo_client_data = (ptr_t)cd;
726 curr_fo -> fo_mark_proc = mp;
727 /* Reinsert it. We deleted it first to maintain */
728 /* consistency in the event of a signal. */
730 GC_fnlz_roots.fo_head[index] = curr_fo;
732 fo_set_next(prev_fo, curr_fo);
736 # ifndef DBG_HDRS_ALL
737 if (EXPECT(new_fo != 0, FALSE)) {
738 /* Free unused new_fo returned by GC_oom_fn() */
739 GC_free((void *)new_fo);
745 curr_fo = fo_next(curr_fo);
747 if (EXPECT(new_fo != 0, FALSE)) {
748 /* new_fo is returned by GC_oom_fn(). */
751 if (NULL == hhdr) ABORT("Bad hhdr in GC_register_finalizer_inner");
762 if (EXPECT(0 == hhdr, FALSE)) {
763 /* We won't collect it, hence finalizer wouldn't be run. */
769 new_fo = (struct finalizable_object *)
770 GC_INTERNAL_MALLOC(sizeof(struct finalizable_object),NORMAL);
771 if (EXPECT(new_fo != 0, TRUE))
775 new_fo = (struct finalizable_object *)
776 (*oom_fn)(sizeof(struct finalizable_object));
778 /* No enough memory. *ocd and *ofn remains unchanged. */
781 /* It's not likely we'll make it here, but ... */
783 /* Recalculate index since the table may grow and */
784 /* check again that our finalizer is not in the table. */
786 GC_ASSERT(GC_size(new_fo) >= sizeof(struct finalizable_object));
789 new_fo -> fo_hidden_base = GC_HIDE_POINTER(obj);
790 new_fo -> fo_fn = fn;
791 new_fo -> fo_client_data = (ptr_t)cd;
792 new_fo -> fo_object_size = hhdr -> hb_sz;
793 new_fo -> fo_mark_proc = mp;
794 fo_set_next(new_fo, GC_fnlz_roots.fo_head[index]);
796 GC_fnlz_roots.fo_head[index] = new_fo;
800 GC_API void GC_CALL GC_register_finalizer(void * obj,
801 GC_finalization_proc fn, void * cd,
802 GC_finalization_proc *ofn, void ** ocd)
804 GC_register_finalizer_inner(obj, fn, cd, ofn,
805 ocd, GC_normal_finalize_mark_proc);
808 GC_API void GC_CALL GC_register_finalizer_ignore_self(void * obj,
809 GC_finalization_proc fn, void * cd,
810 GC_finalization_proc *ofn, void ** ocd)
812 GC_register_finalizer_inner(obj, fn, cd, ofn,
813 ocd, GC_ignore_self_finalize_mark_proc);
816 GC_API void GC_CALL GC_register_finalizer_no_order(void * obj,
817 GC_finalization_proc fn, void * cd,
818 GC_finalization_proc *ofn, void ** ocd)
820 GC_register_finalizer_inner(obj, fn, cd, ofn,
821 ocd, GC_null_finalize_mark_proc);
824 static GC_bool need_unreachable_finalization = FALSE;
825 /* Avoid the work if this isn't used. */
827 GC_API void GC_CALL GC_register_finalizer_unreachable(void * obj,
828 GC_finalization_proc fn, void * cd,
829 GC_finalization_proc *ofn, void ** ocd)
831 need_unreachable_finalization = TRUE;
832 GC_ASSERT(GC_java_finalization);
833 GC_register_finalizer_inner(obj, fn, cd, ofn,
834 ocd, GC_unreachable_finalize_mark_proc);
838 STATIC void GC_dump_finalization_links(
839 const struct dl_hashtbl_s *dl_hashtbl)
841 size_t dl_size = dl_hashtbl->log_size == -1 ? 0 :
842 (size_t)1 << dl_hashtbl->log_size;
845 for (i = 0; i < dl_size; i++) {
846 struct disappearing_link *curr_dl;
848 for (curr_dl = dl_hashtbl -> head[i]; curr_dl != 0;
849 curr_dl = dl_next(curr_dl)) {
850 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_obj);
851 ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_link);
853 GC_printf("Object: %p, link: %p\n",
854 (void *)real_ptr, (void *)real_link);
859 GC_API void GC_CALL GC_dump_finalization(void)
861 struct finalizable_object * curr_fo;
862 size_t fo_size = log_fo_table_size == -1 ? 0 :
863 (size_t)1 << log_fo_table_size;
866 GC_printf("Disappearing (short) links:\n");
867 GC_dump_finalization_links(&GC_dl_hashtbl);
868 # ifndef GC_LONG_REFS_NOT_NEEDED
869 GC_printf("Disappearing long links:\n");
870 GC_dump_finalization_links(&GC_ll_hashtbl);
872 GC_printf("Finalizers:\n");
873 for (i = 0; i < fo_size; i++) {
874 for (curr_fo = GC_fnlz_roots.fo_head[i];
875 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
876 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
878 GC_printf("Finalizable object: %p\n", (void *)real_ptr);
882 #endif /* !NO_DEBUGGING */
885 STATIC word GC_old_dl_entries = 0; /* for stats printing */
886 # ifndef GC_LONG_REFS_NOT_NEEDED
887 STATIC word GC_old_ll_entries = 0;
889 #endif /* !SMALL_CONFIG */
892 /* Global variables to minimize the level of recursion when a client */
893 /* finalizer allocates memory. */
894 STATIC int GC_finalizer_nested = 0;
895 /* Only the lowest byte is used, the rest is */
896 /* padding for proper global data alignment */
897 /* required for some compilers (like Watcom). */
898 STATIC unsigned GC_finalizer_skipped = 0;
900 /* Checks and updates the level of finalizers recursion. */
901 /* Returns NULL if GC_invoke_finalizers() should not be called by the */
902 /* collector (to minimize the risk of a deep finalizers recursion), */
903 /* otherwise returns a pointer to GC_finalizer_nested. */
904 STATIC unsigned char *GC_check_finalizer_nested(void)
906 unsigned nesting_level = *(unsigned char *)&GC_finalizer_nested;
908 /* We are inside another GC_invoke_finalizers(). */
909 /* Skip some implicitly-called GC_invoke_finalizers() */
910 /* depending on the nesting (recursion) level. */
911 if (++GC_finalizer_skipped < (1U << nesting_level)) return NULL;
912 GC_finalizer_skipped = 0;
914 *(char *)&GC_finalizer_nested = (char)(nesting_level + 1);
915 return (unsigned char *)&GC_finalizer_nested;
919 #define ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr_dl, prev_dl) \
922 size_t dl_size = dl_hashtbl->log_size == -1 ? 0 : \
923 (size_t)1 << dl_hashtbl->log_size; \
924 for (i = 0; i < dl_size; i++) { \
925 struct disappearing_link *prev_dl = NULL; \
926 curr_dl = dl_hashtbl -> head[i]; \
929 #define ITERATE_DL_HASHTBL_END(curr_dl, prev_dl) \
931 curr_dl = dl_next(curr_dl); \
936 #define DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr_dl, prev_dl, next_dl) \
938 next_dl = dl_next(curr_dl); \
939 if (NULL == prev_dl) { \
940 dl_hashtbl -> head[i] = next_dl; \
942 dl_set_next(prev_dl, next_dl); \
944 GC_clear_mark_bit(curr_dl); \
945 dl_hashtbl -> entries--; \
950 GC_INLINE void GC_make_disappearing_links_disappear(
951 struct dl_hashtbl_s* dl_hashtbl)
953 struct disappearing_link *curr, *next;
955 ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
956 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_obj);
957 ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_link);
959 if (!GC_is_marked(real_ptr)) {
960 *(word *)real_link = 0;
961 GC_clear_mark_bit(curr);
962 DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
964 ITERATE_DL_HASHTBL_END(curr, prev)
967 GC_INLINE void GC_remove_dangling_disappearing_links(
968 struct dl_hashtbl_s* dl_hashtbl)
970 struct disappearing_link *curr, *next;
972 ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
974 (ptr_t)GC_base(GC_REVEAL_POINTER(curr->dl_hidden_link));
976 if (NULL != real_link && !GC_is_marked(real_link)) {
977 GC_clear_mark_bit(curr);
978 DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
980 ITERATE_DL_HASHTBL_END(curr, prev)
983 /* Called with held lock (but the world is running). */
984 /* Cause disappearing links to disappear and unreachable objects to be */
985 /* enqueued for finalization. */
986 GC_INNER void GC_finalize(void)
988 struct finalizable_object * curr_fo, * prev_fo, * next_fo;
991 size_t fo_size = log_fo_table_size == -1 ? 0 :
992 (size_t)1 << log_fo_table_size;
994 # ifndef SMALL_CONFIG
995 /* Save current GC_[dl/ll]_entries value for stats printing */
996 GC_old_dl_entries = GC_dl_hashtbl.entries;
997 # ifndef GC_LONG_REFS_NOT_NEEDED
998 GC_old_ll_entries = GC_ll_hashtbl.entries;
1002 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
1003 GC_mark_togglerefs();
1005 GC_make_disappearing_links_disappear(&GC_dl_hashtbl);
1007 /* Mark all objects reachable via chains of 1 or more pointers */
1008 /* from finalizable objects. */
1009 GC_ASSERT(GC_mark_state == MS_NONE);
1010 for (i = 0; i < fo_size; i++) {
1011 for (curr_fo = GC_fnlz_roots.fo_head[i];
1012 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
1013 GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
1014 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1015 if (!GC_is_marked(real_ptr)) {
1016 GC_MARKED_FOR_FINALIZATION(real_ptr);
1017 GC_MARK_FO(real_ptr, curr_fo -> fo_mark_proc);
1018 if (GC_is_marked(real_ptr)) {
1019 WARN("Finalization cycle involving %p\n", real_ptr);
1024 /* Enqueue for finalization all objects that are still */
1026 GC_bytes_finalized = 0;
1027 for (i = 0; i < fo_size; i++) {
1028 curr_fo = GC_fnlz_roots.fo_head[i];
1030 while (curr_fo != 0) {
1031 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1032 if (!GC_is_marked(real_ptr)) {
1033 if (!GC_java_finalization) {
1034 GC_set_mark_bit(real_ptr);
1036 /* Delete from hash table */
1037 next_fo = fo_next(curr_fo);
1038 if (NULL == prev_fo) {
1039 GC_fnlz_roots.fo_head[i] = next_fo;
1041 fo_set_next(prev_fo, next_fo);
1044 if (GC_object_finalized_proc)
1045 GC_object_finalized_proc(real_ptr);
1047 /* Add to list of objects awaiting finalization. */
1048 fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1049 SET_FINALIZE_NOW(curr_fo);
1050 /* unhide object pointer so any future collections will */
1052 curr_fo -> fo_hidden_base =
1053 (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1054 GC_bytes_finalized +=
1055 curr_fo -> fo_object_size
1056 + sizeof(struct finalizable_object);
1057 GC_ASSERT(GC_is_marked(GC_base(curr_fo)));
1061 curr_fo = fo_next(curr_fo);
1066 if (GC_java_finalization) {
1067 /* make sure we mark everything reachable from objects finalized
1068 using the no_order mark_proc */
1069 for (curr_fo = GC_fnlz_roots.finalize_now;
1070 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
1071 real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1072 if (!GC_is_marked(real_ptr)) {
1073 if (curr_fo -> fo_mark_proc == GC_null_finalize_mark_proc) {
1074 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1076 if (curr_fo -> fo_mark_proc != GC_unreachable_finalize_mark_proc) {
1077 GC_set_mark_bit(real_ptr);
1082 /* now revive finalize-when-unreachable objects reachable from
1083 other finalizable objects */
1084 if (need_unreachable_finalization) {
1085 curr_fo = GC_fnlz_roots.finalize_now;
1086 # if defined(GC_ASSERTIONS) || defined(LINT2)
1087 if (curr_fo != NULL && log_fo_table_size < 0)
1088 ABORT("log_size is negative");
1091 while (curr_fo != NULL) {
1092 next_fo = fo_next(curr_fo);
1093 if (curr_fo -> fo_mark_proc == GC_unreachable_finalize_mark_proc) {
1094 real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1095 if (!GC_is_marked(real_ptr)) {
1096 GC_set_mark_bit(real_ptr);
1098 if (NULL == prev_fo) {
1099 SET_FINALIZE_NOW(next_fo);
1101 fo_set_next(prev_fo, next_fo);
1103 curr_fo -> fo_hidden_base =
1104 GC_HIDE_POINTER(curr_fo -> fo_hidden_base);
1105 GC_bytes_finalized -=
1106 curr_fo->fo_object_size + sizeof(struct finalizable_object);
1108 i = HASH2(real_ptr, log_fo_table_size);
1109 fo_set_next(curr_fo, GC_fnlz_roots.fo_head[i]);
1111 GC_fnlz_roots.fo_head[i] = curr_fo;
1121 GC_remove_dangling_disappearing_links(&GC_dl_hashtbl);
1122 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
1123 GC_clear_togglerefs();
1125 # ifndef GC_LONG_REFS_NOT_NEEDED
1126 GC_make_disappearing_links_disappear(&GC_ll_hashtbl);
1127 GC_remove_dangling_disappearing_links(&GC_ll_hashtbl);
1130 if (GC_fail_count) {
1131 /* Don't prevent running finalizers if there has been an allocation */
1132 /* failure recently. */
1134 GC_reset_finalizer_nested();
1136 GC_finalizer_nested = 0;
1141 #ifndef JAVA_FINALIZATION_NOT_NEEDED
1143 /* Enqueue all remaining finalizers to be run - Assumes lock is held. */
1144 STATIC void GC_enqueue_all_finalizers(void)
1146 struct finalizable_object * next_fo;
1150 fo_size = log_fo_table_size == -1 ? 0 : 1 << log_fo_table_size;
1151 GC_bytes_finalized = 0;
1152 for (i = 0; i < fo_size; i++) {
1153 struct finalizable_object * curr_fo = GC_fnlz_roots.fo_head[i];
1155 GC_fnlz_roots.fo_head[i] = NULL;
1156 while (curr_fo != NULL) {
1157 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1159 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1160 GC_set_mark_bit(real_ptr);
1162 next_fo = fo_next(curr_fo);
1164 /* Add to list of objects awaiting finalization. */
1165 fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1166 SET_FINALIZE_NOW(curr_fo);
1168 /* unhide object pointer so any future collections will */
1170 curr_fo -> fo_hidden_base =
1171 (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1172 GC_bytes_finalized +=
1173 curr_fo -> fo_object_size + sizeof(struct finalizable_object);
1177 GC_fo_entries = 0; /* all entries deleted from the hash table */
1180 /* Invoke all remaining finalizers that haven't yet been run.
1181 * This is needed for strict compliance with the Java standard,
1182 * which can make the runtime guarantee that all finalizers are run.
1183 * Unfortunately, the Java standard implies we have to keep running
1184 * finalizers until there are no more left, a potential infinite loop.
1186 * Note that this is even more dangerous than the usual Java
1187 * finalizers, in that objects reachable from static variables
1188 * may have been finalized when these finalizers are run.
1189 * Finalizers run at this point must be prepared to deal with a
1190 * mostly broken world.
1191 * This routine is externally callable, so is called without
1192 * the allocation lock.
1194 GC_API void GC_CALL GC_finalize_all(void)
1199 while (GC_fo_entries > 0) {
1200 GC_enqueue_all_finalizers();
1202 GC_invoke_finalizers();
1203 /* Running the finalizers in this thread is arguably not a good */
1204 /* idea when we should be notifying another thread to run them. */
1205 /* But otherwise we don't have a great way to wait for them to */
1212 #endif /* !JAVA_FINALIZATION_NOT_NEEDED */
1214 /* Returns true if it is worth calling GC_invoke_finalizers. (Useful if */
1215 /* finalizers can only be called from some kind of "safe state" and */
1216 /* getting into that safe state is expensive.) */
1217 GC_API int GC_CALL GC_should_invoke_finalizers(void)
1219 # ifdef AO_HAVE_load
1220 return AO_load((volatile AO_t *)&GC_fnlz_roots.finalize_now) != 0;
1222 return GC_fnlz_roots.finalize_now != NULL;
1223 # endif /* !THREADS */
1226 /* Invoke finalizers for all objects that are ready to be finalized. */
1227 /* Should be called without allocation lock. */
1228 GC_API int GC_CALL GC_invoke_finalizers(void)
1231 word bytes_freed_before = 0; /* initialized to prevent warning. */
1234 while (GC_should_invoke_finalizers()) {
1235 struct finalizable_object * curr_fo;
1241 bytes_freed_before = GC_bytes_freed;
1242 /* Don't do this outside, since we need the lock. */
1244 curr_fo = GC_fnlz_roots.finalize_now;
1246 if (curr_fo != NULL)
1247 SET_FINALIZE_NOW(fo_next(curr_fo));
1249 if (curr_fo == 0) break;
1251 GC_fnlz_roots.finalize_now = fo_next(curr_fo);
1253 fo_set_next(curr_fo, 0);
1254 (*(curr_fo -> fo_fn))((ptr_t)(curr_fo -> fo_hidden_base),
1255 curr_fo -> fo_client_data);
1256 curr_fo -> fo_client_data = 0;
1258 /* Explicit freeing of curr_fo is probably a bad idea. */
1259 /* It throws off accounting if nearly all objects are */
1260 /* finalizable. Otherwise it should not matter. */
1262 /* bytes_freed_before is initialized whenever count != 0 */
1264 # if defined(THREADS) && !defined(THREAD_SANITIZER)
1265 /* A quick check whether some memory was freed. */
1266 /* The race with GC_free() is safe to be ignored */
1267 /* because we only need to know if the current */
1268 /* thread has deallocated something. */
1269 && bytes_freed_before != GC_bytes_freed
1273 GC_finalizer_bytes_freed += (GC_bytes_freed - bytes_freed_before);
1279 static word last_finalizer_notification = 0;
1281 GC_INNER void GC_notify_or_invoke_finalizers(void)
1283 GC_finalizer_notifier_proc notifier_fn = 0;
1284 # if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1285 static word last_back_trace_gc_no = 1; /* Skip first one. */
1289 # if defined(THREADS) && !defined(KEEP_BACK_PTRS) \
1290 && !defined(MAKE_BACK_GRAPH)
1291 /* Quick check (while unlocked) for an empty finalization queue. */
1292 if (!GC_should_invoke_finalizers())
1297 /* This is a convenient place to generate backtraces if appropriate, */
1298 /* since that code is not callable with the allocation lock. */
1299 # if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1300 if (GC_gc_no > last_back_trace_gc_no) {
1301 # ifdef KEEP_BACK_PTRS
1303 /* Stops when GC_gc_no wraps; that's OK. */
1304 last_back_trace_gc_no = (word)(-1); /* disable others. */
1305 for (i = 0; i < GC_backtraces; ++i) {
1306 /* FIXME: This tolerates concurrent heap mutation, */
1307 /* which may cause occasional mysterious results. */
1308 /* We need to release the GC lock, since GC_print_callers */
1309 /* acquires it. It probably shouldn't. */
1311 GC_generate_random_backtrace_no_gc();
1314 last_back_trace_gc_no = GC_gc_no;
1316 # ifdef MAKE_BACK_GRAPH
1317 if (GC_print_back_height) {
1318 GC_print_back_graph_stats();
1323 if (NULL == GC_fnlz_roots.finalize_now) {
1328 if (!GC_finalize_on_demand) {
1329 unsigned char *pnested = GC_check_finalizer_nested();
1331 /* Skip GC_invoke_finalizers() if nested */
1332 if (pnested != NULL) {
1333 (void) GC_invoke_finalizers();
1334 *pnested = 0; /* Reset since no more finalizers. */
1336 GC_ASSERT(NULL == GC_fnlz_roots.finalize_now);
1337 # endif /* Otherwise GC can run concurrently and add more */
1342 /* These variables require synchronization to avoid data races. */
1343 if (last_finalizer_notification != GC_gc_no) {
1344 last_finalizer_notification = GC_gc_no;
1345 notifier_fn = GC_finalizer_notifier;
1348 if (notifier_fn != 0)
1349 (*notifier_fn)(); /* Invoke the notifier */
1352 #ifndef SMALL_CONFIG
1353 # ifndef GC_LONG_REFS_NOT_NEEDED
1354 # define IF_LONG_REFS_PRESENT_ELSE(x,y) (x)
1356 # define IF_LONG_REFS_PRESENT_ELSE(x,y) (y)
1359 GC_INNER void GC_print_finalization_stats(void)
1361 struct finalizable_object *fo;
1362 unsigned long ready = 0;
1364 GC_log_printf("%lu finalization entries;"
1365 " %lu/%lu short/long disappearing links alive\n",
1366 (unsigned long)GC_fo_entries,
1367 (unsigned long)GC_dl_hashtbl.entries,
1368 (unsigned long)IF_LONG_REFS_PRESENT_ELSE(
1369 GC_ll_hashtbl.entries, 0));
1371 for (fo = GC_fnlz_roots.finalize_now; fo != NULL; fo = fo_next(fo))
1373 GC_log_printf("%lu finalization-ready objects;"
1374 " %ld/%ld short/long links cleared\n",
1376 (long)GC_old_dl_entries - (long)GC_dl_hashtbl.entries,
1377 (long)IF_LONG_REFS_PRESENT_ELSE(
1378 GC_old_ll_entries - GC_ll_hashtbl.entries, 0));
1380 #endif /* !SMALL_CONFIG */
1382 #endif /* !GC_NO_FINALIZATION */