OSDN Git Service

* java/lang/Class.h (_getDeclaredMethod): Declare.
[pf3gnuchains/gcc-fork.git] / libjava / java / lang / natClass.cc
1 // natClass.cc - Implementation of java.lang.Class native methods.
2
3 /* Copyright (C) 1998, 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 #include <config.h>
12
13 #include <limits.h>
14 #include <string.h>
15
16 #pragma implementation "Class.h"
17
18 #include <gcj/cni.h>
19 #include <jvm.h>
20 #include <java-threads.h>
21
22 #include <java/lang/Class.h>
23 #include <java/lang/ClassLoader.h>
24 #include <java/lang/String.h>
25 #include <java/lang/reflect/Modifier.h>
26 #include <java/lang/reflect/Member.h>
27 #include <java/lang/reflect/Method.h>
28 #include <java/lang/reflect/Field.h>
29 #include <java/lang/reflect/Constructor.h>
30 #include <java/lang/AbstractMethodError.h>
31 #include <java/lang/ArrayStoreException.h>
32 #include <java/lang/ClassCastException.h>
33 #include <java/lang/ClassNotFoundException.h>
34 #include <java/lang/ExceptionInInitializerError.h>
35 #include <java/lang/IllegalAccessException.h>
36 #include <java/lang/IllegalAccessError.h>
37 #include <java/lang/IllegalArgumentException.h>
38 #include <java/lang/IncompatibleClassChangeError.h>
39 #include <java/lang/InstantiationException.h>
40 #include <java/lang/NoClassDefFoundError.h>
41 #include <java/lang/NoSuchFieldException.h>
42 #include <java/lang/NoSuchMethodError.h>
43 #include <java/lang/NoSuchMethodException.h>
44 #include <java/lang/Thread.h>
45 #include <java/lang/NullPointerException.h>
46 #include <java/lang/RuntimePermission.h>
47 #include <java/lang/System.h>
48 #include <java/lang/SecurityManager.h>
49 #include <java/lang/StringBuffer.h>
50 #include <gcj/method.h>
51
52 #include <java-cpool.h>
53
54 \f
55
56 using namespace gcj;
57
58 jclass
59 java::lang::Class::forName (jstring className, jboolean initialize,
60                             java::lang::ClassLoader *loader)
61 {
62   if (! className)
63     throw new java::lang::NullPointerException;
64
65   jsize length = _Jv_GetStringUTFLength (className);
66   char buffer[length];
67   _Jv_GetStringUTFRegion (className, 0, length, buffer);
68
69   _Jv_Utf8Const *name = _Jv_makeUtf8Const (buffer, length);
70
71   if (! _Jv_VerifyClassName (name))
72     throw new java::lang::ClassNotFoundException (className);
73
74   // FIXME: should use bootstrap class loader if loader is null.
75   jclass klass = (buffer[0] == '[' 
76                   ? _Jv_FindClassFromSignature (name->data, loader)
77                   : _Jv_FindClass (name, loader));
78
79   if (klass == NULL)
80     throw new java::lang::ClassNotFoundException (className);
81
82   if (initialize)
83     _Jv_InitClass (klass);
84
85   return klass;
86 }
87
88 jclass
89 java::lang::Class::forName (jstring className)
90 {
91   // FIXME: should use class loader from calling method.
92   return forName (className, true, NULL);
93 }
94
95 java::lang::ClassLoader *
96 java::lang::Class::getClassLoader (void)
97 {
98 #if 0
99   // FIXME: the checks we need to do are more complex.  See the spec.
100   // Currently we can't implement them.
101   java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
102   if (s != NULL)
103     s->checkPermission (new RuntimePermission (JvNewStringLatin1 ("getClassLoader")));
104 #endif
105
106   // The spec requires us to return `null' for primitive classes.  In
107   // other cases we have the option of returning `null' for classes
108   // loaded with the bootstrap loader.  All gcj-compiled classes which
109   // are linked into the application used to return `null' here, but
110   // that confuses some poorly-written applications.  It is a useful
111   // and apparently harmless compatibility hack to simply never return
112   // `null' instead.
113   if (isPrimitive ())
114     return NULL;
115   return loader ? loader : ClassLoader::getSystemClassLoader ();
116 }
117
118 java::lang::reflect::Constructor *
119 java::lang::Class::getConstructor (JArray<jclass> *param_types)
120 {
121   jstring partial_sig = getSignature (param_types, true);
122   jint hash = partial_sig->hashCode ();
123
124   int i = isPrimitive () ? 0 : method_count;
125   while (--i >= 0)
126     {
127       // FIXME: access checks.
128       if (_Jv_equalUtf8Consts (methods[i].name, init_name)
129           && _Jv_equal (methods[i].signature, partial_sig, hash))
130         {
131           // Found it.  For getConstructor, the constructor must be
132           // public.
133           using namespace java::lang::reflect;
134           if (! Modifier::isPublic(methods[i].accflags))
135             break;
136           Constructor *cons = new Constructor ();
137           cons->offset = (char *) (&methods[i]) - (char *) methods;
138           cons->declaringClass = this;
139           return cons;
140         }
141     }
142   throw new java::lang::NoSuchMethodException;
143 }
144
145 JArray<java::lang::reflect::Constructor *> *
146 java::lang::Class::_getConstructors (jboolean declared)
147 {
148   // FIXME: this method needs access checks.
149
150   int numConstructors = 0;
151   int max = isPrimitive () ? 0 : method_count;
152   int i;
153   for (i = max; --i >= 0; )
154     {
155       _Jv_Method *method = &methods[i];
156       if (method->name == NULL
157           || ! _Jv_equalUtf8Consts (method->name, init_name))
158         continue;
159       if (! declared
160           && ! java::lang::reflect::Modifier::isPublic(method->accflags))
161         continue;
162       numConstructors++;
163     }
164   JArray<java::lang::reflect::Constructor *> *result
165     = (JArray<java::lang::reflect::Constructor *> *)
166     JvNewObjectArray (numConstructors,
167                       &java::lang::reflect::Constructor::class$,
168                       NULL);
169   java::lang::reflect::Constructor** cptr = elements (result);
170   for (i = 0;  i < max;  i++)
171     {
172       _Jv_Method *method = &methods[i];
173       if (method->name == NULL
174           || ! _Jv_equalUtf8Consts (method->name, init_name))
175         continue;
176       if (! declared
177           && ! java::lang::reflect::Modifier::isPublic(method->accflags))
178         continue;
179       java::lang::reflect::Constructor *cons
180         = new java::lang::reflect::Constructor ();
181       cons->offset = (char *) method - (char *) methods;
182       cons->declaringClass = this;
183       *cptr++ = cons;
184     }
185   return result;
186 }
187
188 java::lang::reflect::Constructor *
189 java::lang::Class::getDeclaredConstructor (JArray<jclass> *param_types)
190 {
191   jstring partial_sig = getSignature (param_types, true);
192   jint hash = partial_sig->hashCode ();
193
194   int i = isPrimitive () ? 0 : method_count;
195   while (--i >= 0)
196     {
197       // FIXME: access checks.
198       if (_Jv_equalUtf8Consts (methods[i].name, init_name)
199           && _Jv_equal (methods[i].signature, partial_sig, hash))
200         {
201           // Found it.
202           using namespace java::lang::reflect;
203           Constructor *cons = new Constructor ();
204           cons->offset = (char *) (&methods[i]) - (char *) methods;
205           cons->declaringClass = this;
206           return cons;
207         }
208     }
209   throw new java::lang::NoSuchMethodException;
210 }
211
212 java::lang::reflect::Field *
213 java::lang::Class::getField (jstring name, jint hash)
214 {
215   java::lang::reflect::Field* rfield;
216   for (int i = 0;  i < field_count;  i++)
217     {
218       _Jv_Field *field = &fields[i];
219       if (! _Jv_equal (field->name, name, hash))
220         continue;
221       if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
222         continue;
223       rfield = new java::lang::reflect::Field ();
224       rfield->offset = (char*) field - (char*) fields;
225       rfield->declaringClass = this;
226       rfield->name = name;
227       return rfield;
228     }
229   jclass superclass = getSuperclass();
230   if (superclass == NULL)
231     return NULL;
232   rfield = superclass->getField(name, hash);
233   for (int i = 0; i < interface_count && rfield == NULL; ++i)
234     rfield = interfaces[i]->getField (name, hash);
235   return rfield;
236 }
237
238 java::lang::reflect::Field *
239 java::lang::Class::getDeclaredField (jstring name)
240 {
241   java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
242   if (s != NULL)
243     s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
244   int hash = name->hashCode();
245   for (int i = 0;  i < field_count;  i++)
246     {
247       _Jv_Field *field = &fields[i];
248       if (! _Jv_equal (field->name, name, hash))
249         continue;
250       java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
251       rfield->offset = (char*) field - (char*) fields;
252       rfield->declaringClass = this;
253       rfield->name = name;
254       return rfield;
255     }
256   throw new java::lang::NoSuchFieldException (name);
257 }
258
259 JArray<java::lang::reflect::Field *> *
260 java::lang::Class::getDeclaredFields (void)
261 {
262   java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
263   if (s != NULL)
264     s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
265   JArray<java::lang::reflect::Field *> *result
266     = (JArray<java::lang::reflect::Field *> *)
267     JvNewObjectArray (field_count, &java::lang::reflect::Field::class$, NULL);
268   java::lang::reflect::Field** fptr = elements (result);
269   for (int i = 0;  i < field_count;  i++)
270     {
271       _Jv_Field *field = &fields[i];
272       java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
273       rfield->offset = (char*) field - (char*) fields;
274       rfield->declaringClass = this;
275       *fptr++ = rfield;
276     }
277   return result;
278 }
279
280 void
281 java::lang::Class::getSignature (java::lang::StringBuffer *buffer)
282 {
283   if (isPrimitive())
284     buffer->append((jchar) method_count);
285   else
286     {
287       jstring name = getName();
288       if (name->charAt(0) != '[')
289         buffer->append((jchar) 'L');
290       buffer->append(name);
291       if (name->charAt(0) != '[')
292         buffer->append((jchar) ';');
293     }
294 }
295
296 // This doesn't have to be native.  It is an implementation detail
297 // only called from the C++ code, though, so maybe this is clearer.
298 jstring
299 java::lang::Class::getSignature (JArray<jclass> *param_types,
300                                  jboolean is_constructor)
301 {
302   java::lang::StringBuffer *buf = new java::lang::StringBuffer ();
303   buf->append((jchar) '(');
304   // A NULL param_types means "no parameters".
305   if (param_types != NULL)
306     {
307       jclass *v = elements (param_types);
308       for (int i = 0; i < param_types->length; ++i)
309         v[i]->getSignature(buf);
310     }
311   buf->append((jchar) ')');
312   if (is_constructor)
313     buf->append((jchar) 'V');
314   return buf->toString();
315 }
316
317 java::lang::reflect::Method *
318 java::lang::Class::_getDeclaredMethod (jstring name,
319                                        JArray<jclass> *param_types)
320 {
321   jstring partial_sig = getSignature (param_types, false);
322   jint p_len = partial_sig->length();
323   _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
324   int i = isPrimitive () ? 0 : method_count;
325   while (--i >= 0)
326     {
327       if (_Jv_equalUtf8Consts (methods[i].name, utf_name)
328           && _Jv_equaln (methods[i].signature, partial_sig, p_len))
329         {
330           // Found it.
331           using namespace java::lang::reflect;
332           Method *rmethod = new Method ();
333           rmethod->offset = (char*) (&methods[i]) - (char*) methods;
334           rmethod->declaringClass = this;
335           return rmethod;
336         }
337     }
338   return NULL;
339 }
340
341 JArray<java::lang::reflect::Method *> *
342 java::lang::Class::getDeclaredMethods (void)
343 {
344   int numMethods = 0;
345   int max = isPrimitive () ? 0 : method_count;
346   int i;
347   for (i = max; --i >= 0; )
348     {
349       _Jv_Method *method = &methods[i];
350       if (method->name == NULL
351           || _Jv_equalUtf8Consts (method->name, clinit_name)
352           || _Jv_equalUtf8Consts (method->name, init_name)
353           || _Jv_equalUtf8Consts (method->name, finit_name))
354         continue;
355       numMethods++;
356     }
357   JArray<java::lang::reflect::Method *> *result
358     = (JArray<java::lang::reflect::Method *> *)
359     JvNewObjectArray (numMethods, &java::lang::reflect::Method::class$, NULL);
360   java::lang::reflect::Method** mptr = elements (result);
361   for (i = 0;  i < max;  i++)
362     {
363       _Jv_Method *method = &methods[i];
364       if (method->name == NULL
365           || _Jv_equalUtf8Consts (method->name, clinit_name)
366           || _Jv_equalUtf8Consts (method->name, init_name)
367           || _Jv_equalUtf8Consts (method->name, finit_name))
368         continue;
369       java::lang::reflect::Method* rmethod
370         = new java::lang::reflect::Method ();
371       rmethod->offset = (char*) method - (char*) methods;
372       rmethod->declaringClass = this;
373       *mptr++ = rmethod;
374     }
375   return result;
376 }
377
378 jstring
379 java::lang::Class::getName (void)
380 {
381   char buffer[name->length + 1];  
382   memcpy (buffer, name->data, name->length); 
383   buffer[name->length] = '\0';
384   return _Jv_NewStringUTF (buffer);
385 }
386
387 JArray<jclass> *
388 java::lang::Class::getClasses (void)
389 {
390   // FIXME: security checking.
391
392   // Until we have inner classes, it always makes sense to return an
393   // empty array.
394   JArray<jclass> *result
395     = (JArray<jclass> *) JvNewObjectArray (0, &java::lang::Class::class$,
396                                            NULL);
397   return result;
398 }
399
400 JArray<jclass> *
401 java::lang::Class::getDeclaredClasses (void)
402 {
403   checkMemberAccess (java::lang::reflect::Member::DECLARED);
404   // Until we have inner classes, it always makes sense to return an
405   // empty array.
406   JArray<jclass> *result
407     = (JArray<jclass> *) JvNewObjectArray (0, &java::lang::Class::class$,
408                                            NULL);
409   return result;
410 }
411
412 jclass
413 java::lang::Class::getDeclaringClass (void)
414 {
415   // Until we have inner classes, it makes sense to always return
416   // NULL.
417   return NULL;
418 }
419
420 jint
421 java::lang::Class::_getFields (JArray<java::lang::reflect::Field *> *result,
422                                jint offset)
423 {
424   int count = 0;
425   for (int i = 0;  i < field_count;  i++)
426     {
427       _Jv_Field *field = &fields[i];
428       if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
429         continue;
430       ++count;
431
432       if (result != NULL)
433         {
434           java::lang::reflect::Field *rfield
435             = new java::lang::reflect::Field ();
436           rfield->offset = (char *) field - (char *) fields;
437           rfield->declaringClass = this;
438           rfield->name = _Jv_NewStringUtf8Const (field->name);
439           (elements (result))[offset++] = rfield;
440         }
441     }
442   jclass superclass = getSuperclass();
443   if (superclass != NULL)
444     {
445       int s_count = superclass->_getFields (result, offset);
446       count += s_count;
447       offset += s_count;
448     }
449   for (int i = 0; i < interface_count; ++i)
450     {
451       int f_count = interfaces[i]->_getFields (result, offset);
452       count += f_count;
453       offset += f_count;
454     }
455   return count;
456 }
457
458 JArray<java::lang::reflect::Field *> *
459 java::lang::Class::getFields (void)
460 {
461   // FIXME: security checking.
462
463   using namespace java::lang::reflect;
464
465   int count = _getFields (NULL, 0);
466
467   JArray<java::lang::reflect::Field *> *result
468     = ((JArray<java::lang::reflect::Field *> *)
469        JvNewObjectArray (count, &java::lang::reflect::Field::class$, NULL));
470
471   _getFields (result, 0);
472
473   return result;
474 }
475
476 JArray<jclass> *
477 java::lang::Class::getInterfaces (void)
478 {
479   jobjectArray r = JvNewObjectArray (interface_count, getClass (), NULL);
480   jobject *data = elements (r);
481   for (int i = 0; i < interface_count; ++i)
482     data[i] = interfaces[i];
483   return reinterpret_cast<JArray<jclass> *> (r);
484 }
485
486 java::lang::reflect::Method *
487 java::lang::Class::_getMethod (jstring name, JArray<jclass> *param_types)
488 {
489   jstring partial_sig = getSignature (param_types, false);
490   jint p_len = partial_sig->length();
491   _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
492   for (Class *klass = this; klass; klass = klass->getSuperclass())
493     {
494       int i = klass->isPrimitive () ? 0 : klass->method_count;
495       while (--i >= 0)
496         {
497           // FIXME: access checks.
498           if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
499               && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
500             {
501               // Found it.
502               using namespace java::lang::reflect;
503
504               // Method must be public.
505               if (! Modifier::isPublic (klass->methods[i].accflags))
506                 break;
507
508               Method *rmethod = new Method ();
509               rmethod->offset = ((char *) (&klass->methods[i])
510                                  - (char *) klass->methods);
511               rmethod->declaringClass = klass;
512               return rmethod;
513             }
514         }
515     }
516
517   // If we haven't found a match, and this class is an interface, then
518   // check all the superinterfaces.
519   if (isInterface())
520     {
521       for (int i = 0; i < interface_count; ++i)
522         {
523           using namespace java::lang::reflect;
524           Method *rmethod = interfaces[i]->_getMethod (name, param_types);
525           if (rmethod != NULL)
526             return rmethod;
527         }
528     }
529
530   return NULL;
531 }
532
533 // This is a very slow implementation, since it re-scans all the
534 // methods we've already listed to make sure we haven't duplicated a
535 // method.  It also over-estimates the required size, so we have to
536 // shrink the result array later.
537 jint
538 java::lang::Class::_getMethods (JArray<java::lang::reflect::Method *> *result,
539                                 jint offset)
540 {
541   jint count = 0;
542
543   // First examine all local methods
544   for (int i = isPrimitive () ? 0 : method_count; --i >= 0; )
545     {
546       _Jv_Method *method = &methods[i];
547       if (method->name == NULL
548           || _Jv_equalUtf8Consts (method->name, clinit_name)
549           || _Jv_equalUtf8Consts (method->name, init_name)
550           || _Jv_equalUtf8Consts (method->name, finit_name))
551         continue;
552       // Only want public methods.
553       if (! java::lang::reflect::Modifier::isPublic (method->accflags))
554         continue;
555
556       // This is where we over-count the slots required if we aren't
557       // filling the result for real.
558       if (result != NULL)
559         {
560           jboolean add = true;
561           java::lang::reflect::Method **mp = elements (result);
562           // If we already have a method with this name and signature,
563           // then ignore this one.  This can happen with virtual
564           // methods.
565           for (int j = 0; j < offset; ++j)
566             {
567               _Jv_Method *meth_2 = _Jv_FromReflectedMethod (mp[j]);
568               if (_Jv_equalUtf8Consts (method->name, meth_2->name)
569                   && _Jv_equalUtf8Consts (method->signature,
570                                           meth_2->signature))
571                 {
572                   add = false;
573                   break;
574                 }
575             }
576           if (! add)
577             continue;
578         }
579
580       if (result != NULL)
581         {
582           using namespace java::lang::reflect;
583           Method *rmethod = new Method ();
584           rmethod->offset = (char *) method - (char *) methods;
585           rmethod->declaringClass = this;
586           Method **mp = elements (result);
587           mp[offset + count] = rmethod;
588         }
589       ++count;
590     }
591   offset += count;
592
593   // Now examine superclasses.
594   if (getSuperclass () != NULL)
595     {
596       jint s_count = getSuperclass()->_getMethods (result, offset);
597       offset += s_count;
598       count += s_count;
599     }
600
601   // Finally, examine interfaces.
602   for (int i = 0; i < interface_count; ++i)
603     {
604       int f_count = interfaces[i]->_getMethods (result, offset);
605       count += f_count;
606       offset += f_count;
607     }
608
609   return count;
610 }
611
612 JArray<java::lang::reflect::Method *> *
613 java::lang::Class::getMethods (void)
614 {
615   using namespace java::lang::reflect;
616
617   // FIXME: security checks.
618
619   // This will overestimate the size we need.
620   jint count = _getMethods (NULL, 0);
621
622   JArray<Method *> *result
623     = ((JArray<Method *> *) JvNewObjectArray (count,
624                                               &Method::class$,
625                                               NULL));
626
627   // When filling the array for real, we get the actual count.  Then
628   // we resize the array.
629   jint real_count = _getMethods (result, 0);
630
631   if (real_count != count)
632     {
633       JArray<Method *> *r2
634         = ((JArray<Method *> *) JvNewObjectArray (real_count,
635                                                   &Method::class$,
636                                                   NULL));
637       
638       Method **destp = elements (r2);
639       Method **srcp = elements (result);
640
641       for (int i = 0; i < real_count; ++i)
642         *destp++ = *srcp++;
643
644       result = r2;
645     }
646
647   return result;
648 }
649
650 jboolean
651 java::lang::Class::isAssignableFrom (jclass klass)
652 {
653   // Arguments may not have been initialized, given ".class" syntax.
654   _Jv_InitClass (this);
655   _Jv_InitClass (klass);
656   return _Jv_IsAssignableFrom (this, klass);
657 }
658
659 jboolean
660 java::lang::Class::isInstance (jobject obj)
661 {
662   if (! obj)
663     return false;
664   _Jv_InitClass (this);
665   return _Jv_IsAssignableFrom (this, JV_CLASS (obj));
666 }
667
668 jobject
669 java::lang::Class::newInstance (void)
670 {
671   // FIXME: do accessibility checks here.  There currently doesn't
672   // seem to be any way to do these.
673   // FIXME: we special-case one check here just to pass a Plum Hall
674   // test.  Once access checking is implemented, remove this.
675   if (this == &java::lang::Class::class$)
676     throw new java::lang::IllegalAccessException;
677
678   if (isPrimitive ()
679       || isInterface ()
680       || isArray ()
681       || java::lang::reflect::Modifier::isAbstract(accflags))
682     throw new java::lang::InstantiationException;
683
684   _Jv_InitClass (this);
685
686   _Jv_Method *meth = _Jv_GetMethodLocal (this, init_name, void_signature);
687   if (! meth)
688     throw new java::lang::NoSuchMethodException;
689
690   jobject r = JvAllocObject (this);
691   ((void (*) (jobject)) meth->ncode) (r);
692   return r;
693 }
694
695 void
696 java::lang::Class::finalize (void)
697 {
698 #ifdef INTERPRETER
699   JvAssert (_Jv_IsInterpretedClass (this));
700   _Jv_UnregisterClass (this);
701 #endif
702 }
703
704 // This implements the initialization process for a class.  From Spec
705 // section 12.4.2.
706 void
707 java::lang::Class::initializeClass (void)
708 {
709   // short-circuit to avoid needless locking.
710   if (state == JV_STATE_DONE)
711     return;
712
713   // Step 1.
714   _Jv_MonitorEnter (this);
715
716   if (state < JV_STATE_LINKED)
717     {    
718 #ifdef INTERPRETER
719       if (_Jv_IsInterpretedClass (this))
720         {
721           // this can throw exceptions, so exit the monitor as a precaution.
722           _Jv_MonitorExit (this);
723           java::lang::ClassLoader::resolveClass0 (this);
724           _Jv_MonitorEnter (this);
725         }
726       else
727 #endif
728         {
729           _Jv_PrepareCompiledClass (this);
730         }
731     }
732
733   if (state <= JV_STATE_LINKED)
734     _Jv_PrepareConstantTimeTables (this);
735
736   // Step 2.
737   java::lang::Thread *self = java::lang::Thread::currentThread();
738   // FIXME: `self' can be null at startup.  Hence this nasty trick.
739   self = (java::lang::Thread *) ((long) self | 1);
740   while (state == JV_STATE_IN_PROGRESS && thread && thread != self)
741     wait ();
742
743   // Steps 3 &  4.
744   if (state == JV_STATE_DONE
745       || state == JV_STATE_IN_PROGRESS
746       || thread == self)
747     {
748       _Jv_MonitorExit (this);
749       return;
750     }
751
752   // Step 5.
753   if (state == JV_STATE_ERROR)
754     {
755       _Jv_MonitorExit (this);
756       throw new java::lang::NoClassDefFoundError;
757     }
758
759   // Step 6.
760   thread = self;
761   state = JV_STATE_IN_PROGRESS;
762   _Jv_MonitorExit (this);
763
764   // Step 7.
765   if (! isInterface () && superclass)
766     {
767       try
768         {
769           _Jv_InitClass (superclass);
770         }
771       catch (java::lang::Throwable *except)
772         {
773           // Caught an exception.
774           _Jv_MonitorEnter (this);
775           state = JV_STATE_ERROR;
776           notifyAll ();
777           _Jv_MonitorExit (this);
778           throw except;
779         }
780     }
781
782   // Steps 8, 9, 10, 11.
783   try
784     {
785       _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name,
786                                              void_signature);
787       if (meth)
788         ((void (*) (void)) meth->ncode) ();
789     }
790   catch (java::lang::Throwable *except)
791     {
792       if (! java::lang::Error::class$.isInstance(except))
793         {
794           try
795             {
796               except = new ExceptionInInitializerError (except);
797             }
798           catch (java::lang::Throwable *t)
799             {
800               except = t;
801             }
802         }
803       _Jv_MonitorEnter (this);
804       state = JV_STATE_ERROR;
805       notifyAll ();
806       _Jv_MonitorExit (this);
807       throw except;
808     }
809
810   _Jv_MonitorEnter (this);
811   state = JV_STATE_DONE;
812   notifyAll ();
813   _Jv_MonitorExit (this);
814 }
815
816 \f
817
818 //
819 // Some class-related convenience functions.
820 //
821
822 // Find a method declared in the class.  If it is not declared locally
823 // (or if it is inherited), return NULL.
824 _Jv_Method *
825 _Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
826                     _Jv_Utf8Const *signature)
827 {
828   for (int i = 0; i < klass->method_count; ++i)
829     {
830       if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
831           && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
832         return &klass->methods[i];
833     }
834   return NULL;
835 }
836
837 _Jv_Method *
838 _Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
839                           _Jv_Utf8Const *signature)
840 {
841   for (; klass; klass = klass->getSuperclass())
842     {
843       _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
844
845       if (meth)
846         return meth;
847     }
848
849   return NULL;
850 }
851
852 // NOTE: MCACHE_SIZE should be a power of 2 minus one.
853 #define MCACHE_SIZE 1023
854
855 struct _Jv_mcache
856 {
857   jclass klass;
858   _Jv_Method *method;
859 };
860
861 static _Jv_mcache method_cache[MCACHE_SIZE + 1];
862
863 static void *
864 _Jv_FindMethodInCache (jclass klass,
865                        _Jv_Utf8Const *name,
866                        _Jv_Utf8Const *signature)
867 {
868   int index = name->hash & MCACHE_SIZE;
869   _Jv_mcache *mc = method_cache + index;
870   _Jv_Method *m = mc->method;
871
872   if (mc->klass == klass
873       && m != NULL             // thread safe check
874       && _Jv_equalUtf8Consts (m->name, name)
875       && _Jv_equalUtf8Consts (m->signature, signature))
876     return mc->method->ncode;
877   return NULL;
878 }
879
880 static void
881 _Jv_AddMethodToCache (jclass klass,
882                        _Jv_Method *method)
883 {
884   _Jv_MonitorEnter (&java::lang::Class::class$); 
885
886   int index = method->name->hash & MCACHE_SIZE;
887
888   method_cache[index].method = method;
889   method_cache[index].klass = klass;
890
891   _Jv_MonitorExit (&java::lang::Class::class$);
892 }
893
894 void *
895 _Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
896                            _Jv_Utf8Const *signature)
897 {
898   using namespace java::lang::reflect;
899
900   void *ncode = _Jv_FindMethodInCache (klass, name, signature);
901   if (ncode != 0)
902     return ncode;
903
904   for (; klass; klass = klass->getSuperclass())
905     {
906       _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
907       if (! meth)
908         continue;
909
910       if (Modifier::isStatic(meth->accflags))
911         throw new java::lang::IncompatibleClassChangeError
912           (_Jv_GetMethodString (klass, meth->name));
913       if (Modifier::isAbstract(meth->accflags))
914         throw new java::lang::AbstractMethodError
915           (_Jv_GetMethodString (klass, meth->name));
916       if (! Modifier::isPublic(meth->accflags))
917         throw new java::lang::IllegalAccessError
918           (_Jv_GetMethodString (klass, meth->name));
919
920       _Jv_AddMethodToCache (klass, meth);
921
922       return meth->ncode;
923     }
924   throw new java::lang::IncompatibleClassChangeError;
925 }
926
927 // Fast interface method lookup by index.
928 void *
929 _Jv_LookupInterfaceMethodIdx (jclass klass, jclass iface, int method_idx)
930 {
931   _Jv_IDispatchTable *cldt = klass->idt;
932   int idx = iface->idt->iface.ioffsets[cldt->cls.iindex] + method_idx;
933   return cldt->cls.itable[idx];
934 }
935
936 jboolean
937 _Jv_IsAssignableFrom (jclass target, jclass source)
938 {
939   if (source == target)
940     return true;
941      
942   // If target is array, so must source be.  
943   if (target->isArray ())
944     {
945       if (! source->isArray())
946         return false;
947       return _Jv_IsAssignableFrom(target->getComponentType(), 
948                                   source->getComponentType());
949     }
950
951   if (target->isInterface())
952     {
953       // Abstract classes have no IDT, and IDTs provide no way to check
954       // two interfaces for assignability.
955       if (__builtin_expect 
956           (source->idt == NULL || source->isInterface(), false))
957         return _Jv_InterfaceAssignableFrom (target, source);
958         
959       _Jv_IDispatchTable *cl_idt = source->idt;
960       _Jv_IDispatchTable *if_idt = target->idt;
961
962       if (__builtin_expect ((if_idt == NULL), false))
963         return false; // No class implementing TARGET has been loaded.    
964       jshort cl_iindex = cl_idt->cls.iindex;
965       if (cl_iindex < if_idt->iface.ioffsets[0])
966         {
967           jshort offset = if_idt->iface.ioffsets[cl_iindex];
968           if (offset != -1 && offset < cl_idt->cls.itable_length
969               && cl_idt->cls.itable[offset] == target)
970             return true;
971         }
972       return false;
973     }
974      
975   // Primitive TYPE classes are only assignable to themselves.
976   if (__builtin_expect (target->isPrimitive(), false))
977     return false;
978     
979   if (target == &java::lang::Object::class$)
980     {
981       if (source->isPrimitive())
982         return false;
983       return true;
984     }
985   else if (source->ancestors != NULL
986            && target->ancestors != NULL
987            && source->depth >= target->depth
988            && source->ancestors[source->depth - target->depth] == target)
989     return true;
990       
991   return false;
992 }
993
994 // Interface type checking, the slow way. Returns TRUE if IFACE is a 
995 // superinterface of SOURCE. This is used when SOURCE is also an interface,
996 // or a class with no interface dispatch table.
997 jboolean
998 _Jv_InterfaceAssignableFrom (jclass iface, jclass source)
999 {
1000   for (int i = 0; i < source->interface_count; i++)
1001     {
1002       jclass interface = source->interfaces[i];
1003       if (iface == interface
1004           || _Jv_InterfaceAssignableFrom (iface, interface))
1005         return true;      
1006     }
1007     
1008   if (!source->isInterface()
1009       && source->superclass 
1010       && _Jv_InterfaceAssignableFrom (iface, source->superclass))
1011     return true;
1012         
1013   return false;
1014 }
1015
1016 jboolean
1017 _Jv_IsInstanceOf(jobject obj, jclass cl)
1018 {
1019   if (__builtin_expect (!obj, false))
1020     return false;
1021   return (_Jv_IsAssignableFrom (cl, JV_CLASS (obj)));
1022 }
1023
1024 void *
1025 _Jv_CheckCast (jclass c, jobject obj)
1026 {
1027   if (__builtin_expect 
1028        (obj != NULL && ! _Jv_IsAssignableFrom(c, JV_CLASS (obj)), false))
1029     throw new java::lang::ClassCastException
1030       ((new java::lang::StringBuffer
1031         (obj->getClass()->getName()))->append
1032        (JvNewStringUTF(" cannot be cast to "))->append
1033        (c->getName())->toString());
1034
1035   return obj;
1036 }
1037
1038 void
1039 _Jv_CheckArrayStore (jobject arr, jobject obj)
1040 {
1041   if (obj)
1042     {
1043       JvAssert (arr != NULL);
1044       jclass elt_class = (JV_CLASS (arr))->getComponentType();
1045       jclass obj_class = JV_CLASS (obj);
1046       if (__builtin_expect 
1047           (! _Jv_IsAssignableFrom (elt_class, obj_class), false))
1048         throw new java::lang::ArrayStoreException;
1049     }
1050 }
1051
1052 #define INITIAL_IOFFSETS_LEN 4
1053 #define INITIAL_IFACES_LEN 4
1054
1055 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
1056
1057 // Generate tables for constant-time assignment testing and interface
1058 // method lookup. This implements the technique described by Per Bothner
1059 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
1060 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
1061 void 
1062 _Jv_PrepareConstantTimeTables (jclass klass)
1063 {  
1064   if (klass->isPrimitive () || klass->isInterface ())
1065     return;
1066   
1067   // Short-circuit in case we've been called already.
1068   if ((klass->idt != NULL) || klass->depth != 0)
1069     return;
1070
1071   // Calculate the class depth and ancestor table. The depth of a class 
1072   // is how many "extends" it is removed from Object. Thus the depth of 
1073   // java.lang.Object is 0, but the depth of java.io.FilterOutputStream 
1074   // is 2. Depth is defined for all regular and array classes, but not 
1075   // interfaces or primitive types.
1076    
1077   jclass klass0 = klass;
1078   jboolean has_interfaces = 0;
1079   while (klass0 != &java::lang::Object::class$)
1080     {
1081       has_interfaces += klass0->interface_count;
1082       klass0 = klass0->superclass;
1083       klass->depth++;
1084     }
1085
1086   // We do class member testing in constant time by using a small table 
1087   // of all the ancestor classes within each class. The first element is 
1088   // a pointer to the current class, and the rest are pointers to the 
1089   // classes ancestors, ordered from the current class down by decreasing 
1090   // depth. We do not include java.lang.Object in the table of ancestors, 
1091   // since it is redundant.
1092         
1093   klass->ancestors = (jclass *) _Jv_Malloc (klass->depth * sizeof (jclass));
1094   klass0 = klass;
1095   for (int index = 0; index < klass->depth; index++)
1096     {
1097       klass->ancestors[index] = klass0;
1098       klass0 = klass0->superclass;
1099     }
1100     
1101   if (java::lang::reflect::Modifier::isAbstract (klass->accflags))
1102     return;
1103   
1104   // Optimization: If class implements no interfaces, use a common
1105   // predefined interface table.
1106   if (!has_interfaces)
1107     {
1108       klass->idt = &null_idt;
1109       return;
1110     }
1111
1112   klass->idt = 
1113     (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1114     
1115   _Jv_ifaces ifaces;
1116
1117   ifaces.count = 0;
1118   ifaces.len = INITIAL_IFACES_LEN;
1119   ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
1120
1121   int itable_size = _Jv_GetInterfaces (klass, &ifaces);
1122
1123   if (ifaces.count > 0)
1124     {
1125       klass->idt->cls.itable = 
1126         (void **) _Jv_Malloc (itable_size * sizeof (void *));
1127       klass->idt->cls.itable_length = itable_size;
1128           
1129       jshort *itable_offsets = 
1130         (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
1131
1132       _Jv_GenerateITable (klass, &ifaces, itable_offsets);
1133
1134       jshort cls_iindex = 
1135         _Jv_FindIIndex (ifaces.list, itable_offsets, ifaces.count);
1136
1137       for (int i=0; i < ifaces.count; i++)
1138         {
1139           ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
1140             itable_offsets[i];
1141         }
1142
1143       klass->idt->cls.iindex = cls_iindex;          
1144
1145       _Jv_Free (ifaces.list);
1146       _Jv_Free (itable_offsets);
1147     }
1148   else 
1149     {
1150       klass->idt->cls.iindex = SHRT_MAX;
1151     }
1152 }
1153
1154 // Return index of item in list, or -1 if item is not present.
1155 inline jshort
1156 _Jv_IndexOf (void *item, void **list, jshort list_len)
1157 {
1158   for (int i=0; i < list_len; i++)
1159     {
1160       if (list[i] == item)
1161         return i;
1162     }
1163   return -1;
1164 }
1165
1166 // Find all unique interfaces directly or indirectly implemented by klass.
1167 // Returns the size of the interface dispatch table (itable) for klass, which 
1168 // is the number of unique interfaces plus the total number of methods that 
1169 // those interfaces declare. May extend ifaces if required.
1170 jshort
1171 _Jv_GetInterfaces (jclass klass, _Jv_ifaces *ifaces)
1172 {
1173   jshort result = 0;
1174   
1175   for (int i=0; i < klass->interface_count; i++)
1176     {
1177       jclass iface = klass->interfaces[i];
1178       if (_Jv_IndexOf (iface, (void **) ifaces->list, ifaces->count) == -1)
1179         {
1180           if (ifaces->count + 1 >= ifaces->len)
1181             {
1182               /* Resize ifaces list */
1183               ifaces->len = ifaces->len * 2;
1184               ifaces->list = (jclass *) _Jv_Realloc (ifaces->list, 
1185                              ifaces->len * sizeof(jclass));
1186             }
1187           ifaces->list[ifaces->count] = iface;
1188           ifaces->count++;
1189
1190           result += _Jv_GetInterfaces (klass->interfaces[i], ifaces);
1191         }
1192     }
1193     
1194   if (klass->isInterface())
1195     {
1196       result += klass->method_count + 1;
1197     }
1198   else
1199     {
1200       if (klass->superclass)
1201         {
1202           result += _Jv_GetInterfaces (klass->superclass, ifaces);
1203         }
1204     }
1205   return result;
1206 }
1207
1208 // Fill out itable in klass, resolving method declarations in each ifaces.
1209 // itable_offsets is filled out with the position of each iface in itable,
1210 // such that itable[itable_offsets[n]] == ifaces.list[n].
1211 void
1212 _Jv_GenerateITable (jclass klass, _Jv_ifaces *ifaces, jshort *itable_offsets)
1213 {
1214   void **itable = klass->idt->cls.itable;
1215   jshort itable_pos = 0;
1216
1217   for (int i=0; i < ifaces->count; i++)
1218     { 
1219       jclass iface = ifaces->list[i];
1220       itable_offsets[i] = itable_pos;
1221       itable_pos = _Jv_AppendPartialITable (klass, iface, itable, itable_pos);
1222       
1223       /* Create interface dispatch table for iface */
1224       if (iface->idt == NULL)
1225         {
1226           iface->idt = 
1227             (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1228
1229           // The first element of ioffsets is its length (itself included).
1230           jshort *ioffsets = 
1231             (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN * sizeof (jshort));
1232           ioffsets[0] = INITIAL_IOFFSETS_LEN;
1233           for (int i=1; i < INITIAL_IOFFSETS_LEN; i++)
1234             ioffsets[i] = -1;
1235
1236           iface->idt->iface.ioffsets = ioffsets;            
1237         }
1238     }
1239 }
1240
1241 // Format method name for use in error messages.
1242 jstring
1243 _Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
1244 {
1245   jstring r = JvNewStringUTF (klass->name->data);
1246   r = r->concat (JvNewStringUTF ("."));
1247   r = r->concat (JvNewStringUTF (name->data));
1248   return r;
1249 }
1250
1251 void 
1252 _Jv_ThrowNoSuchMethodError ()
1253 {
1254   throw new java::lang::NoSuchMethodError;
1255 }
1256
1257 // Each superinterface of a class (i.e. each interface that the class
1258 // directly or indirectly implements) has a corresponding "Partial
1259 // Interface Dispatch Table" whose size is (number of methods + 1) words.
1260 // The first word is a pointer to the interface (i.e. the java.lang.Class
1261 // instance for that interface).  The remaining words are pointers to the
1262 // actual methods that implement the methods declared in the interface,
1263 // in order of declaration.
1264 //
1265 // Append partial interface dispatch table for "iface" to "itable", at
1266 // position itable_pos.
1267 // Returns the offset at which the next partial ITable should be appended.
1268 jshort
1269 _Jv_AppendPartialITable (jclass klass, jclass iface, void **itable, 
1270                          jshort pos)
1271 {
1272   using namespace java::lang::reflect;
1273
1274   itable[pos++] = (void *) iface;
1275   _Jv_Method *meth;
1276   
1277   for (int j=0; j < iface->method_count; j++)
1278     {
1279       meth = NULL;
1280       for (jclass cl = klass; cl; cl = cl->getSuperclass())
1281         {
1282           meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
1283                                      iface->methods[j].signature);
1284                  
1285           if (meth)
1286             break;
1287         }
1288
1289       if (meth && (meth->name->data[0] == '<'))
1290         {
1291           // leave a placeholder in the itable for hidden init methods.
1292           itable[pos] = NULL;   
1293         }
1294       else if (meth)
1295         {
1296           if (Modifier::isStatic(meth->accflags))
1297             throw new java::lang::IncompatibleClassChangeError
1298               (_Jv_GetMethodString (klass, meth->name));
1299           if (Modifier::isAbstract(meth->accflags))
1300             throw new java::lang::AbstractMethodError
1301               (_Jv_GetMethodString (klass, meth->name));
1302           if (! Modifier::isPublic(meth->accflags))
1303             throw new java::lang::IllegalAccessError
1304               (_Jv_GetMethodString (klass, meth->name));
1305
1306           itable[pos] = meth->ncode;
1307         }
1308       else
1309         {
1310           // The method doesn't exist in klass. Binary compatibility rules
1311           // permit this, so we delay the error until runtime using a pointer
1312           // to a method which throws an exception.
1313           itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
1314         }
1315       pos++;
1316     }
1317     
1318   return pos;
1319 }
1320
1321 static _Jv_Mutex_t iindex_mutex;
1322 bool iindex_mutex_initialized = false;
1323
1324 // We need to find the correct offset in the Class Interface Dispatch 
1325 // Table for a given interface. Once we have that, invoking an interface 
1326 // method just requires combining the Method's index in the interface 
1327 // (known at compile time) to get the correct method.  Doing a type test 
1328 // (cast or instanceof) is the same problem: Once we have a possible Partial 
1329 // Interface Dispatch Table, we just compare the first element to see if it 
1330 // matches the desired interface. So how can we find the correct offset?  
1331 // Our solution is to keep a vector of candiate offsets in each interface 
1332 // (idt->iface.ioffsets), and in each class we have an index 
1333 // (idt->cls.iindex) used to select the correct offset from ioffsets.
1334 //
1335 // Calculate and return iindex for a new class. 
1336 // ifaces is a vector of num interfaces that the class implements.
1337 // offsets[j] is the offset in the interface dispatch table for the
1338 // interface corresponding to ifaces[j].
1339 // May extend the interface ioffsets if required.
1340 jshort
1341 _Jv_FindIIndex (jclass *ifaces, jshort *offsets, jshort num)
1342 {
1343   int i;
1344   int j;
1345   
1346   // Acquire a global lock to prevent itable corruption in case of multiple 
1347   // classes that implement an intersecting set of interfaces being linked
1348   // simultaneously. We can assume that the mutex will be initialized
1349   // single-threaded.
1350   if (! iindex_mutex_initialized)
1351     {
1352       _Jv_MutexInit (&iindex_mutex);
1353       iindex_mutex_initialized = true;
1354     }
1355   
1356   _Jv_MutexLock (&iindex_mutex);
1357   
1358   for (i=1;; i++)  /* each potential position in ioffsets */
1359     {
1360       for (j=0;; j++)  /* each iface */
1361         {
1362           if (j >= num)
1363             goto found;
1364           if (i >= ifaces[j]->idt->iface.ioffsets[0])
1365             continue;
1366           int ioffset = ifaces[j]->idt->iface.ioffsets[i];
1367           /* We can potentially share this position with another class. */
1368           if (ioffset >= 0 && ioffset != offsets[j])
1369             break; /* Nope. Try next i. */        
1370         }
1371     }
1372   found:
1373   for (j = 0; j < num; j++)
1374     {
1375       int len = ifaces[j]->idt->iface.ioffsets[0];
1376       if (i >= len) 
1377         {
1378           /* Resize ioffsets. */
1379           int newlen = 2 * len;
1380           if (i >= newlen)
1381             newlen = i + 3;
1382           jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
1383           jshort *new_ioffsets = (jshort *) _Jv_Realloc (old_ioffsets, 
1384                                           newlen * sizeof(jshort));       
1385           new_ioffsets[0] = newlen;
1386
1387           while (len < newlen)
1388             new_ioffsets[len++] = -1;
1389           
1390           ifaces[j]->idt->iface.ioffsets = new_ioffsets;
1391         }
1392       ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
1393     }
1394
1395   _Jv_MutexUnlock (&iindex_mutex);
1396
1397   return i;
1398 }
1399
1400 // Only used by serialization
1401 java::lang::reflect::Field *
1402 java::lang::Class::getPrivateField (jstring name)
1403 {
1404   int hash = name->hashCode ();
1405
1406   java::lang::reflect::Field* rfield;
1407   for (int i = 0;  i < field_count;  i++)
1408     {
1409       _Jv_Field *field = &fields[i];
1410       if (! _Jv_equal (field->name, name, hash))
1411         continue;
1412       rfield = new java::lang::reflect::Field ();
1413       rfield->offset = (char*) field - (char*) fields;
1414       rfield->declaringClass = this;
1415       rfield->name = name;
1416       return rfield;
1417     }
1418   jclass superclass = getSuperclass();
1419   if (superclass == NULL)
1420     return NULL;
1421   rfield = superclass->getPrivateField(name);
1422   for (int i = 0; i < interface_count && rfield == NULL; ++i)
1423     rfield = interfaces[i]->getPrivateField (name);
1424   return rfield;
1425 }
1426
1427 // Only used by serialization
1428 java::lang::reflect::Method *
1429 java::lang::Class::getPrivateMethod (jstring name, JArray<jclass> *param_types)
1430 {
1431   jstring partial_sig = getSignature (param_types, false);
1432   jint p_len = partial_sig->length();
1433   _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
1434   for (Class *klass = this; klass; klass = klass->getSuperclass())
1435     {
1436       int i = klass->isPrimitive () ? 0 : klass->method_count;
1437       while (--i >= 0)
1438         {
1439           if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
1440               && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
1441             {
1442               // Found it.
1443               using namespace java::lang::reflect;
1444
1445               Method *rmethod = new Method ();
1446               rmethod->offset = ((char *) (&klass->methods[i])
1447                                  - (char *) klass->methods);
1448               rmethod->declaringClass = klass;
1449               return rmethod;
1450             }
1451         }
1452     }
1453   throw new java::lang::NoSuchMethodException;
1454 }
1455
1456 // Private accessor method for Java code to retrieve the protection domain.
1457 java::security::ProtectionDomain *
1458 java::lang::Class::getProtectionDomain0 ()
1459 {
1460   return protectionDomain;
1461 }
1462
1463 // Functions for indirect dispatch (symbolic virtual method binding) support.
1464
1465 // Resolve entries in the virtual method offset symbol table 
1466 // (klass->otable_syms). The vtable offset (in bytes) for each resolved method 
1467 // is placed at the corresponding position in the virtual method offset table 
1468 // (klass->otable). A single otable and otable_syms pair may be shared by many 
1469 // classes.
1470 void
1471 _Jv_LinkOffsetTable(jclass klass)
1472 {
1473   //// FIXME: Need to lock the otable ////
1474   
1475   if (klass->otable == NULL
1476       || klass->otable->state != 0)
1477     return;
1478   
1479   klass->otable->state = 1;
1480
1481   int index = 0;
1482   _Jv_MethodSymbol sym = klass->otable_syms[0];
1483
1484   while (sym.name != NULL)
1485     {
1486       jclass target_class = _Jv_FindClass (sym.class_name, NULL);
1487       _Jv_Method *meth = NULL;            
1488       
1489       if (target_class != NULL)
1490         if (target_class->isInterface())
1491           {
1492             // FIXME: This does not yet fully conform to binary compatibility
1493             // rules. It will break if a declaration is moved into a 
1494             // superinterface.
1495             for (int i=0; i < target_class->method_count; i++)
1496               {
1497                 meth = &target_class->methods[i];
1498                 if (_Jv_equalUtf8Consts (sym.name, meth->name)
1499                     && _Jv_equalUtf8Consts (sym.signature, meth->signature))
1500                   {
1501                     klass->otable->offsets[index] = i + 1;
1502                     break;
1503                   }
1504               }
1505           }
1506         else
1507           {
1508             // If the target class does not have a vtable_method_count yet, 
1509             // then we can't tell the offsets for its methods, so we must lay 
1510             // it out now.
1511             if (target_class->vtable_method_count == -1)
1512               {
1513                 JvSynchronize sync (target_class);
1514                 _Jv_LayoutVTableMethods (target_class);
1515               }
1516
1517             meth = _Jv_LookupDeclaredMethod(target_class, sym.name, 
1518                                             sym.signature);
1519
1520             if (meth != NULL)
1521               {
1522                 klass->otable->offsets[index] = 
1523                   _Jv_VTable::idx_to_offset (meth->index);
1524               }
1525           }
1526
1527       if (meth == NULL)
1528         // FIXME: This should be special index for ThrowNoSuchMethod().
1529         klass->otable->offsets[index] = -1;
1530
1531       sym = klass->otable_syms[++index];
1532     }
1533 }
1534
1535 // Returns true if METH should get an entry in a VTable.
1536 static bool
1537 isVirtualMethod (_Jv_Method *meth)
1538 {
1539   using namespace java::lang::reflect;
1540   return (((meth->accflags & (Modifier::STATIC | Modifier::PRIVATE)) == 0)
1541           && meth->name->data[0] != '<');
1542 }
1543
1544 // Prepare virtual method declarations in KLASS, and any superclasses as 
1545 // required, by determining their vtable index, setting method->index, and
1546 // finally setting the class's vtable_method_count. Must be called with the
1547 // lock for KLASS held.
1548 void
1549 _Jv_LayoutVTableMethods (jclass klass)
1550 {
1551   if (klass->vtable != NULL || klass->isInterface() 
1552       || klass->vtable_method_count != -1)
1553     return;
1554     
1555   jclass superclass = klass->superclass;
1556
1557   if (superclass != NULL && superclass->vtable_method_count == -1)
1558     {
1559       JvSynchronize sync (superclass);
1560       _Jv_LayoutVTableMethods (superclass);
1561     }
1562     
1563   int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1564
1565   for (int i = 0; i < klass->method_count; ++i)
1566     {
1567       _Jv_Method *meth = &klass->methods[i];
1568       _Jv_Method *super_meth = NULL;
1569     
1570       if (!isVirtualMethod(meth))
1571         continue;
1572               
1573       if (superclass != NULL)
1574         super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name, 
1575                                                meth->signature);
1576       
1577       if (super_meth)
1578         meth->index = super_meth->index;
1579       else
1580         meth->index = index++;
1581     }
1582   
1583   klass->vtable_method_count = index;
1584 }
1585
1586 // Set entries in VTABLE for virtual methods declared in KLASS. If KLASS has
1587 // an immediate abstract parent, recursivly do its methods first.
1588 void
1589 _Jv_SetVTableEntries (jclass klass, _Jv_VTable *vtable)
1590 {
1591   using namespace java::lang::reflect;
1592
1593   jclass superclass = klass->getSuperclass();
1594
1595   if (superclass != NULL && (superclass->getModifiers() & Modifier::ABSTRACT))
1596     _Jv_SetVTableEntries (superclass, vtable);
1597     
1598   for (int i = klass->method_count - 1; i >= 0; i--)
1599     {
1600       _Jv_Method *meth = &klass->methods[i];
1601       if (!isVirtualMethod(meth))
1602         continue;
1603       vtable->set_method(meth->index, meth->ncode);
1604     }
1605 }
1606
1607 // Allocate and lay out the virtual method table for KLASS. This will also
1608 // cause vtables to be generated for any non-abstract superclasses, and
1609 // virtual method layout to occur for any abstract superclasses. Must be
1610 // called with monitor lock for KLASS held.
1611 void
1612 _Jv_MakeVTable (jclass klass)
1613 {
1614   using namespace java::lang::reflect;  
1615
1616   if (klass->vtable != NULL || klass->isInterface() 
1617       || (klass->accflags & Modifier::ABSTRACT))
1618     return;
1619   
1620   //  out before we can create a vtable. 
1621   if (klass->vtable_method_count == -1)
1622     _Jv_LayoutVTableMethods (klass);
1623
1624   // Allocate the new vtable.
1625   _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1626   klass->vtable = vtable;
1627   
1628   // Copy the vtable of the closest non-abstract superclass.
1629   jclass superclass = klass->superclass;
1630   if (superclass != NULL)
1631     {
1632       while ((superclass->accflags & Modifier::ABSTRACT) != 0)
1633         superclass = superclass->superclass;
1634
1635       if (superclass->vtable == NULL)
1636         {
1637           JvSynchronize sync (superclass);
1638           _Jv_MakeVTable (superclass);
1639         }
1640
1641       for (int i = 0; i < superclass->vtable_method_count; ++i)
1642         vtable->set_method (i, superclass->vtable->get_method (i));
1643     }
1644
1645   // Set the class pointer and GC descriptor.
1646   vtable->clas = klass;
1647   vtable->gc_descr = _Jv_BuildGCDescr (klass);
1648
1649   // For each virtual declared in klass and any immediate abstract 
1650   // superclasses, set new vtable entry or override an old one.
1651   _Jv_SetVTableEntries (klass, vtable);
1652 }