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::defineClass (java::lang::ClassLoader *cl,
180 return cl->defineClass (name, data, offset, length);
184 java::lang::VMClassLoader::getPrimitiveClass (jchar type)
187 sig[0] = (char) type;
189 return _Jv_FindClassFromSignature (sig, NULL);
193 java::lang::ClassLoader::findLoadedClass (jstring name)
195 return _Jv_FindClassInCache (_Jv_makeUtf8Const (name), this);
198 /** This function does class-preparation for compiled classes.
199 NOTE: It contains replicated functionality from
200 _Jv_ResolvePoolEntry, and this is intentional, since that function
201 lives in resolve.cc which is entirely conditionally compiled.
204 _Jv_PrepareCompiledClass (jclass klass)
206 if (klass->state >= JV_STATE_LINKED)
209 // Short-circuit, so that mutually dependent classes are ok.
210 klass->state = JV_STATE_LINKED;
212 _Jv_Constants *pool = &klass->constants;
213 for (int index = 1; index < pool->size; ++index)
215 if (pool->tags[index] == JV_CONSTANT_Class)
217 _Jv_Utf8Const *name = pool->data[index].utf8;
220 if (name->data[0] == '[')
221 found = _Jv_FindClassFromSignature (&name->data[0],
224 found = _Jv_FindClass (name, klass->loader);
228 jstring str = _Jv_NewStringUTF (name->data);
229 throw new java::lang::NoClassDefFoundError (str);
232 pool->data[index].clazz = found;
233 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
235 else if (pool->tags[index] == JV_CONSTANT_String)
239 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
240 pool->data[index].o = str;
241 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
246 // FIXME: although the comment up top says that this function is
247 // only called for compiled classes, it is actually called for every
249 if (! _Jv_IsInterpretedClass (klass))
251 #endif /* INTERPRETER */
252 jfieldID f = JvGetFirstStaticField (klass);
253 for (int n = JvNumStaticFields (klass); n > 0; --n)
255 int mod = f->getModifiers ();
256 // If we have a static String field with a non-null initial
257 // value, we know it points to a Utf8Const.
258 if (f->getClass () == &java::lang::String::class$
259 && java::lang::reflect::Modifier::isStatic (mod))
261 jstring *strp = (jstring *) f->u.addr;
263 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
265 f = f->getNextField ();
269 #endif /* INTERPRETER */
271 if (klass->vtable == NULL)
272 _Jv_MakeVTable(klass);
274 if (klass->otable != NULL && klass->otable->state == 0)
275 _Jv_LinkOffsetTable(klass);
279 _Jv_PushClass (klass);
284 // A single class can have many "initiating" class loaders,
285 // and a single "defining" class loader. The Defining
286 // class loader is what is returned from Class.getClassLoader()
287 // and is used when loading dependent classes during resolution.
288 // The set of initiating class loaders are used to ensure
289 // safety of linking, and is maintained in the hash table
290 // "initiated_classes". A defining classloader is by definition also
291 // initiating, so we only store classes in this table, if they have more
292 // than one class loader associated.
296 // Size of local hash table.
297 #define HASH_LEN 1013
299 // Hash function for Utf8Consts.
300 #define HASH_UTF(Utf) (((Utf)->hash) % HASH_LEN)
302 struct _Jv_LoaderInfo {
303 _Jv_LoaderInfo *next;
304 java::lang::Class *klass;
305 java::lang::ClassLoader *loader;
308 static _Jv_LoaderInfo *initiated_classes[HASH_LEN];
309 static jclass loaded_classes[HASH_LEN];
311 // This is the root of a linked list of classes
316 _Jv_FindClassInCache (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
318 _Jv_MonitorEnter (&java::lang::Class::class$);
319 jint hash = HASH_UTF (name);
321 // first, if LOADER is a defining loader, then it is also initiating
323 for (klass = loaded_classes[hash]; klass; klass = klass->next)
325 if (loader == klass->loader && _Jv_equalUtf8Consts (name, klass->name))
329 // otherwise, it may be that the class in question was defined
330 // by some other loader, but that the loading was initiated by
331 // the loader in question.
334 _Jv_LoaderInfo *info;
335 for (info = initiated_classes[hash]; info; info = info->next)
337 if (loader == info->loader
338 && _Jv_equalUtf8Consts (name, info->klass->name))
346 _Jv_MonitorExit (&java::lang::Class::class$);
352 _Jv_UnregisterClass (jclass the_class)
354 _Jv_MonitorEnter (&java::lang::Class::class$);
355 jint hash = HASH_UTF(the_class->name);
357 jclass *klass = &(loaded_classes[hash]);
358 for ( ; *klass; klass = &((*klass)->next))
360 if (*klass == the_class)
362 *klass = (*klass)->next;
367 _Jv_LoaderInfo **info = &(initiated_classes[hash]);
368 for ( ; ; info = &((*info)->next))
370 while (*info && (*info)->klass == the_class)
372 *info = (*info)->next;
379 _Jv_MonitorExit (&java::lang::Class::class$);
383 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
386 _Jv_LoaderInfo *info = (_Jv_LoaderInfo *) _Jv_Malloc (sizeof(_Jv_LoaderInfo));
387 jint hash = HASH_UTF(klass->name);
389 _Jv_MonitorEnter (&java::lang::Class::class$);
390 info->loader = loader;
392 info->next = initiated_classes[hash];
393 initiated_classes[hash] = info;
394 _Jv_MonitorExit (&java::lang::Class::class$);
397 // This function is called many times during startup, before main() is
398 // run. At that point in time we know for certain we are running
399 // single-threaded, so we don't need to lock when adding classes to the
400 // class chain. At all other times, the caller should synchronize on
403 _Jv_RegisterClasses (jclass *classes)
405 for (; *classes; ++classes)
407 jclass klass = *classes;
409 (*_Jv_RegisterClassHook) (klass);
411 // registering a compiled class causes
412 // it to be immediately "prepared".
413 if (klass->state == JV_STATE_NOTHING)
414 klass->state = JV_STATE_COMPILED;
419 _Jv_RegisterClassHookDefault (jclass klass)
421 jint hash = HASH_UTF (klass->name);
423 jclass check_class = loaded_classes[hash];
425 // If the class is already registered, don't re-register it.
426 while (check_class != NULL)
428 if (check_class == klass)
430 // If you get this, it means you have the same class in two
431 // different libraries.
432 #define TEXT "Duplicate class registration: "
433 // We size-limit MESSAGE so that you can't trash the stack.
435 strcpy (message, TEXT);
436 strncpy (message + sizeof (TEXT) - 1, klass->name->data,
437 sizeof (message) - sizeof (TEXT));
438 message[sizeof (message) - 1] = '\0';
439 if (! gcj::runtimeInitialized)
443 java::lang::String *str = JvNewStringLatin1 (message);
444 throw new java::lang::VirtualMachineError (str);
448 check_class = check_class->next;
451 klass->next = loaded_classes[hash];
452 loaded_classes[hash] = klass;
455 // A pointer to a function that actually registers a class.
456 // Normally _Jv_RegisterClassHookDefault, but could be some other function
457 // that registers the class in e.g. a ClassLoader-local table.
458 // Should synchronize on Class:class$ while setting/restore this variable.
460 void (*_Jv_RegisterClassHook) (jclass cl) = _Jv_RegisterClassHookDefault;
463 _Jv_RegisterClass (jclass klass)
468 _Jv_RegisterClasses (classes);
472 _Jv_FindClass (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
474 jclass klass = _Jv_FindClassInCache (name, loader);
478 jstring sname = _Jv_NewStringUTF (name->data);
482 // Load using a user-defined loader, jvmspec 5.3.2
483 klass = loader->loadClass(sname, false);
485 // If "loader" delegated the loadClass operation to another
486 // loader, explicitly register that it is also an initiating
487 // loader of the given class.
488 if (klass && (klass->getClassLoader () != loader))
489 _Jv_RegisterInitiatingLoader (klass, loader);
493 java::lang::ClassLoader *sys
494 = java::lang::ClassLoader::getSystemClassLoader ();
496 // Load using the bootstrap loader jvmspec 5.3.1.
497 klass = sys->loadClass (sname, false);
499 // Register that we're an initiating loader.
501 _Jv_RegisterInitiatingLoader (klass, 0);
506 // we need classes to be in the hash while
507 // we're loading, so that they can refer to themselves.
508 _Jv_WaitForState (klass, JV_STATE_LOADED);
515 _Jv_InitNewClassFields (jclass ret)
520 ret->superclass = NULL;
521 ret->constants.size = 0;
522 ret->constants.tags = NULL;
523 ret->constants.data = NULL;
525 ret->method_count = 0;
526 ret->vtable_method_count = 0;
528 ret->size_in_bytes = 0;
529 ret->field_count = 0;
530 ret->static_field_count = 0;
532 ret->interfaces = NULL;
534 ret->interface_count = 0;
535 ret->state = JV_STATE_NOTHING;
538 ret->ancestors = NULL;
540 ret->arrayclass = NULL;
541 ret->protectionDomain = NULL;
546 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
547 java::lang::ClassLoader *loader)
549 jclass ret = (jclass) JvAllocObject (&java::lang::Class::class$);
550 _Jv_InitNewClassFields (ret);
552 ret->superclass = superclass;
553 ret->loader = loader;
555 _Jv_RegisterClass (ret);
560 static _Jv_IDispatchTable *array_idt = NULL;
561 static jshort array_depth = 0;
562 static jclass *array_ancestors = NULL;
564 // Create a class representing an array of ELEMENT and store a pointer to it
565 // in element->arrayclass. LOADER is the ClassLoader which _initiated_ the
566 // instantiation of this array. ARRAY_VTABLE is the vtable to use for the new
567 // array class. This parameter is optional.
569 _Jv_NewArrayClass (jclass element, java::lang::ClassLoader *loader,
570 _Jv_VTable *array_vtable)
572 JvSynchronize sync (element);
574 _Jv_Utf8Const *array_name;
577 if (element->arrayclass)
580 if (element->isPrimitive())
582 if (element == JvPrimClass (void))
583 throw new java::lang::ClassNotFoundException ();
587 len = element->name->length + 5;
592 signature[index++] = '[';
593 // Compute name of array class.
594 if (element->isPrimitive())
596 signature[index++] = (char) element->method_count;
600 size_t length = element->name->length;
601 const char *const name = element->name->data;
603 signature[index++] = 'L';
604 memcpy (&signature[index], name, length);
607 signature[index++] = ';';
609 array_name = _Jv_makeUtf8Const (signature, index);
612 // Create new array class.
613 jclass array_class = _Jv_NewClass (array_name, &java::lang::Object::class$,
616 // Note that `vtable_method_count' doesn't include the initial
618 JvAssert (java::lang::Object::class$.vtable_method_count
619 == NUM_OBJECT_METHODS);
620 int dm_count = java::lang::Object::class$.vtable_method_count;
622 // Create a new vtable by copying Object's vtable.
625 vtable = array_vtable;
627 vtable = _Jv_VTable::new_vtable (dm_count);
628 vtable->clas = array_class;
629 vtable->gc_descr = java::lang::Object::class$.vtable->gc_descr;
630 for (int i = 0; i < dm_count; ++i)
631 vtable->set_method (i, java::lang::Object::class$.vtable->get_method (i));
633 array_class->vtable = vtable;
634 array_class->vtable_method_count
635 = java::lang::Object::class$.vtable_method_count;
637 // Stash the pointer to the element type.
638 array_class->methods = (_Jv_Method *) element;
640 // Register our interfaces.
641 static jclass interfaces[] =
643 &java::lang::Cloneable::class$,
644 &java::io::Serializable::class$
646 array_class->interfaces = interfaces;
647 array_class->interface_count = sizeof interfaces / sizeof interfaces[0];
649 // Since all array classes have the same interface dispatch table, we can
650 // cache one and reuse it. It is not necessary to synchronize this.
653 _Jv_PrepareConstantTimeTables (array_class);
654 array_idt = array_class->idt;
655 array_depth = array_class->depth;
656 array_ancestors = array_class->ancestors;
660 array_class->idt = array_idt;
661 array_class->depth = array_depth;
662 array_class->ancestors = array_ancestors;
665 using namespace java::lang::reflect;
667 // Array classes are "abstract final"...
668 _Jv_ushort accflags = Modifier::FINAL | Modifier::ABSTRACT;
669 // ... and inherit accessibility from element type, per vmspec 5.3.3.2
670 accflags |= (element->accflags & Modifier::PUBLIC);
671 accflags |= (element->accflags & Modifier::PROTECTED);
672 accflags |= (element->accflags & Modifier::PRIVATE);
673 array_class->accflags = accflags;
676 // An array class has no visible instance fields. "length" is invisible to
679 // say this class is initialized and ready to go!
680 array_class->state = JV_STATE_DONE;
682 // vmspec, section 5.3.3 describes this
683 if (element->loader != loader)
684 _Jv_RegisterInitiatingLoader (array_class, loader);
686 element->arrayclass = array_class;
689 static jclass stack_head;
691 // These two functions form a stack of classes. When a class is loaded
692 // it is pushed onto the stack by the class loader; this is so that
693 // StackTrace can quickly determine which classes have been loaded.
698 JvSynchronize sync (&java::lang::Class::class$);
701 jclass tmp = stack_head;
702 stack_head = tmp->chain;
709 _Jv_PushClass (jclass k)
711 JvSynchronize sync (&java::lang::Class::class$);
712 jclass tmp = stack_head;