1 // natClassLoader.cc - Implementation of java.lang.ClassLoader native methods.
3 /* Copyright (C) 1999, 2000 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/reflect/Modifier.h>
37 #include <java/lang/Runtime.h>
39 #define CloneableClass _CL_Q34java4lang9Cloneable
40 extern java::lang::Class CloneableClass;
41 #define ObjectClass _CL_Q34java4lang6Object
42 extern java::lang::Class ObjectClass;
43 #define ClassClass _CL_Q34java4lang5Class
44 extern java::lang::Class ClassClass;
45 #define VMClassLoaderClass _CL_Q34java4lang17VMClassLoader
46 extern java::lang::Class VMClassLoader;
47 #define ClassLoaderClass _CL_Q34java4lang11ClassLoader
48 extern java::lang::Class ClassLoaderClass;
49 #define SerializableClass _CL_Q34java2io12Serializable
50 extern java::lang::Class SerializableClass;
51 /////////// java.lang.ClassLoader native methods ////////////
53 java::lang::ClassLoader *
54 java::lang::ClassLoader::getSystemClassLoader (void)
56 JvSynchronize sync (&ClassLoaderClass);
58 system = gnu::gcj::runtime::VMClassLoader::getVMClassLoader ();
63 java::lang::ClassLoader::defineClass0 (jstring name,
70 klass = (jclass) JvAllocObject (&ClassClass, sizeof (_Jv_InterpClass));
72 // synchronize on the class, so that it is not
73 // attempted initialized until we're done loading.
74 _Jv_MonitorEnter (klass);
76 // record which is the defining loader
79 // register that we are the initiating loader...
82 _Jv_Utf8Const * name2 = _Jv_makeUtf8Const (name);
84 _Jv_VerifyClassName (name2);
91 _Jv_DefineClass (klass, data, offset, length);
93 catch (java::lang::Throwable *ex)
95 klass->state = JV_STATE_ERROR;
98 _Jv_UnregisterClass (klass);
100 _Jv_MonitorExit (klass);
102 // FIXME: Here we may want to test that EX does
103 // indeed represent a valid exception. That is,
104 // anything but ClassNotFoundException,
105 // or some kind of Error.
110 // if everything proceeded sucessfully, we're loaded.
111 JvAssert (klass->state == JV_STATE_LOADED);
113 // if an exception is generated, this is initially missed.
114 // however, we come back here in handleException0 below...
115 _Jv_MonitorExit (klass);
126 _Jv_WaitForState (jclass klass, int state)
128 if (klass->state >= state)
131 _Jv_MonitorEnter (klass) ;
133 if (state == JV_STATE_LINKED)
135 // Must call _Jv_PrepareCompiledClass while holding the class
137 _Jv_PrepareCompiledClass (klass);
138 _Jv_MonitorExit (klass);
142 java::lang::Thread *self = java::lang::Thread::currentThread();
144 // this is similar to the strategy for class initialization.
145 // if we already hold the lock, just leave.
146 while (klass->state <= state
148 && klass->thread != self)
151 _Jv_MonitorExit (klass);
153 if (klass->state == JV_STATE_ERROR)
155 _Jv_Throw (new java::lang::LinkageError ());
159 // Finish linking a class. Only called from ClassLoader::resolveClass.
161 java::lang::ClassLoader::linkClass0 (java::lang::Class *klass)
163 if (klass->state >= JV_STATE_LINKED)
167 if (_Jv_IsInterpretedClass (klass))
168 _Jv_PrepareClass (klass);
171 _Jv_PrepareCompiledClass (klass);
175 java::lang::ClassLoader::markClassErrorState0 (java::lang::Class *klass)
177 klass->state = JV_STATE_ERROR;
182 /** this is the only native method in VMClassLoader, so
183 we define it here. */
185 gnu::gcj::runtime::VMClassLoader::findSystemClass (jstring name)
187 _Jv_Utf8Const *name_u = _Jv_makeUtf8Const (name);
188 jclass klass = _Jv_FindClassInCache (name_u, 0);
192 // Turn `gnu.pkg.quux' into `gnu-pkg-quux'. Then search for a
193 // module named (eg, on Linux) `gnu-pkg-quux.so', followed by
194 // `gnu-pkg.so' and `gnu.so'. If loading one of these causes
195 // the class to appear in the cache, then use it.
196 jstring so_base_name = name->replace ('.', '-');
198 while (! klass && so_base_name && so_base_name->length() > 0)
200 using namespace ::java::lang;
201 Runtime *rt = Runtime::getRuntime();
202 jboolean loaded = rt->loadLibraryInternal (so_base_name);
204 jint nd = so_base_name->lastIndexOf ('-');
208 so_base_name = so_base_name->substring (0, nd);
211 klass = _Jv_FindClassInCache (name_u, 0);
219 java::lang::ClassLoader::findLoadedClass (jstring name)
221 return _Jv_FindClassInCache (_Jv_makeUtf8Const (name), this);
225 /** This function does class-preparation for compiled classes.
226 NOTE: It contains replicated functionality from
227 _Jv_ResolvePoolEntry, and this is intentional, since that function
228 lives in resolve.cc which is entirely conditionally compiled.
231 _Jv_PrepareCompiledClass (jclass klass)
233 if (klass->state >= JV_STATE_LINKED)
236 // Short-circuit, so that mutually dependent classes are ok.
237 klass->state = JV_STATE_LINKED;
239 _Jv_Constants *pool = &klass->constants;
240 for (int index = 1; index < pool->size; ++index)
242 if (pool->tags[index] == JV_CONSTANT_Class)
244 _Jv_Utf8Const *name = pool->data[index].utf8;
247 if (name->data[0] == '[')
248 found = _Jv_FindClassFromSignature (&name->data[0],
251 found = _Jv_FindClass (name, klass->loader);
255 jstring str = _Jv_NewStringUTF (name->data);
256 JvThrow (new java::lang::ClassNotFoundException (str));
259 pool->data[index].clazz = found;
260 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
262 else if (pool->tags[index] == JV_CONSTANT_String)
265 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
266 pool->data[index].o = str;
267 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
272 // FIXME: although the comment up top says that this function is
273 // only called for compiled classes, it is actually called for every
275 if (! _Jv_IsInterpretedClass (klass))
277 #endif /* INTERPRETER */
278 jfieldID f = JvGetFirstStaticField (klass);
279 for (int n = JvNumStaticFields (klass); n > 0; --n)
281 int mod = f->getModifiers ();
282 // Maybe the compiler should mark these with
283 // _Jv_FIELD_CONSTANT_VALUE? For now we just know that this
284 // only happens for constant strings.
285 if (f->getClass () == &StringClass
286 && java::lang::reflect::Modifier::isStatic (mod)
287 && java::lang::reflect::Modifier::isFinal (mod))
289 jstring *strp = (jstring *) f->u.addr;
291 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
293 f = f->getNextField ();
297 #endif /* INTERPRETER */
304 // A single class can have many "initiating" class loaders,
305 // and a single "defining" class loader. The Defining
306 // class loader is what is returned from Class.getClassLoader()
307 // and is used when loading dependent classes during resolution.
308 // The set of initiating class loaders are used to ensure
309 // safety of linking, and is maintained in the hash table
310 // "initiated_classes". A defining classloader is by definition also
311 // initiating, so we only store classes in this table, if they have more
312 // than one class loader associated.
316 // Size of local hash table.
317 #define HASH_LEN 1013
319 // Hash function for Utf8Consts.
320 #define HASH_UTF(Utf) (((Utf)->hash) % HASH_LEN)
322 struct _Jv_LoaderInfo {
323 _Jv_LoaderInfo *next;
324 java::lang::Class *klass;
325 java::lang::ClassLoader *loader;
328 static _Jv_LoaderInfo *initiated_classes[HASH_LEN];
329 static jclass loaded_classes[HASH_LEN];
331 // This is the root of a linked list of classes
336 _Jv_FindClassInCache (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
338 _Jv_MonitorEnter (&ClassClass);
339 jint hash = HASH_UTF (name);
341 // first, if LOADER is a defining loader, then it is also initiating
343 for (klass = loaded_classes[hash]; klass; klass = klass->next)
345 if (loader == klass->loader && _Jv_equalUtf8Consts (name, klass->name))
349 // otherwise, it may be that the class in question was defined
350 // by some other loader, but that the loading was initiated by
351 // the loader in question.
354 _Jv_LoaderInfo *info;
355 for (info = initiated_classes[hash]; info; info = info->next)
357 if (loader == info->loader
358 && _Jv_equalUtf8Consts (name, info->klass->name))
366 _Jv_MonitorExit (&ClassClass);
372 _Jv_UnregisterClass (jclass the_class)
374 _Jv_MonitorEnter (&ClassClass);
375 jint hash = HASH_UTF(the_class->name);
377 jclass *klass = &(loaded_classes[hash]);
378 for ( ; *klass; klass = &((*klass)->next))
380 if (*klass == the_class)
382 *klass = (*klass)->next;
387 _Jv_LoaderInfo **info = &(initiated_classes[hash]);
388 for ( ; ; info = &((*info)->next))
390 while (*info && (*info)->klass == the_class)
392 *info = (*info)->next;
399 _Jv_MonitorExit (&ClassClass);
403 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
405 _Jv_LoaderInfo *info = new _Jv_LoaderInfo; // non-gc alloc!
406 jint hash = HASH_UTF(klass->name);
408 _Jv_MonitorEnter (&ClassClass);
409 info->loader = loader;
411 info->next = initiated_classes[hash];
412 initiated_classes[hash] = info;
413 _Jv_MonitorExit (&ClassClass);
417 // This function is called many times during startup, before main() is
418 // run. We do our runtime initialization here the very first time we
419 // are called. At that point in time we know for certain we are
420 // running single-threaded, so we don't need to lock when modifying
421 // `init'. CLASSES is NULL-terminated.
423 _Jv_RegisterClasses (jclass *classes)
425 static bool init = false;
432 _Jv_InitializeSyncMutex ();
435 JvSynchronize sync (&ClassClass);
436 for (; *classes; ++classes)
438 jclass klass = *classes;
439 jint hash = HASH_UTF (klass->name);
440 klass->next = loaded_classes[hash];
441 loaded_classes[hash] = klass;
443 // registering a compiled class causes
444 // it to be immediately "prepared".
445 if (klass->state == JV_STATE_NOTHING)
446 klass->state = JV_STATE_COMPILED;
451 _Jv_RegisterClass (jclass klass)
456 _Jv_RegisterClasses (classes);
460 _Jv_FindClass (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
462 jclass klass = _Jv_FindClassInCache (name, loader);
466 jstring sname = _Jv_NewStringUTF (name->data);
470 // Load using a user-defined loader, jvmspec 5.3.2
471 klass = loader->loadClass(sname, false);
473 // If "loader" delegated the loadClass operation to another
474 // loader, explicitly register that it is also an initiating
475 // loader of the given class.
476 if (klass && (klass->getClassLoader () != loader))
477 _Jv_RegisterInitiatingLoader (klass, loader);
481 java::lang::ClassLoader *sys = java::lang::ClassLoader::system;
484 _Jv_InitClass (&ClassLoaderClass);
485 sys = java::lang::ClassLoader::getSystemClassLoader ();
488 // Load using the bootstrap loader jvmspec 5.3.1.
489 klass = sys->loadClass (sname, false);
491 // Register that we're an initiating loader.
493 _Jv_RegisterInitiatingLoader (klass, 0);
498 // we need classes to be in the hash while
499 // we're loading, so that they can refer to themselves.
500 _Jv_WaitForState (klass, JV_STATE_LOADED);
507 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
508 java::lang::ClassLoader *loader)
510 jclass ret = (jclass) JvAllocObject (&ClassClass);
515 ret->superclass = superclass;
516 ret->constants.size = 0;
517 ret->constants.tags = NULL;
518 ret->constants.data = NULL;
520 ret->method_count = 0;
521 ret->vtable_method_count = 0;
523 ret->size_in_bytes = 0;
524 ret->field_count = 0;
525 ret->static_field_count = 0;
527 ret->interfaces = NULL;
528 ret->loader = loader;
529 ret->interface_count = 0;
530 ret->state = JV_STATE_NOTHING;
533 ret->ancestors = NULL;
536 _Jv_RegisterClass (ret);
542 _Jv_FindArrayClass (jclass element, java::lang::ClassLoader *loader,
543 _Jv_VTable *array_vtable)
545 _Jv_Utf8Const *array_name;
547 if (element->isPrimitive())
549 // For primitive types the array is cached in the class.
550 jclass ret = (jclass) element->methods;
556 len = element->name->length + 5;
561 signature[index++] = '[';
562 // Compute name of array class to see if we've already cached it.
563 if (element->isPrimitive())
565 signature[index++] = (char) element->method_count;
569 size_t length = element->name->length;
570 const char *const name = element->name->data;
572 signature[index++] = 'L';
573 memcpy (&signature[index], name, length);
576 signature[index++] = ';';
578 array_name = _Jv_makeUtf8Const (signature, index);
581 jclass array_class = _Jv_FindClassInCache (array_name, element->loader);
585 // Create new array class.
586 array_class = _Jv_NewClass (array_name, &ObjectClass, element->loader);
588 // Note that `vtable_method_count' doesn't include the initial
590 JvAssert (ObjectClass.vtable_method_count == NUM_OBJECT_METHODS);
591 int dm_count = ObjectClass.vtable_method_count;
593 // Create a new vtable by copying Object's vtable (except the
594 // class pointer, of course). Note that we allocate this as
595 // unscanned memory -- the vtables are handled specially by the
597 int size = (sizeof (_Jv_VTable) + ((dm_count - 1) * sizeof (void *)));
600 vtable = array_vtable;
602 vtable = (_Jv_VTable *) _Jv_AllocBytes (size);
603 vtable->clas = array_class;
604 memcpy (vtable->method, ObjectClass.vtable->method,
605 dm_count * sizeof (void *));
606 vtable->gc_descr = ObjectClass.vtable->gc_descr;
607 array_class->vtable = vtable;
608 array_class->vtable_method_count = ObjectClass.vtable_method_count;
610 // Stash the pointer to the element type.
611 array_class->methods = (_Jv_Method *) element;
613 // Register our interfaces.
614 static jclass interfaces[] = { &CloneableClass, &SerializableClass };
615 array_class->interfaces = interfaces;
616 array_class->interface_count = sizeof interfaces / sizeof interfaces[0];
618 // FIXME: Shouldn't this be synchronized? _Jv_PrepareConstantTimeTables
619 // needs to be called with the mutex for array_class held.
620 // Generate the interface dispatch table.
621 _Jv_PrepareConstantTimeTables (array_class);
623 // as per vmspec 5.3.3.2
624 array_class->accflags = element->accflags;
626 // FIXME: initialize other Class instance variables,
629 // say this class is initialized and ready to go!
630 array_class->state = JV_STATE_DONE;
632 // vmspec, section 5.3.3 describes this
633 if (element->loader != loader)
634 _Jv_RegisterInitiatingLoader (array_class, loader);
637 // For primitive types, point back at this array.
638 if (element->isPrimitive())
639 element->methods = (_Jv_Method *) array_class;