OSDN Git Service

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