Implement bitmap descriptor based marking for Boehm GC.
[platform/upstream/gcc.git] / libjava / java / lang / natClassLoader.cc
1 // natClassLoader.cc - Implementation of java.lang.ClassLoader native methods.
2
3 /* Copyright (C) 1999, 2000  Free Software Foundation
4
5    This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
9 details.  */
10
11 /* Author: Kresten Krab Thorup <krab@gnu.org>  */
12
13 #include <config.h>
14
15 #include <stdlib.h>
16 #include <string.h>
17
18 #include <gcj/cni.h>
19 #include <jvm.h>
20
21 #include <java-threads.h>
22 #include <java-interp.h>
23
24 #include <java/lang/Character.h>
25 #include <java/lang/Thread.h>
26 #include <java/lang/ClassLoader.h>
27 #include <gnu/gcj/runtime/VMClassLoader.h>
28 #include <java/lang/InternalError.h>
29 #include <java/lang/IllegalAccessError.h>
30 #include <java/lang/LinkageError.h>
31 #include <java/lang/ClassFormatError.h>
32 #include <java/lang/NoClassDefFoundError.h>
33 #include <java/lang/ClassNotFoundException.h>
34 #include <java/lang/ClassCircularityError.h>
35 #include <java/lang/IncompatibleClassChangeError.h>
36 #include <java/lang/reflect/Modifier.h>
37 #include <java/lang/Runtime.h>
38
39 #define CloneableClass _CL_Q34java4lang9Cloneable
40 extern java::lang::Class CloneableClass;
41 #define ObjectClass _CL_Q34java4lang6Object
42 extern java::lang::Class ObjectClass;
43 #define ClassClass _CL_Q34java4lang5Class
44 extern java::lang::Class ClassClass;
45 #define VMClassLoaderClass _CL_Q34java4lang17VMClassLoader
46 extern java::lang::Class VMClassLoader;
47 #define ClassLoaderClass _CL_Q34java4lang11ClassLoader
48 extern java::lang::Class ClassLoaderClass;
49 #define SerializableClass _CL_Q34java2io12Serializable
50 extern java::lang::Class SerializableClass;
51 /////////// java.lang.ClassLoader native methods ////////////
52
53 java::lang::ClassLoader *
54 java::lang::ClassLoader::getSystemClassLoader (void)
55 {
56   JvSynchronize sync (&ClassLoaderClass);
57   if (! system)
58     system = gnu::gcj::runtime::VMClassLoader::getVMClassLoader ();
59   return system;
60 }
61
62 java::lang::Class *
63 java::lang::ClassLoader::defineClass0 (jstring name,
64                                        jbyteArray data, 
65                                        jint offset,
66                                        jint length)
67 {
68 #ifdef INTERPRETER
69   jclass klass;
70   klass = (jclass) JvAllocObject (&ClassClass, sizeof (_Jv_InterpClass));
71
72   // synchronize on the class, so that it is not
73   // attempted initialized until we're done loading.
74   _Jv_MonitorEnter (klass);
75
76   // record which is the defining loader
77   klass->loader = this;
78
79   // register that we are the initiating loader...
80   if (name != 0)
81     {
82       _Jv_Utf8Const *   name2 = _Jv_makeUtf8Const (name);
83
84       _Jv_VerifyClassName (name2);
85
86       klass->name = name2;
87     }
88
89   try
90     {
91       _Jv_DefineClass (klass, data, offset, length);
92     }
93   catch (java::lang::Throwable *ex)
94     {
95       klass->state = JV_STATE_ERROR;
96       klass->notifyAll ();
97
98       _Jv_UnregisterClass (klass);
99
100       _Jv_MonitorExit (klass);
101
102       // FIXME: Here we may want to test that EX does
103       // indeed represent a valid exception.  That is,
104       // anything but ClassNotFoundException, 
105       // or some kind of Error.
106
107       JvThrow (ex);
108     }
109
110   // if everything proceeded sucessfully, we're loaded.
111   JvAssert (klass->state == JV_STATE_LOADED);
112
113   // if an exception is generated, this is initially missed.
114   // however, we come back here in handleException0 below...
115   _Jv_MonitorExit (klass);
116
117   return klass;
118
119 #else // INTERPRETER
120
121   return 0;
122 #endif
123 }
124
125 void
126 _Jv_WaitForState (jclass klass, int state)
127 {
128   if (klass->state >= state)
129     return;
130   
131   _Jv_MonitorEnter (klass) ;
132
133   if (state == JV_STATE_LINKED)
134     {
135       // Must call _Jv_PrepareCompiledClass while holding the class
136       // mutex.
137       _Jv_PrepareCompiledClass (klass);
138       _Jv_MonitorExit (klass);
139       return;
140     }
141         
142   java::lang::Thread *self = java::lang::Thread::currentThread();
143
144   // this is similar to the strategy for class initialization.
145   // if we already hold the lock, just leave.
146   while (klass->state <= state
147          && klass->thread 
148          && klass->thread != self)
149     klass->wait ();
150
151   _Jv_MonitorExit (klass);
152
153   if (klass->state == JV_STATE_ERROR)
154     {
155       _Jv_Throw (new java::lang::LinkageError ());
156     }
157 }
158
159 // Finish linking a class.  Only called from ClassLoader::resolveClass.
160 void
161 java::lang::ClassLoader::linkClass0 (java::lang::Class *klass)
162 {
163   if (klass->state >= JV_STATE_LINKED)
164     return;
165
166 #ifdef INTERPRETER
167   if (_Jv_IsInterpretedClass (klass))
168     _Jv_PrepareClass (klass);
169 #endif
170
171   _Jv_PrepareCompiledClass (klass);
172 }
173
174 void
175 java::lang::ClassLoader::markClassErrorState0 (java::lang::Class *klass)
176 {
177   klass->state = JV_STATE_ERROR;
178   klass->notifyAll ();
179 }
180
181
182 /** this is the only native method in VMClassLoader, so 
183     we define it here. */
184 jclass
185 gnu::gcj::runtime::VMClassLoader::findSystemClass (jstring name)
186 {
187   _Jv_Utf8Const *name_u = _Jv_makeUtf8Const (name);
188   jclass klass = _Jv_FindClassInCache (name_u, 0);
189
190   if (! klass)
191     {
192       // Turn `gnu.pkg.quux' into `gnu-pkg-quux'.  Then search for a
193       // module named (eg, on Linux) `gnu-pkg-quux.so', followed by
194       // `gnu-pkg.so' and `gnu.so'.  If loading one of these causes
195       // the class to appear in the cache, then use it.
196       jstring so_base_name = name->replace ('.', '-');
197
198       while (! klass && so_base_name && so_base_name->length() > 0)
199         {
200           using namespace ::java::lang;
201           Runtime *rt = Runtime::getRuntime();
202           jboolean loaded = rt->loadLibraryInternal (so_base_name);
203
204           jint nd = so_base_name->lastIndexOf ('-');
205           if (nd == -1)
206             so_base_name = NULL;
207           else
208             so_base_name = so_base_name->substring (0, nd);
209
210           if (loaded)
211             klass = _Jv_FindClassInCache (name_u, 0);
212         }
213     }
214
215   return klass;
216 }
217
218 jclass
219 java::lang::ClassLoader::findLoadedClass (jstring name)
220 {
221   return _Jv_FindClassInCache (_Jv_makeUtf8Const (name), this);
222 }
223
224
225 /** This function does class-preparation for compiled classes.  
226     NOTE: It contains replicated functionality from
227     _Jv_ResolvePoolEntry, and this is intentional, since that function
228     lives in resolve.cc which is entirely conditionally compiled.
229  */
230 void
231 _Jv_PrepareCompiledClass (jclass klass)
232 {
233   if (klass->state >= JV_STATE_LINKED)
234     return;
235
236   // Short-circuit, so that mutually dependent classes are ok.
237   klass->state = JV_STATE_LINKED;
238
239   _Jv_Constants *pool = &klass->constants;
240   for (int index = 1; index < pool->size; ++index)
241     {
242       if (pool->tags[index] == JV_CONSTANT_Class)
243         {
244           _Jv_Utf8Const *name = pool->data[index].utf8;
245           
246           jclass found;
247           if (name->data[0] == '[')
248             found = _Jv_FindClassFromSignature (&name->data[0],
249                                                 klass->loader);
250           else
251             found = _Jv_FindClass (name, klass->loader);
252                 
253           if (! found)
254             {
255               jstring str = _Jv_NewStringUTF (name->data);
256               JvThrow (new java::lang::ClassNotFoundException (str));
257             }
258
259           pool->data[index].clazz = found;
260           pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
261         }
262       else if (pool->tags[index] == JV_CONSTANT_String)
263         {
264           jstring str;
265           str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
266           pool->data[index].o = str;
267           pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
268         }
269     }
270
271 #ifdef INTERPRETER
272   // FIXME: although the comment up top says that this function is
273   // only called for compiled classes, it is actually called for every
274   // class.
275   if (! _Jv_IsInterpretedClass (klass))
276     {
277 #endif /* INTERPRETER */
278       jfieldID f = JvGetFirstStaticField (klass);
279       for (int n = JvNumStaticFields (klass); n > 0; --n)
280         {
281           int mod = f->getModifiers ();
282           // Maybe the compiler should mark these with
283           // _Jv_FIELD_CONSTANT_VALUE?  For now we just know that this
284           // only happens for constant strings.
285           if (f->getClass () == &StringClass
286               && java::lang::reflect::Modifier::isStatic (mod)
287               && java::lang::reflect::Modifier::isFinal (mod))
288             {
289               jstring *strp = (jstring *) f->u.addr;
290               if (*strp)
291                 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
292             }
293           f = f->getNextField ();
294         }
295 #ifdef INTERPRETER
296     }
297 #endif /* INTERPRETER */
298
299   klass->notifyAll ();
300 }
301
302
303 //
304 //  A single class can have many "initiating" class loaders,
305 //  and a single "defining" class loader.  The Defining
306 //  class loader is what is returned from Class.getClassLoader()
307 //  and is used when loading dependent classes during resolution.
308 //  The set of initiating class loaders are used to ensure
309 //  safety of linking, and is maintained in the hash table
310 //  "initiated_classes".  A defining classloader is by definition also
311 //  initiating, so we only store classes in this table, if they have more
312 //  than one class loader associated.
313 //
314
315
316 // Size of local hash table.
317 #define HASH_LEN 1013
318
319 // Hash function for Utf8Consts.
320 #define HASH_UTF(Utf) (((Utf)->hash) % HASH_LEN)
321
322 struct _Jv_LoaderInfo {
323     _Jv_LoaderInfo          *next;
324     java::lang::Class       *klass;
325     java::lang::ClassLoader *loader;
326 };
327
328 static _Jv_LoaderInfo *initiated_classes[HASH_LEN];
329 static jclass loaded_classes[HASH_LEN];
330
331 // This is the root of a linked list of classes
332
333 \f
334
335 jclass
336 _Jv_FindClassInCache (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
337 {
338   _Jv_MonitorEnter (&ClassClass);
339   jint hash = HASH_UTF (name);
340
341   // first, if LOADER is a defining loader, then it is also initiating
342   jclass klass;
343   for (klass = loaded_classes[hash]; klass; klass = klass->next)
344     {
345       if (loader == klass->loader && _Jv_equalUtf8Consts (name, klass->name))
346         break;
347     }
348
349   // otherwise, it may be that the class in question was defined
350   // by some other loader, but that the loading was initiated by 
351   // the loader in question.
352   if (!klass)
353     {
354       _Jv_LoaderInfo *info;
355       for (info = initiated_classes[hash]; info; info = info->next)
356         {
357           if (loader == info->loader
358               && _Jv_equalUtf8Consts (name, info->klass->name))
359             {
360               klass = info->klass;
361               break;
362             }
363         }
364     }
365
366   _Jv_MonitorExit (&ClassClass);
367
368   return klass;
369 }
370
371 void
372 _Jv_UnregisterClass (jclass the_class)
373 {
374   _Jv_MonitorEnter (&ClassClass);
375   jint hash = HASH_UTF(the_class->name);
376
377   jclass *klass = &(loaded_classes[hash]);
378   for ( ; *klass; klass = &((*klass)->next))
379     {
380       if (*klass == the_class)
381         {
382           *klass = (*klass)->next;
383           break;
384         }
385     }
386
387   _Jv_LoaderInfo **info = &(initiated_classes[hash]);
388   for ( ; ; info = &((*info)->next))
389     {
390       while (*info && (*info)->klass == the_class)
391         {
392           *info = (*info)->next;
393         }
394
395       if (*info == NULL)
396         break;
397     }
398
399   _Jv_MonitorExit (&ClassClass);
400 }
401
402 void
403 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
404 {
405   _Jv_LoaderInfo *info = new _Jv_LoaderInfo; // non-gc alloc!
406   jint hash = HASH_UTF(klass->name);
407
408   _Jv_MonitorEnter (&ClassClass);
409   info->loader = loader;
410   info->klass  = klass;
411   info->next   = initiated_classes[hash];
412   initiated_classes[hash] = info;
413   _Jv_MonitorExit (&ClassClass);
414   
415 }
416
417 // This function is called many times during startup, before main() is
418 // run.  We do our runtime initialization here the very first time we
419 // are called.  At that point in time we know for certain we are
420 // running single-threaded, so we don't need to lock when modifying
421 // `init'.  CLASSES is NULL-terminated.
422 void
423 _Jv_RegisterClasses (jclass *classes)
424 {
425   static bool init = false;
426
427   if (! init)
428     {
429       init = true;
430       _Jv_InitThreads ();
431       _Jv_InitGC ();
432       _Jv_InitializeSyncMutex ();
433     }
434
435   JvSynchronize sync (&ClassClass);
436   for (; *classes; ++classes)
437     {
438       jclass klass = *classes;
439       jint hash = HASH_UTF (klass->name);
440       klass->next = loaded_classes[hash];
441       loaded_classes[hash] = klass;
442
443       // registering a compiled class causes
444       // it to be immediately "prepared".  
445       if (klass->state == JV_STATE_NOTHING)
446         klass->state = JV_STATE_COMPILED;
447     }
448 }
449
450 void
451 _Jv_RegisterClass (jclass klass)
452 {
453   jclass classes[2];
454   classes[0] = klass;
455   classes[1] = NULL;
456   _Jv_RegisterClasses (classes);
457 }
458
459 jclass
460 _Jv_FindClass (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
461 {
462   jclass klass = _Jv_FindClassInCache (name, loader);
463
464   if (! klass)
465     {
466       jstring sname = _Jv_NewStringUTF (name->data);
467
468       if (loader)
469         {
470           // Load using a user-defined loader, jvmspec 5.3.2
471           klass = loader->loadClass(sname, false);
472
473           // If "loader" delegated the loadClass operation to another
474           // loader, explicitly register that it is also an initiating
475           // loader of the given class.
476           if (klass && (klass->getClassLoader () != loader))
477             _Jv_RegisterInitiatingLoader (klass, loader);
478         }
479       else 
480         {
481           java::lang::ClassLoader *sys = java::lang::ClassLoader::system;
482           if (sys == NULL)
483             {
484               _Jv_InitClass (&ClassLoaderClass);
485               sys = java::lang::ClassLoader::getSystemClassLoader ();
486             }
487
488           // Load using the bootstrap loader jvmspec 5.3.1.
489           klass = sys->loadClass (sname, false); 
490
491           // Register that we're an initiating loader.
492           if (klass)
493             _Jv_RegisterInitiatingLoader (klass, 0);
494         }
495     }
496   else
497     {
498       // we need classes to be in the hash while
499       // we're loading, so that they can refer to themselves. 
500       _Jv_WaitForState (klass, JV_STATE_LOADED);
501     }
502
503   return klass;
504 }
505
506 jclass
507 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
508               java::lang::ClassLoader *loader)
509 {
510   jclass ret = (jclass) JvAllocObject (&ClassClass);
511
512   ret->next = NULL;
513   ret->name = name;
514   ret->accflags = 0;
515   ret->superclass = superclass;
516   ret->constants.size = 0;
517   ret->constants.tags = NULL;
518   ret->constants.data = NULL;
519   ret->methods = NULL;
520   ret->method_count = 0;
521   ret->vtable_method_count = 0;
522   ret->fields = NULL;
523   ret->size_in_bytes = 0;
524   ret->field_count = 0;
525   ret->static_field_count = 0;
526   ret->vtable = NULL;
527   ret->interfaces = NULL;
528   ret->loader = loader;
529   ret->interface_count = 0;
530   ret->state = JV_STATE_NOTHING;
531   ret->thread = NULL;
532   ret->depth = 0;
533   ret->ancestors = NULL;
534   ret->idt = NULL;
535
536   _Jv_RegisterClass (ret);
537
538   return ret;
539 }
540
541 jclass
542 _Jv_FindArrayClass (jclass element, java::lang::ClassLoader *loader,
543                     _Jv_VTable *array_vtable)
544 {
545   _Jv_Utf8Const *array_name;
546   int len;
547   if (element->isPrimitive())
548     {
549       // For primitive types the array is cached in the class.
550       jclass ret = (jclass) element->methods;
551       if (ret)
552         return ret;
553       len = 3;
554     }
555   else
556     len = element->name->length + 5;
557
558   {
559     char signature[len];
560     int index = 0;
561     signature[index++] = '[';
562     // Compute name of array class to see if we've already cached it.
563     if (element->isPrimitive())
564       {
565         signature[index++] = (char) element->method_count;
566       }
567     else
568       {
569         size_t length = element->name->length;
570         const char *const name = element->name->data;
571         if (name[0] != '[')
572           signature[index++] = 'L';
573         memcpy (&signature[index], name, length);
574         index += length;
575         if (name[0] != '[')
576           signature[index++] = ';';
577       }      
578     array_name = _Jv_makeUtf8Const (signature, index);
579   }
580
581   jclass array_class = _Jv_FindClassInCache (array_name, element->loader);
582
583   if (! array_class)
584     {
585       // Create new array class.
586       array_class = _Jv_NewClass (array_name, &ObjectClass, element->loader);
587
588       // Note that `vtable_method_count' doesn't include the initial
589       // gc_descr slot.
590       JvAssert (ObjectClass.vtable_method_count == NUM_OBJECT_METHODS);
591       int dm_count = ObjectClass.vtable_method_count;
592
593       // Create a new vtable by copying Object's vtable (except the
594       // class pointer, of course).  Note that we allocate this as
595       // unscanned memory -- the vtables are handled specially by the
596       // GC.
597       int size = (sizeof (_Jv_VTable) + ((dm_count - 1) * sizeof (void *)));
598       _Jv_VTable *vtable;
599       if (array_vtable)
600         vtable = array_vtable;
601       else
602         vtable = (_Jv_VTable *) _Jv_AllocBytes (size);
603       vtable->clas = array_class;
604       memcpy (vtable->method, ObjectClass.vtable->method,
605               dm_count * sizeof (void *));
606       vtable->gc_descr = ObjectClass.vtable->gc_descr;
607       array_class->vtable = vtable;
608       array_class->vtable_method_count = ObjectClass.vtable_method_count;
609
610       // Stash the pointer to the element type.
611       array_class->methods = (_Jv_Method *) element;
612
613       // Register our interfaces.
614       static jclass interfaces[] = { &CloneableClass, &SerializableClass };
615       array_class->interfaces = interfaces;
616       array_class->interface_count = sizeof interfaces / sizeof interfaces[0];
617
618       // FIXME: Shouldn't this be synchronized? _Jv_PrepareConstantTimeTables
619       // needs to be called with the mutex for array_class held.
620       // Generate the interface dispatch table.
621       _Jv_PrepareConstantTimeTables (array_class);
622
623       // as per vmspec 5.3.3.2
624       array_class->accflags = element->accflags;
625
626       // FIXME: initialize other Class instance variables,
627       // e.g. `fields'.
628
629       // say this class is initialized and ready to go!
630       array_class->state = JV_STATE_DONE;
631
632       // vmspec, section 5.3.3 describes this
633       if (element->loader != loader)
634         _Jv_RegisterInitiatingLoader (array_class, loader);
635     }
636
637   // For primitive types, point back at this array.
638   if (element->isPrimitive())
639     element->methods = (_Jv_Method *) array_class;
640
641   return array_class;
642 }