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 };
81 GC_API void GC_CALL GC_push_finalizer_structures(void)
83 GC_ASSERT((word)&GC_dl_hashtbl.head % sizeof(word) == 0);
84 GC_ASSERT((word)&GC_fnlz_roots % sizeof(word) == 0);
85 # ifndef GC_LONG_REFS_NOT_NEEDED
86 GC_ASSERT((word)&GC_ll_hashtbl.head % sizeof(word) == 0);
87 GC_PUSH_ALL_SYM(GC_ll_hashtbl.head);
89 GC_PUSH_ALL_SYM(GC_dl_hashtbl.head);
90 GC_PUSH_ALL_SYM(GC_fnlz_roots);
93 /* Double the size of a hash table. *size_ptr is the log of its current */
94 /* size. May be a no-op. */
95 /* *table is a pointer to an array of hash headers. If we succeed, we */
96 /* update both *table and *log_size_ptr. Lock is held. */
97 STATIC void GC_grow_table(struct hash_chain_entry ***table,
98 signed_word *log_size_ptr)
101 struct hash_chain_entry *p;
102 signed_word log_old_size = *log_size_ptr;
103 signed_word log_new_size = log_old_size + 1;
104 word old_size = log_old_size == -1 ? 0 : (word)1 << log_old_size;
105 word new_size = (word)1 << log_new_size;
106 /* FIXME: Power of 2 size often gets rounded up to one more page. */
107 struct hash_chain_entry **new_table;
109 GC_ASSERT(I_HOLD_LOCK());
110 new_table = (struct hash_chain_entry **)
111 GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
112 (size_t)new_size * sizeof(struct hash_chain_entry *),
114 if (new_table == 0) {
116 ABORT("Insufficient space for initial table allocation");
121 for (i = 0; i < old_size; i++) {
124 ptr_t real_key = (ptr_t)GC_REVEAL_POINTER(p->hidden_key);
125 struct hash_chain_entry *next = p -> next;
126 size_t new_hash = HASH3(real_key, new_size, log_new_size);
128 p -> next = new_table[new_hash];
129 new_table[new_hash] = p;
133 *log_size_ptr = log_new_size;
137 GC_API int GC_CALL GC_register_disappearing_link(void * * link)
141 base = (ptr_t)GC_base(link);
143 ABORT("Bad arg to GC_register_disappearing_link");
144 return(GC_general_register_disappearing_link(link, base));
147 STATIC int GC_register_disappearing_link_inner(
148 struct dl_hashtbl_s *dl_hashtbl, void **link,
149 const void *obj, const char *tbl_log_name)
151 struct disappearing_link *curr_dl;
153 struct disappearing_link * new_dl;
156 if (EXPECT(GC_find_leak, FALSE)) return GC_UNIMPLEMENTED;
158 GC_ASSERT(obj != NULL && GC_base_C(obj) == obj);
159 if (dl_hashtbl -> log_size == -1
160 || dl_hashtbl -> entries > ((word)1 << dl_hashtbl -> log_size)) {
161 GC_grow_table((struct hash_chain_entry ***)&dl_hashtbl -> head,
162 &dl_hashtbl -> log_size);
164 if (dl_hashtbl->log_size < 0) ABORT("log_size is negative");
166 GC_COND_LOG_PRINTF("Grew %s table to %u entries\n", tbl_log_name,
167 1 << (unsigned)dl_hashtbl -> log_size);
169 index = HASH2(link, dl_hashtbl -> log_size);
170 for (curr_dl = dl_hashtbl -> head[index]; curr_dl != 0;
171 curr_dl = dl_next(curr_dl)) {
172 if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
173 curr_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
178 new_dl = (struct disappearing_link *)
179 GC_INTERNAL_MALLOC(sizeof(struct disappearing_link),NORMAL);
181 GC_oom_func oom_fn = GC_oom_fn;
183 new_dl = (struct disappearing_link *)
184 (*oom_fn)(sizeof(struct disappearing_link));
188 /* It's not likely we'll make it here, but ... */
190 /* Recalculate index since the table may grow. */
191 index = HASH2(link, dl_hashtbl -> log_size);
192 /* Check again that our disappearing link not in the table. */
193 for (curr_dl = dl_hashtbl -> head[index]; curr_dl != 0;
194 curr_dl = dl_next(curr_dl)) {
195 if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
196 curr_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
198 # ifndef DBG_HDRS_ALL
199 /* Free unused new_dl returned by GC_oom_fn() */
200 GC_free((void *)new_dl);
206 new_dl -> dl_hidden_obj = GC_HIDE_POINTER(obj);
207 new_dl -> dl_hidden_link = GC_HIDE_POINTER(link);
208 dl_set_next(new_dl, dl_hashtbl -> head[index]);
209 dl_hashtbl -> head[index] = new_dl;
210 dl_hashtbl -> entries++;
215 GC_API int GC_CALL GC_general_register_disappearing_link(void * * link,
218 if (((word)link & (ALIGNMENT-1)) != 0 || !NONNULL_ARG_NOT_NULL(link))
219 ABORT("Bad arg to GC_general_register_disappearing_link");
220 return GC_register_disappearing_link_inner(&GC_dl_hashtbl, link, obj,
225 # define FREE_DL_ENTRY(curr_dl) dl_set_next(curr_dl, NULL)
227 # define FREE_DL_ENTRY(curr_dl) GC_free(curr_dl)
230 /* Unregisters given link and returns the link entry to free. */
231 /* Assume the lock is held. */
232 GC_INLINE struct disappearing_link *GC_unregister_disappearing_link_inner(
233 struct dl_hashtbl_s *dl_hashtbl, void **link)
235 struct disappearing_link *curr_dl;
236 struct disappearing_link *prev_dl = NULL;
239 if (dl_hashtbl->log_size == -1)
240 return NULL; /* prevent integer shift by a negative amount */
242 index = HASH2(link, dl_hashtbl->log_size);
243 for (curr_dl = dl_hashtbl -> head[index]; curr_dl;
244 curr_dl = dl_next(curr_dl)) {
245 if (curr_dl -> dl_hidden_link == GC_HIDE_POINTER(link)) {
246 /* Remove found entry from the table. */
247 if (NULL == prev_dl) {
248 dl_hashtbl -> head[index] = dl_next(curr_dl);
250 dl_set_next(prev_dl, dl_next(curr_dl));
252 dl_hashtbl -> entries--;
260 GC_API int GC_CALL GC_unregister_disappearing_link(void * * link)
262 struct disappearing_link *curr_dl;
265 if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
268 curr_dl = GC_unregister_disappearing_link_inner(&GC_dl_hashtbl, link);
270 if (NULL == curr_dl) return 0;
271 FREE_DL_ENTRY(curr_dl);
275 /* Toggle-ref support. */
276 #ifndef GC_TOGGLE_REFS_NOT_NEEDED
278 /* Lowest bit is used to distinguish between choices. */
280 GC_hidden_pointer weak_ref;
283 STATIC GC_toggleref_func GC_toggleref_callback = 0;
284 STATIC GCToggleRef *GC_toggleref_arr = NULL;
285 STATIC int GC_toggleref_array_size = 0;
286 STATIC int GC_toggleref_array_capacity = 0;
288 GC_INNER void GC_process_togglerefs(void)
293 GC_ASSERT(I_HOLD_LOCK());
294 for (i = 0; i < GC_toggleref_array_size; ++i) {
295 GCToggleRef r = GC_toggleref_arr[i];
296 void *obj = r.strong_ref;
298 if (((word)obj & 1) != 0) {
299 obj = GC_REVEAL_POINTER(r.weak_ref);
304 switch (GC_toggleref_callback(obj)) {
305 case GC_TOGGLE_REF_DROP:
307 case GC_TOGGLE_REF_STRONG:
308 GC_toggleref_arr[new_size++].strong_ref = obj;
310 case GC_TOGGLE_REF_WEAK:
311 GC_toggleref_arr[new_size++].weak_ref = GC_HIDE_POINTER(obj);
314 ABORT("Bad toggle-ref status returned by callback");
318 if (new_size < GC_toggleref_array_size) {
319 BZERO(&GC_toggleref_arr[new_size],
320 (GC_toggleref_array_size - new_size) * sizeof(GCToggleRef));
321 GC_toggleref_array_size = new_size;
325 STATIC void GC_normal_finalize_mark_proc(ptr_t);
327 static void push_and_mark_object(void *p)
329 GC_normal_finalize_mark_proc((ptr_t)p);
330 while (!GC_mark_stack_empty()) {
331 MARK_FROM_MARK_STACK();
334 if (GC_mark_state != MS_NONE) {
335 while (!GC_mark_some(0)) {
341 STATIC void GC_mark_togglerefs(void)
344 if (NULL == GC_toggleref_arr)
347 /* TODO: Hide GC_toggleref_arr to avoid its marking from roots. */
348 GC_set_mark_bit(GC_toggleref_arr);
349 for (i = 0; i < GC_toggleref_array_size; ++i) {
350 void *obj = GC_toggleref_arr[i].strong_ref;
351 if (obj != NULL && ((word)obj & 1) == 0) {
352 push_and_mark_object(obj);
357 STATIC void GC_clear_togglerefs(void)
360 for (i = 0; i < GC_toggleref_array_size; ++i) {
361 if ((GC_toggleref_arr[i].weak_ref & 1) != 0) {
362 if (!GC_is_marked(GC_REVEAL_POINTER(GC_toggleref_arr[i].weak_ref))) {
363 GC_toggleref_arr[i].weak_ref = 0;
365 /* No need to copy, BDWGC is a non-moving collector. */
371 GC_API void GC_CALL GC_set_toggleref_func(GC_toggleref_func fn)
376 GC_toggleref_callback = fn;
380 GC_API GC_toggleref_func GC_CALL GC_get_toggleref_func(void)
382 GC_toggleref_func fn;
386 fn = GC_toggleref_callback;
391 static GC_bool ensure_toggleref_capacity(int capacity_inc)
393 GC_ASSERT(capacity_inc >= 0);
394 if (NULL == GC_toggleref_arr) {
395 GC_toggleref_array_capacity = 32; /* initial capacity */
396 GC_toggleref_arr = (GCToggleRef *)GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
397 GC_toggleref_array_capacity * sizeof(GCToggleRef),
399 if (NULL == GC_toggleref_arr)
402 if ((unsigned)GC_toggleref_array_size + (unsigned)capacity_inc
403 >= (unsigned)GC_toggleref_array_capacity) {
404 GCToggleRef *new_array;
405 while ((unsigned)GC_toggleref_array_capacity
406 < (unsigned)GC_toggleref_array_size + (unsigned)capacity_inc) {
407 GC_toggleref_array_capacity *= 2;
408 if (GC_toggleref_array_capacity < 0) /* overflow */
412 new_array = (GCToggleRef *)GC_INTERNAL_MALLOC_IGNORE_OFF_PAGE(
413 GC_toggleref_array_capacity * sizeof(GCToggleRef),
415 if (NULL == new_array)
417 if (EXPECT(GC_toggleref_array_size > 0, TRUE))
418 BCOPY(GC_toggleref_arr, new_array,
419 GC_toggleref_array_size * sizeof(GCToggleRef));
420 GC_INTERNAL_FREE(GC_toggleref_arr);
421 GC_toggleref_arr = new_array;
426 GC_API int GC_CALL GC_toggleref_add(void *obj, int is_strong_ref)
428 int res = GC_SUCCESS;
431 GC_ASSERT(NONNULL_ARG_NOT_NULL(obj));
433 if (GC_toggleref_callback != 0) {
434 if (!ensure_toggleref_capacity(1)) {
437 GC_toggleref_arr[GC_toggleref_array_size++].strong_ref =
438 is_strong_ref ? obj : (void *)GC_HIDE_POINTER(obj);
444 #endif /* !GC_TOGGLE_REFS_NOT_NEEDED */
446 /* Finalizer callback support. */
447 STATIC GC_await_finalize_proc GC_object_finalized_proc = 0;
449 GC_API void GC_CALL GC_set_await_finalize_proc(GC_await_finalize_proc fn)
454 GC_object_finalized_proc = fn;
458 GC_API GC_await_finalize_proc GC_CALL GC_get_await_finalize_proc(void)
460 GC_await_finalize_proc fn;
464 fn = GC_object_finalized_proc;
469 #ifndef GC_LONG_REFS_NOT_NEEDED
470 GC_API int GC_CALL GC_register_long_link(void * * link, const void * obj)
472 if (((word)link & (ALIGNMENT-1)) != 0 || !NONNULL_ARG_NOT_NULL(link))
473 ABORT("Bad arg to GC_register_long_link");
474 return GC_register_disappearing_link_inner(&GC_ll_hashtbl, link, obj,
478 GC_API int GC_CALL GC_unregister_long_link(void * * link)
480 struct disappearing_link *curr_dl;
483 if (((word)link & (ALIGNMENT-1)) != 0) return(0); /* Nothing to do. */
486 curr_dl = GC_unregister_disappearing_link_inner(&GC_ll_hashtbl, link);
488 if (NULL == curr_dl) return 0;
489 FREE_DL_ENTRY(curr_dl);
492 #endif /* !GC_LONG_REFS_NOT_NEEDED */
494 #ifndef GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED
495 /* Moves a link. Assume the lock is held. */
496 STATIC int GC_move_disappearing_link_inner(
497 struct dl_hashtbl_s *dl_hashtbl,
498 void **link, void **new_link)
500 struct disappearing_link *curr_dl, *prev_dl, *new_dl;
501 size_t curr_index, new_index;
502 word curr_hidden_link;
503 word new_hidden_link;
505 if (dl_hashtbl->log_size == -1)
506 return GC_NOT_FOUND; /* prevent integer shift by a negative amount */
508 /* Find current link. */
509 curr_index = HASH2(link, dl_hashtbl -> log_size);
510 curr_hidden_link = GC_HIDE_POINTER(link);
512 for (curr_dl = dl_hashtbl -> head[curr_index]; curr_dl;
513 curr_dl = dl_next(curr_dl)) {
514 if (curr_dl -> dl_hidden_link == curr_hidden_link)
519 if (NULL == curr_dl) {
523 if (link == new_link) {
524 return GC_SUCCESS; /* Nothing to do. */
527 /* link found; now check new_link not present. */
528 new_index = HASH2(new_link, dl_hashtbl -> log_size);
529 new_hidden_link = GC_HIDE_POINTER(new_link);
530 for (new_dl = dl_hashtbl -> head[new_index]; new_dl;
531 new_dl = dl_next(new_dl)) {
532 if (new_dl -> dl_hidden_link == new_hidden_link) {
533 /* Target already registered; bail. */
538 /* Remove from old, add to new, update link. */
539 if (NULL == prev_dl) {
540 dl_hashtbl -> head[curr_index] = dl_next(curr_dl);
542 dl_set_next(prev_dl, dl_next(curr_dl));
544 curr_dl -> dl_hidden_link = new_hidden_link;
545 dl_set_next(curr_dl, dl_hashtbl -> head[new_index]);
546 dl_hashtbl -> head[new_index] = curr_dl;
550 GC_API int GC_CALL GC_move_disappearing_link(void **link, void **new_link)
555 if (((word)new_link & (ALIGNMENT-1)) != 0
556 || !NONNULL_ARG_NOT_NULL(new_link))
557 ABORT("Bad new_link arg to GC_move_disappearing_link");
558 if (((word)link & (ALIGNMENT-1)) != 0)
559 return GC_NOT_FOUND; /* Nothing to do. */
562 result = GC_move_disappearing_link_inner(&GC_dl_hashtbl, link, new_link);
567 # ifndef GC_LONG_REFS_NOT_NEEDED
568 GC_API int GC_CALL GC_move_long_link(void **link, void **new_link)
573 if (((word)new_link & (ALIGNMENT-1)) != 0
574 || !NONNULL_ARG_NOT_NULL(new_link))
575 ABORT("Bad new_link arg to GC_move_long_link");
576 if (((word)link & (ALIGNMENT-1)) != 0)
577 return GC_NOT_FOUND; /* Nothing to do. */
580 result = GC_move_disappearing_link_inner(&GC_ll_hashtbl, link, new_link);
584 # endif /* !GC_LONG_REFS_NOT_NEEDED */
585 #endif /* !GC_MOVE_DISAPPEARING_LINK_NOT_NEEDED */
587 /* Possible finalization_marker procedures. Note that mark stack */
588 /* overflow is handled by the caller, and is not a disaster. */
589 STATIC void GC_normal_finalize_mark_proc(ptr_t p)
593 PUSH_OBJ(p, hhdr, GC_mark_stack_top,
594 &(GC_mark_stack[GC_mark_stack_size]));
597 /* This only pays very partial attention to the mark descriptor. */
598 /* It does the right thing for normal and atomic objects, and treats */
599 /* most others as normal. */
600 STATIC void GC_ignore_self_finalize_mark_proc(ptr_t p)
603 word descr = hhdr -> hb_descr;
606 ptr_t target_limit = p + hhdr -> hb_sz - 1;
608 if ((descr & GC_DS_TAGS) == GC_DS_LENGTH) {
609 scan_limit = p + descr - sizeof(word);
611 scan_limit = target_limit + 1 - sizeof(word);
613 for (q = p; (word)q <= (word)scan_limit; q += ALIGNMENT) {
616 if (r < (word)p || r > (word)target_limit) {
617 GC_PUSH_ONE_HEAP(r, q, GC_mark_stack_top);
622 STATIC void GC_null_finalize_mark_proc(ptr_t p GC_ATTR_UNUSED) {}
624 /* Possible finalization_marker procedures. Note that mark stack */
625 /* overflow is handled by the caller, and is not a disaster. */
627 /* GC_unreachable_finalize_mark_proc is an alias for normal marking, */
628 /* but it is explicitly tested for, and triggers different */
629 /* behavior. Objects registered in this way are not finalized */
630 /* if they are reachable by other finalizable objects, even if those */
631 /* other objects specify no ordering. */
632 STATIC void GC_unreachable_finalize_mark_proc(ptr_t p)
634 GC_normal_finalize_mark_proc(p);
637 /* Register a finalization function. See gc.h for details. */
638 /* The last parameter is a procedure that determines */
639 /* marking for finalization ordering. Any objects marked */
640 /* by that procedure will be guaranteed to not have been */
641 /* finalized when this finalizer is invoked. */
642 STATIC void GC_register_finalizer_inner(void * obj,
643 GC_finalization_proc fn, void *cd,
644 GC_finalization_proc *ofn, void **ocd,
645 finalization_mark_proc mp)
647 struct finalizable_object * curr_fo;
649 struct finalizable_object *new_fo = 0;
650 hdr *hhdr = NULL; /* initialized to prevent warning. */
653 if (EXPECT(GC_find_leak, FALSE)) return;
655 if (log_fo_table_size == -1
656 || GC_fo_entries > ((word)1 << log_fo_table_size)) {
657 GC_grow_table((struct hash_chain_entry ***)&GC_fnlz_roots.fo_head,
660 if (log_fo_table_size < 0) ABORT("log_size is negative");
662 GC_COND_LOG_PRINTF("Grew fo table to %u entries\n",
663 1 << (unsigned)log_fo_table_size);
665 /* in the THREADS case we hold allocation lock. */
667 struct finalizable_object *prev_fo = NULL;
670 index = HASH2(obj, log_fo_table_size);
671 curr_fo = GC_fnlz_roots.fo_head[index];
672 while (curr_fo != 0) {
673 GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
674 if (curr_fo -> fo_hidden_base == GC_HIDE_POINTER(obj)) {
675 /* Interruption by a signal in the middle of this */
676 /* should be safe. The client may see only *ocd */
677 /* updated, but we'll declare that to be his problem. */
678 if (ocd) *ocd = (void *) (curr_fo -> fo_client_data);
679 if (ofn) *ofn = curr_fo -> fo_fn;
680 /* Delete the structure for obj. */
682 GC_fnlz_roots.fo_head[index] = fo_next(curr_fo);
684 fo_set_next(prev_fo, fo_next(curr_fo));
688 /* May not happen if we get a signal. But a high */
689 /* estimate will only make the table larger than */
691 # if !defined(THREADS) && !defined(DBG_HDRS_ALL)
692 GC_free((void *)curr_fo);
695 curr_fo -> fo_fn = fn;
696 curr_fo -> fo_client_data = (ptr_t)cd;
697 curr_fo -> fo_mark_proc = mp;
698 /* Reinsert it. We deleted it first to maintain */
699 /* consistency in the event of a signal. */
701 GC_fnlz_roots.fo_head[index] = curr_fo;
703 fo_set_next(prev_fo, curr_fo);
707 # ifndef DBG_HDRS_ALL
708 if (EXPECT(new_fo != 0, FALSE)) {
709 /* Free unused new_fo returned by GC_oom_fn() */
710 GC_free((void *)new_fo);
716 curr_fo = fo_next(curr_fo);
718 if (EXPECT(new_fo != 0, FALSE)) {
719 /* new_fo is returned by GC_oom_fn(). */
722 if (NULL == hhdr) ABORT("Bad hhdr in GC_register_finalizer_inner");
733 if (EXPECT(0 == hhdr, FALSE)) {
734 /* We won't collect it, hence finalizer wouldn't be run. */
740 new_fo = (struct finalizable_object *)
741 GC_INTERNAL_MALLOC(sizeof(struct finalizable_object),NORMAL);
742 if (EXPECT(new_fo != 0, TRUE))
746 new_fo = (struct finalizable_object *)
747 (*oom_fn)(sizeof(struct finalizable_object));
749 /* No enough memory. *ocd and *ofn remains unchanged. */
752 /* It's not likely we'll make it here, but ... */
754 /* Recalculate index since the table may grow and */
755 /* check again that our finalizer is not in the table. */
757 GC_ASSERT(GC_size(new_fo) >= sizeof(struct finalizable_object));
760 new_fo -> fo_hidden_base = GC_HIDE_POINTER(obj);
761 new_fo -> fo_fn = fn;
762 new_fo -> fo_client_data = (ptr_t)cd;
763 new_fo -> fo_object_size = hhdr -> hb_sz;
764 new_fo -> fo_mark_proc = mp;
765 fo_set_next(new_fo, GC_fnlz_roots.fo_head[index]);
767 GC_fnlz_roots.fo_head[index] = new_fo;
771 GC_API void GC_CALL GC_register_finalizer(void * obj,
772 GC_finalization_proc fn, void * cd,
773 GC_finalization_proc *ofn, void ** ocd)
775 GC_register_finalizer_inner(obj, fn, cd, ofn,
776 ocd, GC_normal_finalize_mark_proc);
779 GC_API void GC_CALL GC_register_finalizer_ignore_self(void * obj,
780 GC_finalization_proc fn, void * cd,
781 GC_finalization_proc *ofn, void ** ocd)
783 GC_register_finalizer_inner(obj, fn, cd, ofn,
784 ocd, GC_ignore_self_finalize_mark_proc);
787 GC_API void GC_CALL GC_register_finalizer_no_order(void * obj,
788 GC_finalization_proc fn, void * cd,
789 GC_finalization_proc *ofn, void ** ocd)
791 GC_register_finalizer_inner(obj, fn, cd, ofn,
792 ocd, GC_null_finalize_mark_proc);
795 static GC_bool need_unreachable_finalization = FALSE;
796 /* Avoid the work if this isn't used. */
798 GC_API void GC_CALL GC_register_finalizer_unreachable(void * obj,
799 GC_finalization_proc fn, void * cd,
800 GC_finalization_proc *ofn, void ** ocd)
802 need_unreachable_finalization = TRUE;
803 GC_ASSERT(GC_java_finalization);
804 GC_register_finalizer_inner(obj, fn, cd, ofn,
805 ocd, GC_unreachable_finalize_mark_proc);
809 STATIC void GC_dump_finalization_links(
810 const struct dl_hashtbl_s *dl_hashtbl)
812 size_t dl_size = dl_hashtbl->log_size == -1 ? 0 :
813 (size_t)1 << dl_hashtbl->log_size;
816 for (i = 0; i < dl_size; i++) {
817 struct disappearing_link *curr_dl;
819 for (curr_dl = dl_hashtbl -> head[i]; curr_dl != 0;
820 curr_dl = dl_next(curr_dl)) {
821 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_obj);
822 ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr_dl->dl_hidden_link);
824 GC_printf("Object: %p, link: %p\n",
825 (void *)real_ptr, (void *)real_link);
830 GC_API void GC_CALL GC_dump_finalization(void)
832 struct finalizable_object * curr_fo;
833 size_t fo_size = log_fo_table_size == -1 ? 0 :
834 (size_t)1 << log_fo_table_size;
837 GC_printf("Disappearing (short) links:\n");
838 GC_dump_finalization_links(&GC_dl_hashtbl);
839 # ifndef GC_LONG_REFS_NOT_NEEDED
840 GC_printf("Disappearing long links:\n");
841 GC_dump_finalization_links(&GC_ll_hashtbl);
843 GC_printf("Finalizers:\n");
844 for (i = 0; i < fo_size; i++) {
845 for (curr_fo = GC_fnlz_roots.fo_head[i];
846 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
847 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
849 GC_printf("Finalizable object: %p\n", (void *)real_ptr);
853 #endif /* !NO_DEBUGGING */
856 STATIC word GC_old_dl_entries = 0; /* for stats printing */
857 # ifndef GC_LONG_REFS_NOT_NEEDED
858 STATIC word GC_old_ll_entries = 0;
860 #endif /* !SMALL_CONFIG */
863 /* Global variables to minimize the level of recursion when a client */
864 /* finalizer allocates memory. */
865 STATIC int GC_finalizer_nested = 0;
866 /* Only the lowest byte is used, the rest is */
867 /* padding for proper global data alignment */
868 /* required for some compilers (like Watcom). */
869 STATIC unsigned GC_finalizer_skipped = 0;
871 /* Checks and updates the level of finalizers recursion. */
872 /* Returns NULL if GC_invoke_finalizers() should not be called by the */
873 /* collector (to minimize the risk of a deep finalizers recursion), */
874 /* otherwise returns a pointer to GC_finalizer_nested. */
875 STATIC unsigned char *GC_check_finalizer_nested(void)
877 unsigned nesting_level = *(unsigned char *)&GC_finalizer_nested;
879 /* We are inside another GC_invoke_finalizers(). */
880 /* Skip some implicitly-called GC_invoke_finalizers() */
881 /* depending on the nesting (recursion) level. */
882 if (++GC_finalizer_skipped < (1U << nesting_level)) return NULL;
883 GC_finalizer_skipped = 0;
885 *(char *)&GC_finalizer_nested = (char)(nesting_level + 1);
886 return (unsigned char *)&GC_finalizer_nested;
890 #define ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr_dl, prev_dl) \
893 size_t dl_size = dl_hashtbl->log_size == -1 ? 0 : \
894 (size_t)1 << dl_hashtbl->log_size; \
895 for (i = 0; i < dl_size; i++) { \
896 struct disappearing_link *prev_dl = NULL; \
897 curr_dl = dl_hashtbl -> head[i]; \
900 #define ITERATE_DL_HASHTBL_END(curr_dl, prev_dl) \
902 curr_dl = dl_next(curr_dl); \
907 #define DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr_dl, prev_dl, next_dl) \
909 next_dl = dl_next(curr_dl); \
910 if (NULL == prev_dl) { \
911 dl_hashtbl -> head[i] = next_dl; \
913 dl_set_next(prev_dl, next_dl); \
915 GC_clear_mark_bit(curr_dl); \
916 dl_hashtbl -> entries--; \
921 GC_INLINE void GC_make_disappearing_links_disappear(
922 struct dl_hashtbl_s* dl_hashtbl)
924 struct disappearing_link *curr, *next;
926 ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
927 ptr_t real_ptr = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_obj);
928 ptr_t real_link = (ptr_t)GC_REVEAL_POINTER(curr->dl_hidden_link);
930 if (!GC_is_marked(real_ptr)) {
931 *(word *)real_link = 0;
932 GC_clear_mark_bit(curr);
933 DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
935 ITERATE_DL_HASHTBL_END(curr, prev)
938 GC_INLINE void GC_remove_dangling_disappearing_links(
939 struct dl_hashtbl_s* dl_hashtbl)
941 struct disappearing_link *curr, *next;
943 ITERATE_DL_HASHTBL_BEGIN(dl_hashtbl, curr, prev)
945 (ptr_t)GC_base(GC_REVEAL_POINTER(curr->dl_hidden_link));
947 if (NULL != real_link && !GC_is_marked(real_link)) {
948 GC_clear_mark_bit(curr);
949 DELETE_DL_HASHTBL_ENTRY(dl_hashtbl, curr, prev, next);
951 ITERATE_DL_HASHTBL_END(curr, prev)
954 /* Called with held lock (but the world is running). */
955 /* Cause disappearing links to disappear and unreachable objects to be */
956 /* enqueued for finalization. */
957 GC_INNER void GC_finalize(void)
959 struct finalizable_object * curr_fo, * prev_fo, * next_fo;
962 size_t fo_size = log_fo_table_size == -1 ? 0 :
963 (size_t)1 << log_fo_table_size;
965 # ifndef SMALL_CONFIG
966 /* Save current GC_[dl/ll]_entries value for stats printing */
967 GC_old_dl_entries = GC_dl_hashtbl.entries;
968 # ifndef GC_LONG_REFS_NOT_NEEDED
969 GC_old_ll_entries = GC_ll_hashtbl.entries;
973 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
974 GC_mark_togglerefs();
976 GC_make_disappearing_links_disappear(&GC_dl_hashtbl);
978 /* Mark all objects reachable via chains of 1 or more pointers */
979 /* from finalizable objects. */
980 GC_ASSERT(GC_mark_state == MS_NONE);
981 for (i = 0; i < fo_size; i++) {
982 for (curr_fo = GC_fnlz_roots.fo_head[i];
983 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
984 GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
985 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
986 if (!GC_is_marked(real_ptr)) {
987 GC_MARKED_FOR_FINALIZATION(real_ptr);
988 GC_MARK_FO(real_ptr, curr_fo -> fo_mark_proc);
989 if (GC_is_marked(real_ptr)) {
990 WARN("Finalization cycle involving %p\n", real_ptr);
995 /* Enqueue for finalization all objects that are still */
997 GC_bytes_finalized = 0;
998 for (i = 0; i < fo_size; i++) {
999 curr_fo = GC_fnlz_roots.fo_head[i];
1001 while (curr_fo != 0) {
1002 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1003 if (!GC_is_marked(real_ptr)) {
1004 if (!GC_java_finalization) {
1005 GC_set_mark_bit(real_ptr);
1007 /* Delete from hash table */
1008 next_fo = fo_next(curr_fo);
1009 if (NULL == prev_fo) {
1010 GC_fnlz_roots.fo_head[i] = next_fo;
1012 fo_set_next(prev_fo, next_fo);
1015 if (GC_object_finalized_proc)
1016 GC_object_finalized_proc(real_ptr);
1018 /* Add to list of objects awaiting finalization. */
1019 fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1020 GC_fnlz_roots.finalize_now = curr_fo;
1021 /* unhide object pointer so any future collections will */
1023 curr_fo -> fo_hidden_base =
1024 (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1025 GC_bytes_finalized +=
1026 curr_fo -> fo_object_size
1027 + sizeof(struct finalizable_object);
1028 GC_ASSERT(GC_is_marked(GC_base(curr_fo)));
1032 curr_fo = fo_next(curr_fo);
1037 if (GC_java_finalization) {
1038 /* make sure we mark everything reachable from objects finalized
1039 using the no_order mark_proc */
1040 for (curr_fo = GC_fnlz_roots.finalize_now;
1041 curr_fo != NULL; curr_fo = fo_next(curr_fo)) {
1042 real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1043 if (!GC_is_marked(real_ptr)) {
1044 if (curr_fo -> fo_mark_proc == GC_null_finalize_mark_proc) {
1045 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1047 if (curr_fo -> fo_mark_proc != GC_unreachable_finalize_mark_proc) {
1048 GC_set_mark_bit(real_ptr);
1053 /* now revive finalize-when-unreachable objects reachable from
1054 other finalizable objects */
1055 if (need_unreachable_finalization) {
1056 curr_fo = GC_fnlz_roots.finalize_now;
1057 # if defined(GC_ASSERTIONS) || defined(LINT2)
1058 if (curr_fo != NULL && log_fo_table_size < 0)
1059 ABORT("log_size is negative");
1062 while (curr_fo != NULL) {
1063 next_fo = fo_next(curr_fo);
1064 if (curr_fo -> fo_mark_proc == GC_unreachable_finalize_mark_proc) {
1065 real_ptr = (ptr_t)curr_fo -> fo_hidden_base;
1066 if (!GC_is_marked(real_ptr)) {
1067 GC_set_mark_bit(real_ptr);
1069 if (NULL == prev_fo) {
1070 GC_fnlz_roots.finalize_now = next_fo;
1072 fo_set_next(prev_fo, next_fo);
1074 curr_fo -> fo_hidden_base =
1075 GC_HIDE_POINTER(curr_fo -> fo_hidden_base);
1076 GC_bytes_finalized -=
1077 curr_fo->fo_object_size + sizeof(struct finalizable_object);
1079 i = HASH2(real_ptr, log_fo_table_size);
1080 fo_set_next(curr_fo, GC_fnlz_roots.fo_head[i]);
1082 GC_fnlz_roots.fo_head[i] = curr_fo;
1092 GC_remove_dangling_disappearing_links(&GC_dl_hashtbl);
1093 # ifndef GC_TOGGLE_REFS_NOT_NEEDED
1094 GC_clear_togglerefs();
1096 # ifndef GC_LONG_REFS_NOT_NEEDED
1097 GC_make_disappearing_links_disappear(&GC_ll_hashtbl);
1098 GC_remove_dangling_disappearing_links(&GC_ll_hashtbl);
1101 if (GC_fail_count) {
1102 /* Don't prevent running finalizers if there has been an allocation */
1103 /* failure recently. */
1105 GC_reset_finalizer_nested();
1107 GC_finalizer_nested = 0;
1112 #ifndef JAVA_FINALIZATION_NOT_NEEDED
1114 /* Enqueue all remaining finalizers to be run - Assumes lock is held. */
1115 STATIC void GC_enqueue_all_finalizers(void)
1117 struct finalizable_object * curr_fo, * next_fo;
1122 fo_size = log_fo_table_size == -1 ? 0 : 1 << log_fo_table_size;
1123 GC_bytes_finalized = 0;
1124 for (i = 0; i < fo_size; i++) {
1125 curr_fo = GC_fnlz_roots.fo_head[i];
1126 GC_fnlz_roots.fo_head[i] = NULL;
1127 while (curr_fo != NULL) {
1128 real_ptr = (ptr_t)GC_REVEAL_POINTER(curr_fo->fo_hidden_base);
1129 GC_MARK_FO(real_ptr, GC_normal_finalize_mark_proc);
1130 GC_set_mark_bit(real_ptr);
1132 next_fo = fo_next(curr_fo);
1134 /* Add to list of objects awaiting finalization. */
1135 fo_set_next(curr_fo, GC_fnlz_roots.finalize_now);
1136 GC_fnlz_roots.finalize_now = curr_fo;
1138 /* unhide object pointer so any future collections will */
1140 curr_fo -> fo_hidden_base =
1141 (word)GC_REVEAL_POINTER(curr_fo -> fo_hidden_base);
1142 GC_bytes_finalized +=
1143 curr_fo -> fo_object_size + sizeof(struct finalizable_object);
1147 GC_fo_entries = 0; /* all entries deleted from the hash table */
1150 /* Invoke all remaining finalizers that haven't yet been run.
1151 * This is needed for strict compliance with the Java standard,
1152 * which can make the runtime guarantee that all finalizers are run.
1153 * Unfortunately, the Java standard implies we have to keep running
1154 * finalizers until there are no more left, a potential infinite loop.
1156 * Note that this is even more dangerous than the usual Java
1157 * finalizers, in that objects reachable from static variables
1158 * may have been finalized when these finalizers are run.
1159 * Finalizers run at this point must be prepared to deal with a
1160 * mostly broken world.
1161 * This routine is externally callable, so is called without
1162 * the allocation lock.
1164 GC_API void GC_CALL GC_finalize_all(void)
1169 while (GC_fo_entries > 0) {
1170 GC_enqueue_all_finalizers();
1172 GC_invoke_finalizers();
1173 /* Running the finalizers in this thread is arguably not a good */
1174 /* idea when we should be notifying another thread to run them. */
1175 /* But otherwise we don't have a great way to wait for them to */
1182 #endif /* !JAVA_FINALIZATION_NOT_NEEDED */
1184 /* Returns true if it is worth calling GC_invoke_finalizers. (Useful if */
1185 /* finalizers can only be called from some kind of "safe state" and */
1186 /* getting into that safe state is expensive.) */
1187 GC_ATTR_NO_SANITIZE_THREAD
1188 GC_API int GC_CALL GC_should_invoke_finalizers(void)
1190 return GC_fnlz_roots.finalize_now != NULL;
1193 /* Invoke finalizers for all objects that are ready to be finalized. */
1194 /* Should be called without allocation lock. */
1195 GC_API int GC_CALL GC_invoke_finalizers(void)
1198 word bytes_freed_before = 0; /* initialized to prevent warning. */
1201 while (GC_should_invoke_finalizers()) {
1202 struct finalizable_object * curr_fo;
1208 bytes_freed_before = GC_bytes_freed;
1209 /* Don't do this outside, since we need the lock. */
1211 curr_fo = GC_fnlz_roots.finalize_now;
1213 if (curr_fo != 0) GC_fnlz_roots.finalize_now = fo_next(curr_fo);
1215 if (curr_fo == 0) break;
1217 GC_fnlz_roots.finalize_now = fo_next(curr_fo);
1219 fo_set_next(curr_fo, 0);
1220 (*(curr_fo -> fo_fn))((ptr_t)(curr_fo -> fo_hidden_base),
1221 curr_fo -> fo_client_data);
1222 curr_fo -> fo_client_data = 0;
1224 /* Explicit freeing of curr_fo is probably a bad idea. */
1225 /* It throws off accounting if nearly all objects are */
1226 /* finalizable. Otherwise it should not matter. */
1228 /* bytes_freed_before is initialized whenever count != 0 */
1230 # if defined(THREADS) && !defined(THREAD_SANITIZER)
1231 /* A quick check whether some memory was freed. */
1232 /* The race with GC_free() is safe to be ignored */
1233 /* because we only need to know if the current */
1234 /* thread has deallocated something. */
1235 && bytes_freed_before != GC_bytes_freed
1239 GC_finalizer_bytes_freed += (GC_bytes_freed - bytes_freed_before);
1245 static word last_finalizer_notification = 0;
1247 GC_INNER void GC_notify_or_invoke_finalizers(void)
1249 GC_finalizer_notifier_proc notifier_fn = 0;
1250 # if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1251 static word last_back_trace_gc_no = 1; /* Skip first one. */
1255 # if defined(THREADS) && !defined(KEEP_BACK_PTRS) \
1256 && !defined(MAKE_BACK_GRAPH)
1257 /* Quick check (while unlocked) for an empty finalization queue. */
1258 if (!GC_should_invoke_finalizers())
1263 /* This is a convenient place to generate backtraces if appropriate, */
1264 /* since that code is not callable with the allocation lock. */
1265 # if defined(KEEP_BACK_PTRS) || defined(MAKE_BACK_GRAPH)
1266 if (GC_gc_no > last_back_trace_gc_no) {
1267 # ifdef KEEP_BACK_PTRS
1269 /* Stops when GC_gc_no wraps; that's OK. */
1270 last_back_trace_gc_no = (word)(-1); /* disable others. */
1271 for (i = 0; i < GC_backtraces; ++i) {
1272 /* FIXME: This tolerates concurrent heap mutation, */
1273 /* which may cause occasional mysterious results. */
1274 /* We need to release the GC lock, since GC_print_callers */
1275 /* acquires it. It probably shouldn't. */
1277 GC_generate_random_backtrace_no_gc();
1280 last_back_trace_gc_no = GC_gc_no;
1282 # ifdef MAKE_BACK_GRAPH
1283 if (GC_print_back_height) {
1285 GC_print_back_graph_stats();
1291 if (NULL == GC_fnlz_roots.finalize_now) {
1296 if (!GC_finalize_on_demand) {
1297 unsigned char *pnested = GC_check_finalizer_nested();
1299 /* Skip GC_invoke_finalizers() if nested */
1300 if (pnested != NULL) {
1301 (void) GC_invoke_finalizers();
1302 *pnested = 0; /* Reset since no more finalizers. */
1304 GC_ASSERT(NULL == GC_fnlz_roots.finalize_now);
1305 # endif /* Otherwise GC can run concurrently and add more */
1310 /* These variables require synchronization to avoid data races. */
1311 if (last_finalizer_notification != GC_gc_no) {
1312 last_finalizer_notification = GC_gc_no;
1313 notifier_fn = GC_finalizer_notifier;
1316 if (notifier_fn != 0)
1317 (*notifier_fn)(); /* Invoke the notifier */
1320 #ifndef SMALL_CONFIG
1321 # ifndef GC_LONG_REFS_NOT_NEEDED
1322 # define IF_LONG_REFS_PRESENT_ELSE(x,y) (x)
1324 # define IF_LONG_REFS_PRESENT_ELSE(x,y) (y)
1327 GC_INNER void GC_print_finalization_stats(void)
1329 struct finalizable_object *fo;
1330 unsigned long ready = 0;
1332 GC_log_printf("%lu finalization entries;"
1333 " %lu/%lu short/long disappearing links alive\n",
1334 (unsigned long)GC_fo_entries,
1335 (unsigned long)GC_dl_hashtbl.entries,
1336 (unsigned long)IF_LONG_REFS_PRESENT_ELSE(
1337 GC_ll_hashtbl.entries, 0));
1339 for (fo = GC_fnlz_roots.finalize_now; fo != NULL; fo = fo_next(fo))
1341 GC_log_printf("%lu finalization-ready objects;"
1342 " %ld/%ld short/long links cleared\n",
1344 (long)GC_old_dl_entries - (long)GC_dl_hashtbl.entries,
1345 (long)IF_LONG_REFS_PRESENT_ELSE(
1346 GC_old_ll_entries - GC_ll_hashtbl.entries, 0));
1348 #endif /* !SMALL_CONFIG */
1350 #endif /* !GC_NO_FINALIZATION */