1 // natClassLoader.cc - Implementation of java.lang.ClassLoader native methods.
2 
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003  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 <string.h>
17 
18 #include <gcj/cni.h>
19 #include <jvm.h>
20 
21 #include <java-threads.h>
22 #include <java-interp.h>
23 
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>
43 
44 /////////// java.lang.ClassLoader native methods ////////////
45 
46 java::lang::Class *
defineClass(java::lang::ClassLoader * loader,jstring name,jbyteArray data,jint offset,jint length,java::security::ProtectionDomain * pd)47 java::lang::VMClassLoader::defineClass (java::lang::ClassLoader *loader,
48 					jstring name,
49 					jbyteArray data,
50 					jint offset,
51 					jint length,
52 					java::security::ProtectionDomain *pd)
53 {
54 #ifdef INTERPRETER
55   jclass klass;
56   klass = (jclass) JvAllocObject (&java::lang::Class::class$,
57 				  sizeof (_Jv_InterpClass));
58 
59   // Synchronize on the class, so that it is not attempted initialized
60   // until we're done loading.
61   JvSynchronize sync (klass);
62 
63   // Record the defining loader.  For the system class loader, we
64   // record NULL.
65   if (loader != java::lang::ClassLoader::getSystemClassLoader())
66     klass->loader = loader;
67 
68   if (name != 0)
69     {
70       _Jv_Utf8Const *name2 = _Jv_makeUtf8Const (name);
71 
72       if (! _Jv_VerifyClassName (name2))
73 	throw new java::lang::ClassFormatError
74 	  (JvNewStringLatin1 ("erroneous class name"));
75 
76       klass->name = name2;
77     }
78 
79   try
80     {
81       _Jv_DefineClass (klass, data, offset, length);
82     }
83   catch (java::lang::Throwable *ex)
84     {
85       klass->state = JV_STATE_ERROR;
86       klass->notifyAll ();
87 
88       _Jv_UnregisterClass (klass);
89 
90       // If EX is not a ClassNotFoundException, that's ok, because we
91       // account for the possibility in defineClass().
92       throw ex;
93     }
94 
95   klass->protectionDomain = pd;
96 
97   // if everything proceeded sucessfully, we're loaded.
98   JvAssert (klass->state == JV_STATE_LOADED);
99 
100   return klass;
101 
102 #else // INTERPRETER
103 
104   return 0;
105 #endif
106 }
107 
108 // Finish linking a class.  Only called from ClassLoader::resolveClass.
109 void
linkClass0(java::lang::Class * klass)110 java::lang::VMClassLoader::linkClass0 (java::lang::Class *klass)
111 {
112   _Jv_WaitForState (klass, JV_STATE_LINKED);
113 }
114 
115 void
markClassErrorState0(java::lang::Class * klass)116 java::lang::VMClassLoader::markClassErrorState0 (java::lang::Class *klass)
117 {
118   klass->state = JV_STATE_ERROR;
119   klass->notifyAll ();
120 }
121 
122 java::lang::ClassLoader *
getSystemClassLoaderInternal()123 java::lang::VMClassLoader::getSystemClassLoaderInternal()
124 {
125   _Jv_InitClass (&gnu::gcj::runtime::VMClassLoader::class$);
126   return gnu::gcj::runtime::VMClassLoader::instance;
127 }
128 
129 jclass
getPrimitiveClass(jchar type)130 java::lang::VMClassLoader::getPrimitiveClass (jchar type)
131 {
132   char sig[2];
133   sig[0] = (char) type;
134   sig[1] = '\0';
135   return _Jv_FindClassFromSignature (sig, NULL);
136 }
137 
138 jclass
loadClass(jstring name,jboolean resolve)139 java::lang::VMClassLoader::loadClass(jstring name, jboolean resolve)
140 {
141   _Jv_Utf8Const *utf = _Jv_makeUtf8Const (name);
142   // FIXME: we culd make _Jv_FindClassFromSignature a template.
143   jclass klass = _Jv_FindClassInCache (utf, NULL);
144   if (klass && resolve)
145     _Jv_InitClass (klass);
146   return klass;
147 }
148 
149 void
_Jv_WaitForState(jclass klass,int state)150 _Jv_WaitForState (jclass klass, int state)
151 {
152   if (klass->state >= state)
153     return;
154 
155   _Jv_MonitorEnter (klass) ;
156 
157   if (state == JV_STATE_LINKED)
158     {
159       // Must call _Jv_PrepareCompiledClass while holding the class
160       // mutex.
161 #ifdef INTERPRETER
162       if (_Jv_IsInterpretedClass (klass))
163 	_Jv_PrepareClass (klass);
164 #endif
165       _Jv_PrepareCompiledClass (klass);
166       _Jv_MonitorExit (klass);
167       return;
168     }
169 
170   java::lang::Thread *self = java::lang::Thread::currentThread();
171 
172   // this is similar to the strategy for class initialization.
173   // if we already hold the lock, just leave.
174   while (klass->state <= state
175 	 && klass->thread
176 	 && klass->thread != self)
177     klass->wait ();
178 
179   _Jv_MonitorExit (klass);
180 
181   if (klass->state == JV_STATE_ERROR)
182     throw new java::lang::LinkageError;
183 }
184 
185 typedef unsigned int uaddr __attribute__ ((mode (pointer)));
186 
187 /** This function does class-preparation for compiled classes.
188     NOTE: It contains replicated functionality from
189     _Jv_ResolvePoolEntry, and this is intentional, since that function
190     lives in resolve.cc which is entirely conditionally compiled.
191  */
192 void
_Jv_PrepareCompiledClass(jclass klass)193 _Jv_PrepareCompiledClass (jclass klass)
194 {
195   if (klass->state >= JV_STATE_LINKED)
196     return;
197 
198   // Short-circuit, so that mutually dependent classes are ok.
199   klass->state = JV_STATE_LINKED;
200 
201   _Jv_Constants *pool = &klass->constants;
202 
203   // Resolve class constants first, since other constant pool
204   // entries may rely on these.
205   for (int index = 1; index < pool->size; ++index)
206     {
207       if (pool->tags[index] == JV_CONSTANT_Class)
208 	{
209 	  _Jv_Utf8Const *name = pool->data[index].utf8;
210 
211 	  jclass found;
212 	  if (name->data[0] == '[')
213 	    found = _Jv_FindClassFromSignature (&name->data[0],
214 						klass->loader);
215 	  else
216 	    found = _Jv_FindClass (name, klass->loader);
217 
218 	  if (! found)
219 	    {
220 	      jstring str = _Jv_NewStringUTF (name->data);
221 	      throw new java::lang::NoClassDefFoundError (str);
222 	    }
223 
224 	  pool->data[index].clazz = found;
225 	  pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
226 	}
227     }
228 
229   // If superclass looks like a constant pool entry,
230   // resolve it now.
231   if ((uaddr) klass->superclass < pool->size)
232     klass->superclass = pool->data[(int) klass->superclass].clazz;
233 
234   // Likewise for interfaces.
235   for (int i = 0; i < klass->interface_count; i++)
236     if ((uaddr) klass->interfaces[i] < pool->size)
237       klass->interfaces[i] = pool->data[(int) klass->interfaces[i]].clazz;
238 
239   // Resolve the remaining constant pool entries.
240   for (int index = 1; index < pool->size; ++index)
241     {
242       if (pool->tags[index] == JV_CONSTANT_String)
243 	{
244 	  jstring str;
245 
246 	  str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
247 	  pool->data[index].o = str;
248 	  pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
249 	}
250     }
251 
252 #ifdef INTERPRETER
253   // FIXME: although the comment up top says that this function is
254   // only called for compiled classes, it is actually called for every
255   // class.
256   if (! _Jv_IsInterpretedClass (klass))
257     {
258 #endif /* INTERPRETER */
259       jfieldID f = JvGetFirstStaticField (klass);
260       for (int n = JvNumStaticFields (klass); n > 0; --n)
261 	{
262 	  int mod = f->getModifiers ();
263 	  // If we have a static String field with a non-null initial
264 	  // value, we know it points to a Utf8Const.
265 	  _Jv_ResolveField(f, klass->loader);
266 	  if (f->getClass () == &java::lang::String::class$
267 	      && java::lang::reflect::Modifier::isStatic (mod))
268 	    {
269 	      jstring *strp = (jstring *) f->u.addr;
270 	      if (*strp)
271 		*strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
272 	    }
273 	  f = f->getNextField ();
274 	}
275 #ifdef INTERPRETER
276     }
277 #endif /* INTERPRETER */
278 
279   klass->notifyAll ();
280 
281   _Jv_PushClass (klass);
282 }
283 
284 
285 //
286 //  A single class can have many "initiating" class loaders,
287 //  and a single "defining" class loader.  The Defining
288 //  class loader is what is returned from Class.getClassLoader()
289 //  and is used when loading dependent classes during resolution.
290 //  The set of initiating class loaders are used to ensure
291 //  safety of linking, and is maintained in the hash table
292 //  "initiated_classes".  A defining classloader is by definition also
293 //  initiating, so we only store classes in this table if they have more
294 //  than one class loader associated.
295 //
296 
297 
298 // Size of local hash table.
299 #define HASH_LEN 1013
300 
301 // Hash function for Utf8Consts.
302 #define HASH_UTF(Utf) (((Utf)->hash) % HASH_LEN)
303 
304 struct _Jv_LoaderInfo
305 {
306   _Jv_LoaderInfo          *next;
307   java::lang::Class       *klass;
308   java::lang::ClassLoader *loader;
309 };
310 
311 static _Jv_LoaderInfo *initiated_classes[HASH_LEN];
312 static jclass loaded_classes[HASH_LEN];
313 
314 // This is the root of a linked list of classes
315 
316 
317 
318 jclass
_Jv_FindClassInCache(_Jv_Utf8Const * name,java::lang::ClassLoader * loader)319 _Jv_FindClassInCache (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
320 {
321   JvSynchronize sync (&java::lang::Class::class$);
322   jint hash = HASH_UTF (name);
323 
324   if (loader && loader == java::lang::ClassLoader::getSystemClassLoader())
325     loader = NULL;
326 
327   // first, if LOADER is a defining loader, then it is also initiating
328   jclass klass;
329   for (klass = loaded_classes[hash]; klass; klass = klass->next)
330     {
331       if (loader == klass->loader && _Jv_equalUtf8Consts (name, klass->name))
332 	break;
333     }
334 
335   // otherwise, it may be that the class in question was defined
336   // by some other loader, but that the loading was initiated by
337   // the loader in question.
338   if (!klass)
339     {
340       _Jv_LoaderInfo *info;
341       for (info = initiated_classes[hash]; info; info = info->next)
342 	{
343 	  if (loader == info->loader
344 	      && _Jv_equalUtf8Consts (name, info->klass->name))
345 	    {
346 	      klass = info->klass;
347 	      break;
348 	    }
349 	}
350     }
351 
352   return klass;
353 }
354 
355 void
_Jv_UnregisterClass(jclass the_class)356 _Jv_UnregisterClass (jclass the_class)
357 {
358   JvSynchronize sync (&java::lang::Class::class$);
359   jint hash = HASH_UTF(the_class->name);
360 
361   jclass *klass = &(loaded_classes[hash]);
362   for ( ; *klass; klass = &((*klass)->next))
363     {
364       if (*klass == the_class)
365 	{
366 	  *klass = (*klass)->next;
367 	  break;
368 	}
369     }
370 
371   _Jv_LoaderInfo **info = &(initiated_classes[hash]);
372   for ( ; ; info = &((*info)->next))
373     {
374       while (*info && (*info)->klass == the_class)
375 	{
376 	  _Jv_LoaderInfo *old = *info;
377 	  *info = (*info)->next;
378 	  _Jv_Free (old);
379 	}
380 
381       if (*info == NULL)
382 	break;
383     }
384 }
385 
386 void
_Jv_RegisterInitiatingLoader(jclass klass,java::lang::ClassLoader * loader)387 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
388 {
389   if (loader && loader == java::lang::ClassLoader::getSystemClassLoader())
390     loader = NULL;
391 
392   // This information can't be visible to the GC.
393   _Jv_LoaderInfo *info
394     = (_Jv_LoaderInfo *) _Jv_Malloc (sizeof(_Jv_LoaderInfo));
395   jint hash = HASH_UTF(klass->name);
396 
397   JvSynchronize sync (&java::lang::Class::class$);
398   info->loader = loader;
399   info->klass  = klass;
400   info->next   = initiated_classes[hash];
401   initiated_classes[hash] = info;
402 }
403 
404 // This function is called many times during startup, before main() is
405 // run.  At that point in time we know for certain we are running
406 // single-threaded, so we don't need to lock when adding classes to the
407 // class chain.  At all other times, the caller should synchronize on
408 // Class::class$.
409 void
_Jv_RegisterClasses(jclass * classes)410 _Jv_RegisterClasses (jclass *classes)
411 {
412   for (; *classes; ++classes)
413     {
414       jclass klass = *classes;
415 
416       (*_Jv_RegisterClassHook) (klass);
417 
418       // registering a compiled class causes
419       // it to be immediately "prepared".
420       if (klass->state == JV_STATE_NOTHING)
421 	klass->state = JV_STATE_COMPILED;
422     }
423 }
424 
425 void
_Jv_RegisterClassHookDefault(jclass klass)426 _Jv_RegisterClassHookDefault (jclass klass)
427 {
428   jint hash = HASH_UTF (klass->name);
429 
430   jclass check_class = loaded_classes[hash];
431 
432   // If the class is already registered, don't re-register it.
433   while (check_class != NULL)
434     {
435       if (check_class == klass)
436 	{
437 	  // If you get this, it means you have the same class in two
438 	  // different libraries.
439 #define TEXT "Duplicate class registration: "
440 	  // We size-limit MESSAGE so that you can't trash the stack.
441 	  char message[200];
442 	  strcpy (message, TEXT);
443 	  strncpy (message + sizeof (TEXT) - 1, klass->name->data,
444 		   sizeof (message) - sizeof (TEXT));
445 	  message[sizeof (message) - 1] = '\0';
446 	  if (! gcj::runtimeInitialized)
447 	    JvFail (message);
448 	  else
449 	    {
450 	      java::lang::String *str = JvNewStringLatin1 (message);
451 	      throw new java::lang::VirtualMachineError (str);
452 	    }
453 	}
454 
455       check_class = check_class->next;
456     }
457 
458   klass->next = loaded_classes[hash];
459   loaded_classes[hash] = klass;
460 }
461 
462 // A pointer to a function that actually registers a class.
463 // Normally _Jv_RegisterClassHookDefault, but could be some other function
464 // that registers the class in e.g. a ClassLoader-local table.
465 // Should synchronize on Class:class$ while setting/restore this variable.
466 
467 void (*_Jv_RegisterClassHook) (jclass cl) = _Jv_RegisterClassHookDefault;
468 
469 void
_Jv_RegisterClass(jclass klass)470 _Jv_RegisterClass (jclass klass)
471 {
472   jclass classes[2];
473   classes[0] = klass;
474   classes[1] = NULL;
475   _Jv_RegisterClasses (classes);
476 }
477 
478 jclass
_Jv_FindClass(_Jv_Utf8Const * name,java::lang::ClassLoader * loader)479 _Jv_FindClass (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
480 {
481   jclass klass = _Jv_FindClassInCache (name, loader);
482 
483   if (! klass)
484     {
485       jstring sname = _Jv_NewStringUTF (name->data);
486 
487       java::lang::ClassLoader *sys
488 	= java::lang::ClassLoader::getSystemClassLoader ();
489 
490       if (loader)
491 	{
492 	  // Load using a user-defined loader, jvmspec 5.3.2
493 	  klass = loader->loadClass(sname, false);
494 
495 	  // If "loader" delegated the loadClass operation to another
496 	  // loader, explicitly register that it is also an initiating
497 	  // loader of the given class.
498 	  java::lang::ClassLoader *delegate = (loader == sys
499 					       ? NULL
500 					       : loader);
501 	  if (klass && klass->getClassLoaderInternal () != delegate)
502 	    _Jv_RegisterInitiatingLoader (klass, loader);
503 	}
504       else
505 	{
506 	  // Load using the bootstrap loader jvmspec 5.3.1.
507 	  klass = sys->loadClass (sname, false);
508 
509 	  // Register that we're an initiating loader.
510 	  if (klass)
511 	    _Jv_RegisterInitiatingLoader (klass, 0);
512 	}
513     }
514   else
515     {
516       // we need classes to be in the hash while
517       // we're loading, so that they can refer to themselves.
518       _Jv_WaitForState (klass, JV_STATE_LOADED);
519     }
520 
521   return klass;
522 }
523 
524 jclass
_Jv_NewClass(_Jv_Utf8Const * name,jclass superclass,java::lang::ClassLoader * loader)525 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
526 	      java::lang::ClassLoader *loader)
527 {
528   jclass ret = (jclass) JvAllocObject (&java::lang::Class::class$);
529   ret->name = name;
530   ret->superclass = superclass;
531   ret->loader = loader;
532 
533   _Jv_RegisterClass (ret);
534 
535   return ret;
536 }
537 
538 static _Jv_IDispatchTable *array_idt = NULL;
539 static jshort array_depth = 0;
540 static jclass *array_ancestors = NULL;
541 
542 // Create a class representing an array of ELEMENT and store a pointer to it
543 // in element->arrayclass. LOADER is the ClassLoader which _initiated_ the
544 // instantiation of this array. ARRAY_VTABLE is the vtable to use for the new
545 // array class. This parameter is optional.
546 void
_Jv_NewArrayClass(jclass element,java::lang::ClassLoader * loader,_Jv_VTable * array_vtable)547 _Jv_NewArrayClass (jclass element, java::lang::ClassLoader *loader,
548 		   _Jv_VTable *array_vtable)
549 {
550   JvSynchronize sync (element);
551 
552   _Jv_Utf8Const *array_name;
553   int len;
554 
555   if (element->arrayclass)
556     return;
557 
558   if (element->isPrimitive())
559     {
560       if (element == JvPrimClass (void))
561 	throw new java::lang::ClassNotFoundException ();
562       len = 3;
563     }
564   else
565     len = element->name->length + 5;
566 
567   {
568     char signature[len];
569     int index = 0;
570     signature[index++] = '[';
571     // Compute name of array class.
572     if (element->isPrimitive())
573       {
574 	signature[index++] = (char) element->method_count;
575       }
576     else
577       {
578 	size_t length = element->name->length;
579 	const char *const name = element->name->data;
580 	if (name[0] != '[')
581 	  signature[index++] = 'L';
582 	memcpy (&signature[index], name, length);
583 	index += length;
584 	if (name[0] != '[')
585 	  signature[index++] = ';';
586       }
587     array_name = _Jv_makeUtf8Const (signature, index);
588   }
589 
590   // Create new array class.
591   jclass array_class = _Jv_NewClass (array_name, &java::lang::Object::class$,
592   				     element->loader);
593 
594   // Note that `vtable_method_count' doesn't include the initial
595   // gc_descr slot.
596   JvAssert (java::lang::Object::class$.vtable_method_count
597 	    == NUM_OBJECT_METHODS);
598   int dm_count = java::lang::Object::class$.vtable_method_count;
599 
600   // Create a new vtable by copying Object's vtable.
601   _Jv_VTable *vtable;
602   if (array_vtable)
603     vtable = array_vtable;
604   else
605     vtable = _Jv_VTable::new_vtable (dm_count);
606   vtable->clas = array_class;
607   vtable->gc_descr = java::lang::Object::class$.vtable->gc_descr;
608   for (int i = 0; i < dm_count; ++i)
609     vtable->set_method (i, java::lang::Object::class$.vtable->get_method (i));
610 
611   array_class->vtable = vtable;
612   array_class->vtable_method_count
613     = java::lang::Object::class$.vtable_method_count;
614 
615   // Stash the pointer to the element type.
616   array_class->methods = (_Jv_Method *) element;
617 
618   // Register our interfaces.
619   static jclass interfaces[] =
620     {
621       &java::lang::Cloneable::class$,
622       &java::io::Serializable::class$
623     };
624   array_class->interfaces = interfaces;
625   array_class->interface_count = sizeof interfaces / sizeof interfaces[0];
626 
627   // Since all array classes have the same interface dispatch table, we can
628   // cache one and reuse it. It is not necessary to synchronize this.
629   if (!array_idt)
630     {
631       _Jv_PrepareConstantTimeTables (array_class);
632       array_idt = array_class->idt;
633       array_depth = array_class->depth;
634       array_ancestors = array_class->ancestors;
635     }
636   else
637     {
638       array_class->idt = array_idt;
639       array_class->depth = array_depth;
640       array_class->ancestors = array_ancestors;
641     }
642 
643   using namespace java::lang::reflect;
644   {
645     // Array classes are "abstract final"...
646     _Jv_ushort accflags = Modifier::FINAL | Modifier::ABSTRACT;
647     // ... and inherit accessibility from element type, per vmspec 5.3.3.2
648     accflags |= (element->accflags & Modifier::PUBLIC);
649     accflags |= (element->accflags & Modifier::PROTECTED);
650     accflags |= (element->accflags & Modifier::PRIVATE);
651     array_class->accflags = accflags;
652   }
653 
654   // An array class has no visible instance fields. "length" is invisible to
655   // reflection.
656 
657   // say this class is initialized and ready to go!
658   array_class->state = JV_STATE_DONE;
659 
660   // vmspec, section 5.3.3 describes this
661   if (element->loader != loader)
662     _Jv_RegisterInitiatingLoader (array_class, loader);
663 
664   element->arrayclass = array_class;
665 }
666 
667 static jclass stack_head;
668 
669 // These two functions form a stack of classes.   When a class is loaded
670 // it is pushed onto the stack by the class loader; this is so that
671 // StackTrace can quickly determine which classes have been loaded.
672 
673 jclass
_Jv_PopClass(void)674 _Jv_PopClass (void)
675 {
676   JvSynchronize sync (&java::lang::Class::class$);
677   if (stack_head)
678     {
679       jclass tmp = stack_head;
680       stack_head = tmp->chain;
681       return tmp;
682     }
683   return NULL;
684 }
685 
686 void
_Jv_PushClass(jclass k)687 _Jv_PushClass (jclass k)
688 {
689   JvSynchronize sync (&java::lang::Class::class$);
690   jclass tmp = stack_head;
691   stack_head = k;
692   k->chain = tmp;
693 }
694