lang.c (java_init): Handle flag_indirect_classes.
[gcc.git] / libjava / boehm.cc
1 // boehm.cc - interface between libjava and Boehm GC.
2
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
4 Free Software Foundation
5
6 This file is part of libgcj.
7
8 This software is copyrighted work licensed under the terms of the
9 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
10 details. */
11
12 #include <config.h>
13
14 #include <stdio.h>
15 #include <limits.h>
16
17 #include <jvm.h>
18 #include <gcj/cni.h>
19
20 #include <java/lang/Class.h>
21 #include <java/lang/reflect/Modifier.h>
22 #include <java-interp.h>
23
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.
26 #undef TRUE
27 #undef FALSE
28
29 // We include two autoconf headers. Avoid multiple definition warnings.
30 #undef PACKAGE_NAME
31 #undef PACKAGE_STRING
32 #undef PACKAGE_TARNAME
33 #undef PACKAGE_VERSION
34
35 #ifdef HAVE_DLFCN_H
36 #undef _GNU_SOURCE
37 #define _GNU_SOURCE
38 #include <dlfcn.h>
39 #include <link.h>
40 #endif
41
42 extern "C"
43 {
44 #include <gc_config.h>
45
46 // Set GC_DEBUG before including gc.h!
47 #ifdef LIBGCJ_GC_DEBUG
48 # define GC_DEBUG
49 #endif
50
51 #include <gc_mark.h>
52 #include <gc_gcj.h>
53 #include <javaxfc.h> // GC_finalize_all declaration.
54
55 #ifdef THREAD_LOCAL_ALLOC
56 # define GC_REDIRECT_TO_LOCAL
57 # include <gc_local_alloc.h>
58 #endif
59
60 // From boehm's misc.c
61 void GC_enable();
62 void GC_disable();
63 };
64
65 #define MAYBE_MARK(Obj, Top, Limit, Source) \
66 Top=GC_MARK_AND_PUSH((GC_PTR) Obj, Top, Limit, (GC_PTR *) Source)
67
68 // `kind' index used when allocating Java arrays.
69 static int array_kind_x;
70
71 // Freelist used for Java arrays.
72 static void **array_free_list;
73
74 static int _Jv_GC_has_static_roots (const char *filename, void *, size_t);
75
76 \f
77
78 // This is called by the GC during the mark phase. It marks a Java
79 // object. We use `void *' arguments and return, and not what the
80 // Boehm GC wants, to avoid pollution in our headers.
81 void *
82 _Jv_MarkObj (void *addr, void *msp, void *msl, void *env)
83 {
84 struct GC_ms_entry *mark_stack_ptr = (struct GC_ms_entry *)msp;
85 struct GC_ms_entry *mark_stack_limit = (struct GC_ms_entry *)msl;
86
87 if (env == (void *)1) /* Object allocated with debug allocator. */
88 addr = (GC_PTR)GC_USR_PTR_FROM_BASE(addr);
89 jobject obj = (jobject) addr;
90
91 _Jv_VTable *dt = *(_Jv_VTable **) addr;
92 // The object might not yet have its vtable set, or it might
93 // really be an object on the freelist. In either case, the vtable slot
94 // will either be 0, or it will point to a cleared object.
95 // This assumes Java objects have size at least 3 words,
96 // including the header. But this should remain true, since this
97 // should only be used with debugging allocation or with large objects.
98 if (__builtin_expect (! dt || !(dt -> get_finalizer()), false))
99 return mark_stack_ptr;
100 jclass klass = dt->clas;
101 GC_PTR p;
102
103 p = (GC_PTR) dt;
104 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
105
106 # ifndef JV_HASH_SYNCHRONIZATION
107 // Every object has a sync_info pointer.
108 p = (GC_PTR) obj->sync_info;
109 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
110 # endif
111
112 if (__builtin_expect (klass == &java::lang::Class::class$, false))
113 {
114 // Currently we allocate some of the memory referenced from class objects
115 // as pointerfree memory, and then mark it more intelligently here.
116 // We ensure that the ClassClass mark descriptor forces invocation of
117 // this procedure.
118 // Correctness of this is subtle, but it looks OK to me for now. For the incremental
119 // collector, we need to make sure that the class object is written whenever
120 // any of the subobjects are altered and may need rescanning. This may be tricky
121 // during construction, and this may not be the right way to do this with
122 // incremental collection.
123 // If we overflow the mark stack, we will rescan the class object, so we should
124 // be OK. The same applies if we redo the mark phase because win32 unmapped part
125 // of our root set. - HB
126 jclass c = (jclass) addr;
127
128 p = (GC_PTR) c->name;
129 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
130 p = (GC_PTR) c->superclass;
131 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
132
133 p = (GC_PTR) c->constants.tags;
134 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
135 p = (GC_PTR) c->constants.data;
136 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
137
138 // If the class is an array, then the methods field holds a
139 // pointer to the element class. If the class is primitive,
140 // then the methods field holds a pointer to the array class.
141 p = (GC_PTR) c->methods;
142 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
143
144 p = (GC_PTR) c->fields;
145 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
146
147 // The vtable might be allocated even for compiled code.
148 p = (GC_PTR) c->vtable;
149 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
150
151 p = (GC_PTR) c->interfaces;
152 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
153 p = (GC_PTR) c->loader;
154 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
155
156 // The dispatch tables can be allocated at runtime.
157 p = (GC_PTR) c->ancestors;
158 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
159
160 p = (GC_PTR) c->idt;
161 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
162
163 p = (GC_PTR) c->arrayclass;
164 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
165 p = (GC_PTR) c->protectionDomain;
166 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
167 p = (GC_PTR) c->hack_signers;
168 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
169 p = (GC_PTR) c->aux_info;
170 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, c);
171 }
172 else
173 {
174 // NOTE: each class only holds information about the class
175 // itself. So we must do the marking for the entire inheritance
176 // tree in order to mark all fields. FIXME: what about
177 // interfaces? We skip Object here, because Object only has a
178 // sync_info, and we handled that earlier.
179 // Note: occasionally `klass' can be null. For instance, this
180 // can happen if a GC occurs between the point where an object
181 // is allocated and where the vtbl slot is set.
182 while (klass && klass != &java::lang::Object::class$)
183 {
184 jfieldID field = JvGetFirstInstanceField (klass);
185 jint max = JvNumInstanceFields (klass);
186
187 for (int i = 0; i < max; ++i)
188 {
189 if (JvFieldIsRef (field))
190 {
191 jobject val = JvGetObjectField (obj, field);
192 p = (GC_PTR) val;
193 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, obj);
194 }
195 field = field->getNextField ();
196 }
197 klass = klass->getSuperclass();
198 }
199 }
200
201 return mark_stack_ptr;
202 }
203
204 // This is called by the GC during the mark phase. It marks a Java
205 // array (of objects). We use `void *' arguments and return, and not
206 // what the Boehm GC wants, to avoid pollution in our headers.
207 void *
208 _Jv_MarkArray (void *addr, void *msp, void *msl, void *env)
209 {
210 struct GC_ms_entry *mark_stack_ptr = (struct GC_ms_entry *)msp;
211 struct GC_ms_entry *mark_stack_limit = (struct GC_ms_entry *)msl;
212
213 if (env == (void *)1) /* Object allocated with debug allocator. */
214 addr = (void *)GC_USR_PTR_FROM_BASE(addr);
215 jobjectArray array = (jobjectArray) addr;
216
217 _Jv_VTable *dt = *(_Jv_VTable **) addr;
218 // Assumes size >= 3 words. That's currently true since arrays have
219 // a vtable, sync pointer, and size. If the sync pointer goes away,
220 // we may need to round up the size.
221 if (__builtin_expect (! dt || !(dt -> get_finalizer()), false))
222 return mark_stack_ptr;
223 GC_PTR p;
224
225 p = (GC_PTR) dt;
226 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
227
228 # ifndef JV_HASH_SYNCHRONIZATION
229 // Every object has a sync_info pointer.
230 p = (GC_PTR) array->sync_info;
231 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
232 # endif
233
234 for (int i = 0; i < JvGetArrayLength (array); ++i)
235 {
236 jobject obj = elements (array)[i];
237 p = (GC_PTR) obj;
238 MAYBE_MARK (p, mark_stack_ptr, mark_stack_limit, array);
239 }
240
241 return mark_stack_ptr;
242 }
243
244 // Generate a GC marking descriptor for a class.
245 //
246 // We assume that the gcj mark proc has index 0. This is a dubious assumption,
247 // since another one could be registered first. But the compiler also
248 // knows this, so in that case everything else will break, too.
249 #define GCJ_DEFAULT_DESCR GC_MAKE_PROC(GC_GCJ_RESERVED_MARK_PROC_INDEX,0)
250
251 void *
252 _Jv_BuildGCDescr(jclass self)
253 {
254 jlong desc = 0;
255 jint bits_per_word = CHAR_BIT * sizeof (void *);
256
257 // Note: for now we only consider a bitmap mark descriptor. We
258 // could also handle the case where the first N fields of a type are
259 // references. However, this is not very likely to be used by many
260 // classes, and it is easier to compute things this way.
261
262 // The vtable pointer.
263 desc |= 1ULL << (bits_per_word - 1);
264 #ifndef JV_HASH_SYNCHRONIZATION
265 // The sync_info field.
266 desc |= 1ULL << (bits_per_word - 2);
267 #endif
268
269 for (jclass klass = self; klass != NULL; klass = klass->getSuperclass())
270 {
271 jfieldID field = JvGetFirstInstanceField(klass);
272 int count = JvNumInstanceFields(klass);
273
274 for (int i = 0; i < count; ++i)
275 {
276 if (field->isRef())
277 {
278 unsigned int off = field->getOffset();
279 // If we run into a weird situation, we bail.
280 if (off % sizeof (void *) != 0)
281 return (void *) (GCJ_DEFAULT_DESCR);
282 off /= sizeof (void *);
283 // If we find a field outside the range of our bitmap,
284 // fall back to procedure marker. The bottom 2 bits are
285 // reserved.
286 if (off >= (unsigned) bits_per_word - 2)
287 return (void *) (GCJ_DEFAULT_DESCR);
288 desc |= 1ULL << (bits_per_word - off - 1);
289 }
290
291 field = field->getNextField();
292 }
293 }
294
295 // For bitmap mark type, bottom bits are 01.
296 desc |= 1;
297 // Bogus warning avoidance (on many platforms).
298 return (void *) (unsigned long) desc;
299 }
300
301 // Allocate some space that is known to be pointer-free.
302 void *
303 _Jv_AllocBytes (jsize size)
304 {
305 void *r = GC_MALLOC_ATOMIC (size);
306 // We have to explicitly zero memory here, as the GC doesn't
307 // guarantee that PTRFREE allocations are zeroed. Note that we
308 // don't have to do this for other allocation types because we set
309 // the `ok_init' flag in the type descriptor.
310 memset (r, 0, size);
311 return r;
312 }
313
314 #ifdef LIBGCJ_GC_DEBUG
315
316 void *
317 _Jv_AllocObj (jsize size, jclass klass)
318 {
319 return GC_GCJ_MALLOC (size, klass->vtable);
320 }
321
322 void *
323 _Jv_AllocPtrFreeObj (jsize size, jclass klass)
324 {
325 #ifdef JV_HASH_SYNCHRONIZATION
326 void * obj = GC_MALLOC_ATOMIC(size);
327 *((_Jv_VTable **) obj) = klass->vtable;
328 #else
329 void * obj = GC_GCJ_MALLOC(size, klass->vtable);
330 #endif
331 return obj;
332 }
333
334 #endif /* LIBGCJ_GC_DEBUG */
335 // In the non-debug case, the above two functions are defined
336 // as inline functions in boehm-gc.h. In the debug case we
337 // really want to take advantage of the definitions in gc_gcj.h.
338
339 // Allocate space for a new Java array.
340 // Used only for arrays of objects.
341 void *
342 _Jv_AllocArray (jsize size, jclass klass)
343 {
344 void *obj;
345
346 #ifdef LIBGCJ_GC_DEBUG
347 // There isn't much to lose by scanning this conservatively.
348 // If we didn't, the mark proc would have to understand that
349 // it needed to skip the header.
350 obj = GC_MALLOC(size);
351 #else
352 const jsize min_heap_addr = 16*1024;
353 // A heuristic. If size is less than this value, the size
354 // stored in the array can't possibly be misinterpreted as
355 // a pointer. Thus we lose nothing by scanning the object
356 // completely conservatively, since no misidentification can
357 // take place.
358
359 if (size < min_heap_addr)
360 obj = GC_MALLOC(size);
361 else
362 obj = GC_generic_malloc (size, array_kind_x);
363 #endif
364 *((_Jv_VTable **) obj) = klass->vtable;
365 return obj;
366 }
367
368 /* Allocate space for a new non-Java object, which does not have the usual
369 Java object header but may contain pointers to other GC'ed objects. */
370 void *
371 _Jv_AllocRawObj (jsize size)
372 {
373 return (void *) GC_MALLOC (size ? size : 1);
374 }
375
376 static void
377 call_finalizer (GC_PTR obj, GC_PTR client_data)
378 {
379 _Jv_FinalizerFunc *fn = (_Jv_FinalizerFunc *) client_data;
380 jobject jobj = (jobject) obj;
381
382 (*fn) (jobj);
383 }
384
385 void
386 _Jv_RegisterFinalizer (void *object, _Jv_FinalizerFunc *meth)
387 {
388 GC_REGISTER_FINALIZER_NO_ORDER (object, call_finalizer, (GC_PTR) meth,
389 NULL, NULL);
390 }
391
392 void
393 _Jv_RunFinalizers (void)
394 {
395 GC_invoke_finalizers ();
396 }
397
398 void
399 _Jv_RunAllFinalizers (void)
400 {
401 GC_finalize_all ();
402 }
403
404 void
405 _Jv_RunGC (void)
406 {
407 GC_gcollect ();
408 }
409
410 long
411 _Jv_GCTotalMemory (void)
412 {
413 return GC_get_heap_size ();
414 }
415
416 long
417 _Jv_GCFreeMemory (void)
418 {
419 return GC_get_free_bytes ();
420 }
421
422 void
423 _Jv_GCSetInitialHeapSize (size_t size)
424 {
425 size_t current = GC_get_heap_size ();
426 if (size > current)
427 GC_expand_hp (size - current);
428 }
429
430 void
431 _Jv_GCSetMaximumHeapSize (size_t size)
432 {
433 GC_set_max_heap_size ((GC_word) size);
434 }
435
436 void
437 _Jv_DisableGC (void)
438 {
439 GC_disable();
440 }
441
442 void
443 _Jv_EnableGC (void)
444 {
445 GC_enable();
446 }
447
448 static void * handle_out_of_memory(size_t)
449 {
450 _Jv_ThrowNoMemory();
451 }
452
453 static void
454 gcj_describe_type_fn(void *obj, char *out_buf)
455 {
456 _Jv_VTable *dt = *(_Jv_VTable **) obj;
457
458 if (! dt /* Shouldn't happen */)
459 {
460 strcpy(out_buf, "GCJ (bad)");
461 return;
462 }
463 jclass klass = dt->clas;
464 if (!klass /* shouldn't happen */)
465 {
466 strcpy(out_buf, "GCJ (bad)");
467 return;
468 }
469 jstring name = klass -> getName();
470 size_t len = name -> length();
471 if (len >= GC_TYPE_DESCR_LEN) len = GC_TYPE_DESCR_LEN - 1;
472 JvGetStringUTFRegion (name, 0, len, out_buf);
473 out_buf[len] = '\0';
474 }
475
476 void
477 _Jv_InitGC (void)
478 {
479 int proc;
480 static bool gc_initialized;
481
482 if (gc_initialized)
483 return;
484
485 gc_initialized = 1;
486
487 // Ignore pointers that do not point to the start of an object.
488 GC_all_interior_pointers = 0;
489
490 #ifdef HAVE_DLFCN_H
491 // Tell the collector to ask us before scanning DSOs.
492 GC_register_has_static_roots_callback (_Jv_GC_has_static_roots);
493 #endif
494
495 // Configure the collector to use the bitmap marking descriptors that we
496 // stash in the class vtable.
497 // We always use mark proc descriptor 0, since the compiler knows
498 // about it.
499 GC_init_gcj_malloc (0, (void *) _Jv_MarkObj);
500
501 // Cause an out of memory error to be thrown from the allocators,
502 // instead of returning 0. This is cheaper than checking on allocation.
503 GC_oom_fn = handle_out_of_memory;
504
505 GC_java_finalization = 1;
506
507 // We use a different mark procedure for object arrays. This code
508 // configures a different object `kind' for object array allocation and
509 // marking.
510 array_free_list = GC_new_free_list();
511 proc = GC_new_proc((GC_mark_proc)_Jv_MarkArray);
512 array_kind_x = GC_new_kind(array_free_list, GC_MAKE_PROC (proc, 0), 0, 1);
513
514 // Arrange to have the GC print Java class names in backtraces, etc.
515 GC_register_describe_type_fn(GC_gcj_kind, gcj_describe_type_fn);
516 GC_register_describe_type_fn(GC_gcj_debug_kind, gcj_describe_type_fn);
517 }
518
519 #ifdef JV_HASH_SYNCHRONIZATION
520 // Allocate an object with a fake vtable pointer, which causes only
521 // the first field (beyond the fake vtable pointer) to be traced.
522 // Eventually this should probably be generalized.
523
524 static _Jv_VTable trace_one_vtable = {
525 0, // class pointer
526 (void *)(2 * sizeof(void *)),
527 // descriptor; scan 2 words incl. vtable ptr.
528 // Least significant bits must be zero to
529 // identify this as a length descriptor
530 {0} // First method
531 };
532
533 void *
534 _Jv_AllocTraceOne (jsize size /* includes vtable slot */)
535 {
536 return GC_GCJ_MALLOC (size, &trace_one_vtable);
537 }
538
539 // Ditto for two words.
540 // the first field (beyond the fake vtable pointer) to be traced.
541 // Eventually this should probably be generalized.
542
543 static _Jv_VTable trace_two_vtable =
544 {
545 0, // class pointer
546 (void *)(3 * sizeof(void *)),
547 // descriptor; scan 3 words incl. vtable ptr.
548 {0} // First method
549 };
550
551 void *
552 _Jv_AllocTraceTwo (jsize size /* includes vtable slot */)
553 {
554 return GC_GCJ_MALLOC (size, &trace_two_vtable);
555 }
556
557 #endif /* JV_HASH_SYNCHRONIZATION */
558
559 void
560 _Jv_GCInitializeFinalizers (void (*notifier) (void))
561 {
562 GC_finalize_on_demand = 1;
563 GC_finalizer_notifier = notifier;
564 }
565
566 void
567 _Jv_GCRegisterDisappearingLink (jobject *objp)
568 {
569 // This test helps to ensure that we meet a precondition of
570 // GC_general_register_disappearing_link, viz. "Obj must be a
571 // pointer to the first word of an object we allocated."
572 if (GC_base(*objp))
573 GC_general_register_disappearing_link ((GC_PTR *) objp, (GC_PTR) *objp);
574 }
575
576 jboolean
577 _Jv_GCCanReclaimSoftReference (jobject)
578 {
579 // For now, always reclaim soft references. FIXME.
580 return true;
581 }
582
583 \f
584
585 #ifdef HAVE_DLFCN_H
586
587 // We keep a store of the filenames of DSOs that need to be
588 // conservatively scanned by the garbage collector. During collection
589 // the gc calls _Jv_GC_has_static_roots() to see if the data segment
590 // of a DSO should be scanned.
591 typedef struct filename_node
592 {
593 char *name;
594 struct filename_node *link;
595 } filename_node;
596
597 #define FILENAME_STORE_SIZE 17
598 static filename_node *filename_store[FILENAME_STORE_SIZE];
599
600 // Find a filename in filename_store.
601 static filename_node **
602 find_file (const char *filename)
603 {
604 int index = strlen (filename) % FILENAME_STORE_SIZE;
605 filename_node **node = &filename_store[index];
606
607 while (*node)
608 {
609 if (strcmp ((*node)->name, filename) == 0)
610 return node;
611 node = &(*node)->link;
612 }
613
614 return node;
615 }
616
617 // Print the store of filenames of DSOs that need collection.
618 void
619 _Jv_print_gc_store (void)
620 {
621 for (int i = 0; i < FILENAME_STORE_SIZE; i++)
622 {
623 filename_node *node = filename_store[i];
624 while (node)
625 {
626 fprintf (stderr, "%s\n", node->name);
627 node = node->link;
628 }
629 }
630 }
631
632 // Create a new node in the store of libraries to collect.
633 static filename_node *
634 new_node (const char *filename)
635 {
636 filename_node *node = (filename_node*)_Jv_Malloc (sizeof (filename_node));
637 node->name = (char *)_Jv_Malloc (strlen (filename) + 1);
638 node->link = NULL;
639 strcpy (node->name, filename);
640
641 return node;
642 }
643
644 // Nonzero if the gc should scan this lib.
645 static int
646 _Jv_GC_has_static_roots (const char *filename, void *, size_t)
647 {
648 if (filename == NULL || strlen (filename) == 0)
649 // No filename; better safe than sorry.
650 return 1;
651
652 filename_node **node = find_file (filename);
653 if (*node)
654 return 1;
655
656 return 0;
657 }
658
659 #endif
660
661 // Register the DSO that contains p for collection.
662 void
663 _Jv_RegisterLibForGc (const void *p __attribute__ ((__unused__)))
664 {
665 #ifdef HAVE_DLFCN_H
666 Dl_info info;
667
668 if (dladdr (p, &info) != 0)
669 {
670 filename_node **node = find_file (info.dli_fname);
671 if (! *node)
672 *node = new_node (info.dli_fname);
673 }
674 #endif
675 }
676