1 // natClassLoader.cc - Implementation of java.lang.ClassLoader native methods.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
11 /* Author: Kresten Krab Thorup <krab@gnu.org> */
21 #include <execution.h>
23 #include <java-threads.h>
24 #include <java-interp.h>
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>
48 // Size of local hash table.
51 // Hash function for Utf8Consts.
52 #define HASH_UTF(Utf) ((Utf)->hash16() % HASH_LEN)
54 // This records classes which will be registered with the system class
55 // loader when it is initialized.
56 static jclass system_class_list;
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)
63 static jclass loaded_classes[HASH_LEN];
65 // This is the root of a linked list of classes
66 static jclass stack_head;
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;
79 java::lang::ClassLoader::loadClassFromSig(jstring name)
81 int len = _Jv_GetStringUTFLength (name);
83 _Jv_GetStringUTFRegion (name, 0, name->length(), sig);
84 jclass result = _Jv_FindClassFromSignature(sig, this);
86 throw new ClassNotFoundException(name);
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().
96 _Jv_FindClassInCache (_Jv_Utf8Const *name)
98 JvSynchronize sync (&java::lang::Class::class$);
99 jint hash = HASH_UTF (name);
102 for (klass = loaded_classes[hash]; klass; klass = klass->next_or_version)
104 if (_Jv_equalUtf8Consts (name, klass->name))
112 _Jv_UnregisterClass (jclass the_class)
114 // This can happen if the class could not be defined properly.
115 if (! the_class->name)
118 JvSynchronize sync (&java::lang::Class::class$);
119 jint hash = HASH_UTF(the_class->name);
121 jclass *klass = &(loaded_classes[hash]);
122 for ( ; *klass; klass = &((*klass)->next_or_version))
124 if (*klass == the_class)
126 *klass = (*klass)->next_or_version;
132 // Register an initiating class loader for a given class.
134 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
137 loader = java::lang::VMClassLoader::bootLoader;
140 // Very early in the bootstrap process, the Bootstrap classloader may
142 // FIXME: We could maintain a list of these and come back and register
146 loader->loadedClasses->put(klass->name->toString(), klass);
149 // If we found an error while defining an interpreted class, we must
150 // go back and unregister it.
152 _Jv_UnregisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
155 loader = java::lang::VMClassLoader::bootLoader;
156 loader->loadedClasses->remove(klass->name->toString());
160 // Class registration.
162 // There are two kinds of functions that register classes.
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.
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.
178 // _Jv_RegisterClasses() and _Jv_RegisterClasses_Counted() are
179 // functions of Type 1, and _Jv_NewClassFromInitializer() and
180 // _Jv_RegisterNewClasses() are of Type 2.
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.
188 _Jv_CheckABIVersion (unsigned long value)
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)
195 // The 20 low-end bits are used for the version number.
196 unsigned long version = value & 0xfffff;
198 if (value & FLAG_BINARYCOMPAT_ABI)
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)
209 if (version == GCJ_CXX_ABI_VERSION)
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");
219 throw new ::java::lang::ClassFormatError
220 (JvNewStringLatin1 ("Library compiled with later ABI version than"
221 " this version of libgcj supports"));
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
230 _Jv_RegisterClasses (const jclass *classes)
232 _Jv_RegisterLibForGc (classes);
234 for (; *classes; ++classes)
236 jclass klass = *classes;
238 _Jv_CheckABIVersion ((unsigned long) klass->next_or_version);
239 (*_Jv_RegisterClassHook) (klass);
243 // This is a version of _Jv_RegisterClasses that takes a count.
245 _Jv_RegisterClasses_Counted (const jclass * classes, size_t count)
249 _Jv_RegisterLibForGc (classes);
251 for (i = 0; i < count; i++)
253 jclass klass = classes[i];
255 _Jv_CheckABIVersion ((unsigned long) klass->next_or_version);
256 (*_Jv_RegisterClassHook) (klass);
260 // Create a class on the heap from an initializer struct.
262 _Jv_NewClassFromInitializer (const char *class_initializer)
264 const unsigned long version
266 ((::java::lang::Class *)class_initializer)->next_or_version);
267 _Jv_CheckABIVersion (version);
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. */
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)
281 memcpy (dst, src, len);
283 new_class->engine = &_Jv_soleIndirectCompiledEngine;
285 /* FIXME: Way back before the dawn of time, we overloaded the
286 SYNTHETIC class access modifier to mean INTERPRETED. This was a
287 Bad Thing, but it didn't matter then because classes were never
288 marked synthetic. However, it is possible to redeem the
289 situation: _Jv_NewClassFromInitializer is only called from
290 compiled classes, so we clear the INTERPRETED flag. This is a
292 new_class->accflags &= ~java::lang::reflect::Modifier::INTERPRETED;
294 (*_Jv_RegisterClassHook) (new_class);
299 // Called by compiler-generated code at DSO initialization. CLASSES
300 // is an array of pairs: the first item of each pair is a pointer to
301 // the initialized data that is a class initializer in a DSO, and the
302 // second is a pointer to a class reference.
303 // _Jv_NewClassFromInitializer() creates the new class (on the Java
304 // heap) and we write the address of the new class into the address
305 // pointed to by the second word.
307 _Jv_RegisterNewClasses (char **classes)
311 const char *initializer;
313 while ((initializer = *classes++))
315 jclass *class_ptr = (jclass *)*classes++;
316 *class_ptr = _Jv_NewClassFromInitializer (initializer);
321 _Jv_RegisterClassHookDefault (jclass klass)
323 // This is bogus, but there doesn't seem to be a better place to do
326 klass->engine = &_Jv_soleCompiledEngine;
328 if (system_class_list != SYSTEM_LOADER_INITIALIZED)
330 unsigned long abi = (unsigned long) klass->next_or_version;
331 if (! _Jv_ClassForBootstrapLoader (abi))
333 klass->next_or_version = system_class_list;
334 system_class_list = klass;
339 jint hash = HASH_UTF (klass->name);
341 // If the class is already registered, don't re-register it.
342 for (jclass check_class = loaded_classes[hash];
344 check_class = check_class->next_or_version)
346 if (check_class == klass)
348 // If you get this, it means you have the same class in two
349 // different libraries.
350 #define TEXT "Duplicate class registration: "
351 // We size-limit MESSAGE so that you can't trash the stack.
353 strcpy (message, TEXT);
354 strncpy (message + sizeof (TEXT) - 1, klass->name->chars(),
355 sizeof (message) - sizeof (TEXT));
356 message[sizeof (message) - 1] = '\0';
357 if (! gcj::runtimeInitialized)
361 java::lang::String *str = JvNewStringLatin1 (message);
362 throw new java::lang::VirtualMachineError (str);
367 klass->next_or_version = loaded_classes[hash];
368 loaded_classes[hash] = klass;
371 // A pointer to a function that actually registers a class.
372 // Normally _Jv_RegisterClassHookDefault, but could be some other function
373 // that registers the class in e.g. a ClassLoader-local table.
374 // Should synchronize on Class:class$ while setting/restore this variable.
376 void (*_Jv_RegisterClassHook) (jclass cl) = _Jv_RegisterClassHookDefault;
379 _Jv_RegisterClass (jclass klass)
384 _Jv_RegisterClasses (classes);
387 // This is used during initialization to register all compiled-in
388 // classes that are not part of the core with the system class loader.
390 _Jv_CopyClassesToSystemLoader (gnu::gcj::runtime::SystemClassLoader *loader)
392 for (jclass klass = system_class_list;
394 klass = klass->next_or_version)
396 klass->loader = loader;
397 loader->addClass(klass);
399 system_class_list = SYSTEM_LOADER_INITIALIZED;
402 // An internal variant of _Jv_FindClass which simply swallows a
403 // NoClassDefFoundError or a ClassNotFoundException. This gives the
404 // caller a chance to evaluate the situation and behave accordingly.
406 _Jv_FindClassNoException (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
412 klass = _Jv_FindClass(name, loader);
414 catch ( java::lang::NoClassDefFoundError *ncdfe )
418 catch ( java::lang::ClassNotFoundException *cnfe )
427 _Jv_FindClass (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
429 // See if the class was already loaded by this loader. This handles
430 // initiating loader checks, as we register classes with their
431 // initiating loaders.
433 java::lang::ClassLoader *boot = java::lang::VMClassLoader::bootLoader;
434 java::lang::ClassLoader *real = loader;
437 jstring sname = name->toString();
438 // We might still be bootstrapping the VM, in which case there
439 // won't be a bootstrap class loader yet.
440 jclass klass = real ? real->findLoadedClass (sname) : NULL;
446 // Load using a user-defined loader, jvmspec 5.3.2.
447 // Note that we explicitly must call the single-argument form.
448 klass = loader->loadClass(sname);
450 // If "loader" delegated the loadClass operation to another
451 // loader, explicitly register that it is also an initiating
452 // loader of the given class.
453 java::lang::ClassLoader *delegate = (loader == boot
456 if (klass && klass->getClassLoaderInternal () != delegate)
457 _Jv_RegisterInitiatingLoader (klass, loader);
461 // Load using the bootstrap loader jvmspec 5.3.1.
462 klass = java::lang::VMClassLoader::loadClass (sname, false);
464 // Register that we're an initiating loader.
466 _Jv_RegisterInitiatingLoader (klass, 0);
470 // Not even a bootstrap loader, try the built-in cache.
471 klass = _Jv_FindClassInCache (name);
476 for (int i = 0; i < bootstrap_index; ++i)
478 if (bootstrap_class_list[i] == klass)
486 if (bootstrap_index == BOOTSTRAP_CLASS_LIST_SIZE)
488 bootstrap_class_list[bootstrap_index++] = klass;
498 _Jv_RegisterBootstrapPackages ()
500 for (int i = 0; i < bootstrap_index; ++i)
501 java::lang::VMClassLoader::definePackageForNative(bootstrap_class_list[i]->getName());
505 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
506 java::lang::ClassLoader *loader)
508 jclass ret = (jclass) _Jv_AllocObject (&java::lang::Class::class$);
510 ret->superclass = superclass;
511 ret->loader = loader;
513 _Jv_RegisterInitiatingLoader (ret, loader);
518 static _Jv_IDispatchTable *array_idt = NULL;
519 static jshort array_depth = 0;
520 static jclass *array_ancestors = NULL;
522 static jclass interfaces[] =
524 &java::lang::Cloneable::class$,
525 &java::io::Serializable::class$
528 // Create a class representing an array of ELEMENT and store a pointer to it
529 // in element->arrayclass. LOADER is the ClassLoader which _initiated_ the
530 // instantiation of this array. ARRAY_VTABLE is the vtable to use for the new
531 // array class. This parameter is optional.
533 _Jv_NewArrayClass (jclass element, java::lang::ClassLoader *loader,
534 _Jv_VTable *array_vtable)
536 JvSynchronize sync (element);
538 _Jv_Utf8Const *array_name;
541 if (element->arrayclass)
544 if (element->isPrimitive())
546 if (element == JvPrimClass (void))
547 throw new java::lang::ClassNotFoundException ();
551 len = element->name->len() + 5;
556 signature[index++] = '[';
557 // Compute name of array class.
558 if (element->isPrimitive())
560 signature[index++] = (char) element->method_count;
564 size_t length = element->name->len();
565 const char *const name = element->name->chars();
567 signature[index++] = 'L';
568 memcpy (&signature[index], name, length);
571 signature[index++] = ';';
573 array_name = _Jv_makeUtf8Const (signature, index);
576 // Create new array class.
577 jclass array_class = _Jv_NewClass (array_name, &java::lang::Object::class$,
580 // Note that `vtable_method_count' doesn't include the initial
582 int dm_count = java::lang::Object::class$.vtable_method_count;
584 // Create a new vtable by copying Object's vtable.
587 vtable = array_vtable;
589 vtable = _Jv_VTable::new_vtable (dm_count);
590 vtable->clas = array_class;
591 vtable->gc_descr = java::lang::Object::class$.vtable->gc_descr;
592 for (int i = 0; i < dm_count; ++i)
593 vtable->set_method (i, java::lang::Object::class$.vtable->get_method (i));
595 array_class->vtable = vtable;
596 array_class->vtable_method_count
597 = java::lang::Object::class$.vtable_method_count;
599 // Stash the pointer to the element type.
600 array_class->element_type = element;
602 // Register our interfaces.
603 array_class->interfaces = interfaces;
604 array_class->interface_count = sizeof interfaces / sizeof interfaces[0];
606 // Since all array classes have the same interface dispatch table, we can
607 // cache one and reuse it. It is not necessary to synchronize this.
610 _Jv_Linker::wait_for_state(array_class, JV_STATE_PREPARED);
611 array_idt = array_class->idt;
612 array_depth = array_class->depth;
613 array_ancestors = array_class->ancestors;
617 array_class->idt = array_idt;
618 array_class->depth = array_depth;
619 array_class->ancestors = array_ancestors;
622 using namespace java::lang::reflect;
624 // Array classes are "abstract final" and inherit accessibility
625 // from element type, per vmspec 5.3.3.2
626 _Jv_ushort accflags = (Modifier::FINAL | Modifier::ABSTRACT
628 & (Modifier::PUBLIC | Modifier::PROTECTED
629 | Modifier::PRIVATE)));
630 array_class->accflags = accflags;
633 // An array class has no visible instance fields. "length" is invisible to
636 // Say this class is initialized and ready to go!
637 array_class->state = JV_STATE_DONE;
639 // vmspec, section 5.3.3 describes this
640 if (element->loader != loader)
641 _Jv_RegisterInitiatingLoader (array_class, loader);
643 element->arrayclass = array_class;
646 // These two functions form a stack of classes. When a class is loaded
647 // it is pushed onto the stack by the class loader; this is so that
648 // StackTrace can quickly determine which classes have been loaded.
653 JvSynchronize sync (&java::lang::Class::class$);
656 jclass tmp = stack_head;
657 stack_head = tmp->chain;
664 _Jv_PushClass (jclass k)
666 JvSynchronize sync (&java::lang::Class::class$);
667 jclass tmp = stack_head;