OSDN Git Service

2007-01-31 Andrew Haley <aph@redhat.com>
[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, 2005, 2006  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 <stdio.h>
17 #include <string.h>
18
19 #include <gcj/cni.h>
20 #include <jvm.h>
21 #include <execution.h>
22
23 #include <java-threads.h>
24 #include <java-interp.h>
25
26 #include <java/lang/Character.h>
27 #include <java/lang/Thread.h>
28 #include <java/lang/ClassLoader.h>
29 #include <java/lang/InternalError.h>
30 #include <java/lang/IllegalAccessError.h>
31 #include <java/lang/LinkageError.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/ClassFormatError.h>
37 #include <java/lang/VirtualMachineError.h>
38 #include <java/lang/VMClassLoader.h>
39 #include <java/lang/reflect/Modifier.h>
40 #include <java/lang/Runtime.h>
41 #include <java/lang/StringBuffer.h>
42 #include <java/io/Serializable.h>
43 #include <java/lang/Cloneable.h>
44 #include <java/util/HashMap.h>
45 #include <gnu/gcj/runtime/BootClassLoader.h>
46 #include <gnu/gcj/runtime/SystemClassLoader.h>
47
48 // Size of local hash table.
49 #define HASH_LEN 1013
50
51 // Hash function for Utf8Consts.
52 #define HASH_UTF(Utf) ((Utf)->hash16() % HASH_LEN)
53
54 // This records classes which will be registered with the system class
55 // loader when it is initialized.
56 static jclass system_class_list;
57
58 // This is used as the value of system_class_list after we have
59 // initialized the system class loader; it lets us know that we should
60 // no longer pay attention to the system abi flag.
61 #define SYSTEM_LOADER_INITIALIZED ((jclass) -1)
62
63 static jclass loaded_classes[HASH_LEN];
64
65 // This is the root of a linked list of classes
66 static jclass stack_head;
67
68 // While bootstrapping we keep a list of classes we found, so that we
69 // can register their packages.  There aren't many of these so we
70 // just keep a small buffer here and abort if we overflow.
71 #define BOOTSTRAP_CLASS_LIST_SIZE 20
72 static jclass bootstrap_class_list[BOOTSTRAP_CLASS_LIST_SIZE];
73 static int bootstrap_index;
74
75
76 \f
77
78 jclass
79 java::lang::ClassLoader::loadClassFromSig(jstring name)
80 {
81   int len = _Jv_GetStringUTFLength (name);
82   char sig[len + 1];
83   _Jv_GetStringUTFRegion (name, 0, name->length(), sig);
84   jclass result = _Jv_FindClassFromSignature(sig, this);
85   if (result == NULL)
86     throw new ClassNotFoundException(name);
87   return result;
88 }
89
90 \f
91
92 // This tries to find a class in our built-in cache.  This cache is
93 // used only for classes which are linked in to the executable or
94 // loaded via dlopen().
95 jclass
96 _Jv_FindClassInCache (_Jv_Utf8Const *name)
97 {
98   JvSynchronize sync (&java::lang::Class::class$);
99   jint hash = HASH_UTF (name);
100
101   jclass klass;
102   for (klass = loaded_classes[hash]; klass; klass = klass->next_or_version)
103     {
104       if (_Jv_equalUtf8Consts (name, klass->name))
105         break;
106     }
107
108   return klass;
109 }
110
111 void
112 _Jv_UnregisterClass (jclass the_class)
113 {
114   // This can happen if the class could not be defined properly.
115   if (! the_class->name)
116     return;
117
118   JvSynchronize sync (&java::lang::Class::class$);
119   jint hash = HASH_UTF(the_class->name);
120
121   jclass *klass = &(loaded_classes[hash]);
122   for ( ; *klass; klass = &((*klass)->next_or_version))
123     {
124       if (*klass == the_class)
125         {
126           *klass = (*klass)->next_or_version;
127           break;
128         }
129     }
130 }
131
132 // Register an initiating class loader for a given class.
133 void
134 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
135 {
136   if (! loader)
137     loader = java::lang::VMClassLoader::bootLoader;
138   if (! loader)
139     {
140       // Very early in the bootstrap process, the Bootstrap classloader may 
141       // not exist yet.
142       // FIXME: We could maintain a list of these and come back and register
143       // them later.
144       return;
145     }
146   loader->loadedClasses->put(klass->name->toString(), klass);
147 }
148
149 // If we found an error while defining an interpreted class, we must
150 // go back and unregister it.
151 void
152 _Jv_UnregisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
153 {
154   if (! loader)
155     loader = java::lang::VMClassLoader::bootLoader;
156   loader->loadedClasses->remove(klass->name->toString());
157 }
158
159
160 // Class registration.
161 //
162 // There are two kinds of functions that register classes.  
163 //
164 // Type 1:
165 //
166 // These take the address of a class that is in an object file.
167 // Because these classes are not allocated on the heap, It is also
168 // necessary to register the address of the object for garbage
169 // collection.  This is used with the "old" C++ ABI and with
170 // -findirect-dispatch -fno-indirect-classes.
171 //
172 // Type 2:
173 //
174 // These take an initializer struct, create the class, and return the
175 // address of the newly created class to their caller.  These are used
176 // with -findirect-dispatch.
177 //
178 // _Jv_RegisterClasses() and _Jv_RegisterClasses_Counted() are
179 // functions of Type 1, and _Jv_NewClassFromInitializer() and
180 // _Jv_RegisterNewClasses() are of Type 2.
181
182
183 // Check that the file we're trying to load has been compiled with a
184 // compatible version of gcj.  In previous versions of libgcj we
185 // silently failed to register classes of an incompatible ABI version,
186 // but this was totally bogus.
187 void
188 _Jv_CheckABIVersion (unsigned long value)
189 {
190   // We are compatible with GCJ 4.0.0 BC-ABI classes. This release used a
191   // different format for the version ID string.
192    if (value == OLD_GCJ_40_BC_ABI_VERSION)
193      return;
194      
195   // The 20 low-end bits are used for the version number.
196   unsigned long version = value & 0xfffff;
197
198   if (value & FLAG_BINARYCOMPAT_ABI)
199     {
200       int abi_rev = version % 100;
201       int abi_ver = version - abi_rev;
202       // We are compatible with abi_rev 0 and 1.
203       if (abi_ver == GCJ_40_BC_ABI_VERSION && abi_rev <= 1)
204         return;
205     }
206   else
207     {
208       // C++ ABI
209       if (version == GCJ_CXX_ABI_VERSION)
210         return;
211
212       // If we've loaded a library that uses the C++ ABI, and this
213       // library is an incompatible version, then we're dead.  There's
214       // no point throwing an exception: that will crash.
215       JvFail ("gcj linkage error.\n"
216               "Incorrect library ABI version detected.  Aborting.\n");
217     }
218
219   throw new ::java::lang::ClassFormatError
220     (JvNewStringLatin1 ("Library compiled with later ABI version than"
221                         " this version of libgcj supports"));
222 }
223
224 // This function is called many times during startup, before main() is
225 // run.  At that point in time we know for certain we are running 
226 // single-threaded, so we don't need to lock when adding classes to the 
227 // class chain.  At all other times, the caller should synchronize on
228 // Class::class$.
229 void
230 _Jv_RegisterClasses (const jclass *classes)
231 {
232   _Jv_RegisterLibForGc (classes);
233
234   for (; *classes; ++classes)
235     {
236       jclass klass = *classes;
237
238       _Jv_CheckABIVersion ((unsigned long) klass->next_or_version);
239       (*_Jv_RegisterClassHook) (klass);
240     }
241 }
242
243 // This is a version of _Jv_RegisterClasses that takes a count.
244 void
245 _Jv_RegisterClasses_Counted (const jclass * classes, size_t count)
246 {
247   size_t i;
248
249   _Jv_RegisterLibForGc (classes);
250
251   for (i = 0; i < count; i++)
252     {
253       jclass klass = classes[i];
254
255       _Jv_CheckABIVersion ((unsigned long) klass->next_or_version);
256       (*_Jv_RegisterClassHook) (klass);
257     }
258 }
259
260 // Create a class on the heap from an initializer struct.
261 inline jclass
262 _Jv_NewClassFromInitializer (const char *class_initializer)
263 {
264   const unsigned long version 
265     = ((unsigned long) 
266        ((::java::lang::Class *)class_initializer)->next_or_version);
267   _Jv_CheckABIVersion (version);
268   
269   /* We create an instance of java::lang::Class and copy all of its
270      fields except the first word (the vtable pointer) from
271      CLASS_INITIALIZER.  This first word is pre-initialized by
272      _Jv_AllocObj, and we don't want to overwrite it.  */
273   
274   jclass new_class
275     = (jclass)_Jv_AllocObj (sizeof (::java::lang::Class),
276                             &::java::lang::Class::class$);
277   const char *src = class_initializer + sizeof (void*);
278   char *dst = (char*)new_class + sizeof (void*);
279   size_t len = (::java::lang::Class::initializerSize (version) 
280                 - sizeof (void*));
281   memcpy (dst, src, len);
282   
283   new_class->engine = &_Jv_soleIndirectCompiledEngine;
284   
285   (*_Jv_RegisterClassHook) (new_class);
286   
287   return new_class;
288 }
289
290 // Called by compiler-generated code at DSO initialization.  CLASSES
291 // is an array of pairs: the first item of each pair is a pointer to
292 // the initialized data that is a class initializer in a DSO, and the
293 // second is a pointer to a class reference.
294 // _Jv_NewClassFromInitializer() creates the new class (on the Java
295 // heap) and we write the address of the new class into the address
296 // pointed to by the second word.
297 void
298 _Jv_RegisterNewClasses (char **classes)
299 {
300   _Jv_InitGC ();
301
302   const char *initializer;
303
304   while ((initializer = *classes++))
305     {
306       jclass *class_ptr = (jclass *)*classes++;
307       *class_ptr = _Jv_NewClassFromInitializer (initializer);
308     }      
309 }
310   
311 void
312 _Jv_RegisterClassHookDefault (jclass klass)
313 {
314   // This is bogus, but there doesn't seem to be a better place to do
315   // it.
316   if (! klass->engine)
317     klass->engine = &_Jv_soleCompiledEngine;
318
319   if (system_class_list != SYSTEM_LOADER_INITIALIZED)
320     {
321       unsigned long abi = (unsigned long) klass->next_or_version;
322       if (! _Jv_ClassForBootstrapLoader (abi))
323         {
324           klass->next_or_version = system_class_list;
325           system_class_list = klass;
326           return;
327         }
328     }
329
330   jint hash = HASH_UTF (klass->name);
331
332   // If the class is already registered, don't re-register it.
333   for (jclass check_class = loaded_classes[hash];
334        check_class != NULL;
335        check_class = check_class->next_or_version)
336     {
337       if (check_class == klass)
338         {
339           // If you get this, it means you have the same class in two
340           // different libraries.
341 #define TEXT "Duplicate class registration: "
342           // We size-limit MESSAGE so that you can't trash the stack.
343           char message[200];
344           strcpy (message, TEXT);
345           strncpy (message + sizeof (TEXT) - 1, klass->name->chars(),
346                    sizeof (message) - sizeof (TEXT));
347           message[sizeof (message) - 1] = '\0';
348           if (! gcj::runtimeInitialized)
349             JvFail (message);
350           else
351             {
352               java::lang::String *str = JvNewStringLatin1 (message);
353               throw new java::lang::VirtualMachineError (str);
354             }
355         }
356     }
357
358   klass->next_or_version = loaded_classes[hash];
359   loaded_classes[hash] = klass;
360 }
361
362 // A pointer to a function that actually registers a class.
363 // Normally _Jv_RegisterClassHookDefault, but could be some other function
364 // that registers the class in e.g. a ClassLoader-local table.
365 // Should synchronize on Class:class$ while setting/restore this variable.
366
367 void (*_Jv_RegisterClassHook) (jclass cl) = _Jv_RegisterClassHookDefault;
368
369 void
370 _Jv_RegisterClass (jclass klass)
371 {
372   jclass classes[2];
373   classes[0] = klass;
374   classes[1] = NULL;
375   _Jv_RegisterClasses (classes);
376 }
377
378 // This is used during initialization to register all compiled-in
379 // classes that are not part of the core with the system class loader.
380 void
381 _Jv_CopyClassesToSystemLoader (gnu::gcj::runtime::SystemClassLoader *loader)
382 {
383   for (jclass klass = system_class_list;
384        klass;
385        klass = klass->next_or_version)
386     {
387       klass->loader = loader;
388       loader->addClass(klass);
389     }
390   system_class_list = SYSTEM_LOADER_INITIALIZED;
391 }
392
393 // An internal variant of _Jv_FindClass which simply swallows a
394 // NoClassDefFoundError or a ClassNotFoundException. This gives the
395 // caller a chance to evaluate the situation and behave accordingly.
396 jclass
397 _Jv_FindClassNoException (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
398 {
399   jclass klass;
400
401   try
402     {
403       klass = _Jv_FindClass(name, loader);
404     }
405   catch ( java::lang::NoClassDefFoundError *ncdfe )
406     {
407       return NULL;
408     }
409   catch ( java::lang::ClassNotFoundException *cnfe )
410     {
411       return NULL;
412     }
413
414   return klass;
415 }
416
417 jclass
418 _Jv_FindClass (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
419 {
420   // See if the class was already loaded by this loader.  This handles
421   // initiating loader checks, as we register classes with their
422   // initiating loaders.
423
424   java::lang::ClassLoader *boot = java::lang::VMClassLoader::bootLoader;
425   java::lang::ClassLoader *real = loader;
426   if (! real)
427     real = boot;
428   jstring sname = name->toString();
429   // We might still be bootstrapping the VM, in which case there
430   // won't be a bootstrap class loader yet.
431   jclass klass = real ? real->findLoadedClass (sname) : NULL;
432
433   if (! klass)
434     {
435       if (loader)
436         {
437           // Load using a user-defined loader, jvmspec 5.3.2.
438           // Note that we explicitly must call the single-argument form.
439           klass = loader->loadClass(sname);
440
441           // If "loader" delegated the loadClass operation to another
442           // loader, explicitly register that it is also an initiating
443           // loader of the given class.
444           java::lang::ClassLoader *delegate = (loader == boot
445                                                ? NULL
446                                                : loader);
447           if (klass && klass->getClassLoaderInternal () != delegate)
448             _Jv_RegisterInitiatingLoader (klass, loader);
449         }
450       else if (boot)
451         {
452           // Load using the bootstrap loader jvmspec 5.3.1.
453           klass = java::lang::VMClassLoader::loadClass (sname, false); 
454
455           // Register that we're an initiating loader.
456           if (klass)
457             _Jv_RegisterInitiatingLoader (klass, 0);
458         }
459       else
460         {
461           // Not even a bootstrap loader, try the built-in cache.
462           klass = _Jv_FindClassInCache (name);
463
464           if (klass)
465             {
466               bool found = false;
467               for (int i = 0; i < bootstrap_index; ++i)
468                 {
469                   if (bootstrap_class_list[i] == klass)
470                     {
471                       found = true;
472                       break;
473                     }
474                 }
475               if (! found)
476                 {
477                   if (bootstrap_index == BOOTSTRAP_CLASS_LIST_SIZE)
478                     abort ();
479                   bootstrap_class_list[bootstrap_index++] = klass;
480                 }
481             }
482         }
483     }
484
485   return klass;
486 }
487
488 void
489 _Jv_RegisterBootstrapPackages ()
490 {
491   for (int i = 0; i < bootstrap_index; ++i)
492     java::lang::VMClassLoader::definePackageForNative(bootstrap_class_list[i]->getName());
493 }
494
495 jclass
496 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
497               java::lang::ClassLoader *loader)
498 {
499   jclass ret = (jclass) _Jv_AllocObject (&java::lang::Class::class$);
500   ret->name = name;
501   ret->superclass = superclass;
502   ret->loader = loader;
503
504   _Jv_RegisterInitiatingLoader (ret, loader);
505
506   return ret;
507 }
508
509 static _Jv_IDispatchTable *array_idt = NULL;
510 static jshort array_depth = 0;
511 static jclass *array_ancestors = NULL;
512
513 static jclass interfaces[] =
514 {
515   &java::lang::Cloneable::class$,
516   &java::io::Serializable::class$
517 };
518
519 // Create a class representing an array of ELEMENT and store a pointer to it
520 // in element->arrayclass. LOADER is the ClassLoader which _initiated_ the 
521 // instantiation of this array. ARRAY_VTABLE is the vtable to use for the new 
522 // array class. This parameter is optional.
523 void
524 _Jv_NewArrayClass (jclass element, java::lang::ClassLoader *loader,
525                    _Jv_VTable *array_vtable)
526 {
527   JvSynchronize sync (element);
528
529   _Jv_Utf8Const *array_name;
530   int len;
531
532   if (element->arrayclass)
533     return;
534
535   if (element->isPrimitive())
536     {
537       if (element == JvPrimClass (void))
538         throw new java::lang::ClassNotFoundException ();
539       len = 3;
540     }
541   else
542     len = element->name->len() + 5;
543
544   {
545     char signature[len];
546     int index = 0;
547     signature[index++] = '[';
548     // Compute name of array class.
549     if (element->isPrimitive())
550       {
551         signature[index++] = (char) element->method_count;
552       }
553     else
554       {
555         size_t length = element->name->len();
556         const char *const name = element->name->chars();
557         if (name[0] != '[')
558           signature[index++] = 'L';
559         memcpy (&signature[index], name, length);
560         index += length;
561         if (name[0] != '[')
562           signature[index++] = ';';
563       }      
564     array_name = _Jv_makeUtf8Const (signature, index);
565   }
566
567   // Create new array class.
568   jclass array_class = _Jv_NewClass (array_name, &java::lang::Object::class$,
569                                      element->loader);
570
571   // Note that `vtable_method_count' doesn't include the initial
572   // gc_descr slot.
573   int dm_count = java::lang::Object::class$.vtable_method_count;
574
575   // Create a new vtable by copying Object's vtable.
576   _Jv_VTable *vtable;
577   if (array_vtable)
578     vtable = array_vtable;
579   else
580     vtable = _Jv_VTable::new_vtable (dm_count);
581   vtable->clas = array_class;
582   vtable->gc_descr = java::lang::Object::class$.vtable->gc_descr;
583   for (int i = 0; i < dm_count; ++i)
584     vtable->set_method (i, java::lang::Object::class$.vtable->get_method (i));
585
586   array_class->vtable = vtable;
587   array_class->vtable_method_count
588     = java::lang::Object::class$.vtable_method_count;
589
590   // Stash the pointer to the element type.
591   array_class->element_type = element;
592
593   // Register our interfaces.
594   array_class->interfaces = interfaces;
595   array_class->interface_count = sizeof interfaces / sizeof interfaces[0];
596
597   // Since all array classes have the same interface dispatch table, we can 
598   // cache one and reuse it. It is not necessary to synchronize this.
599   if (!array_idt)
600     {
601       _Jv_Linker::wait_for_state(array_class, JV_STATE_PREPARED);
602       array_idt = array_class->idt;
603       array_depth = array_class->depth;
604       array_ancestors = array_class->ancestors;
605     }
606   else
607     {
608       array_class->idt = array_idt;
609       array_class->depth = array_depth;
610       array_class->ancestors = array_ancestors;
611     }
612
613   using namespace java::lang::reflect;
614   {
615     // Array classes are "abstract final" and inherit accessibility
616     // from element type, per vmspec 5.3.3.2
617     _Jv_ushort accflags = (Modifier::FINAL | Modifier::ABSTRACT
618                            | (element->accflags
619                               & (Modifier::PUBLIC | Modifier::PROTECTED
620                                  | Modifier::PRIVATE)));
621     array_class->accflags = accflags;
622   }
623
624   // An array class has no visible instance fields. "length" is invisible to 
625   // reflection.
626
627   // Say this class is initialized and ready to go!
628   array_class->state = JV_STATE_DONE;
629
630   // vmspec, section 5.3.3 describes this
631   if (element->loader != loader)
632     _Jv_RegisterInitiatingLoader (array_class, loader);
633
634   element->arrayclass = array_class;
635 }
636
637 // These two functions form a stack of classes.   When a class is loaded
638 // it is pushed onto the stack by the class loader; this is so that
639 // StackTrace can quickly determine which classes have been loaded.
640
641 jclass
642 _Jv_PopClass (void)
643 {
644   JvSynchronize sync (&java::lang::Class::class$);
645   if (stack_head)
646     {
647       jclass tmp = stack_head;
648       stack_head = tmp->chain;
649       return tmp;
650     }
651   return NULL;
652 }
653
654 void
655 _Jv_PushClass (jclass k)
656 {
657   JvSynchronize sync (&java::lang::Class::class$);
658   jclass tmp = stack_head;
659   stack_head = k;
660   k->chain = tmp;
661 }