OSDN Git Service

Jumbo patch:
[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  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     {
169       _Jv_PrepareClass (klass);
170     }
171 #endif
172
173   _Jv_PrepareCompiledClass (klass);
174 }
175
176 void
177 java::lang::ClassLoader::markClassErrorState0 (java::lang::Class *klass)
178 {
179   klass->state = JV_STATE_ERROR;
180   klass->notifyAll ();
181 }
182
183
184 /** this is the only native method in VMClassLoader, so 
185     we define it here. */
186 jclass
187 gnu::gcj::runtime::VMClassLoader::findSystemClass (jstring name)
188 {
189   _Jv_Utf8Const *name_u = _Jv_makeUtf8Const (name);
190   jclass klass = _Jv_FindClassInCache (name_u, 0);
191
192   if (! klass)
193     {
194       // Turn `gnu.pkg.quux' into `gnu-pkg-quux'.  Then search for a
195       // module named (eg, on Linux) `gnu-pkg-quux.so', followed by
196       // `gnu-pkg.so' and `gnu.so'.  If loading one of these causes
197       // the class to appear in the cache, then use it.
198       jstring so_base_name = name->replace ('.', '-');
199
200       while (! klass && so_base_name && so_base_name->length() > 0)
201         {
202           using namespace ::java::lang;
203           Runtime *rt = Runtime::getRuntime();
204           jboolean loaded = rt->loadLibraryInternal (so_base_name);
205
206           jint nd = so_base_name->lastIndexOf ('-');
207           if (nd == -1)
208             so_base_name = NULL;
209           else
210             so_base_name = so_base_name->substring (0, nd);
211
212           if (loaded)
213             klass = _Jv_FindClassInCache (name_u, 0);
214         }
215     }
216
217   return klass;
218 }
219
220 jclass
221 java::lang::ClassLoader::findLoadedClass (jstring name)
222 {
223   return _Jv_FindClassInCache (_Jv_makeUtf8Const (name), this);
224 }
225
226
227 /** This function does class-preparation for compiled classes.  
228     NOTE: It contains replicated functionality from
229     _Jv_ResolvePoolEntry, and this is intentional, since that function
230     lives in resolve.cc which is entirely conditionally compiled.
231  */
232 void
233 _Jv_PrepareCompiledClass(jclass klass)
234 {
235   if (klass->state >= JV_STATE_LINKED)
236     return;
237
238   // Short-circuit, so that mutually dependent classes are ok.
239   klass->state = JV_STATE_LINKED;
240
241   _Jv_Constants *pool = &klass->constants;
242   for (int index = 1; index < pool->size; ++index)
243     {
244       if (pool->tags[index] == JV_CONSTANT_Class)
245         {
246           _Jv_Utf8Const *name = pool->data[index].utf8;
247           
248           jclass found;
249           if (name->data[0] == '[')
250             found = _Jv_FindClassFromSignature (&name->data[0],
251                                                 klass->loader);
252           else
253             found = _Jv_FindClass (name, klass->loader);
254                 
255           if (! found)
256             {
257               jstring str = _Jv_NewStringUTF (name->data);
258               JvThrow (new java::lang::ClassNotFoundException (str));
259             }
260
261           pool->data[index].clazz = found;
262           pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
263         }
264             
265       else if (pool->tags[index] == JV_CONSTANT_String)
266         {
267           jstring str;
268           str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
269           pool->data[index].o = str;
270           pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
271         }
272     }
273
274   klass->notifyAll ();
275 }
276
277
278 //
279 //  A single class can have many "initiating" class loaders,
280 //  and a single "defining" class loader.  The Defining
281 //  class loader is what is returned from Class.getClassLoader()
282 //  and is used when loading dependent classes during resolution.
283 //  The set of initiating class loaders are used to ensure
284 //  safety of linking, and is maintained in the hash table
285 //  "initiated_classes".  A defining classloader is by definition also
286 //  initiating, so we only store classes in this table, if they have more
287 //  than one class loader associated.
288 //
289
290
291 // Size of local hash table.
292 #define HASH_LEN 1013
293
294 // Hash function for Utf8Consts.
295 #define HASH_UTF(Utf) (((Utf)->hash) % HASH_LEN)
296
297 struct _Jv_LoaderInfo {
298     _Jv_LoaderInfo          *next;
299     java::lang::Class       *klass;
300     java::lang::ClassLoader *loader;
301 };
302
303 static _Jv_LoaderInfo *initiated_classes[HASH_LEN];
304 static jclass loaded_classes[HASH_LEN];
305
306 // This is the root of a linked list of classes
307
308 \f
309
310 jclass
311 _Jv_FindClassInCache (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
312 {
313   _Jv_MonitorEnter (&ClassClass);
314   jint hash = HASH_UTF (name);
315
316   // first, if LOADER is a defining loader, then it is also initiating
317   jclass klass;
318   for (klass = loaded_classes[hash]; klass; klass = klass->next)
319     {
320       if (loader == klass->loader && _Jv_equalUtf8Consts (name, klass->name))
321         break;
322     }
323
324   // otherwise, it may be that the class in question was defined
325   // by some other loader, but that the loading was initiated by 
326   // the loader in question.
327   if (!klass)
328     {
329       _Jv_LoaderInfo *info;
330       for (info = initiated_classes[hash]; info; info = info->next)
331         {
332           if (loader == info->loader
333               && _Jv_equalUtf8Consts (name, info->klass->name))
334             {
335               klass = info->klass;
336               break;
337             }
338         }
339     }
340
341   _Jv_MonitorExit (&ClassClass);
342
343   return klass;
344 }
345
346 void
347 _Jv_UnregisterClass (jclass the_class)
348 {
349   _Jv_MonitorEnter (&ClassClass);
350   jint hash = HASH_UTF(the_class->name);
351
352   jclass *klass = &(loaded_classes[hash]);
353   for ( ; *klass; klass = &((*klass)->next))
354     {
355       if (*klass == the_class)
356         {
357           *klass = (*klass)->next;
358           break;
359         }
360     }
361
362   _Jv_LoaderInfo **info = &(initiated_classes[hash]);
363   for ( ; ; info = &((*info)->next))
364     {
365       while (*info && (*info)->klass == the_class)
366         {
367           *info = (*info)->next;
368         }
369
370       if (*info == NULL)
371         break;
372     }
373
374   _Jv_MonitorExit (&ClassClass);
375 }
376
377 void
378 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
379 {
380   _Jv_LoaderInfo *info = new _Jv_LoaderInfo; // non-gc alloc!
381   jint hash = HASH_UTF(klass->name);
382
383   _Jv_MonitorEnter (&ClassClass);
384   info->loader = loader;
385   info->klass  = klass;
386   info->next   = initiated_classes[hash];
387   initiated_classes[hash] = info;
388   _Jv_MonitorExit (&ClassClass);
389   
390 }
391
392 // This function is called many times during startup, before main() is
393 // run.  We do our runtime initialization here the very first time we
394 // are called.  At that point in time we know for certain we are
395 // running single-threaded, so we don't need to lock when modifying
396 // `init'.  CLASSES is NULL-terminated.
397 void
398 _Jv_RegisterClasses (jclass *classes)
399 {
400   static bool init = false;
401
402   if (! init)
403     {
404       init = true;
405       _Jv_InitThreads ();
406       _Jv_InitGC ();
407       _Jv_InitializeSyncMutex ();
408     }
409
410   JvSynchronize sync (&ClassClass);
411   for (; *classes; ++classes)
412     {
413       jclass klass = *classes;
414       jint hash = HASH_UTF (klass->name);
415       klass->next = loaded_classes[hash];
416       loaded_classes[hash] = klass;
417
418       // registering a compiled class causes
419       // it to be immediately "prepared".  
420       if (klass->state == JV_STATE_NOTHING)
421         klass->state = JV_STATE_COMPILED;
422     }
423 }
424
425 void
426 _Jv_RegisterClass (jclass klass)
427 {
428   jclass classes[2];
429   classes[0] = klass;
430   classes[1] = NULL;
431   _Jv_RegisterClasses (classes);
432 }
433
434 jclass
435 _Jv_FindClass (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
436 {
437   jclass klass = _Jv_FindClassInCache (name, loader);
438
439   if (! klass)
440     {
441       jstring sname = _Jv_NewStringUTF (name->data);
442
443       if (loader)
444         {
445           // Load using a user-defined loader, jvmspec 5.3.2
446           klass = loader->loadClass(sname, false);
447
448           // If "loader" delegated the loadClass operation to another
449           // loader, explicitly register that it is also an initiating
450           // loader of the given class.
451           if (klass && (klass->getClassLoader () != loader))
452             _Jv_RegisterInitiatingLoader (klass, loader);
453         }
454       else 
455         {
456           java::lang::ClassLoader *sys = java::lang::ClassLoader::system;
457           if (sys == NULL)
458             {
459               _Jv_InitClass (&ClassLoaderClass);
460               sys = java::lang::ClassLoader::getSystemClassLoader ();
461             }
462
463           // Load using the bootstrap loader jvmspec 5.3.1.
464           klass = sys->loadClass (sname, false); 
465
466           // Register that we're an initiating loader.
467           if (klass)
468             _Jv_RegisterInitiatingLoader (klass, 0);
469         }
470     }
471   else
472     {
473       // we need classes to be in the hash while
474       // we're loading, so that they can refer to themselves. 
475       _Jv_WaitForState (klass, JV_STATE_LOADED);
476     }
477
478   return klass;
479 }
480
481 jclass
482 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
483               java::lang::ClassLoader *loader)
484 {
485   jclass ret = (jclass) JvAllocObject (&ClassClass);
486
487   ret->next = NULL;
488   ret->name = name;
489   ret->accflags = 0;
490   ret->superclass = superclass;
491   ret->constants.size = 0;
492   ret->constants.tags = NULL;
493   ret->constants.data = NULL;
494   ret->methods = NULL;
495   ret->method_count = 0;
496   ret->vtable_method_count = 0;
497   ret->fields = NULL;
498   ret->size_in_bytes = 0;
499   ret->field_count = 0;
500   ret->static_field_count = 0;
501   ret->vtable = NULL;
502   ret->interfaces = NULL;
503   ret->loader = loader;
504   ret->interface_count = 0;
505   ret->state = JV_STATE_NOTHING;
506   ret->thread = NULL;
507   ret->depth = 0;
508   ret->ancestors = NULL;
509   ret->idt = NULL;
510
511   _Jv_RegisterClass (ret);
512
513   return ret;
514 }
515
516 jclass
517 _Jv_FindArrayClass (jclass element, java::lang::ClassLoader *loader)
518 {
519   _Jv_Utf8Const *array_name;
520   int len;
521   if (element->isPrimitive())
522     {
523       // For primitive types the array is cached in the class.
524       jclass ret = (jclass) element->methods;
525       if (ret)
526         return ret;
527       len = 3;
528     }
529   else
530     len = element->name->length + 5;
531
532   {
533     char signature[len];
534     int index = 0;
535     signature[index++] = '[';
536     // Compute name of array class to see if we've already cached it.
537     if (element->isPrimitive())
538       {
539         signature[index++] = (char) element->method_count;
540       }
541     else
542       {
543         size_t length = element->name->length;
544         const char *const name = element->name->data;
545         if (name[0] != '[')
546           signature[index++] = 'L';
547         memcpy (&signature[index], name, length);
548         index += length;
549         if (name[0] != '[')
550           signature[index++] = ';';
551       }      
552     array_name = _Jv_makeUtf8Const (signature, index);
553   }
554
555   jclass array_class = _Jv_FindClassInCache (array_name, element->loader);
556
557   if (! array_class)
558     {
559       // Create new array class.
560       array_class = _Jv_NewClass (array_name, &ObjectClass, element->loader);
561
562       // Note that `vtable_method_count' doesn't include the initial
563       // NULL slot.
564       int dm_count = ObjectClass.vtable_method_count + 1;
565
566       // Create a new vtable by copying Object's vtable (except the
567       // class pointer, of course).  Note that we allocate this as
568       // unscanned memory -- the vtables are handled specially by the
569       // GC.
570       int size = (sizeof (_Jv_VTable) +
571                   ((dm_count - 1) * sizeof (void *)));
572       _Jv_VTable *vtable = (_Jv_VTable *) _Jv_AllocBytes (size);
573       vtable->clas = array_class;
574       memcpy (vtable->method, ObjectClass.vtable->method,
575               dm_count * sizeof (void *));
576       array_class->vtable = vtable;
577       array_class->vtable_method_count = ObjectClass.vtable_method_count;
578
579       // Stash the pointer to the element type.
580       array_class->methods = (_Jv_Method *) element;
581
582       // Register our interfaces.
583       static jclass interfaces[] = { &CloneableClass, &SerializableClass };
584       array_class->interfaces = interfaces;
585       array_class->interface_count = sizeof interfaces / sizeof interfaces[0];
586
587       // Generate the interface dispatch table.
588       _Jv_PrepareConstantTimeTables (array_class);
589
590       // as per vmspec 5.3.3.2
591       array_class->accflags = element->accflags;
592
593       // FIXME: initialize other Class instance variables,
594       // e.g. `fields'.
595
596       // say this class is initialized and ready to go!
597       array_class->state = JV_STATE_DONE;
598
599       // vmspec, section 5.3.3 describes this
600       if (element->loader != loader)
601         _Jv_RegisterInitiatingLoader (array_class, loader);
602     }
603
604   // For primitive types, point back at this array.
605   if (element->isPrimitive())
606     element->methods = (_Jv_Method *) array_class;
607
608   return array_class;
609 }
610
611