1 // natClassLoader.cc - Implementation of java.lang.ClassLoader native methods.
3 /* Copyright (C) 1999, 2000, 2001, 2002 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 <java-threads.h>
22 #include <java-interp.h>
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/VirtualMachineError.h>
37 #include <java/lang/VMClassLoader.h>
38 #include <java/lang/reflect/Modifier.h>
39 #include <java/lang/Runtime.h>
40 #include <java/lang/StringBuffer.h>
41 #include <java/io/Serializable.h>
42 #include <java/lang/Cloneable.h>
44 /////////// java.lang.ClassLoader native methods ////////////
47 java::lang::ClassLoader::defineClass0 (jstring name,
51 java::security::ProtectionDomain *pd)
55 klass = (jclass) JvAllocObject (&java::lang::Class::class$,
56 sizeof (_Jv_InterpClass));
57 _Jv_InitNewClassFields (klass);
59 // synchronize on the class, so that it is not
60 // attempted initialized until we're done loading.
61 _Jv_MonitorEnter (klass);
63 // record which is the defining loader
66 // register that we are the initiating loader...
69 _Jv_Utf8Const * name2 = _Jv_makeUtf8Const (name);
71 if (! _Jv_VerifyClassName (name2))
72 throw new java::lang::ClassFormatError
73 (JvNewStringLatin1 ("erroneous class name"));
80 _Jv_DefineClass (klass, data, offset, length);
82 catch (java::lang::Throwable *ex)
84 klass->state = JV_STATE_ERROR;
87 _Jv_UnregisterClass (klass);
89 _Jv_MonitorExit (klass);
91 // FIXME: Here we may want to test that EX does
92 // indeed represent a valid exception. That is,
93 // anything but ClassNotFoundException,
94 // or some kind of Error.
96 // FIXME: Rewrite this as a cleanup instead of
97 // as a catch handler.
102 klass->protectionDomain = pd;
104 // if everything proceeded sucessfully, we're loaded.
105 JvAssert (klass->state == JV_STATE_LOADED);
107 // if an exception is generated, this is initially missed.
108 // however, we come back here in handleException0 below...
109 _Jv_MonitorExit (klass);
120 _Jv_WaitForState (jclass klass, int state)
122 if (klass->state >= state)
125 _Jv_MonitorEnter (klass) ;
127 if (state == JV_STATE_LINKED)
129 // Must call _Jv_PrepareCompiledClass while holding the class
131 _Jv_PrepareCompiledClass (klass);
132 _Jv_MonitorExit (klass);
136 java::lang::Thread *self = java::lang::Thread::currentThread();
138 // this is similar to the strategy for class initialization.
139 // if we already hold the lock, just leave.
140 while (klass->state <= state
142 && klass->thread != self)
145 _Jv_MonitorExit (klass);
147 if (klass->state == JV_STATE_ERROR)
148 throw new java::lang::LinkageError;
151 // Finish linking a class. Only called from ClassLoader::resolveClass.
153 java::lang::ClassLoader::linkClass0 (java::lang::Class *klass)
155 if (klass->state >= JV_STATE_LINKED)
159 if (_Jv_IsInterpretedClass (klass))
160 _Jv_PrepareClass (klass);
163 _Jv_PrepareCompiledClass (klass);
167 java::lang::ClassLoader::markClassErrorState0 (java::lang::Class *klass)
169 klass->state = JV_STATE_ERROR;
174 java::lang::VMClassLoader::getPrimitiveClass (jchar type)
177 sig[0] = (char) type;
179 return _Jv_FindClassFromSignature (sig, NULL);
182 // This is the findClass() implementation for the System classloader. It is
183 // the only native method in VMClassLoader, so we define it here.
185 gnu::gcj::runtime::VMClassLoader::findClass (jstring name)
187 _Jv_Utf8Const *name_u = _Jv_makeUtf8Const (name);
188 jclass klass = _Jv_FindClassInCache (name_u, 0);
192 // Turn `gnu.pkg.quux' into `lib-gnu-pkg-quux'. Then search for
193 // a module named (eg, on Linux) `lib-gnu-pkg-quux.so', followed
194 // by `lib-gnu-pkg.so' and `lib-gnu.so'. If loading one of
195 // these causes the class to appear in the cache, then use it.
196 java::lang::StringBuffer *sb = new java::lang::StringBuffer (JvNewStringLatin1("lib-"));
197 jstring so_base_name = (sb->append (name)->toString ())->replace ('.', '-');
199 // Compare against `3' because that is the length of "lib".
200 while (! klass && so_base_name && so_base_name->length() > 3)
202 using namespace ::java::lang;
203 Runtime *rt = Runtime::getRuntime();
204 jboolean loaded = rt->loadLibraryInternal (so_base_name);
206 jint nd = so_base_name->lastIndexOf ('-');
210 so_base_name = so_base_name->substring (0, nd);
213 klass = _Jv_FindClassInCache (name_u, 0);
217 // Now try loading using the interpreter.
220 klass = java::net::URLClassLoader::findClass (name);
227 java::lang::ClassLoader::findLoadedClass (jstring name)
229 return _Jv_FindClassInCache (_Jv_makeUtf8Const (name), this);
232 /** This function does class-preparation for compiled classes.
233 NOTE: It contains replicated functionality from
234 _Jv_ResolvePoolEntry, and this is intentional, since that function
235 lives in resolve.cc which is entirely conditionally compiled.
238 _Jv_PrepareCompiledClass (jclass klass)
240 if (klass->state >= JV_STATE_LINKED)
243 // Short-circuit, so that mutually dependent classes are ok.
244 klass->state = JV_STATE_LINKED;
246 _Jv_Constants *pool = &klass->constants;
247 for (int index = 1; index < pool->size; ++index)
249 if (pool->tags[index] == JV_CONSTANT_Class)
251 _Jv_Utf8Const *name = pool->data[index].utf8;
254 if (name->data[0] == '[')
255 found = _Jv_FindClassFromSignature (&name->data[0],
258 found = _Jv_FindClass (name, klass->loader);
262 jstring str = _Jv_NewStringUTF (name->data);
263 throw new java::lang::NoClassDefFoundError (str);
266 pool->data[index].clazz = found;
267 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
269 else if (pool->tags[index] == JV_CONSTANT_String)
272 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
273 pool->data[index].o = str;
274 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
279 // FIXME: although the comment up top says that this function is
280 // only called for compiled classes, it is actually called for every
282 if (! _Jv_IsInterpretedClass (klass))
284 #endif /* INTERPRETER */
285 jfieldID f = JvGetFirstStaticField (klass);
286 for (int n = JvNumStaticFields (klass); n > 0; --n)
288 int mod = f->getModifiers ();
289 // If we have a static String field with a non-null initial
290 // value, we know it points to a Utf8Const.
291 if (f->getClass () == &java::lang::String::class$
292 && java::lang::reflect::Modifier::isStatic (mod))
294 jstring *strp = (jstring *) f->u.addr;
296 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
298 f = f->getNextField ();
302 #endif /* INTERPRETER */
304 if (klass->vtable == NULL)
305 _Jv_MakeVTable(klass);
307 if (klass->otable != NULL && klass->otable->state == 0)
308 _Jv_LinkOffsetTable(klass);
315 // A single class can have many "initiating" class loaders,
316 // and a single "defining" class loader. The Defining
317 // class loader is what is returned from Class.getClassLoader()
318 // and is used when loading dependent classes during resolution.
319 // The set of initiating class loaders are used to ensure
320 // safety of linking, and is maintained in the hash table
321 // "initiated_classes". A defining classloader is by definition also
322 // initiating, so we only store classes in this table, if they have more
323 // than one class loader associated.
327 // Size of local hash table.
328 #define HASH_LEN 1013
330 // Hash function for Utf8Consts.
331 #define HASH_UTF(Utf) (((Utf)->hash) % HASH_LEN)
333 struct _Jv_LoaderInfo {
334 _Jv_LoaderInfo *next;
335 java::lang::Class *klass;
336 java::lang::ClassLoader *loader;
339 static _Jv_LoaderInfo *initiated_classes[HASH_LEN];
340 static jclass loaded_classes[HASH_LEN];
342 // This is the root of a linked list of classes
347 _Jv_FindClassInCache (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
349 _Jv_MonitorEnter (&java::lang::Class::class$);
350 jint hash = HASH_UTF (name);
352 // first, if LOADER is a defining loader, then it is also initiating
354 for (klass = loaded_classes[hash]; klass; klass = klass->next)
356 if (loader == klass->loader && _Jv_equalUtf8Consts (name, klass->name))
360 // otherwise, it may be that the class in question was defined
361 // by some other loader, but that the loading was initiated by
362 // the loader in question.
365 _Jv_LoaderInfo *info;
366 for (info = initiated_classes[hash]; info; info = info->next)
368 if (loader == info->loader
369 && _Jv_equalUtf8Consts (name, info->klass->name))
377 _Jv_MonitorExit (&java::lang::Class::class$);
383 _Jv_UnregisterClass (jclass the_class)
385 _Jv_MonitorEnter (&java::lang::Class::class$);
386 jint hash = HASH_UTF(the_class->name);
388 jclass *klass = &(loaded_classes[hash]);
389 for ( ; *klass; klass = &((*klass)->next))
391 if (*klass == the_class)
393 *klass = (*klass)->next;
398 _Jv_LoaderInfo **info = &(initiated_classes[hash]);
399 for ( ; ; info = &((*info)->next))
401 while (*info && (*info)->klass == the_class)
403 *info = (*info)->next;
410 _Jv_MonitorExit (&java::lang::Class::class$);
414 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
417 _Jv_LoaderInfo *info = (_Jv_LoaderInfo *) _Jv_Malloc (sizeof(_Jv_LoaderInfo));
418 jint hash = HASH_UTF(klass->name);
420 _Jv_MonitorEnter (&java::lang::Class::class$);
421 info->loader = loader;
423 info->next = initiated_classes[hash];
424 initiated_classes[hash] = info;
425 _Jv_MonitorExit (&java::lang::Class::class$);
428 // This function is called many times during startup, before main() is
429 // run. At that point in time we know for certain we are running
430 // single-threaded, so we don't need to lock when adding classes to the
431 // class chain. At all other times, the caller should synchronize on
434 _Jv_RegisterClasses (jclass *classes)
436 for (; *classes; ++classes)
438 jclass klass = *classes;
440 (*_Jv_RegisterClassHook) (klass);
442 // registering a compiled class causes
443 // it to be immediately "prepared".
444 if (klass->state == JV_STATE_NOTHING)
445 klass->state = JV_STATE_COMPILED;
450 _Jv_RegisterClassHookDefault (jclass klass)
452 jint hash = HASH_UTF (klass->name);
454 jclass check_class = loaded_classes[hash];
456 // If the class is already registered, don't re-register it.
457 while (check_class != NULL)
459 if (check_class == klass)
461 // If you get this, it means you have the same class in two
462 // different libraries.
463 #define TEXT "Duplicate class registration: "
464 // We size-limit MESSAGE so that you can't trash the stack.
466 strcpy (message, TEXT);
467 strncpy (message + sizeof (TEXT) - 1, klass->name->data,
468 sizeof (message) - sizeof (TEXT));
469 message[sizeof (message) - 1] = '\0';
470 if (! gcj::runtimeInitialized)
474 java::lang::String *str = JvNewStringLatin1 (message);
475 throw new java::lang::VirtualMachineError (str);
479 check_class = check_class->next;
482 klass->next = loaded_classes[hash];
483 loaded_classes[hash] = klass;
486 // A pointer to a function that actually registers a class.
487 // Normally _Jv_RegisterClassHookDefault, but could be some other function
488 // that registers the class in e.g. a ClassLoader-local table.
489 // Should synchronize on Class:class$ while setting/restore this variable.
491 void (*_Jv_RegisterClassHook) (jclass cl) = _Jv_RegisterClassHookDefault;
494 _Jv_RegisterClass (jclass klass)
499 _Jv_RegisterClasses (classes);
503 _Jv_FindClass (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
505 jclass klass = _Jv_FindClassInCache (name, loader);
509 jstring sname = _Jv_NewStringUTF (name->data);
513 // Load using a user-defined loader, jvmspec 5.3.2
514 klass = loader->loadClass(sname, false);
516 // If "loader" delegated the loadClass operation to another
517 // loader, explicitly register that it is also an initiating
518 // loader of the given class.
519 if (klass && (klass->getClassLoader () != loader))
520 _Jv_RegisterInitiatingLoader (klass, loader);
524 java::lang::ClassLoader *sys
525 = java::lang::ClassLoader::getSystemClassLoader ();
527 // Load using the bootstrap loader jvmspec 5.3.1.
528 klass = sys->loadClass (sname, false);
530 // Register that we're an initiating loader.
532 _Jv_RegisterInitiatingLoader (klass, 0);
537 // we need classes to be in the hash while
538 // we're loading, so that they can refer to themselves.
539 _Jv_WaitForState (klass, JV_STATE_LOADED);
546 _Jv_InitNewClassFields (jclass ret)
551 ret->superclass = NULL;
552 ret->constants.size = 0;
553 ret->constants.tags = NULL;
554 ret->constants.data = NULL;
556 ret->method_count = 0;
557 ret->vtable_method_count = 0;
559 ret->size_in_bytes = 0;
560 ret->field_count = 0;
561 ret->static_field_count = 0;
563 ret->interfaces = NULL;
565 ret->interface_count = 0;
566 ret->state = JV_STATE_NOTHING;
569 ret->ancestors = NULL;
571 ret->arrayclass = NULL;
575 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
576 java::lang::ClassLoader *loader)
578 jclass ret = (jclass) JvAllocObject (&java::lang::Class::class$);
579 _Jv_InitNewClassFields (ret);
581 ret->superclass = superclass;
582 ret->loader = loader;
584 _Jv_RegisterClass (ret);
589 static _Jv_IDispatchTable *array_idt = NULL;
590 static jshort array_depth = 0;
591 static jclass *array_ancestors = NULL;
593 // Create a class representing an array of ELEMENT and store a pointer to it
594 // in element->arrayclass. LOADER is the ClassLoader which _initiated_ the
595 // instantiation of this array. ARRAY_VTABLE is the vtable to use for the new
596 // array class. This parameter is optional.
598 _Jv_NewArrayClass (jclass element, java::lang::ClassLoader *loader,
599 _Jv_VTable *array_vtable)
601 JvSynchronize sync (element);
603 _Jv_Utf8Const *array_name;
606 if (element->arrayclass)
609 if (element->isPrimitive())
611 if (element == JvPrimClass (void))
612 throw new java::lang::ClassNotFoundException ();
616 len = element->name->length + 5;
621 signature[index++] = '[';
622 // Compute name of array class.
623 if (element->isPrimitive())
625 signature[index++] = (char) element->method_count;
629 size_t length = element->name->length;
630 const char *const name = element->name->data;
632 signature[index++] = 'L';
633 memcpy (&signature[index], name, length);
636 signature[index++] = ';';
638 array_name = _Jv_makeUtf8Const (signature, index);
641 // Create new array class.
642 jclass array_class = _Jv_NewClass (array_name, &java::lang::Object::class$,
645 // Note that `vtable_method_count' doesn't include the initial
647 JvAssert (java::lang::Object::class$.vtable_method_count
648 == NUM_OBJECT_METHODS);
649 int dm_count = java::lang::Object::class$.vtable_method_count;
651 // Create a new vtable by copying Object's vtable.
654 vtable = array_vtable;
656 vtable = _Jv_VTable::new_vtable (dm_count);
657 vtable->clas = array_class;
658 vtable->gc_descr = java::lang::Object::class$.vtable->gc_descr;
659 for (int i = 0; i < dm_count; ++i)
660 vtable->set_method (i, java::lang::Object::class$.vtable->get_method (i));
662 array_class->vtable = vtable;
663 array_class->vtable_method_count
664 = java::lang::Object::class$.vtable_method_count;
666 // Stash the pointer to the element type.
667 array_class->methods = (_Jv_Method *) element;
669 // Register our interfaces.
670 static jclass interfaces[] =
672 &java::lang::Cloneable::class$,
673 &java::io::Serializable::class$
675 array_class->interfaces = interfaces;
676 array_class->interface_count = sizeof interfaces / sizeof interfaces[0];
678 // Since all array classes have the same interface dispatch table, we can
679 // cache one and reuse it. It is not necessary to synchronize this.
682 _Jv_PrepareConstantTimeTables (array_class);
683 array_idt = array_class->idt;
684 array_depth = array_class->depth;
685 array_ancestors = array_class->ancestors;
689 array_class->idt = array_idt;
690 array_class->depth = array_depth;
691 array_class->ancestors = array_ancestors;
694 using namespace java::lang::reflect;
696 // Array classes are "abstract final"...
697 _Jv_ushort accflags = Modifier::FINAL | Modifier::ABSTRACT;
698 // ... and inherit accessibility from element type, per vmspec 5.3.3.2
699 accflags |= (element->accflags & Modifier::PUBLIC);
700 accflags |= (element->accflags & Modifier::PROTECTED);
701 accflags |= (element->accflags & Modifier::PRIVATE);
702 array_class->accflags = accflags;
705 // An array class has no visible instance fields. "length" is invisible to
708 // say this class is initialized and ready to go!
709 array_class->state = JV_STATE_DONE;
711 // vmspec, section 5.3.3 describes this
712 if (element->loader != loader)
713 _Jv_RegisterInitiatingLoader (array_class, loader);
715 element->arrayclass = array_class;