OSDN Git Service

* Makefile.in: Rebuilt.
[pf3gnuchains/gcc-fork.git] / libjava / java / lang / natClassLoader.cc
1 // natClassLoader.cc - Implementation of java.lang.ClassLoader native methods.
2
3 /* Copyright (C) 1999, 2000, 2001, 2002  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 *
47 java::lang::ClassLoader::defineClass0 (jstring name,
48                                        jbyteArray data, 
49                                        jint offset,
50                                        jint length,
51                                        java::security::ProtectionDomain *pd)
52 {
53 #ifdef INTERPRETER
54   jclass klass;
55   klass = (jclass) JvAllocObject (&java::lang::Class::class$,
56                                   sizeof (_Jv_InterpClass));
57   _Jv_InitNewClassFields (klass);
58
59   // synchronize on the class, so that it is not
60   // attempted initialized until we're done loading.
61   _Jv_MonitorEnter (klass);
62
63   // record which is the defining loader
64   klass->loader = this;
65
66   // register that we are the initiating loader...
67   if (name != 0)
68     {
69       _Jv_Utf8Const *   name2 = _Jv_makeUtf8Const (name);
70
71       if (! _Jv_VerifyClassName (name2))
72         throw new java::lang::ClassFormatError
73           (JvNewStringLatin1 ("erroneous class name"));
74
75       klass->name = name2;
76     }
77
78   try
79     {
80       _Jv_DefineClass (klass, data, offset, length);
81     }
82   catch (java::lang::Throwable *ex)
83     {
84       klass->state = JV_STATE_ERROR;
85       klass->notifyAll ();
86
87       _Jv_UnregisterClass (klass);
88
89       _Jv_MonitorExit (klass);
90
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.
95
96       // FIXME: Rewrite this as a cleanup instead of
97       // as a catch handler.
98
99       throw ex;
100     }
101     
102   klass->protectionDomain = pd;
103
104   // if everything proceeded sucessfully, we're loaded.
105   JvAssert (klass->state == JV_STATE_LOADED);
106
107   // if an exception is generated, this is initially missed.
108   // however, we come back here in handleException0 below...
109   _Jv_MonitorExit (klass);
110
111   return klass;
112
113 #else // INTERPRETER
114
115   return 0;
116 #endif
117 }
118
119 void
120 _Jv_WaitForState (jclass klass, int state)
121 {
122   if (klass->state >= state)
123     return;
124   
125   _Jv_MonitorEnter (klass) ;
126
127   if (state == JV_STATE_LINKED)
128     {
129       // Must call _Jv_PrepareCompiledClass while holding the class
130       // mutex.
131       _Jv_PrepareCompiledClass (klass);
132       _Jv_MonitorExit (klass);
133       return;
134     }
135         
136   java::lang::Thread *self = java::lang::Thread::currentThread();
137
138   // this is similar to the strategy for class initialization.
139   // if we already hold the lock, just leave.
140   while (klass->state <= state
141          && klass->thread 
142          && klass->thread != self)
143     klass->wait ();
144
145   _Jv_MonitorExit (klass);
146
147   if (klass->state == JV_STATE_ERROR)
148     throw new java::lang::LinkageError;
149 }
150
151 // Finish linking a class.  Only called from ClassLoader::resolveClass.
152 void
153 java::lang::ClassLoader::linkClass0 (java::lang::Class *klass)
154 {
155   if (klass->state >= JV_STATE_LINKED)
156     return;
157
158 #ifdef INTERPRETER
159   if (_Jv_IsInterpretedClass (klass))
160     _Jv_PrepareClass (klass);
161 #endif
162
163   _Jv_PrepareCompiledClass (klass);
164 }
165
166 void
167 java::lang::ClassLoader::markClassErrorState0 (java::lang::Class *klass)
168 {
169   klass->state = JV_STATE_ERROR;
170   klass->notifyAll ();
171 }
172
173 jclass
174 java::lang::VMClassLoader::defineClass (java::lang::ClassLoader *cl, 
175                                         jstring name,
176                                         jbyteArray data, 
177                                         jint offset,
178                                         jint length)
179 {
180   return cl->defineClass (name, data, offset, length);
181 }
182
183 jclass
184 java::lang::VMClassLoader::getPrimitiveClass (jchar type)
185 {
186   char sig[2];
187   sig[0] = (char) type;
188   sig[1] = '\0';
189   return _Jv_FindClassFromSignature (sig, NULL);
190 }
191
192 jclass
193 java::lang::ClassLoader::findLoadedClass (jstring name)
194 {
195   return _Jv_FindClassInCache (_Jv_makeUtf8Const (name), this);
196 }
197
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.
202  */
203 void
204 _Jv_PrepareCompiledClass (jclass klass)
205 {
206   if (klass->state >= JV_STATE_LINKED)
207     return;
208
209   // Short-circuit, so that mutually dependent classes are ok.
210   klass->state = JV_STATE_LINKED;
211
212   _Jv_Constants *pool = &klass->constants;
213   for (int index = 1; index < pool->size; ++index)
214     {
215       if (pool->tags[index] == JV_CONSTANT_Class)
216         {
217           _Jv_Utf8Const *name = pool->data[index].utf8;
218           
219           jclass found;
220           if (name->data[0] == '[')
221             found = _Jv_FindClassFromSignature (&name->data[0],
222                                                 klass->loader);
223           else
224             found = _Jv_FindClass (name, klass->loader);
225                 
226           if (! found)
227             {
228               jstring str = _Jv_NewStringUTF (name->data);
229               throw new java::lang::NoClassDefFoundError (str);
230             }
231
232           pool->data[index].clazz = found;
233           pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
234         }
235       else if (pool->tags[index] == JV_CONSTANT_String)
236         {
237           jstring str;
238
239           str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
240           pool->data[index].o = str;
241           pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
242         }
243     }
244
245 #ifdef INTERPRETER
246   // FIXME: although the comment up top says that this function is
247   // only called for compiled classes, it is actually called for every
248   // class.
249   if (! _Jv_IsInterpretedClass (klass))
250     {
251 #endif /* INTERPRETER */
252       jfieldID f = JvGetFirstStaticField (klass);
253       for (int n = JvNumStaticFields (klass); n > 0; --n)
254         {
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))
260             {
261               jstring *strp = (jstring *) f->u.addr;
262               if (*strp)
263                 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
264             }
265           f = f->getNextField ();
266         }
267 #ifdef INTERPRETER
268     }
269 #endif /* INTERPRETER */
270
271   if (klass->vtable == NULL)
272     _Jv_MakeVTable(klass);
273
274   if (klass->otable != NULL && klass->otable->state == 0)
275     _Jv_LinkOffsetTable(klass);
276
277   klass->notifyAll ();
278
279   _Jv_PushClass (klass);
280 }
281
282
283 //
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.
293 //
294
295
296 // Size of local hash table.
297 #define HASH_LEN 1013
298
299 // Hash function for Utf8Consts.
300 #define HASH_UTF(Utf) (((Utf)->hash) % HASH_LEN)
301
302 struct _Jv_LoaderInfo {
303     _Jv_LoaderInfo          *next;
304     java::lang::Class       *klass;
305     java::lang::ClassLoader *loader;
306 };
307
308 static _Jv_LoaderInfo *initiated_classes[HASH_LEN];
309 static jclass loaded_classes[HASH_LEN];
310
311 // This is the root of a linked list of classes
312
313 \f
314
315 jclass
316 _Jv_FindClassInCache (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
317 {
318   _Jv_MonitorEnter (&java::lang::Class::class$);
319   jint hash = HASH_UTF (name);
320
321   // first, if LOADER is a defining loader, then it is also initiating
322   jclass klass;
323   for (klass = loaded_classes[hash]; klass; klass = klass->next)
324     {
325       if (loader == klass->loader && _Jv_equalUtf8Consts (name, klass->name))
326         break;
327     }
328
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.
332   if (!klass)
333     {
334       _Jv_LoaderInfo *info;
335       for (info = initiated_classes[hash]; info; info = info->next)
336         {
337           if (loader == info->loader
338               && _Jv_equalUtf8Consts (name, info->klass->name))
339             {
340               klass = info->klass;
341               break;
342             }
343         }
344     }
345
346   _Jv_MonitorExit (&java::lang::Class::class$);
347
348   return klass;
349 }
350
351 void
352 _Jv_UnregisterClass (jclass the_class)
353 {
354   _Jv_MonitorEnter (&java::lang::Class::class$);
355   jint hash = HASH_UTF(the_class->name);
356
357   jclass *klass = &(loaded_classes[hash]);
358   for ( ; *klass; klass = &((*klass)->next))
359     {
360       if (*klass == the_class)
361         {
362           *klass = (*klass)->next;
363           break;
364         }
365     }
366
367   _Jv_LoaderInfo **info = &(initiated_classes[hash]);
368   for ( ; ; info = &((*info)->next))
369     {
370       while (*info && (*info)->klass == the_class)
371         {
372           *info = (*info)->next;
373         }
374
375       if (*info == NULL)
376         break;
377     }
378
379   _Jv_MonitorExit (&java::lang::Class::class$);
380 }
381
382 void
383 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
384 {
385   // non-gc alloc!
386   _Jv_LoaderInfo *info = (_Jv_LoaderInfo *) _Jv_Malloc (sizeof(_Jv_LoaderInfo));
387   jint hash = HASH_UTF(klass->name);
388
389   _Jv_MonitorEnter (&java::lang::Class::class$);
390   info->loader = loader;
391   info->klass  = klass;
392   info->next   = initiated_classes[hash];
393   initiated_classes[hash] = info;
394   _Jv_MonitorExit (&java::lang::Class::class$);
395 }
396
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
401 // Class::class$.
402 void
403 _Jv_RegisterClasses (jclass *classes)
404 {
405   for (; *classes; ++classes)
406     {
407       jclass klass = *classes;
408
409       (*_Jv_RegisterClassHook) (klass);
410
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;
415     }
416 }
417
418 void
419 _Jv_RegisterClassHookDefault (jclass klass)
420 {
421   jint hash = HASH_UTF (klass->name);
422
423   jclass check_class = loaded_classes[hash];
424
425   // If the class is already registered, don't re-register it.
426   while (check_class != NULL)
427     {
428       if (check_class == klass)
429         {
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.
434           char message[200];
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)
440             JvFail (message);
441           else
442             {
443               java::lang::String *str = JvNewStringLatin1 (message);
444               throw new java::lang::VirtualMachineError (str);
445             }
446         }
447
448       check_class = check_class->next;
449     }
450
451   klass->next = loaded_classes[hash];
452   loaded_classes[hash] = klass;
453 }
454
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.
459
460 void (*_Jv_RegisterClassHook) (jclass cl) = _Jv_RegisterClassHookDefault;
461
462 void
463 _Jv_RegisterClass (jclass klass)
464 {
465   jclass classes[2];
466   classes[0] = klass;
467   classes[1] = NULL;
468   _Jv_RegisterClasses (classes);
469 }
470
471 jclass
472 _Jv_FindClass (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
473 {
474   jclass klass = _Jv_FindClassInCache (name, loader);
475
476   if (! klass)
477     {
478       jstring sname = _Jv_NewStringUTF (name->data);
479
480       if (loader)
481         {
482           // Load using a user-defined loader, jvmspec 5.3.2
483           klass = loader->loadClass(sname, false);
484
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);
490         }
491       else 
492         {
493           java::lang::ClassLoader *sys
494             = java::lang::ClassLoader::getSystemClassLoader ();
495
496           // Load using the bootstrap loader jvmspec 5.3.1.
497           klass = sys->loadClass (sname, false); 
498
499           // Register that we're an initiating loader.
500           if (klass)
501             _Jv_RegisterInitiatingLoader (klass, 0);
502         }
503     }
504   else
505     {
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);
509     }
510
511   return klass;
512 }
513
514 void
515 _Jv_InitNewClassFields (jclass ret)
516 {
517   ret->next = NULL;
518   ret->name = NULL;
519   ret->accflags = 0;
520   ret->superclass = NULL;
521   ret->constants.size = 0;
522   ret->constants.tags = NULL;
523   ret->constants.data = NULL;
524   ret->methods = NULL;
525   ret->method_count = 0;
526   ret->vtable_method_count = 0;
527   ret->fields = NULL;
528   ret->size_in_bytes = 0;
529   ret->field_count = 0;
530   ret->static_field_count = 0;
531   ret->vtable = NULL;
532   ret->interfaces = NULL;
533   ret->loader = NULL;
534   ret->interface_count = 0;
535   ret->state = JV_STATE_NOTHING;
536   ret->thread = NULL;
537   ret->depth = 0;
538   ret->ancestors = NULL;
539   ret->idt = NULL;
540   ret->arrayclass = NULL;
541   ret->protectionDomain = NULL;
542   ret->chain = NULL;
543 }
544
545 jclass
546 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
547               java::lang::ClassLoader *loader)
548 {
549   jclass ret = (jclass) JvAllocObject (&java::lang::Class::class$);
550   _Jv_InitNewClassFields (ret);
551   ret->name = name;
552   ret->superclass = superclass;
553   ret->loader = loader;
554
555   _Jv_RegisterClass (ret);
556
557   return ret;
558 }
559
560 static _Jv_IDispatchTable *array_idt = NULL;
561 static jshort array_depth = 0;
562 static jclass *array_ancestors = NULL;
563
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.
568 void
569 _Jv_NewArrayClass (jclass element, java::lang::ClassLoader *loader,
570                    _Jv_VTable *array_vtable)
571 {
572   JvSynchronize sync (element);
573
574   _Jv_Utf8Const *array_name;
575   int len;
576
577   if (element->arrayclass)
578     return;
579
580   if (element->isPrimitive())
581     {
582       if (element == JvPrimClass (void))
583         throw new java::lang::ClassNotFoundException ();
584       len = 3;
585     }
586   else
587     len = element->name->length + 5;
588
589   {
590     char signature[len];
591     int index = 0;
592     signature[index++] = '[';
593     // Compute name of array class.
594     if (element->isPrimitive())
595       {
596         signature[index++] = (char) element->method_count;
597       }
598     else
599       {
600         size_t length = element->name->length;
601         const char *const name = element->name->data;
602         if (name[0] != '[')
603           signature[index++] = 'L';
604         memcpy (&signature[index], name, length);
605         index += length;
606         if (name[0] != '[')
607           signature[index++] = ';';
608       }      
609     array_name = _Jv_makeUtf8Const (signature, index);
610   }
611
612   // Create new array class.
613   jclass array_class = _Jv_NewClass (array_name, &java::lang::Object::class$,
614                                      element->loader);
615
616   // Note that `vtable_method_count' doesn't include the initial
617   // gc_descr slot.
618   JvAssert (java::lang::Object::class$.vtable_method_count
619             == NUM_OBJECT_METHODS);
620   int dm_count = java::lang::Object::class$.vtable_method_count;
621
622   // Create a new vtable by copying Object's vtable.
623   _Jv_VTable *vtable;
624   if (array_vtable)
625     vtable = array_vtable;
626   else
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));
632
633   array_class->vtable = vtable;
634   array_class->vtable_method_count
635     = java::lang::Object::class$.vtable_method_count;
636
637   // Stash the pointer to the element type.
638   array_class->methods = (_Jv_Method *) element;
639
640   // Register our interfaces.
641   static jclass interfaces[] =
642     {
643       &java::lang::Cloneable::class$,
644       &java::io::Serializable::class$
645     };
646   array_class->interfaces = interfaces;
647   array_class->interface_count = sizeof interfaces / sizeof interfaces[0];
648
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.
651   if (!array_idt)
652     {
653       _Jv_PrepareConstantTimeTables (array_class);
654       array_idt = array_class->idt;
655       array_depth = array_class->depth;
656       array_ancestors = array_class->ancestors;
657     }
658   else
659     {
660       array_class->idt = array_idt;
661       array_class->depth = array_depth;
662       array_class->ancestors = array_ancestors;
663     }
664
665   using namespace java::lang::reflect;
666   {
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;
674   }
675
676   // An array class has no visible instance fields. "length" is invisible to 
677   // reflection.
678
679   // say this class is initialized and ready to go!
680   array_class->state = JV_STATE_DONE;
681
682   // vmspec, section 5.3.3 describes this
683   if (element->loader != loader)
684     _Jv_RegisterInitiatingLoader (array_class, loader);
685
686   element->arrayclass = array_class;
687 }
688
689 static jclass stack_head;
690
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.
694
695 jclass
696 _Jv_PopClass (void)
697 {
698   JvSynchronize sync (&java::lang::Class::class$);
699   if (stack_head)
700     {
701       jclass tmp = stack_head;
702       stack_head = tmp->chain;
703       return tmp;
704     }
705   return NULL;
706 }
707
708 void
709 _Jv_PushClass (jclass k)
710 {
711   JvSynchronize sync (&java::lang::Class::class$);
712   jclass tmp = stack_head;
713   stack_head = k;
714   k->chain = tmp;
715 }