OSDN Git Service

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