OSDN Git Service

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