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 /* Double the size of a hash table. *size_ptr is the log of its current */
103 /* size. May be a no-op. */
104 /* *table is a pointer to an array of hash headers. If we succeed, we */
105 /* update both *table and *log_size_ptr. Lock is held. */
106 STATIC void GC_grow_table(struct hash_chain_entry ***table,
107 signed_word *log_size_ptr)
110 struct hash_chain_entry *p;
111 signed_word log_old_size = *log_size_ptr;
112 signed_word log_new_size = log_old_size + 1;
113 word old_size = log_old_size == -1 ? 0 : (word)1 << log_old_size;
114 word new_size = (word)1 << log_new_size;
115 /* FIXME: Power of 2 size often gets rounded up to one more page. */
116 struct hash_chain_entry **new_table;
118 GC_ASSERT(I_HOLD_LOCK());
119 new_table = (struct hash_chain_entry **)
120 GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
121 (size_t)new_size * sizeof(struct hash_chain_entry *),
123 if (new_table == 0) {
125 ABORT("Insufficient space for initial table allocation");
130 for (i = 0; i < old_size; i++) {
133 ptr_t real_key = (ptr_t)GC_REVEAL_POINTER(p->hidden_key);
134 struct hash_chain_entry *next = p -> next;
135 size_t new_hash = HASH3(real_key, new_size, log_new_size);
137 p -> next = new_table[new_hash];
138 new_table[new_hash] = p;
142 *log_size_ptr = log_new_size;
146 GC_API int GC_CALL GC_register_disappearing_link(void * * link)
150 base = (ptr_t)GC_base(link);
152 ABORT("Bad arg to GC_register_disappearing_link");
153 return(GC_general_register_disappearing_link(link, base));
156 STATIC int GC_register_disappearing_link_inner(
157 struct dl_hashtbl_s *dl_hashtbl, void **link,
158 const void *obj, const char *tbl_log_name)
160 struct disappearing_link *curr_dl;
162 struct disappearing_link * new_dl;
165 if (EXPECT(GC_find_leak, FALSE)) return GC_UNIMPLEMENTED;
167 GC_ASSERT(obj != NULL && GC_base_C(obj) == obj);
168 if (dl_hashtbl -> log_size == -1
169 || dl_hashtbl -> entries > ((word)1 << dl_hashtbl -> log_size)) {
170 GC_grow_table((struct hash_chain_entry ***)&dl_hashtbl -> head,
171 &dl_hashtbl -> log_size);
173 if (dl_hashtbl->log_size < 0) ABORT("log_size is negative");
175 GC_COND_LOG_PRINTF("Grew %s table to %u entries\n", tbl_log_name,
176 1 << (unsigned)dl_hashtbl -> log_size);
178 index = HASH2(link, dl_hashtbl -> log_size);
179 for (curr_dl = dl_hashtbl -> head[index]; curr_dl != 0;
180 curr_dl = dl_next(curr_dl)) {
181 if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
182 curr_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
187 new_dl = (struct disappearing_link *)
188 GC_INTERNAL_MALLOC(sizeof(struct disappearing_link),NORMAL);
190 GC_oom_func oom_fn = GC_oom_fn;
192 new_dl = (struct disappearing_link *)
193 (*oom_fn)(sizeof(struct disappearing_link));
197 /* It's not likely we'll make it here, but ... */
199 /* Recalculate index since the table may grow. */
200 index = HASH2(link, dl_hashtbl -> log_size);
201 /* Check again that our disappearing link not in the table. */
202 for (curr_dl = dl_hashtbl -> head[index]; curr_dl != 0;
203 curr_dl = dl_next(curr_dl)) {
204 if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
205 curr_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
207 # ifndef DBG_HDRS_ALL
208 /* Free unused new_dl returned by GC_oom_fn() */
209 GC_free((void *)new_dl);
215 new_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
216 new_dl -> dl_hidden_link = GC_HIDE_POINTER(link);
217 dl_set_next(new_dl, dl_hashtbl -> head[index]);
218 dl_hashtbl -> head[index] = new_dl;
219 dl_hashtbl -> entries++;
224 GC_API int GC_CALL GC_general_register_disappearing_link(void * * link,
227 if (((word)link & (ALIGNMENT-1)) != 0 || !NONNULL_ARG_NOT_NULL(link))
228 ABORT("Bad arg to GC_general_register_disappearing_link");
229 return GC_register_disappearing_link_inner(&GC_dl_hashtbl, link, obj,
234 # define FREE_DL_ENTRY(curr_dl) dl_set_next(curr_dl, NULL)
236 # define FREE_DL_ENTRY(curr_dl) GC_free(curr_dl)
239 /* Unregisters given link and returns the link entry to free. */
240 /* Assume the lock is held. */
241 GC_INLINE struct disappearing_link *GC_unregister_disappearing_link_inner(
242 struct dl_hashtbl_s *dl_hashtbl, void **link)
244 struct disappearing_link *curr_dl;
245 struct disappearing_link *prev_dl = NULL;
248 if (dl_hashtbl->log_size == -1)
249 return NULL; /* prevent integer shift by a negative amount */
251 index = HASH2(link, dl_hashtbl->log_size);
252 for (curr_dl = dl_hashtbl -> head[index]; curr_dl;
253 curr_dl = dl_next(curr_dl)) {
254 if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
255 /* Remove found entry from the table. */
256 if (NULL == prev_dl) {
257 dl_hashtbl -> head[index] = dl_next(curr_dl);
259 dl_set_next(prev_dl, dl_next(curr_dl));
261 dl_hashtbl -> entries--;
269 GC_API int GC_CALL GC_unregister_disappearing_link(void * * link)
271 struct disappearing_link *curr_dl;
274 if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
277 curr_dl = GC_unregister_disappearing_link_inner(&GC_dl_hashtbl, link);
279 if (NULL == curr_dl) return 0;
280 FREE_DL_ENTRY(curr_dl);
284 /* Toggle-ref support. */
285 #ifndef GC_TOGGLE_REFS_NOT_NEEDED
287 /* Lowest bit is used to distinguish between choices. */
289 GC_hidden_pointer weak_ref;
292 STATIC GC_toggleref_func GC_toggleref_callback = 0;
293 STATIC GCToggleRef *GC_toggleref_arr = NULL;
294 STATIC int GC_toggleref_array_size = 0;
295 STATIC int GC_toggleref_array_capacity = 0;
297 GC_INNER void GC_process_togglerefs(void)
302 GC_ASSERT(I_HOLD_LOCK());
303 for (i = 0; i < GC_toggleref_array_size; ++i) {
304 GCToggleRef r = GC_toggleref_arr[i];
305 void *obj = r.strong_ref;
307 if (((word)obj & 1) != 0) {
308 obj = GC_REVEAL_POINTER(r.weak_ref);
313 switch (GC_toggleref_callback(obj)) {
314 case GC_TOGGLE_REF_DROP:
316 case GC_TOGGLE_REF_STRONG:
317 GC_toggleref_arr[new_size++].strong_ref = obj;
319 case GC_TOGGLE_REF_WEAK:
320 GC_toggleref_arr[new_size++].weak_ref = GC_HIDE_POINTER(obj);
323 ABORT("Bad toggle-ref status returned by callback");
327 if (new_size < GC_toggleref_array_size) {
328 BZERO(&GC_toggleref_arr[new_size],
329 (GC_toggleref_array_size - new_size) * sizeof(GCToggleRef));
330 GC_toggleref_array_size = new_size;
334 STATIC void GC_normal_finalize_mark_proc(ptr_t);
336 static void push_and_mark_object(void *p)
338 GC_normal_finalize_mark_proc((ptr_t)p);
339 while (!GC_mark_stack_empty()) {
340 MARK_FROM_MARK_STACK();
343 if (GC_mark_state != MS_NONE) {
344 while (!GC_mark_some(0)) {
350 STATIC void GC_mark_togglerefs(void)
353 if (NULL == GC_toggleref_arr)
356 /* TODO: Hide GC_toggleref_arr to avoid its marking from roots. */
357 GC_set_mark_bit(GC_toggleref_arr);
358 for (i = 0; i < GC_toggleref_array_size; ++i) {
359 void *obj = GC_toggleref_arr[i].strong_ref;
360 if (obj != NULL && ((word)obj & 1) == 0) {
361 push_and_mark_object(obj);
366 STATIC void GC_clear_togglerefs(void)
369 for (i = 0; i < GC_toggleref_array_size; ++i) {
370 if ((GC_toggleref_arr[i].weak_ref & 1) != 0) {
371 if (!GC_is_marked(GC_REVEAL_POINTER(GC_toggleref_arr[i].weak_ref))) {
372 GC_toggleref_arr[i].weak_ref = 0;
374 /* No need to copy, BDWGC is a non-moving collector. */
380 GC_API void GC_CALL GC_set_toggleref_func(GC_toggleref_func fn)
385 GC_toggleref_callback = fn;
389 GC_API GC_toggleref_func GC_CALL GC_get_toggleref_func(void)
391 GC_toggleref_func fn;
395 fn = GC_toggleref_callback;
400 static GC_bool ensure_toggleref_capacity(int capacity_inc)
402 GC_ASSERT(capacity_inc >= 0);
403 GC_ASSERT(I_HOLD_LOCK());
404 if (NULL == GC_toggleref_arr) {
405 GC_toggleref_array_capacity = 32; /* initial capacity */
406 GC_toggleref_arr = (GCToggleRef *)GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
407 GC_toggleref_array_capacity * sizeof(GCToggleRef),
409 if (NULL == GC_toggleref_arr)
412 if ((unsigned)GC_toggleref_array_size + (unsigned)capacity_inc
413 >= (unsigned)GC_toggleref_array_capacity) {
414 GCToggleRef *new_array;
415 while ((unsigned)GC_toggleref_array_capacity
416 < (unsigned)GC_toggleref_array_size + (unsigned)capacity_inc) {
417 GC_toggleref_array_capacity *= 2;
418 if (GC_toggleref_array_capacity < 0) /* overflow */
422 new_array = (GCToggleRef *)GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
423 GC_toggleref_array_capacity * sizeof(GCToggleRef),
425 if (NULL == new_array)
427 if (EXPECT(GC_toggleref_array_size > 0, TRUE))
428 BCOPY(GC_toggleref_arr, new_array,
429 GC_toggleref_array_size * sizeof(GCToggleRef));
430 GC_INTERNAL_FREE(GC_toggleref_arr);
431 GC_toggleref_arr = new_array;
436 GC_API int GC_CALL GC_toggleref_add(void *obj, int is_strong_ref)
438 int res = GC_SUCCESS;
441 GC_ASSERT(NONNULL_ARG_NOT_NULL(obj));
443 if (GC_toggleref_callback != 0) {
444 if (!ensure_toggleref_capacity(1)) {
447 GC_toggleref_arr[GC_toggleref_array_size++].strong_ref =
448 is_strong_ref ? obj : (void *)GC_HIDE_POINTER(obj);
454 #endif /* !GC_TOGGLE_REFS_NOT_NEEDED */
456 /* Finalizer callback support. */
457 STATIC GC_await_finalize_proc GC_object_finalized_proc = 0;
459 GC_API void GC_CALL GC_set_await_finalize_proc(GC_await_finalize_proc fn)
464 GC_object_finalized_proc = fn;
468 GC_API GC_await_finalize_proc GC_CALL GC_get_await_finalize_proc(void)
470 GC_await_finalize_proc fn;
474 fn = GC_object_finalized_proc;
479 #ifndef GC_LONG_REFS_NOT_NEEDED
480 GC_API int GC_CALL GC_register_long_link(void * * link, const void * obj)
482 if (((word)link & (ALIGNMENT-1)) != 0 || !NONNULL_ARG_NOT_NULL(link))
483 ABORT("Bad arg to GC_register_long_link");
484 return GC_register_disappearing_link_inner(&GC_ll_hashtbl, link, obj,
488 GC_API int GC_CALL GC_unregister_long_link(void * * link)
490 struct disappearing_link *curr_dl;
493 if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
496 curr_dl = GC_unregister_disappearing_link_inner(&GC_ll_hashtbl, link);
498 if (NULL == curr_dl) return 0;
499 FREE_DL_ENTRY(curr_dl);
502 #endif /* !GC_LONG_REFS_NOT_NEEDED */
504 #ifndef GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED
505 /* Moves a link. Assume the lock is held. */
506 STATIC int GC_move_disappearing_link_inner(
507 struct dl_hashtbl_s *dl_hashtbl,
508 void **link, void **new_link)
510 struct disappearing_link *curr_dl, *prev_dl, *new_dl;
511 size_t curr_index, new_index;
512 word curr_hidden_link;
513 word new_hidden_link;
515 if (dl_hashtbl->log_size == -1)
516 return GC_NOT_FOUND; /* prevent integer shift by a negative amount */
518 /* Find current link. */
519 curr_index = HASH2(link, dl_hashtbl -> log_size);
520 curr_hidden_link = GC_HIDE_POINTER(link);
522 for (curr_dl = dl_hashtbl -> head[curr_index]; curr_dl;
523 curr_dl = dl_next(curr_dl)) {
524 if (curr_dl -> dl_hidden_link == curr_hidden_link)
529 if (NULL == curr_dl) {
533 if (link == new_link) {
534 return GC_SUCCESS; /* Nothing to do. */
537 /* link found; now check new_link not present. */
538 new_index = HASH2(new_link, dl_hashtbl -> log_size);
539 new_hidden_link = GC_HIDE_POINTER(new_link);
540 for (new_dl = dl_hashtbl -> head[new_index]; new_dl;
541 new_dl = dl_next(new_dl)) {
542 if (new_dl -> dl_hidden_link == new_hidden_link) {
543 /* Target already registered; bail. */
548 /* Remove from old, add to new, update link. */
549 if (NULL == prev_dl) {
550 dl_hashtbl -> head[curr_index] = dl_next(curr_dl);
552 dl_set_next(prev_dl, dl_next(curr_dl));
554 curr_dl -> dl_hidden_link = new_hidden_link;
555 dl_set_next(curr_dl, dl_hashtbl -> head[new_index]);
556 dl_hashtbl -> head[new_index] = curr_dl;
560 GC_API int GC_CALL GC_move_disappearing_link(void **link, void **new_link)
565 if (((word)new_link & (ALIGNMENT-1)) != 0
566 || !NONNULL_ARG_NOT_NULL(new_link))
567 ABORT("Bad new_link arg to GC_move_disappearing_link");
568 if (((word)link & (ALIGNMENT-1)) != 0)
569 return GC_NOT_FOUND; /* Nothing to do. */
572 result = GC_move_disappearing_link_inner(&GC_dl_hashtbl, link, new_link);
577 # ifndef GC_LONG_REFS_NOT_NEEDED
578 GC_API int GC_CALL GC_move_long_link(void **link, void **new_link)
583 if (((word)new_link & (ALIGNMENT-1)) != 0
584 || !NONNULL_ARG_NOT_NULL(new_link))
585 ABORT("Bad new_link arg to GC_move_long_link");
586 if (((word)link & (ALIGNMENT-1)) != 0)
587 return GC_NOT_FOUND; /* Nothing to do. */
590 result = GC_move_disappearing_link_inner(&GC_ll_hashtbl, link, new_link);
594 # endif /* !GC_LONG_REFS_NOT_NEEDED */
595 #endif /* !GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED */
597 /* Possible finalization_marker procedures. Note that mark stack */
598 /* overflow is handled by the caller, and is not a disaster. */
599 STATIC void GC_normal_finalize_mark_proc(ptr_t p)
603 PUSH_OBJ(p, hhdr, GC_mark_stack_top,
604 &(GC_mark_stack[GC_mark_stack_size]));
607 /* This only pays very partial attention to the mark descriptor. */
608 /* It does the right thing for normal and atomic objects, and treats */
609 /* most others as normal. */
610 STATIC void GC_ignore_self_finalize_mark_proc(ptr_t p)
613 word descr = hhdr -> hb_descr;
616 ptr_t target_limit = p + hhdr -> hb_sz - 1;
618 if ((descr & GC_DS_TAGS) == GC_DS_LENGTH) {
619 scan_limit = p + descr - sizeof(word);
621 scan_limit = target_limit + 1 - sizeof(word);
623 for (q = p; (word)q <= (word)scan_limit; q += ALIGNMENT) {
626 if (r < (word)p || r > (word)target_limit) {
627 GC_PUSH_ONE_HEAP(r, q, GC_mark_stack_top);
632 STATIC void GC_null_finalize_mark_proc(ptr_t p GC_ATTR_UNUSED) {}
634 /* Possible finalization_marker procedures. Note that mark stack */
635 /* overflow is handled by the caller, and is not a disaster. */
637 /* GC_unreachable_finalize_mark_proc is an alias for normal marking, */
638 /* but it is explicitly tested for, and triggers different */
639 /* behavior. Objects registered in this way are not finalized */
640 /* if they are reachable by other finalizable objects, even if those */
641 /* other objects specify no ordering. */
642 STATIC void GC_unreachable_finalize_mark_proc(ptr_t p)
644 GC_normal_finalize_mark_proc(p);
647 /* Register a finalization function. See gc.h for details. */
648 /* The last parameter is a procedure that determines */
649 /* marking for finalization ordering. Any objects marked */
650 /* by that procedure will be guaranteed to not have been */
651 /* finalized when this finalizer is invoked. */
652 STATIC void GC_register_finalizer_inner(void * obj,
653 GC_finalization_proc fn, void *cd,
654 GC_finalization_proc *ofn, void **ocd,
655 finalization_mark_proc mp)
657 struct finalizable_object * curr_fo;
659 struct finalizable_object *new_fo = 0;
660 hdr *hhdr = NULL; /* initialized to prevent warning. */
663 if (EXPECT(GC_find_leak, FALSE)) return;
665 if (log_fo_table_size == -1
666 || GC_fo_entries > ((word)1 << log_fo_table_size)) {
667 GC_grow_table((struct hash_chain_entry ***)&GC_fnlz_roots.fo_head,
670 if (log_fo_table_size < 0) ABORT("log_size is negative");
672 GC_COND_LOG_PRINTF("Grew fo table to %u entries\n",
673 1 << (unsigned)log_fo_table_size);
675 /* in the THREADS case we hold allocation lock. */
677 struct finalizable_object *prev_fo = NULL;
680 index = HASH2(obj, log_fo_table_size);
681 curr_fo = GC_fnlz_roots.fo_head[index];
682 while (curr_fo != 0) {
683 GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
684 if (curr_fo -> fo_hidden_base == GC_HIDE_POINTER(obj)) {
685 /* Interruption by a signal in the middle of this */
686 /* should be safe. The client may see only *ocd */
687 /* updated, but we'll declare that to be his problem. */
688 if (ocd) *ocd = (void *) (curr_fo -> fo_client_data);
689 if (ofn) *ofn = curr_fo -> fo_fn;
690 /* Delete the structure for obj. */
692 GC_fnlz_roots.fo_head[index] = fo_next(curr_fo);
694 fo_set_next(prev_fo, fo_next(curr_fo));
698 /* May not happen if we get a signal. But a high */
699 /* estimate will only make the table larger than */
701 # if !defined(THREADS) && !defined(DBG_HDRS_ALL)
702 GC_free((void *)curr_fo);
705 curr_fo -> fo_fn = fn;
706 curr_fo -> fo_client_data = (ptr_t)cd;
707 curr_fo -> fo_mark_proc = mp;
708 /* Reinsert it. We deleted it first to maintain */
709 /* consistency in the event of a signal. */
711 GC_fnlz_roots.fo_head[index] = curr_fo;
713 fo_set_next(prev_fo, curr_fo);
717 # ifndef DBG_HDRS_ALL
718 if (EXPECT(new_fo != 0, FALSE)) {
719 /* Free unused new_fo returned by GC_oom_fn() */
720 GC_free((void *)new_fo);
726 curr_fo = fo_next(curr_fo);
728 if (EXPECT(new_fo != 0, FALSE)) {
729 /* new_fo is returned by GC_oom_fn(). */
732 if (NULL == hhdr) ABORT("Bad hhdr in GC_register_finalizer_inner");
743 if (EXPECT(0 == hhdr, FALSE)) {
744 /* We won't collect it, hence finalizer wouldn't be run. */
750 new_fo = (struct finalizable_object *)
751 GC_INTERNAL_MALLOC(sizeof(struct finalizable_object),NORMAL);
752 if (EXPECT(new_fo != 0, TRUE))
756 new_fo = (struct finalizable_object *)
757 (*oom_fn)(sizeof(struct finalizable_object));
759 /* No enough memory. *ocd and *ofn remains unchanged. */
762 /* It's not likely we'll make it here, but ... */
764 /* Recalculate index since the table may grow and */
765 /* check again that our finalizer is not in the table. */
767 GC_ASSERT(GC_size(new_fo) >= sizeof(struct finalizable_object));
770 new_fo -> fo_hidden_base = GC_HIDE_POINTER(obj);
771 new_fo -> fo_fn = fn;
772 new_fo -> fo_client_data = (ptr_t)cd;
773 new_fo -> fo_object_size = hhdr -> hb_sz;
774 new_fo -> fo_mark_proc = mp;
775 fo_set_next(new_fo, GC_fnlz_roots.fo_head[index]);
777 GC_fnlz_roots.fo_head[index] = new_fo;
781 GC_API void GC_CALL GC_register_finalizer(void * obj,
782 GC_finalization_proc fn, void * cd,
783 GC_finalization_proc *ofn, void ** ocd)
785 GC_register_finalizer_inner(obj, fn, cd, ofn,
786 ocd, GC_normal_finalize_mark_proc);
789 GC_API void GC_CALL GC_register_finalizer_ignore_self(void * obj,
790 GC_finalization_proc fn, void * cd,
791 GC_finalization_proc *ofn, void ** ocd)
793 GC_register_finalizer_inner(obj, fn, cd, ofn,
794 ocd, GC_ignore_self_finalize_mark_proc);
797 GC_API void GC_CALL GC_register_finalizer_no_order(void * obj,
798 GC_finalization_proc fn, void * cd,
799 GC_finalization_proc *ofn, void ** ocd)
801 GC_register_finalizer_inner(obj, fn, cd, ofn,
802 ocd, GC_null_finalize_mark_proc);
805 static GC_bool need_unreachable_finalization = FALSE;
806 /* Avoid the work if this isn't used. */
808 GC_API void GC_CALL GC_register_finalizer_unreachable(void * obj,
809 GC_finalization_proc fn, void * cd,
810 GC_finalization_proc *ofn, void ** ocd)
812 need_unreachable_finalization = TRUE;
813 GC_ASSERT(GC_java_finalization);
814 GC_register_finalizer_inner(obj, fn, cd, ofn,
815 ocd, GC_unreachable_finalize_mark_proc);
819 STATIC void GC_dump_finalization_links(
820 const struct dl_hashtbl_s *dl_hashtbl)
822 size_t dl_size = dl_hashtbl->log_size == -1 ? 0 :
823 (size_t)1 << dl_hashtbl->log_size;
826 for (i = 0; i < dl_size; i++) {
827 struct disappearing_link *curr_dl;
829 for (curr_dl = dl_hashtbl -> head[i]; curr_dl != 0;
830 curr_dl = dl_next(curr_dl)) {
831 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_obj);
832 ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_link);
834 GC_printf("Object: %p, link: %p\n",
835 (void *)real_ptr, (void *)real_link);
840 GC_API void GC_CALL GC_dump_finalization(void)
842 struct finalizable_object * curr_fo;
843 size_t fo_size = log_fo_table_size == -1 ? 0 :
844 (size_t)1 << log_fo_table_size;
847 GC_printf("Disappearing (short) links:\n");
848 GC_dump_finalization_links(&GC_dl_hashtbl);
849 # ifndef GC_LONG_REFS_NOT_NEEDED
850 GC_printf("Disappearing long links:\n");
851 GC_dump_finalization_links(&GC_ll_hashtbl);
853 GC_printf("Finalizers:\n");
854 for (i = 0; i < fo_size; i++) {
855 for (curr_fo = GC_fnlz_roots.fo_head[i];
856 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
857 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
859 GC_printf("Finalizable object: %p\n", (void *)real_ptr);
863 #endif /* !NO_DEBUGGING */
866 STATIC word GC_old_dl_entries = 0; /* for stats printing */
867 # ifndef GC_LONG_REFS_NOT_NEEDED
868 STATIC word GC_old_ll_entries = 0;
870 #endif /* !SMALL_CONFIG */
873 /* Global variables to minimize the level of recursion when a client */
874 /* finalizer allocates memory. */
875 STATIC int GC_finalizer_nested = 0;
876 /* Only the lowest byte is used, the rest is */
877 /* padding for proper global data alignment */
878 /* required for some compilers (like Watcom). */
879 STATIC unsigned GC_finalizer_skipped = 0;
881 /* Checks and updates the level of finalizers recursion. */
882 /* Returns NULL if GC_invoke_finalizers() should not be called by the */
883 /* collector (to minimize the risk of a deep finalizers recursion), */
884 /* otherwise returns a pointer to GC_finalizer_nested. */
885 STATIC unsigned char *GC_check_finalizer_nested(void)
887 unsigned nesting_level = *(unsigned char *)&GC_finalizer_nested;
889 /* We are inside another GC_invoke_finalizers(). */
890 /* Skip some implicitly-called GC_invoke_finalizers() */
891 /* depending on the nesting (recursion) level. */
892 if (++GC_finalizer_skipped < (1U << nesting_level)) return NULL;
893 GC_finalizer_skipped = 0;
895 *(char *)&GC_finalizer_nested = (char)(nesting_level + 1);
896 return (unsigned char *)&GC_finalizer_nested;
900 #define ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr_dl, prev_dl) \
903 size_t dl_size = dl_hashtbl->log_size == -1 ? 0 : \
904 (size_t)1 << dl_hashtbl->log_size; \
905 for (i = 0; i < dl_size; i++) { \
906 struct disappearing_link *prev_dl = NULL; \
907 curr_dl = dl_hashtbl -> head[i]; \
910 #define ITERATE_DL_HASHTBL_END(curr_dl, prev_dl) \
912 curr_dl = dl_next(curr_dl); \
917 #define DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr_dl, prev_dl, next_dl) \
919 next_dl = dl_next(curr_dl); \
920 if (NULL == prev_dl) { \
921 dl_hashtbl -> head[i] = next_dl; \
923 dl_set_next(prev_dl, next_dl); \
925 GC_clear_mark_bit(curr_dl); \
926 dl_hashtbl -> entries--; \
931 GC_INLINE void GC_make_disappearing_links_disappear(
932 struct dl_hashtbl_s* dl_hashtbl)
934 struct disappearing_link *curr, *next;
936 ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
937 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_obj);
938 ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_link);
940 if (!GC_is_marked(real_ptr)) {
941 *(word *)real_link = 0;
942 GC_clear_mark_bit(curr);
943 DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
945 ITERATE_DL_HASHTBL_END(curr, prev)
948 GC_INLINE void GC_remove_dangling_disappearing_links(
949 struct dl_hashtbl_s* dl_hashtbl)
951 struct disappearing_link *curr, *next;
953 ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
955 (ptr_t)GC_base(GC_REVEAL_POINTER(curr->dl_hidden_link));
957 if (NULL != real_link && !GC_is_marked(real_link)) {
958 GC_clear_mark_bit(curr);
959 DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
961 ITERATE_DL_HASHTBL_END(curr, prev)
964 /* Called with held lock (but the world is running). */
965 /* Cause disappearing links to disappear and unreachable objects to be */
966 /* enqueued for finalization. */
967 GC_INNER void GC_finalize(void)
969 struct finalizable_object * curr_fo, * prev_fo, * next_fo;
972 size_t fo_size = log_fo_table_size == -1 ? 0 :
973 (size_t)1 << log_fo_table_size;
975 # ifndef SMALL_CONFIG
976 /* Save current GC_[dl/ll]_entries value for stats printing */
977 GC_old_dl_entries = GC_dl_hashtbl.entries;
978 # ifndef GC_LONG_REFS_NOT_NEEDED
979 GC_old_ll_entries = GC_ll_hashtbl.entries;
983 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
984 GC_mark_togglerefs();
986 GC_make_disappearing_links_disappear(&GC_dl_hashtbl);
988 /* Mark all objects reachable via chains of 1 or more pointers */
989 /* from finalizable objects. */
990 GC_ASSERT(GC_mark_state == MS_NONE);
991 for (i = 0; i < fo_size; i++) {
992 for (curr_fo = GC_fnlz_roots.fo_head[i];
993 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
994 GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
995 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
996 if (!GC_is_marked(real_ptr)) {
997 GC_MARKED_FOR_FINALIZATION(real_ptr);
998 GC_MARK_FO(real_ptr, curr_fo -> fo_mark_proc);
999 if (GC_is_marked(real_ptr)) {
1000 WARN("Finalization cycle involving %p\n", real_ptr);
1005 /* Enqueue for finalization all objects that are still */
1007 GC_bytes_finalized = 0;
1008 for (i = 0; i < fo_size; i++) {
1009 curr_fo = GC_fnlz_roots.fo_head[i];
1011 while (curr_fo != 0) {
1012 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1013 if (!GC_is_marked(real_ptr)) {
1014 if (!GC_java_finalization) {
1015 GC_set_mark_bit(real_ptr);
1017 /* Delete from hash table */
1018 next_fo = fo_next(curr_fo);
1019 if (NULL == prev_fo) {
1020 GC_fnlz_roots.fo_head[i] = next_fo;
1022 fo_set_next(prev_fo, next_fo);
1025 if (GC_object_finalized_proc)
1026 GC_object_finalized_proc(real_ptr);
1028 /* Add to list of objects awaiting finalization. */
1029 fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1030 SET_FINALIZE_NOW(curr_fo);
1031 /* unhide object pointer so any future collections will */
1033 curr_fo -> fo_hidden_base =
1034 (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1035 GC_bytes_finalized +=
1036 curr_fo -> fo_object_size
1037 + sizeof(struct finalizable_object);
1038 GC_ASSERT(GC_is_marked(GC_base(curr_fo)));
1042 curr_fo = fo_next(curr_fo);
1047 if (GC_java_finalization) {
1048 /* make sure we mark everything reachable from objects finalized
1049 using the no_order mark_proc */
1050 for (curr_fo = GC_fnlz_roots.finalize_now;
1051 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
1052 real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1053 if (!GC_is_marked(real_ptr)) {
1054 if (curr_fo -> fo_mark_proc == GC_null_finalize_mark_proc) {
1055 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1057 if (curr_fo -> fo_mark_proc != GC_unreachable_finalize_mark_proc) {
1058 GC_set_mark_bit(real_ptr);
1063 /* now revive finalize-when-unreachable objects reachable from
1064 other finalizable objects */
1065 if (need_unreachable_finalization) {
1066 curr_fo = GC_fnlz_roots.finalize_now;
1067 # if defined(GC_ASSERTIONS) || defined(LINT2)
1068 if (curr_fo != NULL && log_fo_table_size < 0)
1069 ABORT("log_size is negative");
1072 while (curr_fo != NULL) {
1073 next_fo = fo_next(curr_fo);
1074 if (curr_fo -> fo_mark_proc == GC_unreachable_finalize_mark_proc) {
1075 real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1076 if (!GC_is_marked(real_ptr)) {
1077 GC_set_mark_bit(real_ptr);
1079 if (NULL == prev_fo) {
1080 SET_FINALIZE_NOW(next_fo);
1082 fo_set_next(prev_fo, next_fo);
1084 curr_fo -> fo_hidden_base =
1085 GC_HIDE_POINTER(curr_fo -> fo_hidden_base);
1086 GC_bytes_finalized -=
1087 curr_fo->fo_object_size + sizeof(struct finalizable_object);
1089 i = HASH2(real_ptr, log_fo_table_size);
1090 fo_set_next(curr_fo, GC_fnlz_roots.fo_head[i]);
1092 GC_fnlz_roots.fo_head[i] = curr_fo;
1102 GC_remove_dangling_disappearing_links(&GC_dl_hashtbl);
1103 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
1104 GC_clear_togglerefs();
1106 # ifndef GC_LONG_REFS_NOT_NEEDED
1107 GC_make_disappearing_links_disappear(&GC_ll_hashtbl);
1108 GC_remove_dangling_disappearing_links(&GC_ll_hashtbl);
1111 if (GC_fail_count) {
1112 /* Don't prevent running finalizers if there has been an allocation */
1113 /* failure recently. */
1115 GC_reset_finalizer_nested();
1117 GC_finalizer_nested = 0;
1122 #ifndef JAVA_FINALIZATION_NOT_NEEDED
1124 /* Enqueue all remaining finalizers to be run - Assumes lock is held. */
1125 STATIC void GC_enqueue_all_finalizers(void)
1127 struct finalizable_object * curr_fo, * next_fo;
1132 fo_size = log_fo_table_size == -1 ? 0 : 1 << log_fo_table_size;
1133 GC_bytes_finalized = 0;
1134 for (i = 0; i < fo_size; i++) {
1135 curr_fo = GC_fnlz_roots.fo_head[i];
1136 GC_fnlz_roots.fo_head[i] = NULL;
1137 while (curr_fo != NULL) {
1138 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1139 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1140 GC_set_mark_bit(real_ptr);
1142 next_fo = fo_next(curr_fo);
1144 /* Add to list of objects awaiting finalization. */
1145 fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1146 SET_FINALIZE_NOW(curr_fo);
1148 /* unhide object pointer so any future collections will */
1150 curr_fo -> fo_hidden_base =
1151 (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1152 GC_bytes_finalized +=
1153 curr_fo -> fo_object_size + sizeof(struct finalizable_object);
1157 GC_fo_entries = 0; /* all entries deleted from the hash table */
1160 /* Invoke all remaining finalizers that haven't yet been run.
1161 * This is needed for strict compliance with the Java standard,
1162 * which can make the runtime guarantee that all finalizers are run.
1163 * Unfortunately, the Java standard implies we have to keep running
1164 * finalizers until there are no more left, a potential infinite loop.
1166 * Note that this is even more dangerous than the usual Java
1167 * finalizers, in that objects reachable from static variables
1168 * may have been finalized when these finalizers are run.
1169 * Finalizers run at this point must be prepared to deal with a
1170 * mostly broken world.
1171 * This routine is externally callable, so is called without
1172 * the allocation lock.
1174 GC_API void GC_CALL GC_finalize_all(void)
1179 while (GC_fo_entries > 0) {
1180 GC_enqueue_all_finalizers();
1182 GC_invoke_finalizers();
1183 /* Running the finalizers in this thread is arguably not a good */
1184 /* idea when we should be notifying another thread to run them. */
1185 /* But otherwise we don't have a great way to wait for them to */
1192 #endif /* !JAVA_FINALIZATION_NOT_NEEDED */
1194 /* Returns true if it is worth calling GC_invoke_finalizers. (Useful if */
1195 /* finalizers can only be called from some kind of "safe state" and */
1196 /* getting into that safe state is expensive.) */
1197 GC_API int GC_CALL GC_should_invoke_finalizers(void)
1199 # ifdef AO_HAVE_load
1200 return AO_load((volatile AO_t *)&GC_fnlz_roots.finalize_now) != 0;
1202 return GC_fnlz_roots.finalize_now != NULL;
1203 # endif /* !THREADS */
1206 /* Invoke finalizers for all objects that are ready to be finalized. */
1207 /* Should be called without allocation lock. */
1208 GC_API int GC_CALL GC_invoke_finalizers(void)
1211 word bytes_freed_before = 0; /* initialized to prevent warning. */
1214 while (GC_should_invoke_finalizers()) {
1215 struct finalizable_object * curr_fo;
1221 bytes_freed_before = GC_bytes_freed;
1222 /* Don't do this outside, since we need the lock. */
1224 curr_fo = GC_fnlz_roots.finalize_now;
1226 if (curr_fo != NULL)
1227 SET_FINALIZE_NOW(fo_next(curr_fo));
1229 if (curr_fo == 0) break;
1231 GC_fnlz_roots.finalize_now = fo_next(curr_fo);
1233 fo_set_next(curr_fo, 0);
1234 (*(curr_fo -> fo_fn))((ptr_t)(curr_fo -> fo_hidden_base),
1235 curr_fo -> fo_client_data);
1236 curr_fo -> fo_client_data = 0;
1238 /* Explicit freeing of curr_fo is probably a bad idea. */
1239 /* It throws off accounting if nearly all objects are */
1240 /* finalizable. Otherwise it should not matter. */
1242 /* bytes_freed_before is initialized whenever count != 0 */
1244 # if defined(THREADS) && !defined(THREAD_SANITIZER)
1245 /* A quick check whether some memory was freed. */
1246 /* The race with GC_free() is safe to be ignored */
1247 /* because we only need to know if the current */
1248 /* thread has deallocated something. */
1249 && bytes_freed_before != GC_bytes_freed
1253 GC_finalizer_bytes_freed += (GC_bytes_freed - bytes_freed_before);
1259 static word last_finalizer_notification = 0;
1261 GC_INNER void GC_notify_or_invoke_finalizers(void)
1263 GC_finalizer_notifier_proc notifier_fn = 0;
1264 # if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1265 static word last_back_trace_gc_no = 1; /* Skip first one. */
1269 # if defined(THREADS) && !defined(KEEP_BACK_PTRS) \
1270 && !defined(MAKE_BACK_GRAPH)
1271 /* Quick check (while unlocked) for an empty finalization queue. */
1272 if (!GC_should_invoke_finalizers())
1277 /* This is a convenient place to generate backtraces if appropriate, */
1278 /* since that code is not callable with the allocation lock. */
1279 # if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1280 if (GC_gc_no > last_back_trace_gc_no) {
1281 # ifdef KEEP_BACK_PTRS
1283 /* Stops when GC_gc_no wraps; that's OK. */
1284 last_back_trace_gc_no = (word)(-1); /* disable others. */
1285 for (i = 0; i < GC_backtraces; ++i) {
1286 /* FIXME: This tolerates concurrent heap mutation, */
1287 /* which may cause occasional mysterious results. */
1288 /* We need to release the GC lock, since GC_print_callers */
1289 /* acquires it. It probably shouldn't. */
1291 GC_generate_random_backtrace_no_gc();
1294 last_back_trace_gc_no = GC_gc_no;
1296 # ifdef MAKE_BACK_GRAPH
1297 if (GC_print_back_height) {
1299 GC_print_back_graph_stats();
1305 if (NULL == GC_fnlz_roots.finalize_now) {
1310 if (!GC_finalize_on_demand) {
1311 unsigned char *pnested = GC_check_finalizer_nested();
1313 /* Skip GC_invoke_finalizers() if nested */
1314 if (pnested != NULL) {
1315 (void) GC_invoke_finalizers();
1316 *pnested = 0; /* Reset since no more finalizers. */
1318 GC_ASSERT(NULL == GC_fnlz_roots.finalize_now);
1319 # endif /* Otherwise GC can run concurrently and add more */
1324 /* These variables require synchronization to avoid data races. */
1325 if (last_finalizer_notification != GC_gc_no) {
1326 last_finalizer_notification = GC_gc_no;
1327 notifier_fn = GC_finalizer_notifier;
1330 if (notifier_fn != 0)
1331 (*notifier_fn)(); /* Invoke the notifier */
1334 #ifndef SMALL_CONFIG
1335 # ifndef GC_LONG_REFS_NOT_NEEDED
1336 # define IF_LONG_REFS_PRESENT_ELSE(x,y) (x)
1338 # define IF_LONG_REFS_PRESENT_ELSE(x,y) (y)
1341 GC_INNER void GC_print_finalization_stats(void)
1343 struct finalizable_object *fo;
1344 unsigned long ready = 0;
1346 GC_log_printf("%lu finalization entries;"
1347 " %lu/%lu short/long disappearing links alive\n",
1348 (unsigned long)GC_fo_entries,
1349 (unsigned long)GC_dl_hashtbl.entries,
1350 (unsigned long)IF_LONG_REFS_PRESENT_ELSE(
1351 GC_ll_hashtbl.entries, 0));
1353 for (fo = GC_fnlz_roots.finalize_now; fo != NULL; fo = fo_next(fo))
1355 GC_log_printf("%lu finalization-ready objects;"
1356 " %ld/%ld short/long links cleared\n",
1358 (long)GC_old_dl_entries - (long)GC_dl_hashtbl.entries,
1359 (long)IF_LONG_REFS_PRESENT_ELSE(
1360 GC_old_ll_entries - GC_ll_hashtbl.entries, 0));
1362 #endif /* !SMALL_CONFIG */
1364 #endif /* !GC_NO_FINALIZATION */