1 // boehm.cc - interface between libjava and Boehm GC.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
4 Free Software Foundation
6 This file is part of libgcj.
8 This software is copyrighted work licensed under the terms of the
9 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
20 #include <java/lang/Class.h>
21 #include <java/lang/reflect/Modifier.h>
22 #include <java-interp.h>
24 // More nastiness: the GC wants to define TRUE and FALSE. We don't
25 // need the Java definitions (themselves a hack), so we undefine them.
29 // We include two autoconf headers. Avoid multiple definition warnings.
32 #undef PACKAGE_TARNAME
33 #undef PACKAGE_VERSION
43 #include <gc_config.h>
45 // Set GC_DEBUG before including gc.h!
46 #ifdef LIBGCJ_GC_DEBUG
52 #include <javaxfc.h> // GC_finalize_all declaration.
54 #ifdef THREAD_LOCAL_ALLOC
55 # define GC_REDIRECT_TO_LOCAL
56 # include <gc_local_alloc.h>
59 // From boehm's misc.c
64 #define MAYBE_MARK(Obj, Top, Limit, Source) \
65 Top=GC_MARK_AND_PUSH((GC_PTR) Obj, Top, Limit, (GC_PTR *) Source)
67 // `kind' index used when allocating Java arrays.
68 static int array_kind_x
;
70 // Freelist used for Java arrays.
71 static void **array_free_list
;
73 static int _Jv_GC_has_static_roots (const char *filename
, void *, size_t);
77 // This is called by the GC during the mark phase. It marks a Java
78 // object. We use `void *' arguments and return, and not what the
79 // Boehm GC wants, to avoid pollution in our headers.
81 _Jv_MarkObj (void *addr
, void *msp
, void *msl
, void *env
)
83 struct GC_ms_entry
*mark_stack_ptr
= (struct GC_ms_entry
*)msp
;
84 struct GC_ms_entry
*mark_stack_limit
= (struct GC_ms_entry
*)msl
;
86 if (env
== (void *)1) /* Object allocated with debug allocator. */
87 addr
= (GC_PTR
)GC_USR_PTR_FROM_BASE(addr
);
88 jobject obj
= (jobject
) addr
;
90 _Jv_VTable
*dt
= *(_Jv_VTable
**) addr
;
91 // The object might not yet have its vtable set, or it might
92 // really be an object on the freelist. In either case, the vtable slot
93 // will either be 0, or it will point to a cleared object.
94 // This assumes Java objects have size at least 3 words,
95 // including the header. But this should remain true, since this
96 // should only be used with debugging allocation or with large objects.
97 if (__builtin_expect (! dt
|| !(dt
-> get_finalizer()), false))
98 return mark_stack_ptr
;
99 jclass klass
= dt
->clas
;
103 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, obj
);
105 # ifndef JV_HASH_SYNCHRONIZATION
106 // Every object has a sync_info pointer.
107 p
= (GC_PTR
) obj
->sync_info
;
108 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, obj
);
111 if (__builtin_expect (klass
== &java::lang::Class::class$
, false))
113 // Currently we allocate some of the memory referenced from class objects
114 // as pointerfree memory, and then mark it more intelligently here.
115 // We ensure that the ClassClass mark descriptor forces invocation of
117 // Correctness of this is subtle, but it looks OK to me for now. For the incremental
118 // collector, we need to make sure that the class object is written whenever
119 // any of the subobjects are altered and may need rescanning. This may be tricky
120 // during construction, and this may not be the right way to do this with
121 // incremental collection.
122 // If we overflow the mark stack, we will rescan the class object, so we should
123 // be OK. The same applies if we redo the mark phase because win32 unmapped part
124 // of our root set. - HB
125 jclass c
= (jclass
) addr
;
127 p
= (GC_PTR
) c
->name
;
128 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
129 p
= (GC_PTR
) c
->superclass
;
130 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
132 p
= (GC_PTR
) c
->constants
.tags
;
133 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
134 p
= (GC_PTR
) c
->constants
.data
;
135 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
137 // If the class is an array, then the methods field holds a
138 // pointer to the element class. If the class is primitive,
139 // then the methods field holds a pointer to the array class.
140 p
= (GC_PTR
) c
->methods
;
141 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
143 p
= (GC_PTR
) c
->fields
;
144 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
146 // The vtable might be allocated even for compiled code.
147 p
= (GC_PTR
) c
->vtable
;
148 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
150 p
= (GC_PTR
) c
->interfaces
;
151 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
152 p
= (GC_PTR
) c
->loader
;
153 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
155 // The dispatch tables can be allocated at runtime.
156 p
= (GC_PTR
) c
->ancestors
;
157 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
160 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
162 p
= (GC_PTR
) c
->arrayclass
;
163 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
164 p
= (GC_PTR
) c
->protectionDomain
;
165 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
166 p
= (GC_PTR
) c
->hack_signers
;
167 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
168 p
= (GC_PTR
) c
->aux_info
;
169 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
171 p
= (GC_PTR
) c
->reflection_data
;
172 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
174 // The class chain must be marked for runtime-allocated Classes
175 // loaded by the bootstrap ClassLoader.
176 p
= (GC_PTR
) c
->next_or_version
;
177 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, c
);
181 // NOTE: each class only holds information about the class
182 // itself. So we must do the marking for the entire inheritance
183 // tree in order to mark all fields. FIXME: what about
184 // interfaces? We skip Object here, because Object only has a
185 // sync_info, and we handled that earlier.
186 // Note: occasionally `klass' can be null. For instance, this
187 // can happen if a GC occurs between the point where an object
188 // is allocated and where the vtbl slot is set.
189 while (klass
&& klass
!= &java::lang::Object::class$
)
191 jfieldID field
= JvGetFirstInstanceField (klass
);
192 jint max
= JvNumInstanceFields (klass
);
194 for (int i
= 0; i
< max
; ++i
)
196 if (JvFieldIsRef (field
))
198 jobject val
= JvGetObjectField (obj
, field
);
200 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, obj
);
202 field
= field
->getNextField ();
204 klass
= klass
->getSuperclass();
208 return mark_stack_ptr
;
211 // This is called by the GC during the mark phase. It marks a Java
212 // array (of objects). We use `void *' arguments and return, and not
213 // what the Boehm GC wants, to avoid pollution in our headers.
215 _Jv_MarkArray (void *addr
, void *msp
, void *msl
, void *env
)
217 struct GC_ms_entry
*mark_stack_ptr
= (struct GC_ms_entry
*)msp
;
218 struct GC_ms_entry
*mark_stack_limit
= (struct GC_ms_entry
*)msl
;
220 if (env
== (void *)1) /* Object allocated with debug allocator. */
221 addr
= (void *)GC_USR_PTR_FROM_BASE(addr
);
222 jobjectArray array
= (jobjectArray
) addr
;
224 _Jv_VTable
*dt
= *(_Jv_VTable
**) addr
;
225 // Assumes size >= 3 words. That's currently true since arrays have
226 // a vtable, sync pointer, and size. If the sync pointer goes away,
227 // we may need to round up the size.
228 if (__builtin_expect (! dt
|| !(dt
-> get_finalizer()), false))
229 return mark_stack_ptr
;
233 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, array
);
235 # ifndef JV_HASH_SYNCHRONIZATION
236 // Every object has a sync_info pointer.
237 p
= (GC_PTR
) array
->sync_info
;
238 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, array
);
241 for (int i
= 0; i
< JvGetArrayLength (array
); ++i
)
243 jobject obj
= elements (array
)[i
];
245 MAYBE_MARK (p
, mark_stack_ptr
, mark_stack_limit
, array
);
248 return mark_stack_ptr
;
251 // Generate a GC marking descriptor for a class.
253 // We assume that the gcj mark proc has index 0. This is a dubious assumption,
254 // since another one could be registered first. But the compiler also
255 // knows this, so in that case everything else will break, too.
256 #define GCJ_DEFAULT_DESCR GC_MAKE_PROC(GC_GCJ_RESERVED_MARK_PROC_INDEX,0)
259 _Jv_BuildGCDescr(jclass self
)
262 jint bits_per_word
= CHAR_BIT
* sizeof (void *);
264 // Note: for now we only consider a bitmap mark descriptor. We
265 // could also handle the case where the first N fields of a type are
266 // references. However, this is not very likely to be used by many
267 // classes, and it is easier to compute things this way.
269 // The vtable pointer.
270 desc
|= 1ULL << (bits_per_word
- 1);
271 #ifndef JV_HASH_SYNCHRONIZATION
272 // The sync_info field.
273 desc
|= 1ULL << (bits_per_word
- 2);
276 for (jclass klass
= self
; klass
!= NULL
; klass
= klass
->getSuperclass())
278 jfieldID field
= JvGetFirstInstanceField(klass
);
279 int count
= JvNumInstanceFields(klass
);
281 for (int i
= 0; i
< count
; ++i
)
285 unsigned int off
= field
->getOffset();
286 // If we run into a weird situation, we bail.
287 if (off
% sizeof (void *) != 0)
288 return (void *) (GCJ_DEFAULT_DESCR
);
289 off
/= sizeof (void *);
290 // If we find a field outside the range of our bitmap,
291 // fall back to procedure marker. The bottom 2 bits are
293 if (off
>= (unsigned) bits_per_word
- 2)
294 return (void *) (GCJ_DEFAULT_DESCR
);
295 desc
|= 1ULL << (bits_per_word
- off
- 1);
298 field
= field
->getNextField();
302 // For bitmap mark type, bottom bits are 01.
304 // Bogus warning avoidance (on many platforms).
305 return (void *) (unsigned long) desc
;
308 // Allocate some space that is known to be pointer-free.
310 _Jv_AllocBytes (jsize size
)
312 void *r
= GC_MALLOC_ATOMIC (size
);
313 // We have to explicitly zero memory here, as the GC doesn't
314 // guarantee that PTRFREE allocations are zeroed. Note that we
315 // don't have to do this for other allocation types because we set
316 // the `ok_init' flag in the type descriptor.
321 #ifdef LIBGCJ_GC_DEBUG
324 _Jv_AllocObj (jsize size
, jclass klass
)
326 return GC_GCJ_MALLOC (size
, klass
->vtable
);
330 _Jv_AllocPtrFreeObj (jsize size
, jclass klass
)
332 #ifdef JV_HASH_SYNCHRONIZATION
333 void * obj
= GC_MALLOC_ATOMIC(size
);
334 *((_Jv_VTable
**) obj
) = klass
->vtable
;
336 void * obj
= GC_GCJ_MALLOC(size
, klass
->vtable
);
341 #endif /* LIBGCJ_GC_DEBUG */
342 // In the non-debug case, the above two functions are defined
343 // as inline functions in boehm-gc.h. In the debug case we
344 // really want to take advantage of the definitions in gc_gcj.h.
346 // Allocate space for a new Java array.
347 // Used only for arrays of objects.
349 _Jv_AllocArray (jsize size
, jclass klass
)
353 #ifdef LIBGCJ_GC_DEBUG
354 // There isn't much to lose by scanning this conservatively.
355 // If we didn't, the mark proc would have to understand that
356 // it needed to skip the header.
357 obj
= GC_MALLOC(size
);
359 const jsize min_heap_addr
= 16*1024;
360 // A heuristic. If size is less than this value, the size
361 // stored in the array can't possibly be misinterpreted as
362 // a pointer. Thus we lose nothing by scanning the object
363 // completely conservatively, since no misidentification can
366 if (size
< min_heap_addr
)
367 obj
= GC_MALLOC(size
);
369 obj
= GC_generic_malloc (size
, array_kind_x
);
371 *((_Jv_VTable
**) obj
) = klass
->vtable
;
375 /* Allocate space for a new non-Java object, which does not have the usual
376 Java object header but may contain pointers to other GC'ed objects. */
378 _Jv_AllocRawObj (jsize size
)
380 return (void *) GC_MALLOC (size
? size
: 1);
384 typedef _Jv_ClosureList
*closure_list_pointer
;
386 /* Release closures in a _Jv_ClosureList. */
388 finalize_closure_list (GC_PTR obj
, GC_PTR
)
390 _Jv_ClosureList
**clpp
= (_Jv_ClosureList
**)obj
;
391 _Jv_ClosureList::releaseClosures (clpp
);
394 /* Allocate a double-indirect pointer to a _Jv_ClosureList that will
395 get garbage-collected after this double-indirect pointer becomes
396 unreachable by any other objects, including finalizable ones. */
398 _Jv_ClosureListFinalizer ()
400 _Jv_ClosureList
**clpp
;
401 clpp
= (_Jv_ClosureList
**)_Jv_AllocBytes (sizeof (*clpp
));
402 GC_REGISTER_FINALIZER_UNREACHABLE (clpp
, finalize_closure_list
,
406 #endif // INTERPRETER
409 call_finalizer (GC_PTR obj
, GC_PTR client_data
)
411 _Jv_FinalizerFunc
*fn
= (_Jv_FinalizerFunc
*) client_data
;
412 jobject jobj
= (jobject
) obj
;
418 _Jv_RegisterFinalizer (void *object
, _Jv_FinalizerFunc
*meth
)
420 GC_REGISTER_FINALIZER_NO_ORDER (object
, call_finalizer
, (GC_PTR
) meth
,
425 _Jv_RunFinalizers (void)
427 GC_invoke_finalizers ();
431 _Jv_RunAllFinalizers (void)
443 _Jv_GCTotalMemory (void)
445 return GC_get_heap_size ();
449 _Jv_GCFreeMemory (void)
451 return GC_get_free_bytes ();
455 _Jv_GCSetInitialHeapSize (size_t size
)
457 size_t current
= GC_get_heap_size ();
459 GC_expand_hp (size
- current
);
463 _Jv_GCSetMaximumHeapSize (size_t size
)
465 GC_set_max_heap_size ((GC_word
) size
);
480 static void * handle_out_of_memory(size_t)
486 gcj_describe_type_fn(void *obj
, char *out_buf
)
488 _Jv_VTable
*dt
= *(_Jv_VTable
**) obj
;
490 if (! dt
/* Shouldn't happen */)
492 strcpy(out_buf
, "GCJ (bad)");
495 jclass klass
= dt
->clas
;
496 if (!klass
/* shouldn't happen */)
498 strcpy(out_buf
, "GCJ (bad)");
501 jstring name
= klass
-> getName();
502 size_t len
= name
-> length();
503 if (len
>= GC_TYPE_DESCR_LEN
) len
= GC_TYPE_DESCR_LEN
- 1;
504 JvGetStringUTFRegion (name
, 0, len
, out_buf
);
512 static bool gc_initialized
;
519 // Ignore pointers that do not point to the start of an object.
520 GC_all_interior_pointers
= 0;
522 #if defined (HAVE_DLFCN_H) && defined (HAVE_DLADDR)
523 // Tell the collector to ask us before scanning DSOs.
524 GC_register_has_static_roots_callback (_Jv_GC_has_static_roots
);
527 // Configure the collector to use the bitmap marking descriptors that we
528 // stash in the class vtable.
529 // We always use mark proc descriptor 0, since the compiler knows
531 GC_init_gcj_malloc (0, (void *) _Jv_MarkObj
);
533 // Cause an out of memory error to be thrown from the allocators,
534 // instead of returning 0. This is cheaper than checking on allocation.
535 GC_oom_fn
= handle_out_of_memory
;
537 GC_java_finalization
= 1;
539 // We use a different mark procedure for object arrays. This code
540 // configures a different object `kind' for object array allocation and
542 array_free_list
= GC_new_free_list();
543 proc
= GC_new_proc((GC_mark_proc
)_Jv_MarkArray
);
544 array_kind_x
= GC_new_kind(array_free_list
, GC_MAKE_PROC (proc
, 0), 0, 1);
546 // Arrange to have the GC print Java class names in backtraces, etc.
547 GC_register_describe_type_fn(GC_gcj_kind
, gcj_describe_type_fn
);
548 GC_register_describe_type_fn(GC_gcj_debug_kind
, gcj_describe_type_fn
);
551 #ifdef JV_HASH_SYNCHRONIZATION
552 // Allocate an object with a fake vtable pointer, which causes only
553 // the first field (beyond the fake vtable pointer) to be traced.
554 // Eventually this should probably be generalized.
556 static _Jv_VTable trace_one_vtable
= {
558 (void *)(2 * sizeof(void *)),
559 // descriptor; scan 2 words incl. vtable ptr.
560 // Least significant bits must be zero to
561 // identify this as a length descriptor
566 _Jv_AllocTraceOne (jsize size
/* includes vtable slot */)
568 return GC_GCJ_MALLOC (size
, &trace_one_vtable
);
571 // Ditto for two words.
572 // the first field (beyond the fake vtable pointer) to be traced.
573 // Eventually this should probably be generalized.
575 static _Jv_VTable trace_two_vtable
=
578 (void *)(3 * sizeof(void *)),
579 // descriptor; scan 3 words incl. vtable ptr.
584 _Jv_AllocTraceTwo (jsize size
/* includes vtable slot */)
586 return GC_GCJ_MALLOC (size
, &trace_two_vtable
);
589 #endif /* JV_HASH_SYNCHRONIZATION */
592 _Jv_GCInitializeFinalizers (void (*notifier
) (void))
594 GC_finalize_on_demand
= 1;
595 GC_finalizer_notifier
= notifier
;
599 _Jv_GCRegisterDisappearingLink (jobject
*objp
)
601 // This test helps to ensure that we meet a precondition of
602 // GC_general_register_disappearing_link, viz. "Obj must be a
603 // pointer to the first word of an object we allocated."
605 GC_general_register_disappearing_link ((GC_PTR
*) objp
, (GC_PTR
) *objp
);
609 _Jv_GCCanReclaimSoftReference (jobject
)
611 // For now, always reclaim soft references. FIXME.
617 #if defined (HAVE_DLFCN_H) && defined (HAVE_DLADDR)
619 // We keep a store of the filenames of DSOs that need to be
620 // conservatively scanned by the garbage collector. During collection
621 // the gc calls _Jv_GC_has_static_roots() to see if the data segment
622 // of a DSO should be scanned.
623 typedef struct filename_node
626 struct filename_node
*link
;
629 #define FILENAME_STORE_SIZE 17
630 static filename_node
*filename_store
[FILENAME_STORE_SIZE
];
632 // Find a filename in filename_store.
633 static filename_node
**
634 find_file (const char *filename
)
636 int index
= strlen (filename
) % FILENAME_STORE_SIZE
;
637 filename_node
**node
= &filename_store
[index
];
641 if (strcmp ((*node
)->name
, filename
) == 0)
643 node
= &(*node
)->link
;
649 // Print the store of filenames of DSOs that need collection.
651 _Jv_print_gc_store (void)
653 for (int i
= 0; i
< FILENAME_STORE_SIZE
; i
++)
655 filename_node
*node
= filename_store
[i
];
658 fprintf (stderr
, "%s\n", node
->name
);
664 // Create a new node in the store of libraries to collect.
665 static filename_node
*
666 new_node (const char *filename
)
668 filename_node
*node
= (filename_node
*)_Jv_Malloc (sizeof (filename_node
));
669 node
->name
= (char *)_Jv_Malloc (strlen (filename
) + 1);
671 strcpy (node
->name
, filename
);
676 // Nonzero if the gc should scan this lib.
678 _Jv_GC_has_static_roots (const char *filename
, void *, size_t)
680 if (filename
== NULL
|| strlen (filename
) == 0)
681 // No filename; better safe than sorry.
684 filename_node
**node
= find_file (filename
);
693 // Register the DSO that contains p for collection.
695 _Jv_RegisterLibForGc (const void *p
__attribute__ ((__unused__
)))
697 #if defined (HAVE_DLFCN_H) && defined (HAVE_DLADDR)
700 if (dladdr (const_cast<void *>(p
), &info
) != 0)
702 filename_node
**node
= find_file (info
.dli_fname
);
704 *node
= new_node (info
.dli_fname
);
710 _Jv_SuspendThread (_Jv_Thread_t
*thread
)
712 #if defined(GC_PTHREADS) && !defined(GC_SOLARIS_THREADS) \
713 && !defined(GC_WIN32_THREADS) && !defined(GC_DARWIN_THREADS)
714 GC_suspend_thread (_Jv_GetPlatformThreadID (thread
));
719 _Jv_ResumeThread (_Jv_Thread_t
*thread
)
721 #if defined(GC_PTHREADS) && !defined(GC_SOLARIS_THREADS) \
722 && !defined(GC_WIN32_THREADS) && !defined(GC_DARWIN_THREADS)
723 GC_resume_thread (_Jv_GetPlatformThreadID (thread
));
728 _Jv_IsThreadSuspended (_Jv_Thread_t
*thread
)
730 #if defined(GC_PTHREADS) && !defined(GC_SOLARIS_THREADS) \
731 && !defined(GC_WIN32_THREADS) && !defined(GC_DARWIN_THREADS)
732 return GC_is_thread_suspended (_Jv_GetPlatformThreadID (thread
));
739 _Jv_GCAttachThread ()
741 // The registration interface is only defined on posixy systems and
742 // only actually works if pthread_getattr_np is defined.
743 // FIXME: until gc7 it is simpler to disable this on solaris.
744 #if defined(HAVE_PTHREAD_GETATTR_NP) && !defined(GC_SOLARIS_THREADS)
745 GC_register_my_thread ();
750 _Jv_GCDetachThread ()
752 #if defined(HAVE_PTHREAD_GETATTR_NP) && !defined(GC_SOLARIS_THREADS)
753 GC_unregister_my_thread ();