OSDN Git Service

* java/lang/natClassLoader.cc: Moved VMClassLoader methods...
[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, 2001, 2002, 2003, 2004  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/NoClassDefFoundError.h>
32 #include <java/lang/ClassNotFoundException.h>
33 #include <java/lang/ClassCircularityError.h>
34 #include <java/lang/IncompatibleClassChangeError.h>
35 #include <java/lang/VirtualMachineError.h>
36 #include <java/lang/VMClassLoader.h>
37 #include <java/lang/reflect/Modifier.h>
38 #include <java/lang/Runtime.h>
39 #include <java/lang/StringBuffer.h>
40 #include <java/io/Serializable.h>
41 #include <java/lang/Cloneable.h>
42
43 void
44 _Jv_WaitForState (jclass klass, int state)
45 {
46   if (klass->state >= state)
47     return;
48   
49   _Jv_MonitorEnter (klass) ;
50
51   if (state == JV_STATE_LINKED)
52     {
53       // Must call _Jv_PrepareCompiledClass while holding the class
54       // mutex.
55 #ifdef INTERPRETER
56       if (_Jv_IsInterpretedClass (klass))
57         _Jv_PrepareClass (klass);
58 #endif
59       _Jv_PrepareCompiledClass (klass);
60       _Jv_MonitorExit (klass);
61       return;
62     }
63         
64   java::lang::Thread *self = java::lang::Thread::currentThread();
65
66   // this is similar to the strategy for class initialization.
67   // if we already hold the lock, just leave.
68   while (klass->state <= state
69          && klass->thread 
70          && klass->thread != self)
71     klass->wait ();
72
73   _Jv_MonitorExit (klass);
74
75   if (klass->state == JV_STATE_ERROR)
76     throw new java::lang::LinkageError;
77 }
78
79 typedef unsigned int uaddr __attribute__ ((mode (pointer)));
80
81 /** This function does class-preparation for compiled classes.  
82     NOTE: It contains replicated functionality from
83     _Jv_ResolvePoolEntry, and this is intentional, since that function
84     lives in resolve.cc which is entirely conditionally compiled.
85  */
86 void
87 _Jv_PrepareCompiledClass (jclass klass)
88 {
89   if (klass->state >= JV_STATE_LINKED)
90     return;
91
92   // Short-circuit, so that mutually dependent classes are ok.
93   klass->state = JV_STATE_LINKED;
94
95   _Jv_Constants *pool = &klass->constants;
96
97   // Resolve class constants first, since other constant pool
98   // entries may rely on these.
99   for (int index = 1; index < pool->size; ++index)
100     {
101       if (pool->tags[index] == JV_CONSTANT_Class)
102         {
103           _Jv_Utf8Const *name = pool->data[index].utf8;
104           
105           jclass found;
106           if (name->data[0] == '[')
107             found = _Jv_FindClassFromSignature (&name->data[0],
108                                                 klass->loader);
109           else
110             found = _Jv_FindClass (name, klass->loader);
111                 
112           if (! found)
113             {
114               jstring str = _Jv_NewStringUTF (name->data);
115               throw new java::lang::NoClassDefFoundError (str);
116             }
117
118           pool->data[index].clazz = found;
119           pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
120         }
121     }
122
123   // If superclass looks like a constant pool entry,
124   // resolve it now.
125   if ((uaddr) klass->superclass < pool->size)
126     klass->superclass = pool->data[(int) klass->superclass].clazz;
127
128   // Likewise for interfaces.
129   for (int i = 0; i < klass->interface_count; i++)
130     if ((uaddr) klass->interfaces[i] < pool->size)
131       klass->interfaces[i] = pool->data[(int) klass->interfaces[i]].clazz;
132
133   // Resolve the remaining constant pool entries.
134   for (int index = 1; index < pool->size; ++index)
135     {
136       if (pool->tags[index] == JV_CONSTANT_String)
137         {
138           jstring str;
139
140           str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
141           pool->data[index].o = str;
142           pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
143         }
144     }
145
146 #ifdef INTERPRETER
147   // FIXME: although the comment up top says that this function is
148   // only called for compiled classes, it is actually called for every
149   // class.
150   if (! _Jv_IsInterpretedClass (klass))
151     {
152 #endif /* INTERPRETER */
153       jfieldID f = JvGetFirstStaticField (klass);
154       for (int n = JvNumStaticFields (klass); n > 0; --n)
155         {
156           int mod = f->getModifiers ();
157           // If we have a static String field with a non-null initial
158           // value, we know it points to a Utf8Const.
159           _Jv_ResolveField(f, klass->loader);
160           if (f->getClass () == &java::lang::String::class$
161               && java::lang::reflect::Modifier::isStatic (mod))
162             {
163               jstring *strp = (jstring *) f->u.addr;
164               if (*strp)
165                 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
166             }
167           f = f->getNextField ();
168         }
169 #ifdef INTERPRETER
170     }
171 #endif /* INTERPRETER */
172
173   klass->notifyAll ();
174
175   _Jv_PushClass (klass);
176 }
177
178
179 //
180 //  A single class can have many "initiating" class loaders,
181 //  and a single "defining" class loader.  The Defining
182 //  class loader is what is returned from Class.getClassLoader()
183 //  and is used when loading dependent classes during resolution.
184 //  The set of initiating class loaders are used to ensure
185 //  safety of linking, and is maintained in the hash table
186 //  "initiated_classes".  A defining classloader is by definition also
187 //  initiating, so we only store classes in this table if they have more
188 //  than one class loader associated.
189 //
190
191
192 // Size of local hash table.
193 #define HASH_LEN 1013
194
195 // Hash function for Utf8Consts.
196 #define HASH_UTF(Utf) (((Utf)->hash) % HASH_LEN)
197
198 struct _Jv_LoaderInfo
199 {
200   _Jv_LoaderInfo          *next;
201   java::lang::Class       *klass;
202   java::lang::ClassLoader *loader;
203 };
204
205 static _Jv_LoaderInfo *initiated_classes[HASH_LEN];
206 static jclass loaded_classes[HASH_LEN];
207
208 // This is the root of a linked list of classes
209
210 \f
211
212 jclass
213 _Jv_FindClassInCache (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
214 {
215   JvSynchronize sync (&java::lang::Class::class$);
216   jint hash = HASH_UTF (name);
217
218   if (loader && loader == java::lang::ClassLoader::getSystemClassLoader())
219     loader = NULL;
220
221   // first, if LOADER is a defining loader, then it is also initiating
222   jclass klass;
223   for (klass = loaded_classes[hash]; klass; klass = klass->next)
224     {
225       if (loader == klass->loader && _Jv_equalUtf8Consts (name, klass->name))
226         break;
227     }
228
229   // otherwise, it may be that the class in question was defined
230   // by some other loader, but that the loading was initiated by 
231   // the loader in question.
232   if (!klass)
233     {
234       _Jv_LoaderInfo *info;
235       for (info = initiated_classes[hash]; info; info = info->next)
236         {
237           if (loader == info->loader
238               && _Jv_equalUtf8Consts (name, info->klass->name))
239             {
240               klass = info->klass;
241               break;
242             }
243         }
244     }
245
246   return klass;
247 }
248
249 void
250 _Jv_UnregisterClass (jclass the_class)
251 {
252   JvSynchronize sync (&java::lang::Class::class$);
253   jint hash = HASH_UTF(the_class->name);
254
255   jclass *klass = &(loaded_classes[hash]);
256   for ( ; *klass; klass = &((*klass)->next))
257     {
258       if (*klass == the_class)
259         {
260           *klass = (*klass)->next;
261           break;
262         }
263     }
264
265   _Jv_LoaderInfo **info = &(initiated_classes[hash]);
266   for ( ; ; info = &((*info)->next))
267     {
268       while (*info && (*info)->klass == the_class)
269         {
270           _Jv_LoaderInfo *old = *info;
271           *info = (*info)->next;
272           _Jv_Free (old);
273         }
274
275       if (*info == NULL)
276         break;
277     }
278 }
279
280 void
281 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
282 {
283   if (loader && loader == java::lang::ClassLoader::getSystemClassLoader())
284     loader = NULL;
285
286   // This information can't be visible to the GC.
287   _Jv_LoaderInfo *info
288     = (_Jv_LoaderInfo *) _Jv_Malloc (sizeof(_Jv_LoaderInfo));
289   jint hash = HASH_UTF(klass->name);
290
291   JvSynchronize sync (&java::lang::Class::class$);
292   info->loader = loader;
293   info->klass  = klass;
294   info->next   = initiated_classes[hash];
295   initiated_classes[hash] = info;
296 }
297
298 // This function is called many times during startup, before main() is
299 // run.  At that point in time we know for certain we are running 
300 // single-threaded, so we don't need to lock when adding classes to the 
301 // class chain.  At all other times, the caller should synchronize on
302 // Class::class$.
303 void
304 _Jv_RegisterClasses (jclass *classes)
305 {
306   for (; *classes; ++classes)
307     {
308       jclass klass = *classes;
309
310       (*_Jv_RegisterClassHook) (klass);
311
312       // registering a compiled class causes
313       // it to be immediately "prepared".  
314       if (klass->state == JV_STATE_NOTHING)
315         klass->state = JV_STATE_COMPILED;
316     }
317 }
318
319 void
320 _Jv_RegisterClassHookDefault (jclass klass)
321 {
322   jint hash = HASH_UTF (klass->name);
323
324   jclass check_class = loaded_classes[hash];
325
326   // If the class is already registered, don't re-register it.
327   while (check_class != NULL)
328     {
329       if (check_class == klass)
330         {
331           // If you get this, it means you have the same class in two
332           // different libraries.
333 #define TEXT "Duplicate class registration: "
334           // We size-limit MESSAGE so that you can't trash the stack.
335           char message[200];
336           strcpy (message, TEXT);
337           strncpy (message + sizeof (TEXT) - 1, klass->name->data,
338                    sizeof (message) - sizeof (TEXT));
339           message[sizeof (message) - 1] = '\0';
340           if (! gcj::runtimeInitialized)
341             JvFail (message);
342           else
343             {
344               java::lang::String *str = JvNewStringLatin1 (message);
345               throw new java::lang::VirtualMachineError (str);
346             }
347         }
348
349       check_class = check_class->next;
350     }
351
352   klass->next = loaded_classes[hash];
353   loaded_classes[hash] = klass;
354 }
355
356 // A pointer to a function that actually registers a class.
357 // Normally _Jv_RegisterClassHookDefault, but could be some other function
358 // that registers the class in e.g. a ClassLoader-local table.
359 // Should synchronize on Class:class$ while setting/restore this variable.
360
361 void (*_Jv_RegisterClassHook) (jclass cl) = _Jv_RegisterClassHookDefault;
362
363 void
364 _Jv_RegisterClass (jclass klass)
365 {
366   jclass classes[2];
367   classes[0] = klass;
368   classes[1] = NULL;
369   _Jv_RegisterClasses (classes);
370 }
371
372 jclass
373 _Jv_FindClass (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
374 {
375   jclass klass = _Jv_FindClassInCache (name, loader);
376
377   if (! klass)
378     {
379       jstring sname = _Jv_NewStringUTF (name->data);
380
381       java::lang::ClassLoader *sys
382         = java::lang::ClassLoader::getSystemClassLoader ();
383
384       if (loader)
385         {
386           // Load using a user-defined loader, jvmspec 5.3.2
387           klass = loader->loadClass(sname, false);
388
389           // If "loader" delegated the loadClass operation to another
390           // loader, explicitly register that it is also an initiating
391           // loader of the given class.
392           java::lang::ClassLoader *delegate = (loader == sys
393                                                ? NULL
394                                                : loader);
395           if (klass && klass->getClassLoaderInternal () != delegate)
396             _Jv_RegisterInitiatingLoader (klass, loader);
397         }
398       else 
399         {
400           // Load using the bootstrap loader jvmspec 5.3.1.
401           klass = sys->loadClass (sname, false); 
402
403           // Register that we're an initiating loader.
404           if (klass)
405             _Jv_RegisterInitiatingLoader (klass, 0);
406         }
407     }
408   else
409     {
410       // we need classes to be in the hash while
411       // we're loading, so that they can refer to themselves. 
412       _Jv_WaitForState (klass, JV_STATE_LOADED);
413     }
414
415   return klass;
416 }
417
418 jclass
419 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
420               java::lang::ClassLoader *loader)
421 {
422   jclass ret = (jclass) JvAllocObject (&java::lang::Class::class$);
423   ret->name = name;
424   ret->superclass = superclass;
425   ret->loader = loader;
426
427   _Jv_RegisterClass (ret);
428
429   return ret;
430 }
431
432 static _Jv_IDispatchTable *array_idt = NULL;
433 static jshort array_depth = 0;
434 static jclass *array_ancestors = NULL;
435
436 // Create a class representing an array of ELEMENT and store a pointer to it
437 // in element->arrayclass. LOADER is the ClassLoader which _initiated_ the 
438 // instantiation of this array. ARRAY_VTABLE is the vtable to use for the new 
439 // array class. This parameter is optional.
440 void
441 _Jv_NewArrayClass (jclass element, java::lang::ClassLoader *loader,
442                    _Jv_VTable *array_vtable)
443 {
444   JvSynchronize sync (element);
445
446   _Jv_Utf8Const *array_name;
447   int len;
448
449   if (element->arrayclass)
450     return;
451
452   if (element->isPrimitive())
453     {
454       if (element == JvPrimClass (void))
455         throw new java::lang::ClassNotFoundException ();
456       len = 3;
457     }
458   else
459     len = element->name->length + 5;
460
461   {
462     char signature[len];
463     int index = 0;
464     signature[index++] = '[';
465     // Compute name of array class.
466     if (element->isPrimitive())
467       {
468         signature[index++] = (char) element->method_count;
469       }
470     else
471       {
472         size_t length = element->name->length;
473         const char *const name = element->name->data;
474         if (name[0] != '[')
475           signature[index++] = 'L';
476         memcpy (&signature[index], name, length);
477         index += length;
478         if (name[0] != '[')
479           signature[index++] = ';';
480       }      
481     array_name = _Jv_makeUtf8Const (signature, index);
482   }
483
484   // Create new array class.
485   jclass array_class = _Jv_NewClass (array_name, &java::lang::Object::class$,
486                                      element->loader);
487
488   // Note that `vtable_method_count' doesn't include the initial
489   // gc_descr slot.
490   JvAssert (java::lang::Object::class$.vtable_method_count
491             == NUM_OBJECT_METHODS);
492   int dm_count = java::lang::Object::class$.vtable_method_count;
493
494   // Create a new vtable by copying Object's vtable.
495   _Jv_VTable *vtable;
496   if (array_vtable)
497     vtable = array_vtable;
498   else
499     vtable = _Jv_VTable::new_vtable (dm_count);
500   vtable->clas = array_class;
501   vtable->gc_descr = java::lang::Object::class$.vtable->gc_descr;
502   for (int i = 0; i < dm_count; ++i)
503     vtable->set_method (i, java::lang::Object::class$.vtable->get_method (i));
504
505   array_class->vtable = vtable;
506   array_class->vtable_method_count
507     = java::lang::Object::class$.vtable_method_count;
508
509   // Stash the pointer to the element type.
510   array_class->methods = (_Jv_Method *) element;
511
512   // Register our interfaces.
513   static jclass interfaces[] =
514     {
515       &java::lang::Cloneable::class$,
516       &java::io::Serializable::class$
517     };
518   array_class->interfaces = interfaces;
519   array_class->interface_count = sizeof interfaces / sizeof interfaces[0];
520
521   // Since all array classes have the same interface dispatch table, we can 
522   // cache one and reuse it. It is not necessary to synchronize this.
523   if (!array_idt)
524     {
525       _Jv_PrepareConstantTimeTables (array_class);
526       array_idt = array_class->idt;
527       array_depth = array_class->depth;
528       array_ancestors = array_class->ancestors;
529     }
530   else
531     {
532       array_class->idt = array_idt;
533       array_class->depth = array_depth;
534       array_class->ancestors = array_ancestors;
535     }
536
537   using namespace java::lang::reflect;
538   {
539     // Array classes are "abstract final"...
540     _Jv_ushort accflags = Modifier::FINAL | Modifier::ABSTRACT;
541     // ... and inherit accessibility from element type, per vmspec 5.3.3.2
542     accflags |= (element->accflags & Modifier::PUBLIC);
543     accflags |= (element->accflags & Modifier::PROTECTED);
544     accflags |= (element->accflags & Modifier::PRIVATE);      
545     array_class->accflags = accflags;
546   }
547
548   // An array class has no visible instance fields. "length" is invisible to 
549   // reflection.
550
551   // say this class is initialized and ready to go!
552   array_class->state = JV_STATE_DONE;
553
554   // vmspec, section 5.3.3 describes this
555   if (element->loader != loader)
556     _Jv_RegisterInitiatingLoader (array_class, loader);
557
558   element->arrayclass = array_class;
559 }
560
561 static jclass stack_head;
562
563 // These two functions form a stack of classes.   When a class is loaded
564 // it is pushed onto the stack by the class loader; this is so that
565 // StackTrace can quickly determine which classes have been loaded.
566
567 jclass
568 _Jv_PopClass (void)
569 {
570   JvSynchronize sync (&java::lang::Class::class$);
571   if (stack_head)
572     {
573       jclass tmp = stack_head;
574       stack_head = tmp->chain;
575       return tmp;
576     }
577   return NULL;
578 }
579
580 void
581 _Jv_PushClass (jclass k)
582 {
583   JvSynchronize sync (&java::lang::Class::class$);
584   jclass tmp = stack_head;
585   stack_head = k;
586   k->chain = tmp;
587 }