OSDN Git Service

1999-08-09 Anthony Green <green@cygnus.com>
[pf3gnuchains/gcc-fork.git] / libjava / java / lang / natClassLoader.cc
1 // natClassLoader.cc - Implementation of java.lang.ClassLoader native methods.
2
3 /* Copyright (C) 1999  Cygnus Solutions
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 <cni.h>
19 #include <jvm.h>
20 #include <java/lang/Character.h>
21 #include <java/lang/Thread.h>
22 #include <java/lang/ClassLoader.h>
23 #include <java/lang/VMClassLoader.h>
24 #include <java/lang/InternalError.h>
25 #include <java/lang/LinkageError.h>
26 #include <java/lang/ClassFormatError.h>
27 #include <java/lang/NoClassDefFoundError.h>
28 #include <java/lang/ClassNotFoundException.h>
29 #include <java/lang/ClassCircularityError.h>
30 #include <java/lang/IncompatibleClassChangeError.h>
31 #include <java/lang/reflect/Modifier.h>
32
33 #include <java-interp.h>
34
35 #define CloneableClass _CL_Q34java4lang9Cloneable
36 extern java::lang::Class CloneableClass;
37 #define ObjectClass _CL_Q34java4lang6Object
38 extern java::lang::Class ObjectClass;
39 #define ClassClass _CL_Q34java4lang5Class
40 extern java::lang::Class ClassClass;
41 #define VMClassLoaderClass _CL_Q34java4lang17VMClassLoader
42 extern java::lang::Class VMClassLoader;
43 #define ClassLoaderClass _CL_Q34java4lang11ClassLoader
44 extern java::lang::Class ClassLoaderClass;
45
46 /////////// java.lang.ClassLoader native methods ////////////
47
48 #ifdef INTERPRETER
49 java::lang::VMClassLoader *redirect = 0;
50 #endif
51
52 java::lang::ClassLoader*
53 java::lang::ClassLoader::getVMClassLoader0 ()
54 {
55 #ifdef INTERPRETER
56     if (redirect == 0)
57         redirect = new java::lang::VMClassLoader;
58     return redirect;
59 #else
60     return 0;
61 #endif
62 }
63
64 void
65 java::lang::ClassLoader::defineClass2 (jclass klass, jbyteArray data,
66                                        jint offset, jint length)
67 {
68 #ifdef INTERPRETER
69   _Jv_DefineClass (klass, data, offset, length);
70 #endif
71 }
72
73 java::lang::Class *
74 java::lang::ClassLoader::defineClass0 (jstring name,
75                                        jbyteArray data, 
76                                        jint offset,
77                                        jint length)
78 {
79 #ifdef INTERPRETER
80   jclass klass;
81   klass = (jclass) JvAllocObject (&ClassClass, sizeof (_Jv_InterpClass));
82
83   // synchronize on the class, so that it is not
84   // attempted initialized until we're done loading.
85   _Jv_MonitorEnter (klass);
86
87   // record which is the defining loader
88   klass->loader = this;
89
90   // register that we are the initiating loader...
91   if (name != 0)
92     {
93       _Jv_Utf8Const *   name2 = _Jv_makeUtf8Const (name);
94
95       _Jv_VerifyClassName (name2);
96
97       klass->name = name2;
98     }
99
100   // this will do the magic.  loadInto also operates
101   // as an exception trampoline for now...
102   Throwable *ex = defineClass1 (klass, data, offset, length);
103     
104   if (ex)  // we failed to load it
105     {
106       klass->state = JV_STATE_ERROR;
107       klass->notifyAll ();
108
109       _Jv_UnregisterClass (klass);
110
111       _Jv_MonitorExit (klass);
112           
113       // FIXME: Here we may want to test that EX does
114       // indeed represent a valid exception.  That is,
115       // anything but ClassNotFoundException, 
116       // or some kind of Error.
117           
118       JvThrow (ex);
119     }
120     
121   // if everything proceeded sucessfully, we're loaded.
122   JvAssert (klass->state == JV_STATE_LOADED);
123
124   // if an exception is generated, this is initially missed.
125   // however, we come back here in handleException0 below...
126   _Jv_MonitorExit (klass);
127
128   return klass;
129
130 #else // INTERPRETER
131
132   return 0;
133 #endif
134 }
135
136 void
137 _Jv_WaitForState (jclass klass, int state)
138 {
139   if (klass->state >= state)
140     return;
141   
142   _Jv_MonitorEnter (klass) ;
143
144   if (state == JV_STATE_LINKED)
145     {
146       _Jv_MonitorExit (klass);
147       _Jv_InternClassStrings (klass);
148       return;
149     }
150         
151   java::lang::Thread *self = java::lang::Thread::currentThread();
152
153   // this is similar to the strategy for class initialization.
154   // if we already hold the lock, just leave.
155   while (klass->state <= state
156          && klass->thread 
157          && klass->thread != self)
158     klass->wait ();
159
160   _Jv_MonitorExit (klass);
161
162   if (klass->state == JV_STATE_ERROR)
163     {
164       _Jv_Throw (new java::lang::LinkageError ());
165     }
166 }
167
168 // Finish linking a class.  Only called from ClassLoader::resolveClass.
169 void
170 java::lang::ClassLoader::linkClass0 (java::lang::Class *klass)
171 {
172   if (klass->state >= JV_STATE_LINKED)
173     return;
174
175 #ifdef INTERPRETER
176   if (_Jv_IsInterpretedClass (klass))
177     {
178       _Jv_PrepareClass (klass);
179     }
180 #endif
181
182   _Jv_InternClassStrings (klass);
183 }
184
185 void
186 java::lang::ClassLoader::markClassErrorState0 (java::lang::Class *klass)
187 {
188   klass->state = JV_STATE_ERROR;
189   klass->notifyAll ();
190 }
191
192
193 /** this is the only native method in VMClassLoader, so 
194     we define it here. */
195 jclass
196 java::lang::VMClassLoader::findBootClass (jstring name)
197 {
198   return _Jv_FindClassInCache (_Jv_makeUtf8Const (name), 0);
199 }
200
201 jclass
202 java::lang::ClassLoader::findLoadedClass (jstring name)
203 {
204   return _Jv_FindClassInCache (_Jv_makeUtf8Const (name), this);
205 }
206
207 jclass
208 java::lang::ClassLoader::findSystemClass (jstring name)
209 {
210   return _Jv_FindClass (_Jv_makeUtf8Const (name), 0);
211 }
212
213
214 /* This is the final step of linking, internalizing the constant strings
215  * of a class.  This is called for both compiled and interpreted
216  * classes, and it is *only* called from ClassLoader::linkClass0,
217  * which is always in a context where the current thread has a lock on
218  * the class in question.  We define it here, and not in resolve.cc, so that
219  * the entire resolve.cc can be #ifdef'ed away when not using the
220  * interpreter.   */
221 void
222 _Jv_InternClassStrings(jclass klass)
223 {
224   if (klass->state >= JV_STATE_LINKED)
225     return;
226
227   // short-circuit, so that mutually dependent classes are ok
228   klass->state = JV_STATE_LINKED;
229
230   _Jv_Constants *pool = &klass->constants;
231   for (int i = 1; i < pool->size; ++i)
232     {
233       if (pool->tags[i] == JV_CONSTANT_String)
234         {
235           jstring str;
236           str = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) pool->data[i]);
237           pool->data[i] = (void *) str;
238           pool->tags[i] |= JV_CONSTANT_ResolvedFlag;
239         }
240     }
241
242   klass->notifyAll ();
243 }
244
245
246 //
247 //  A single class can have many "initiating" class loaders,
248 //  and a single "defining" class loader.  The Defining
249 //  class loader is what is returned from Class.getClassLoader()
250 //  and is used when loading dependent classes during resolution.
251 //  The set of initiating class loaders are used to ensure
252 //  safety of linking, and is maintained in the hash table
253 //  "initiated_classes".  A defining classloader is by definition also
254 //  initiating, so we only store classes in this table, if they have more
255 //  than one class loader associated.
256 //
257
258
259 // Size of local hash table.
260 #define HASH_LEN 1013
261
262 // Hash function for Utf8Consts.
263 #define HASH_UTF(Utf) (((Utf)->hash) % HASH_LEN)
264
265 struct _Jv_LoaderInfo {
266     _Jv_LoaderInfo          *next;
267     java::lang::Class       *klass;
268     java::lang::ClassLoader *loader;
269 };
270
271 _Jv_LoaderInfo *initiated_classes[HASH_LEN];
272 jclass loaded_classes[HASH_LEN];
273
274 jclass
275 _Jv_FindClassInCache (_Jv_Utf8Const *name, java::lang::ClassLoader *loader)
276 {
277   _Jv_MonitorEnter (&ClassClass);
278   jint hash = HASH_UTF (name);
279
280   // first, if LOADER is a defining loader, then it is also initiating
281   jclass klass;
282   for (klass = loaded_classes[hash]; klass; klass = klass->next)
283     {
284       if (loader == klass->loader && _Jv_equalUtf8Consts (name, klass->name))
285         break;
286     }
287
288   // otherwise, it may be that the class in question was defined
289   // by some other loader, but that the loading was initiated by 
290   // the loader in question.
291   if (!klass)
292     {
293       _Jv_LoaderInfo *info;
294       for (info = initiated_classes[hash]; info; info = info->next)
295         {
296           if (loader == info->loader
297               && _Jv_equalUtf8Consts (name, info->klass->name))
298             {
299               klass = info->klass;
300               break;
301             }
302         }
303     }
304
305   _Jv_MonitorExit (&ClassClass);
306
307   return klass;
308 }
309
310 void
311 _Jv_UnregisterClass (jclass the_class)
312 {
313   _Jv_MonitorEnter (&ClassClass);
314   jint hash = HASH_UTF(the_class->name);
315
316   jclass *klass = &(loaded_classes[hash]);
317   for ( ; *klass; klass = &((*klass)->next))
318     {
319       if (*klass == the_class)
320         {
321           *klass = (*klass)->next;
322           break;
323         }
324     }
325
326   _Jv_LoaderInfo **info = &(initiated_classes[hash]);
327   for ( ; *info; info = &((*info)->next))
328     {
329       while ((*info)->klass == the_class)
330         {
331           *info = (*info)->next;
332         }
333     }
334
335   _Jv_MonitorExit (&ClassClass);
336 }
337
338 void
339 _Jv_RegisterInitiatingLoader (jclass klass, java::lang::ClassLoader *loader)
340 {
341   _Jv_LoaderInfo *info = new _Jv_LoaderInfo; // non-gc alloc!
342   jint hash = HASH_UTF(klass->name);
343
344   _Jv_MonitorEnter (&ClassClass);
345   info->loader = loader;
346   info->klass  = klass;
347   info->next   = initiated_classes[hash];
348   initiated_classes[hash] = info;
349   _Jv_MonitorExit (&ClassClass);
350   
351 }
352
353 // This function is called many times during startup, before main() is
354 // run.  We do our runtime initialization here the very first time we
355 // are called.  At that point in time we know for certain we are
356 // running single-threaded, so we don't need to lock when modifying
357 // `init'.  CLASSES is NULL-terminated.
358 void
359 _Jv_RegisterClasses (jclass *classes)
360 {
361   static bool init = false;
362
363   if (! init)
364     {
365       init = true;
366       _Jv_InitThreads ();
367       _Jv_InitGC ();
368       _Jv_InitializeSyncMutex ();
369     }
370
371   JvSynchronize sync (&ClassClass);
372   for (; *classes; ++classes)
373     {
374       jclass klass = *classes;
375       jint hash = HASH_UTF (klass->name);
376       klass->next = loaded_classes[hash];
377       loaded_classes[hash] = klass;
378
379       // registering a compiled class causes
380       // it to be immediately "prepared".  
381       if (klass->state == JV_STATE_NOTING)
382         klass->state = JV_STATE_COMPILED;
383     }
384 }
385
386 void
387 _Jv_RegisterClass (jclass klass)
388 {
389   jclass classes[2];
390   classes[0] = klass;
391   classes[1] = NULL;
392   _Jv_RegisterClasses (classes);
393 }
394
395 #if 0
396 // NOTE: this one is out of date with the new loader stuff...
397 jclass
398 _Jv_FindClassInCache (jstring name, java::lang::ClassLoader *loader)
399 {
400   JvSynchronize sync (&ClassClass);
401   jint hash = name->hashCode();
402   jclass klass = loaded_classes[(_Jv_ushort) hash % HASH_LEN];
403   for ( ; klass; klass = klass->next)
404     {
405       if (loader == klass->loader
406           && _Jv_equal (klass->name, name, hash))
407         break;
408     }
409   _Jv_MonitorExit (&ClassClass);
410   return klass;
411 }
412 #endif
413
414 jclass _Jv_FindClass (_Jv_Utf8Const *name,
415                       java::lang::ClassLoader *loader)
416 {
417   jclass klass = _Jv_FindClassInCache (name, loader);
418
419 #ifdef INTERPRETER
420   if (! klass)
421     {
422       jstring sname = _Jv_NewStringUTF (name->data);
423
424       if (loader)
425         {
426           // Load using a user-defined loader, jvmspec 5.3.2
427           klass = loader->loadClass(sname, false);
428
429           // if "loader" delegateted the loadClass operation
430           // to another loader, register explicitly
431           // that he is also an initiating loader of the
432           // given class.         
433
434           if (klass && (klass->getClassLoader () != loader))
435             _Jv_RegisterInitiatingLoader (klass, 0);
436         }
437       else 
438         {
439           if (redirect == NULL)
440             {
441               _Jv_InitClass (&ClassLoaderClass);
442               java::lang::ClassLoader::getSystemClassLoader ();
443             }
444
445           // Load using the bootstrap loader jmspec 5.3.1
446           klass = redirect -> loadClassInternal (sname, false, true); 
447
448           // register that we're an initiating loader
449           if (klass)
450             {
451               _Jv_RegisterInitiatingLoader (klass, 0);
452             }
453         }
454     }
455   else
456     {
457       // we need classes to be in the hash while
458       // we're loading, so that they can refer to themselves. 
459       _Jv_WaitForState (klass, JV_STATE_LOADED);
460     }
461 #endif
462
463   return klass;
464 }
465
466 #if 0
467 // NOTE: this one is out of date with the new class loader stuff...
468 jclass
469 _Jv_FindClass (jstring name, java::lang::ClassLoader *loader)
470 {
471   jclass klass = _Jv_FindClassInCache (name, loader);
472   if (! klass)
473     {
474       if (loader)
475         {
476           klass = loader->loadClass(name);
477         }
478       else
479         {
480           // jmspec 5.3.1.2
481           
482           // delegate to the system loader
483           klass = java::lang::ClassLoader::system.loadClass (sname);
484           
485           // register that we're an initiating loader
486           if (klass)
487             _Jv_RegisterInitiatingLoader (klass, 0);
488         }
489     }
490   else
491     {
492       _Jv_WaitForState (klass, JV_STATE_LOADED);
493     }
494   
495   return klass;
496 }
497 #endif
498
499 jclass
500 _Jv_NewClass (_Jv_Utf8Const *name, jclass superclass,
501               java::lang::ClassLoader *loader)
502 {
503   jclass ret = (jclass) JvAllocObject (&ClassClass);
504
505   ret->next = NULL;
506   ret->name = name;
507   ret->accflags = 0;
508   ret->superclass = superclass;
509   ret->constants.size = 0;
510   ret->constants.tags = NULL;
511   ret->constants.data = NULL;
512   ret->methods = NULL;
513   ret->method_count = 0;
514   ret->vtable_method_count = 0;
515   ret->fields = NULL;
516   ret->size_in_bytes = 0;
517   ret->field_count = 0;
518   ret->static_field_count = 0;
519   ret->vtable = NULL;
520   ret->interfaces = NULL;
521   ret->loader = loader;
522   ret->interface_count = 0;
523   ret->state = 0;
524   ret->thread = NULL;
525
526   _Jv_RegisterClass (ret);
527
528   return ret;
529 }
530
531 jclass
532 _Jv_FindArrayClass (jclass element, java::lang::ClassLoader *loader)
533 {
534   _Jv_Utf8Const *array_name;
535   int len;
536   if (element->isPrimitive())
537     {
538       // For primitive types the array is cached in the class.
539       jclass ret = (jclass) element->methods;
540       if (ret)
541         return ret;
542       len = 3;
543     }
544   else
545     len = element->name->length + 5;
546
547   {
548     char signature[len];
549     int index = 0;
550     signature[index++] = '[';
551     // Compute name of array class to see if we've already cached it.
552     if (element->isPrimitive())
553       {
554         signature[index++] = (char) element->method_count;
555       }
556     else
557       {
558         size_t length = element->name->length;
559         const char *const name = element->name->data;
560         if (name[0] != '[')
561           signature[index++] = 'L';
562         memcpy (&signature[index], name, length);
563         index += length;
564         if (name[0] != '[')
565           signature[index++] = ';';
566       }      
567     array_name = _Jv_makeUtf8Const (signature, index);
568   }
569
570   jclass array_class = _Jv_FindClassInCache (array_name, element->loader);
571
572   if (! array_class)
573     {
574       // Create new array class.
575       array_class = _Jv_NewClass (array_name, &ObjectClass, element->loader);
576
577       // Note that `vtable_method_count' doesn't include the initial
578       // NULL slot.
579       int dm_count = ObjectClass.vtable_method_count + 1;
580
581       // Create a new vtable by copying Object's vtable (except the
582       // class pointer, of course).  Note that we allocate this as
583       // unscanned memory -- the vtables are handled specially by the
584       // GC.
585       int size = (sizeof (_Jv_VTable) +
586                   ((dm_count - 1) * sizeof (void *)));
587       _Jv_VTable *vtable = (_Jv_VTable *) _Jv_AllocBytes (size);
588       vtable->clas = array_class;
589       memcpy (vtable->method, ObjectClass.vtable->method,
590               dm_count * sizeof (void *));
591       array_class->vtable = vtable;
592       array_class->vtable_method_count = ObjectClass.vtable_method_count;
593
594       // Stash the pointer to the element type.
595       array_class->methods = (_Jv_Method *) element;
596
597       // Register our interfaces.
598       // FIXME: for JDK 1.2 we need Serializable.
599       static jclass interfaces[] = { &CloneableClass };
600       array_class->interfaces = interfaces;
601       array_class->interface_count = 1;
602
603       // as per vmspec 5.3.3.2
604       array_class->accflags = element->accflags;
605
606       // FIXME: initialize other Class instance variables,
607       // e.g. `fields'.
608
609       // say this class is initialized and ready to go!
610       array_class->state = JV_STATE_DONE;
611
612       // vmspec, section 5.3.3 describes this
613       if (element->loader != loader)
614         _Jv_RegisterInitiatingLoader (array_class, loader);
615     }
616
617   // For primitive types, point back at this array.
618   if (element->isPrimitive())
619     element->methods = (_Jv_Method *) array_class;
620
621   return array_class;
622 }
623
624