OSDN Git Service

ec4a18f1b51bde9fceb9a9f06fa6631eb152ab29
[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, 2003, 2004, 2005, 2006, 2007,
4    2010 Free Software Foundation
5
6    This file is part of libgcj.
7
8 This software is copyrighted work licensed under the terms of the
9 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
10 details.  */
11
12 #include <config.h>
13
14 #include <limits.h>
15 #include <string.h>
16 #include <stddef.h>
17 #include <stdio.h>
18
19 #pragma implementation "Class.h"
20
21 #include <gcj/cni.h>
22 #include <jvm.h>
23 #include <java-threads.h>
24
25 #include <java/lang/Class.h>
26 #include <java/lang/ClassLoader.h>
27 #include <java/lang/String.h>
28 #include <java/lang/reflect/Modifier.h>
29 #include <java/lang/reflect/Member.h>
30 #include <java/lang/reflect/Method.h>
31 #include <java/lang/reflect/Field.h>
32 #include <java/lang/reflect/Proxy.h>
33 #include <java/lang/reflect/Constructor.h>
34 #include <java/lang/AbstractMethodError.h>
35 #include <java/lang/ArrayStoreException.h>
36 #include <java/lang/ClassCastException.h>
37 #include <java/lang/ClassNotFoundException.h>
38 #include <java/lang/ExceptionInInitializerError.h>
39 #include <java/lang/IllegalAccessException.h>
40 #include <java/lang/IllegalAccessError.h>
41 #include <java/lang/IllegalArgumentException.h>
42 #include <java/lang/IncompatibleClassChangeError.h>
43 #include <java/lang/NoSuchFieldError.h>
44 #include <java/lang/ArrayIndexOutOfBoundsException.h>
45 #include <java/lang/InstantiationException.h>
46 #include <java/lang/NoClassDefFoundError.h>
47 #include <java/lang/NoSuchFieldException.h>
48 #include <java/lang/NoSuchMethodError.h>
49 #include <java/lang/NoSuchMethodException.h>
50 #include <java/lang/Thread.h>
51 #include <java/lang/NullPointerException.h>
52 #include <java/lang/RuntimePermission.h>
53 #include <java/lang/System.h>
54 #include <java/lang/SecurityException.h>
55 #include <java/lang/SecurityManager.h>
56 #include <java/lang/StringBuffer.h>
57 #include <java/lang/VMClassLoader.h>
58 #include <gcj/method.h>
59 #include <gnu/gcj/RawData.h>
60 #include <java/lang/VerifyError.h>
61 #include <java/lang/InternalError.h>
62 #include <java/lang/TypeNotPresentException.h>
63 #include <java/lang/Byte.h>
64 #include <java/lang/Short.h>
65 #include <java/lang/Integer.h>
66 #include <java/lang/Float.h>
67 #include <java/lang/Double.h>
68 #include <java/lang/Long.h>
69 #include <java/lang/Character.h>
70 #include <java/lang/Boolean.h>
71 #include <java/lang/annotation/Annotation.h>
72 #include <java/util/HashMap.h>
73 #include <java/util/Map.h>
74 #include <sun/reflect/annotation/AnnotationInvocationHandler.h>
75 #include <java/lang/Enum.h>
76
77 #include <java-cpool.h>
78 #include <java-interp.h>
79 #include <java-assert.h>
80 #include <java-stack.h>
81 #include <execution.h>
82
83 \f
84
85 using namespace gcj;
86
87 jclass
88 java::lang::Class::forName (jstring className, jboolean initialize,
89                             java::lang::ClassLoader *loader)
90 {
91   if (! className)
92     throw new java::lang::NullPointerException;
93
94   jsize length = _Jv_GetStringUTFLength (className);
95   char buffer[length];
96   _Jv_GetStringUTFRegion (className, 0, className->length(), buffer);
97
98   _Jv_Utf8Const *name = _Jv_makeUtf8Const (buffer, length);
99
100   if (! _Jv_VerifyClassName (name))
101     throw new java::lang::ClassNotFoundException (className);
102
103   jclass klass = (buffer[0] == '[' 
104                   ? _Jv_FindClassFromSignature (name->chars(), loader)
105                   : _Jv_FindClass (name, loader));
106
107   if (klass == NULL)
108     throw new java::lang::ClassNotFoundException (className);
109
110   if (initialize)
111     _Jv_InitClass (klass);
112
113   return klass;
114 }
115
116 jclass
117 java::lang::Class::forName (jstring className)
118 {
119   java::lang::ClassLoader *loader = NULL;
120
121   jclass caller = _Jv_StackTrace::GetCallingClass (&Class::class$);
122   if (caller)
123     loader = caller->getClassLoaderInternal();
124
125   return forName (className, true, loader);
126 }
127
128 java::lang::ClassLoader *
129 java::lang::Class::getClassLoader (void)
130 {
131   java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
132   if (s != NULL)
133     {
134       jclass caller = _Jv_StackTrace::GetCallingClass (&Class::class$);
135       return getClassLoader (caller);
136    }
137
138   return loader;
139 }
140
141 java::lang::ClassLoader *
142 java::lang::Class::getClassLoader (jclass caller)
143 {
144   java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
145   if (s != NULL)
146     {
147       ClassLoader *caller_loader = caller->getClassLoaderInternal();
148
149       // If the caller has a non-null class loader, and that loader
150       // is not this class' loader or an ancestor thereof, then do a
151       // security check.
152       if (caller_loader != NULL && ! caller_loader->isAncestorOf(loader))
153         s->checkPermission (new RuntimePermission (JvNewStringLatin1 ("getClassLoader")));
154     }
155
156   return loader;
157 }
158
159 java::lang::reflect::Constructor *
160 java::lang::Class::getConstructor (JArray<jclass> *param_types)
161 {
162   memberAccessCheck(java::lang::reflect::Member::PUBLIC);
163
164   jstring partial_sig = getSignature (param_types, true);
165   jint hash = partial_sig->hashCode ();
166
167   int i = isPrimitive () ? 0 : method_count;
168   while (--i >= 0)
169     {
170       if (_Jv_equalUtf8Consts (methods[i].name, init_name)
171           && _Jv_equal (methods[i].signature, partial_sig, hash))
172         {
173           // Found it.  For getConstructor, the constructor must be
174           // public.
175           using namespace java::lang::reflect;
176           if (! Modifier::isPublic(methods[i].accflags))
177             break;
178           Constructor *cons = new Constructor ();
179           cons->offset = (char *) (&methods[i]) - (char *) methods;
180           cons->declaringClass = this;
181           return cons;
182         }
183     }
184   throw new java::lang::NoSuchMethodException (_Jv_NewStringUtf8Const (init_name));
185 }
186
187 JArray<java::lang::reflect::Constructor *> *
188 java::lang::Class::getDeclaredConstructors (jboolean publicOnly)
189 {
190   int numConstructors = 0;
191   int max = isPrimitive () ? 0 : method_count;
192   int i;
193   for (i = max; --i >= 0; )
194     {
195       _Jv_Method *method = &methods[i];
196       if (method->name == NULL
197           || ! _Jv_equalUtf8Consts (method->name, init_name))
198         continue;
199       if (publicOnly
200           && ! java::lang::reflect::Modifier::isPublic(method->accflags))
201         continue;
202       numConstructors++;
203     }
204   JArray<java::lang::reflect::Constructor *> *result
205     = (JArray<java::lang::reflect::Constructor *> *)
206     JvNewObjectArray (numConstructors,
207                       &java::lang::reflect::Constructor::class$,
208                       NULL);
209   java::lang::reflect::Constructor** cptr = elements (result);
210   for (i = 0;  i < max;  i++)
211     {
212       _Jv_Method *method = &methods[i];
213       if (method->name == NULL
214           || ! _Jv_equalUtf8Consts (method->name, init_name))
215         continue;
216       if (publicOnly
217           && ! java::lang::reflect::Modifier::isPublic(method->accflags))
218         continue;
219       java::lang::reflect::Constructor *cons
220         = new java::lang::reflect::Constructor ();
221       cons->offset = (char *) method - (char *) methods;
222       cons->declaringClass = this;
223       *cptr++ = cons;
224     }
225   return result;
226 }
227
228 java::lang::reflect::Constructor *
229 java::lang::Class::getDeclaredConstructor (JArray<jclass> *param_types)
230 {
231   memberAccessCheck(java::lang::reflect::Member::DECLARED);
232
233   jstring partial_sig = getSignature (param_types, true);
234   jint hash = partial_sig->hashCode ();
235
236   int i = isPrimitive () ? 0 : method_count;
237   while (--i >= 0)
238     {
239       if (_Jv_equalUtf8Consts (methods[i].name, init_name)
240           && _Jv_equal (methods[i].signature, partial_sig, hash))
241         {
242           // Found it.
243           using namespace java::lang::reflect;
244           Constructor *cons = new Constructor ();
245           cons->offset = (char *) (&methods[i]) - (char *) methods;
246           cons->declaringClass = this;
247           return cons;
248         }
249     }
250   throw new java::lang::NoSuchMethodException (_Jv_NewStringUtf8Const (init_name));
251 }
252
253 java::lang::reflect::Field *
254 java::lang::Class::getField (jstring name, jint hash)
255 {
256   java::lang::reflect::Field* rfield;
257   for (int i = 0;  i < field_count;  i++)
258     {
259       _Jv_Field *field = &fields[i];
260       if (! _Jv_equal (field->name, name, hash))
261         continue;
262       if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
263         continue;
264       rfield = new java::lang::reflect::Field ();
265       rfield->offset = (char*) field - (char*) fields;
266       rfield->declaringClass = this;
267       rfield->name = name;
268       return rfield;
269     }
270   jclass superclass = getSuperclass();
271   if (superclass == NULL)
272     return NULL;
273   rfield = superclass->getField(name, hash);
274   for (int i = 0; i < interface_count && rfield == NULL; ++i)
275     rfield = interfaces[i]->getField (name, hash);
276   return rfield;
277 }
278
279 java::lang::reflect::Field *
280 java::lang::Class::getDeclaredField (jstring name)
281 {
282   memberAccessCheck(java::lang::reflect::Member::DECLARED);
283   int hash = name->hashCode();
284   for (int i = 0;  i < field_count;  i++)
285     {
286       _Jv_Field *field = &fields[i];
287       if (! _Jv_equal (field->name, name, hash))
288         continue;
289       java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
290       rfield->offset = (char*) field - (char*) fields;
291       rfield->declaringClass = this;
292       rfield->name = name;
293       return rfield;
294     }
295   throw new java::lang::NoSuchFieldException (name);
296 }
297
298 JArray<java::lang::reflect::Field *> *
299 java::lang::Class::getDeclaredFields (jboolean public_only)
300 {
301   int size;
302   if (public_only)
303     {
304       size = 0;
305       for (int i = 0; i < field_count; ++i)
306         {
307           _Jv_Field *field = &fields[i];
308           if ((field->flags & java::lang::reflect::Modifier::PUBLIC))
309             ++size;
310         }
311     }
312   else
313     size = field_count;
314
315   JArray<java::lang::reflect::Field *> *result
316     = (JArray<java::lang::reflect::Field *> *)
317     JvNewObjectArray (size, &java::lang::reflect::Field::class$, NULL);
318   java::lang::reflect::Field** fptr = elements (result);
319   for (int i = 0;  i < field_count;  i++)
320     {
321       _Jv_Field *field = &fields[i];
322       if (public_only
323           && ! (field->flags & java::lang::reflect::Modifier::PUBLIC))
324         continue;
325       java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
326       rfield->offset = (char*) field - (char*) fields;
327       rfield->declaringClass = this;
328       *fptr++ = rfield;
329     }
330   return result;
331 }
332
333 void
334 java::lang::Class::getSignature (java::lang::StringBuffer *buffer)
335 {
336   if (isPrimitive())
337     buffer->append((jchar) method_count);
338   else
339     {
340       jstring name = getName();
341       if (name->charAt(0) != '[')
342         buffer->append((jchar) 'L');
343       buffer->append(name);
344       if (name->charAt(0) != '[')
345         buffer->append((jchar) ';');
346     }
347 }
348
349 // This doesn't have to be native.  It is an implementation detail
350 // only called from the C++ code, though, so maybe this is clearer.
351 jstring
352 java::lang::Class::getSignature (JArray<jclass> *param_types,
353                                  jboolean is_constructor)
354 {
355   java::lang::StringBuffer *buf = new java::lang::StringBuffer ();
356   buf->append((jchar) '(');
357   // A NULL param_types means "no parameters".
358   if (param_types != NULL)
359     {
360       jclass *v = elements (param_types);
361       for (int i = 0; i < param_types->length; ++i)
362         v[i]->getSignature(buf);
363     }
364   buf->append((jchar) ')');
365   if (is_constructor)
366     buf->append((jchar) 'V');
367   return buf->toString();
368 }
369
370 java::lang::reflect::Method *
371 java::lang::Class::_getDeclaredMethod (jstring name,
372                                        JArray<jclass> *param_types)
373 {
374   jstring partial_sig = getSignature (param_types, false);
375   jint p_len = partial_sig->length();
376   _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
377   int i = isPrimitive () ? 0 : method_count;
378   while (--i >= 0)
379     {
380       if (_Jv_equalUtf8Consts (methods[i].name, utf_name)
381           && _Jv_equaln (methods[i].signature, partial_sig, p_len)
382           && (methods[i].accflags
383               & java::lang::reflect::Modifier::INVISIBLE) == 0)
384         {
385           // Found it.
386           using namespace java::lang::reflect;
387           Method *rmethod = new Method ();
388           rmethod->offset = (char*) (&methods[i]) - (char*) methods;
389           rmethod->declaringClass = this;
390           return rmethod;
391         }
392     }
393   return NULL;
394 }
395
396 JArray<java::lang::reflect::Method *> *
397 java::lang::Class::getDeclaredMethods (void)
398 {
399   memberAccessCheck(java::lang::reflect::Member::DECLARED);
400
401   int numMethods = 0;
402   int max = isPrimitive () ? 0 : method_count;
403   int i;
404   for (i = max; --i >= 0; )
405     {
406       _Jv_Method *method = &methods[i];
407       if (method->name == NULL
408           || _Jv_equalUtf8Consts (method->name, clinit_name)
409           || _Jv_equalUtf8Consts (method->name, init_name)
410           || _Jv_equalUtf8Consts (method->name, finit_name)
411           || (methods[i].accflags
412               & java::lang::reflect::Modifier::INVISIBLE) != 0)
413         continue;
414       numMethods++;
415     }
416   JArray<java::lang::reflect::Method *> *result
417     = (JArray<java::lang::reflect::Method *> *)
418     JvNewObjectArray (numMethods, &java::lang::reflect::Method::class$, NULL);
419   java::lang::reflect::Method** mptr = elements (result);
420   for (i = 0;  i < max;  i++)
421     {
422       _Jv_Method *method = &methods[i];
423       if (method->name == NULL
424           || _Jv_equalUtf8Consts (method->name, clinit_name)
425           || _Jv_equalUtf8Consts (method->name, init_name)
426           || _Jv_equalUtf8Consts (method->name, finit_name)
427           || (methods[i].accflags
428               & java::lang::reflect::Modifier::INVISIBLE) != 0)
429         continue;
430       java::lang::reflect::Method* rmethod
431         = new java::lang::reflect::Method ();
432       rmethod->offset = (char*) method - (char*) methods;
433       rmethod->declaringClass = this;
434       *mptr++ = rmethod;
435     }
436   return result;
437 }
438
439 jstring
440 java::lang::Class::getName (void)
441 {
442   return name->toString();
443 }
444
445 JArray<jclass> *
446 java::lang::Class::getInterfaces (void)
447 {
448   jobjectArray r = JvNewObjectArray (interface_count, getClass (), NULL);
449   jobject *data = elements (r);
450   for (int i = 0; i < interface_count; ++i)
451     {
452       typedef unsigned int uaddr __attribute__ ((mode (pointer)));
453       data[i] = interfaces[i];
454       if ((uaddr)data[i] < (uaddr)constants.size)
455         fprintf (stderr, "ERROR !!!\n");
456     }
457   return reinterpret_cast<JArray<jclass> *> (r);
458 }
459
460 java::lang::reflect::Method *
461 java::lang::Class::_getMethod (jstring name, JArray<jclass> *param_types)
462 {
463   jstring partial_sig = getSignature (param_types, false);
464   jint p_len = partial_sig->length();
465   _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
466
467    for (Class *klass = this; klass; klass = klass->getSuperclass())
468     {
469       int i = klass->isPrimitive () ? 0 : klass->method_count;
470       while (--i >= 0)
471         {
472           if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
473               && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len)
474               && (klass->methods[i].accflags
475                   & java::lang::reflect::Modifier::INVISIBLE) == 0)
476             {
477               // Found it.
478               using namespace java::lang::reflect;
479
480               // Method must be public.
481               if (! Modifier::isPublic (klass->methods[i].accflags))
482                 break;
483
484               Method *rmethod = new Method ();
485               rmethod->offset = ((char *) (&klass->methods[i])
486                                  - (char *) klass->methods);
487               rmethod->declaringClass = klass;
488               return rmethod;
489             }
490         }
491     }
492
493   // If we haven't found a match, and this class is an interface, then
494   // check all the superinterfaces.
495   if (isInterface())
496     {
497       for (int i = 0; i < interface_count; ++i)
498         {
499           using namespace java::lang::reflect;
500           Method *rmethod = interfaces[i]->_getMethod (name, param_types);
501           if (rmethod != NULL)
502             return rmethod;
503         }
504     }
505
506   return NULL;
507 }
508
509 // This is a very slow implementation, since it re-scans all the
510 // methods we've already listed to make sure we haven't duplicated a
511 // method.  It also over-estimates the required size, so we have to
512 // shrink the result array later.
513 jint
514 java::lang::Class::_getMethods (JArray<java::lang::reflect::Method *> *result,
515                                 jint offset)
516 {
517   jint count = 0;
518
519   // First examine all local methods
520   for (int i = isPrimitive () ? 0 : method_count; --i >= 0; )
521     {
522       _Jv_Method *method = &methods[i];
523       if (method->name == NULL
524           || _Jv_equalUtf8Consts (method->name, clinit_name)
525           || _Jv_equalUtf8Consts (method->name, init_name)
526           || _Jv_equalUtf8Consts (method->name, finit_name)
527           || (method->accflags
528               & java::lang::reflect::Modifier::INVISIBLE) != 0)
529         continue;
530       // Only want public methods.
531       if (! java::lang::reflect::Modifier::isPublic (method->accflags))
532         continue;
533
534       // This is where we over-count the slots required if we aren't
535       // filling the result for real.
536       if (result != NULL)
537         {
538           jboolean add = true;
539           java::lang::reflect::Method **mp = elements (result);
540           // If we already have a method with this name and signature,
541           // then ignore this one.  This can happen with virtual
542           // methods.
543           for (int j = 0; j < offset; ++j)
544             {
545               _Jv_Method *meth_2 = _Jv_FromReflectedMethod (mp[j]);
546               if (_Jv_equalUtf8Consts (method->name, meth_2->name)
547                   && _Jv_equalUtf8Consts (method->signature,
548                                           meth_2->signature))
549                 {
550                   add = false;
551                   break;
552                 }
553             }
554           if (! add)
555             continue;
556         }
557
558       if (result != NULL)
559         {
560           using namespace java::lang::reflect;
561           Method *rmethod = new Method ();
562           rmethod->offset = (char *) method - (char *) methods;
563           rmethod->declaringClass = this;
564           Method **mp = elements (result);
565           mp[offset + count] = rmethod;
566         }
567       ++count;
568     }
569   offset += count;
570
571   // Now examine superclasses.
572   if (getSuperclass () != NULL)
573     {
574       jint s_count = getSuperclass()->_getMethods (result, offset);
575       offset += s_count;
576       count += s_count;
577     }
578
579   // Finally, examine interfaces.
580   for (int i = 0; i < interface_count; ++i)
581     {
582       int f_count = interfaces[i]->_getMethods (result, offset);
583       count += f_count;
584       offset += f_count;
585     }
586
587   return count;
588 }
589
590 JArray<java::lang::reflect::Method *> *
591 java::lang::Class::getMethods (void)
592 {
593   using namespace java::lang::reflect;
594
595   memberAccessCheck(Member::PUBLIC);
596
597   // This will overestimate the size we need.
598   jint count = _getMethods (NULL, 0);
599
600   JArray<Method *> *result
601     = ((JArray<Method *> *) JvNewObjectArray (count,
602                                               &Method::class$,
603                                               NULL));
604
605   // When filling the array for real, we get the actual count.  Then
606   // we resize the array.
607   jint real_count = _getMethods (result, 0);
608
609   if (real_count != count)
610     {
611       JArray<Method *> *r2
612         = ((JArray<Method *> *) JvNewObjectArray (real_count,
613                                                   &Method::class$,
614                                                   NULL));
615       
616       Method **destp = elements (r2);
617       Method **srcp = elements (result);
618
619       for (int i = 0; i < real_count; ++i)
620         *destp++ = *srcp++;
621
622       result = r2;
623     }
624
625   return result;
626 }
627
628 jboolean
629 java::lang::Class::isAssignableFrom (jclass klass)
630 {
631   // Arguments may not have been initialized, given ".class" syntax.
632   // This ensures we can at least look at their superclasses.
633   _Jv_Linker::wait_for_state (this, JV_STATE_LOADING);
634   _Jv_Linker::wait_for_state (klass, JV_STATE_LOADING);
635   return _Jv_IsAssignableFrom (klass, this);
636 }
637
638 jboolean
639 java::lang::Class::isInstance (jobject obj)
640 {
641   if (! obj)
642     return false;
643   return _Jv_IsAssignableFrom (JV_CLASS (obj), this);
644 }
645
646 jobject
647 java::lang::Class::newInstance (void)
648 {
649   memberAccessCheck(java::lang::reflect::Member::PUBLIC);
650
651   if (isPrimitive ()
652       || isInterface ()
653       || isArray ()
654       || java::lang::reflect::Modifier::isAbstract(accflags))
655     throw new java::lang::InstantiationException (getName ());
656
657   _Jv_InitClass (this);
658
659   _Jv_Method *meth = _Jv_GetMethodLocal (this, init_name, void_signature);
660   if (! meth)
661     throw new java::lang::InstantiationException (getName());
662
663   jobject r = _Jv_AllocObject (this);
664   ((void (*) (jobject)) meth->ncode) (r);
665   return r;
666 }
667
668 void
669 java::lang::Class::finalize (void)
670 {
671   // Array classes don't have an engine, and don't need to be finalized.
672    if (engine)
673      engine->unregister(this);
674 }
675
676 #ifdef INTERPRETER
677 void
678 _Jv_ClosureList::releaseClosures (_Jv_ClosureList **closures)
679 {
680   if (!closures)
681     return;
682
683   while (_Jv_ClosureList *current = *closures)
684     {
685       *closures = current->next;
686       ffi_closure_free (current->ptr);
687     }
688 }
689
690 void
691 _Jv_ClosureList::registerClosure (jclass klass, void *ptr)
692 {
693   _Jv_ClosureList **closures = klass->engine->get_closure_list (klass);
694   if (closures)
695     {
696       this->ptr = ptr;
697       this->next = *closures;
698       *closures = this;
699     }
700 }
701 #endif
702
703 // This implements the initialization process for a class.  From Spec
704 // section 12.4.2.
705 void
706 java::lang::Class::initializeClass (void)
707 {
708   // Short-circuit to avoid needless locking (expression includes
709   // JV_STATE_PHANTOM and JV_STATE_DONE).
710   if (state >= JV_STATE_PHANTOM)
711     return;
712
713   // Step 1.  We introduce a new scope so we can synchronize more
714   // easily.
715   {
716     JvSynchronize sync (this);
717
718     if (state < JV_STATE_LINKED)
719       {
720         try
721           {
722             _Jv_Linker::wait_for_state(this, JV_STATE_LINKED);
723           }
724         catch (java::lang::SecurityException *x)
725           {
726             throw x;
727           }
728         catch (java::lang::Throwable *x)
729           {
730             // Turn into a NoClassDefFoundError.
731             java::lang::NoClassDefFoundError *result
732               = new java::lang::NoClassDefFoundError(getName());
733             result->initCause(x);
734             throw result;
735           }
736       }
737
738     // Step 2.
739     java::lang::Thread *self = java::lang::Thread::currentThread();
740     self = (java::lang::Thread *) ((long) self | 1);
741     while (state == JV_STATE_IN_PROGRESS && thread && thread != self)
742       wait ();
743
744     // Steps 3 &  4.
745     if (state == JV_STATE_DONE || state == JV_STATE_IN_PROGRESS)
746       return;
747
748     // Step 5.
749     if (state == JV_STATE_ERROR)
750       throw new java::lang::NoClassDefFoundError (getName());
751
752     // Step 6.
753     thread = self;
754     _Jv_Linker::wait_for_state (this, JV_STATE_LINKED);
755     state = JV_STATE_IN_PROGRESS;
756   }
757
758   // Step 7.
759   if (! isInterface () && superclass)
760     {
761       try
762         {
763           _Jv_InitClass (superclass);
764         }
765       catch (java::lang::SecurityException *x)
766         {
767           throw x;
768         }
769       catch (java::lang::Throwable *except)
770         {
771           // Caught an exception.
772           JvSynchronize sync (this);
773           state = JV_STATE_ERROR;
774           notifyAll ();
775           throw except;
776         }
777     }
778
779   // Steps 8, 9, 10, 11.
780   try
781     {
782       _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name,
783                                              void_signature);
784       if (meth)
785         ((void (*) (void)) meth->ncode) ();
786     }
787   catch (java::lang::SecurityException *x)
788     {
789       throw x;
790     }
791   catch (java::lang::Throwable *except)
792     {
793       if (! java::lang::Error::class$.isInstance(except))
794         {
795           try
796             {
797               except = new ExceptionInInitializerError (except);
798             }
799           catch (java::lang::Throwable *t)
800             {
801               except = t;
802             }
803         }
804
805       JvSynchronize sync (this);
806       state = JV_STATE_ERROR;
807       notifyAll ();
808       throw except;
809     }
810
811   JvSynchronize sync (this);
812   state = JV_STATE_DONE;
813   notifyAll ();
814 }
815
816 // Only used by serialization
817 java::lang::reflect::Field *
818 java::lang::Class::getPrivateField (jstring name)
819 {
820   int hash = name->hashCode ();
821
822   java::lang::reflect::Field* rfield;
823   for (int i = 0;  i < field_count;  i++)
824     {
825       _Jv_Field *field = &fields[i];
826       if (! _Jv_equal (field->name, name, hash))
827         continue;
828       rfield = new java::lang::reflect::Field ();
829       rfield->offset = (char*) field - (char*) fields;
830       rfield->declaringClass = this;
831       rfield->name = name;
832       return rfield;
833     }
834   jclass superclass = getSuperclass();
835   if (superclass == NULL)
836     return NULL;
837   rfield = superclass->getPrivateField(name);
838   for (int i = 0; i < interface_count && rfield == NULL; ++i)
839     rfield = interfaces[i]->getPrivateField (name);
840   return rfield;
841 }
842
843 // Only used by serialization
844 java::lang::reflect::Method *
845 java::lang::Class::getPrivateMethod (jstring name, JArray<jclass> *param_types)
846 {
847   jstring partial_sig = getSignature (param_types, false);
848   jint p_len = partial_sig->length();
849   _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
850   for (Class *klass = this; klass; klass = klass->getSuperclass())
851     {
852       int i = klass->isPrimitive () ? 0 : klass->method_count;
853       while (--i >= 0)
854         {
855           if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
856               && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
857             {
858               // Found it.
859               using namespace java::lang::reflect;
860
861               Method *rmethod = new Method ();
862               rmethod->offset = ((char *) (&klass->methods[i])
863                                  - (char *) klass->methods);
864               rmethod->declaringClass = klass;
865               return rmethod;
866             }
867         }
868     }
869   throw new java::lang::NoSuchMethodException (name);
870 }
871
872 // Private accessor method for Java code to retrieve the protection domain.
873 java::security::ProtectionDomain *
874 java::lang::Class::getProtectionDomain0 ()
875 {
876   return protectionDomain;
877 }
878
879 JArray<jobject> *
880 java::lang::Class::getSigners()
881 {
882   return hack_signers;
883 }
884
885 void
886 java::lang::Class::setSigners(JArray<jobject> *s)
887 {
888   hack_signers = s;
889 }
890
891 \f
892
893 static unsigned char
894 read_u1 (unsigned char *&p)
895 {
896   return *p++;
897 }
898
899 static unsigned char
900 read_u1 (unsigned char *&p, unsigned char *next)
901 {
902   if (next - p < 1)
903     throw new java::lang::InternalError();
904   return *p++;
905 }
906
907 static unsigned int
908 read_u2 (unsigned char *&p)
909 {
910   unsigned int b1 = *p++;
911   unsigned int b2 = *p++;
912   return (b1 << 8) | b2;
913 }
914
915 static unsigned int
916 read_u2 (unsigned char *&p, unsigned char *next)
917 {
918   if (next - p < 2)
919     throw new java::lang::InternalError();
920   return read_u2 (p);
921 }
922
923 static int
924 read_4 (unsigned char *&p)
925 {
926   int b1 = *p++;
927   int b2 = *p++;
928   int b3 = *p++;
929   int b4 = *p++;
930   return (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
931 }
932
933 jstring
934 java::lang::Class::getReflectionSignature (jint /*jv_attr_type*/ type,
935                                            jint obj_index)
936 {
937   // We just re-parse the bytecode for this data each time.  If
938   // necessary we can cache results, but I suspect this is not
939   // performance sensitive.
940   unsigned char *bytes = reflection_data;
941   if (bytes == NULL)
942     return NULL;
943   while (true)
944     {
945       int kind = read_u1 (bytes);
946       if (kind == JV_DONE_ATTR)
947         return NULL;
948       int len = read_4 (bytes);
949       unsigned char *next = bytes + len;
950       if (kind != type)
951         {
952           bytes = next;
953           continue;
954         }
955       if (type != JV_CLASS_ATTR)
956         {
957           unsigned short index = read_u2 (bytes, next);
958           if (index != obj_index)
959             {
960               bytes = next;
961               continue;
962             }
963         }
964       int nt = read_u1 (bytes, next);
965       if (nt != JV_SIGNATURE_KIND)
966         {
967           bytes = next;
968           continue;
969         }
970       unsigned int cpool_idx = read_u2 (bytes, next);
971       if (cpool_idx >= (unsigned int) constants.size
972           || constants.tags[cpool_idx] != JV_CONSTANT_Utf8)
973         {
974           // We just ignore errors for now.  It isn't clear what is
975           // best to do here, as an encoding error here means a bug
976           // either in the compiler or in defineclass.cc.
977           return NULL;
978         }
979       return _Jv_NewStringUtf8Const (constants.data[cpool_idx].utf8);
980     }
981 }
982
983 jstring
984 java::lang::Class::getReflectionSignature (::java::lang::reflect::Constructor *c)
985 {
986   _Jv_Method *meth = _Jv_FromReflectedConstructor (c);
987   unsigned short meth_index = meth - methods;
988   return getReflectionSignature (JV_METHOD_ATTR, meth_index);
989 }
990
991 jstring
992 java::lang::Class::getReflectionSignature (::java::lang::reflect::Method *m)
993 {
994   _Jv_Method *meth = _Jv_FromReflectedMethod (m);
995   unsigned short meth_index = meth - methods;
996   return getReflectionSignature (JV_METHOD_ATTR, meth_index);
997 }
998
999 jstring
1000 java::lang::Class::getReflectionSignature (::java::lang::reflect::Field *f)
1001 {
1002   _Jv_Field *fld = _Jv_FromReflectedField (f);
1003   unsigned short fld_index = fld - fields;
1004   return getReflectionSignature (JV_FIELD_ATTR, fld_index);
1005 }
1006
1007 jstring
1008 java::lang::Class::getClassSignature()
1009 {
1010   return getReflectionSignature (JV_CLASS_ATTR, 0);
1011 }
1012
1013 jint
1014 java::lang::Class::getEnclosingMethodData()
1015 {
1016   unsigned char *bytes = reflection_data;
1017   if (bytes == NULL)
1018     return 0;
1019   while (true)
1020     {
1021       int kind = read_u1 (bytes);
1022       if (kind == JV_DONE_ATTR)
1023         return 0;
1024       int len = read_4 (bytes);
1025       unsigned char *next = bytes + len;
1026       if (kind != JV_CLASS_ATTR)
1027         {
1028           bytes = next;
1029           continue;
1030         }
1031       int type = read_u1 (bytes, next);
1032       if (type != JV_ENCLOSING_METHOD_KIND)
1033         {
1034           bytes = next;
1035           continue;
1036         }
1037       int class_index = read_u2 (bytes, next);
1038       int method_index = read_u2 (bytes, next);
1039       _Jv_word result;
1040       _Jv_storeIndexes (&result, class_index, method_index);
1041       return result.i;
1042     }
1043 }
1044
1045 jclass
1046 java::lang::Class::getEnclosingClass()
1047 {
1048   _Jv_word indexes;
1049   indexes.i = getEnclosingMethodData();
1050   if (indexes.i == 0)
1051     // No enclosing method, but perhaps a member or anonymous class
1052     return getDeclaringClass();
1053   _Jv_ushort class_index, method_index;
1054   _Jv_loadIndexes (&indexes, class_index, method_index);
1055   return _Jv_Linker::resolve_pool_entry (this, class_index).clazz;
1056 }
1057
1058 ::java::lang::reflect::Method *
1059 java::lang::Class::getEnclosingMethod()
1060 {
1061   _Jv_word indexes;
1062   indexes.i = getEnclosingMethodData();
1063   if (indexes.i == 0)
1064     return NULL;
1065   _Jv_ushort class_index, method_index;
1066   _Jv_loadIndexes (&indexes, class_index, method_index);
1067   jclass found_class;
1068   _Jv_Method *method = _Jv_Linker::resolve_method_entry (this, found_class,
1069                                                          class_index,
1070                                                          method_index,
1071                                                          false, false);
1072   using namespace java::lang::reflect;
1073   Method *rmethod = new Method ();
1074   rmethod->offset = (char *) method - (char *) found_class->methods;
1075   rmethod->declaringClass = found_class;
1076   return rmethod;
1077 }
1078
1079 ::java::lang::reflect::Constructor *
1080 java::lang::Class::getEnclosingConstructor()
1081 {
1082   _Jv_word indexes;
1083   indexes.i = getEnclosingMethodData();
1084   if (indexes.i == 0)
1085     return NULL;
1086   _Jv_ushort class_index, method_index;
1087   _Jv_loadIndexes (&indexes, class_index, method_index);
1088   jclass found_class;
1089   _Jv_Method *method = _Jv_Linker::resolve_method_entry (this, found_class,
1090                                                          class_index,
1091                                                          method_index,
1092                                                          false, false);
1093   using namespace java::lang::reflect;
1094   Constructor *cons = new Constructor ();
1095   cons->offset = (char *) method - (char *) found_class->methods;
1096   cons->declaringClass = this;
1097   return cons;
1098 }
1099
1100 static void
1101 check_constant (_Jv_Constants *pool, jint cpool_index, jint type)
1102 {
1103   if (cpool_index <= 0 || cpool_index >= pool->size)
1104     throw new InternalError(JvNewStringLatin1("invalid constant pool index"));
1105   if ((pool->tags[cpool_index] & 
1106         ~(JV_CONSTANT_ResolvedFlag|JV_CONSTANT_LazyFlag)) != type)
1107     {
1108       ::java::lang::StringBuffer *sb = new ::java::lang::StringBuffer();
1109       sb->append(JvNewStringLatin1("expected pool constant "));
1110       sb->append(type);
1111       sb->append(JvNewStringLatin1(" but got "));
1112       sb->append(jint (pool->tags[cpool_index]));
1113       throw new InternalError(sb->toString());
1114     }
1115 }
1116
1117 // Forward declaration
1118 static ::java::lang::annotation::Annotation *
1119 parseAnnotation(jclass klass, _Jv_Constants *pool,
1120                 unsigned char *&bytes, unsigned char *last);
1121
1122 static jobject
1123 parseAnnotationElement(jclass klass, _Jv_Constants *pool,
1124                        unsigned char *&bytes, unsigned char *last)
1125 {
1126   int tag = read_u1 (bytes, last);
1127   jobject result;
1128   switch (tag)
1129     {
1130     case 'B':
1131       {
1132         int cindex = read_u2 (bytes, last);
1133         check_constant (pool, cindex, JV_CONSTANT_Integer);
1134         result = Byte::valueOf (pool->data[cindex].i);
1135       }
1136       break;
1137     case 'C':
1138       {
1139         int cindex = read_u2 (bytes, last);
1140         check_constant (pool, cindex, JV_CONSTANT_Integer);
1141         result = Character::valueOf (pool->data[cindex].i);
1142       }
1143       break;
1144     case 'S':
1145       {
1146         int cindex = read_u2 (bytes, last);
1147         check_constant (pool, cindex, JV_CONSTANT_Integer);
1148         result = Short::valueOf (pool->data[cindex].i);
1149       }
1150       break;
1151     case 'Z':
1152       {
1153         int cindex = read_u2 (bytes, last);
1154         check_constant (pool, cindex, JV_CONSTANT_Integer);
1155         result = Boolean::valueOf (jboolean (pool->data[cindex].i));
1156       }
1157       break;
1158     case 'I':
1159       {
1160         int cindex = read_u2 (bytes, last);
1161         check_constant (pool, cindex, JV_CONSTANT_Integer);
1162         result = Integer::valueOf (pool->data[cindex].i);
1163       }
1164       break;
1165     case 'D':
1166       {
1167         int cindex = read_u2 (bytes, last);
1168         check_constant (pool, cindex, JV_CONSTANT_Double);
1169         _Jv_word2 word;
1170         memcpy (&word, &pool->data[cindex], 2 * sizeof (_Jv_word));
1171         result = Double::valueOf (word.d);
1172       }
1173       break;
1174     case 'F':
1175       {
1176         int cindex = read_u2 (bytes, last);
1177         check_constant (pool, cindex, JV_CONSTANT_Float);
1178         result = Float::valueOf (pool->data[cindex].f);
1179       }
1180       break;
1181     case 'J':
1182       {
1183         int cindex = read_u2 (bytes, last);
1184         check_constant (pool, cindex, JV_CONSTANT_Long);
1185         _Jv_word2 word;
1186         memcpy (&word, &pool->data[cindex], 2 * sizeof (_Jv_word));
1187         result = Long::valueOf (word.l);
1188       }
1189       break;
1190     case 's':
1191       {
1192         int cindex = read_u2 (bytes, last);
1193         // Despite what the JVM spec says, compilers generate a Utf8
1194         // constant here, not a String.
1195         check_constant (pool, cindex, JV_CONSTANT_Utf8);
1196         result = pool->data[cindex].utf8->toString();
1197       }
1198       break;
1199     case 'e':
1200       {
1201         int type_name_index = read_u2 (bytes, last);
1202         check_constant (pool, type_name_index, JV_CONSTANT_Utf8);
1203         int const_name_index = read_u2 (bytes, last);
1204         check_constant (pool, const_name_index, JV_CONSTANT_Utf8);
1205
1206         _Jv_Utf8Const *u_name = pool->data[type_name_index].utf8;
1207         _Jv_Utf8Const *e_name = pool->data[const_name_index].utf8;
1208
1209         // FIXME: throw correct exceptions at the correct times.
1210         jclass e_class = _Jv_FindClassFromSignature(u_name->chars(),
1211                                                     klass->getClassLoaderInternal());
1212         result = ::java::lang::Enum::valueOf(e_class, e_name->toString());
1213       }
1214       break;
1215     case 'c':
1216       {
1217         int cindex = read_u2 (bytes, last);
1218         check_constant (pool, cindex, JV_CONSTANT_Utf8);
1219         _Jv_Utf8Const *u_name = pool->data[cindex].utf8;
1220         jclass anno_class
1221           = _Jv_FindClassFromSignatureNoException(u_name->chars(),
1222                                                   klass->getClassLoaderInternal());
1223         // FIXME: not correct: we should lazily do this when trying to
1224         // read the element.  This means that
1225         // AnnotationInvocationHandler needs to have a special case.
1226         if (! anno_class)
1227           // FIXME: original exception...
1228           throw new TypeNotPresentException(u_name->toString(), NULL);
1229         result = anno_class;
1230       }
1231       break;
1232     case '@':
1233       result = parseAnnotation (klass, pool, bytes, last);
1234       break;
1235     case '[':
1236       {
1237         int n_array_elts = read_u2 (bytes, last);
1238         jobjectArray aresult = _Jv_NewObjectArray (n_array_elts,
1239                                                    &Object::class$, NULL);
1240         jobject *elts = elements (aresult);
1241         for (int i = 0; i < n_array_elts; ++i)
1242           elts[i] = parseAnnotationElement(klass, pool, bytes, last);
1243         result = aresult;
1244       }
1245       break;
1246     default:
1247       throw new java::lang::InternalError();
1248     }
1249   return result;
1250 }
1251
1252 static ::java::lang::annotation::Annotation *
1253 parseAnnotation(jclass klass, _Jv_Constants *pool,
1254                 unsigned char *&bytes, unsigned char *last)
1255 {
1256   int type_index = read_u2 (bytes, last);
1257   check_constant (pool, type_index, JV_CONSTANT_Utf8);
1258
1259   _Jv_Utf8Const *u_name = pool->data[type_index].utf8;
1260   jclass anno_class = _Jv_FindClassFromSignatureNoException(u_name->chars(),
1261                                                             klass->getClassLoaderInternal());
1262   // FIXME: what to do if anno_class==NULL?
1263
1264   ::java::util::HashMap *hmap = new ::java::util::HashMap();
1265   int npairs = read_u2 (bytes, last);
1266   for (int i = 0; i < npairs; ++i)
1267     {
1268       int name_index = read_u2 (bytes, last);
1269       check_constant (pool, name_index, JV_CONSTANT_Utf8);
1270       jstring name = _Jv_NewStringUtf8Const (pool->data[name_index].utf8);
1271       jobject value = parseAnnotationElement (klass, pool, bytes, last);
1272       // FIXME: any checks needed for name?
1273       hmap->put(name, value);
1274     }
1275   using namespace ::sun::reflect::annotation;
1276   return AnnotationInvocationHandler::create (anno_class,
1277                                               (::java::util::Map *) hmap);
1278 }
1279
1280 static jobjectArray
1281 parseAnnotations(jclass klass, _Jv_Constants *pool,
1282                  unsigned char *&bytes, unsigned char *last)
1283 {
1284   int num = read_u2 (bytes, last);
1285   jobjectArray result = _Jv_NewObjectArray (num,
1286                                             &::java::lang::annotation::Annotation::class$,
1287                                             NULL);
1288   jobject *elts = elements (result);
1289   for (int i = 0; i < num; ++i)
1290     elts[i] = parseAnnotation(klass, pool, bytes, last);
1291   return result;
1292 }
1293
1294 static jobjectArray
1295 parseParameterAnnotations(jclass klass, _Jv_Constants *pool,
1296                           unsigned char *&bytes, unsigned char *last)
1297 {
1298   jclass anno = &::java::lang::annotation::Annotation::class$;
1299   jclass annoary = _Jv_GetArrayClass (anno, anno->getClassLoaderInternal());
1300
1301   // FIXME: something should check the number of params versus the
1302   // method
1303   int n_params = read_u1 (bytes, last);
1304   jobjectArray result = _Jv_NewObjectArray (n_params, annoary, NULL);
1305   jobject *elts = elements (result);
1306   for (int i = 0; i < n_params; ++i)
1307     elts[i] = parseAnnotations(klass, pool, bytes, last);
1308   return result;
1309 }
1310
1311 jobject
1312 java::lang::Class::getMethodDefaultValue(::java::lang::reflect::Method *meth)
1313 {
1314   // FIXME: could cache the value here...
1315
1316   unsigned char *bytes = reflection_data;
1317   if (bytes == NULL)
1318     return 0;
1319
1320   unsigned short meth_index = _Jv_FromReflectedMethod (meth) - methods;
1321
1322   while (true)
1323     {
1324       int type = read_u1 (bytes);
1325       if (type == JV_DONE_ATTR)
1326         return NULL;
1327       int len = read_4 (bytes);
1328       unsigned char *next = bytes + len;
1329       if (type != JV_METHOD_ATTR)
1330         {
1331           bytes = next;
1332           continue;
1333         }
1334       int kind = read_u1 (bytes, next);
1335       if (kind != JV_ANNOTATION_DEFAULT_KIND)
1336         {
1337           bytes = next;
1338           continue;
1339         }
1340       int index = read_u2 (bytes, next);
1341       if (meth_index != index)
1342         {
1343           bytes = next;
1344           continue;
1345         }
1346
1347       // FIXME: could cache here.  If we do then we have to clone any
1348       // array result.
1349       return parseAnnotationElement(this, &this->constants, bytes, next);
1350     }
1351 }
1352
1353 jobjectArray
1354 java::lang::Class::getDeclaredAnnotations(jint /* jv_attr_type */ member_type,
1355                                           jint member_index,
1356                                           jint /* jv_attr_kind */ kind_req)
1357 {
1358   using namespace java::lang::annotation;
1359   jobjectArray result;
1360
1361   unsigned char *bytes = reflection_data;
1362   if (bytes == NULL)
1363     return 0;
1364
1365   if (loader == NULL)
1366     loader = (ClassLoader *)VMClassLoader::bootLoader;
1367
1368   result = (loader->getDeclaredAnnotations
1369             (this, member_type, member_index, kind_req));
1370   if (result)
1371     return result;
1372
1373   for (;;)
1374     {
1375       int type = read_u1 (bytes);
1376       if (type == JV_DONE_ATTR)
1377         return NULL;
1378       int len = read_4 (bytes);
1379       unsigned char *next = bytes + len;
1380       if (type != member_type)
1381         {
1382           bytes = next;
1383           continue;
1384         }
1385       int kind = read_u1 (bytes, next);
1386       if (kind != kind_req)
1387         {
1388           bytes = next;
1389           continue;
1390         }
1391       if (member_type != JV_CLASS_ATTR)
1392         {
1393           int index = read_u2 (bytes, next);
1394           if (member_index != index)
1395             {
1396               bytes = next;
1397               continue;
1398             }
1399         }
1400
1401       if (kind_req == JV_PARAMETER_ANNOTATIONS_KIND)
1402         result = ((parseParameterAnnotations 
1403                    (this, &this->constants, bytes, next)));
1404       else
1405         result = ((parseAnnotations (this, &this->constants, bytes, next)));
1406       break;
1407     }
1408
1409   return (loader->putDeclaredAnnotations
1410           (this, member_type, member_index, kind_req, result));
1411 }
1412
1413 jobjectArray
1414 java::lang::Class::getDeclaredAnnotations(::java::lang::reflect::Method *meth,
1415                                           jboolean is_param)
1416 {
1417   unsigned short meth_index = _Jv_FromReflectedMethod (meth) - methods;
1418   return getDeclaredAnnotations(JV_METHOD_ATTR, meth_index,
1419                                 (is_param
1420                                  ? JV_PARAMETER_ANNOTATIONS_KIND
1421                                  : JV_ANNOTATIONS_KIND));
1422 }
1423
1424 jobjectArray
1425 java::lang::Class::getDeclaredAnnotations(::java::lang::reflect::Constructor *cons,
1426                                           jboolean is_param)
1427 {
1428   unsigned short meth_index = _Jv_FromReflectedConstructor (cons) - methods;
1429   return getDeclaredAnnotations(JV_METHOD_ATTR, meth_index,
1430                                 (is_param
1431                                  ? JV_PARAMETER_ANNOTATIONS_KIND
1432                                  : JV_ANNOTATIONS_KIND));
1433 }
1434
1435 jobjectArray
1436 java::lang::Class::getDeclaredAnnotations(::java::lang::reflect::Field *fld)
1437 {
1438   unsigned short field_index = _Jv_FromReflectedField (fld) - fields;
1439   return getDeclaredAnnotations(JV_FIELD_ATTR, field_index,
1440                                 JV_ANNOTATIONS_KIND);
1441 }
1442
1443 JArray< ::java::lang::annotation::Annotation *> *
1444 java::lang::Class::getDeclaredAnnotationsInternal()
1445 {
1446   return (JArray< ::java::lang::annotation::Annotation *> *) getDeclaredAnnotations(JV_CLASS_ATTR, 0, JV_ANNOTATIONS_KIND);
1447 }
1448
1449 static jclass
1450 resolve_class_constant (jclass klass, _Jv_Constants *pool, int cpool_index)
1451 {
1452   check_constant (pool, cpool_index, JV_CONSTANT_Class);
1453   // FIXME: what is the correct thing to do with an exception here?
1454   return _Jv_Linker::resolve_pool_entry (klass, cpool_index, false).clazz;
1455 }
1456
1457 jint
1458 java::lang::Class::findInnerClassAttribute()
1459 {
1460   unsigned char *bytes = reflection_data;
1461   if (bytes == NULL)
1462     return -1;
1463   while (true)
1464     {
1465       int type = read_u1 (bytes);
1466       if (type == JV_DONE_ATTR)
1467         break;
1468       // After the type but before the length.
1469       unsigned char *save = bytes;
1470       int len = read_4 (bytes);
1471       unsigned char *next = bytes + len;
1472       if (type != JV_CLASS_ATTR)
1473         {
1474           bytes = next;
1475           continue;
1476         }
1477       int kind = read_u1 (bytes, next);
1478       if (kind != JV_INNER_CLASSES_KIND)
1479         {
1480           bytes = next;
1481           continue;
1482         }
1483       return save - reflection_data;
1484     }
1485   return -1;
1486 }
1487
1488 jint
1489 java::lang::Class::findDeclaredClasses(JArray<jclass> *result,
1490                                        jboolean publicOnly,
1491                                        jint offset)
1492 {
1493   unsigned char *bytes = reflection_data + offset;
1494   int len = read_4 (bytes);
1495   unsigned char *next = bytes + len;
1496   // Skip a byte.
1497   read_u1 (bytes, next);
1498   int n_classes = read_u2 (bytes, next);
1499   int count = 0;
1500   for (int i = 0; i < n_classes; ++i)
1501     {
1502       int inner_class_index = read_u2 (bytes, next);
1503       int outer_class_index = read_u2 (bytes, next);
1504       /*int inner_name_index = */ read_u2 (bytes, next);
1505       int inner_flags = read_u2 (bytes, next);
1506
1507       if (inner_class_index == 0 || outer_class_index == 0)
1508         continue;
1509       if (resolve_class_constant (this, &constants, outer_class_index) == this)
1510         {
1511           jclass inner = resolve_class_constant (this, &constants,
1512                                                  inner_class_index);
1513           if (! publicOnly
1514               || ((inner_flags
1515                    & java::lang::reflect::Modifier::PUBLIC) != 0))
1516             {
1517               if (result)
1518                 {
1519                   jclass *elts = elements (result);
1520                   elts[count] = inner;
1521                 }
1522               ++count;
1523             }
1524         }
1525     }
1526
1527   return count;
1528 }
1529
1530 JArray<jclass> *
1531 java::lang::Class::getDeclaredClasses (jboolean publicOnly)
1532 {
1533   int offset = findInnerClassAttribute();
1534   int count;
1535   if (offset == -1)
1536     {
1537       // No InnerClasses attribute, so no declared classes.
1538       count = 0;
1539     }
1540   else
1541     count = findDeclaredClasses(NULL, publicOnly, offset);
1542   JArray<jclass> *result
1543     = (JArray<jclass> *) JvNewObjectArray (count, &java::lang::Class::class$,
1544                                            NULL);
1545   if (count > 0)
1546     findDeclaredClasses(result, publicOnly, offset);
1547   return result;
1548 }
1549
1550 jclass
1551 java::lang::Class::getDeclaringClass (void)
1552 {
1553   int offset = findInnerClassAttribute();
1554   if (offset == -1)
1555     return NULL;
1556
1557   unsigned char *bytes = reflection_data + offset;
1558   int len = read_4 (bytes);
1559   unsigned char *next = bytes + len;
1560   // Skip a byte.
1561   read_u1 (bytes, next);
1562   int n_classes = read_u2 (bytes, next);
1563   for (int i = 0; i < n_classes; ++i)
1564     {
1565       int inner_class_index = read_u2 (bytes, next);
1566       int outer_class_index = read_u2 (bytes, next);
1567       /*int inner_name_index = */read_u2 (bytes, next);
1568       /*int inner_flags = */read_u2 (bytes, next);
1569
1570       if (inner_class_index == 0 || outer_class_index == 0)
1571         continue;
1572       if (resolve_class_constant (this, &constants, inner_class_index) == this)
1573         return resolve_class_constant (this, &constants, outer_class_index);
1574     }
1575
1576   return NULL;
1577 }
1578
1579 jboolean
1580 java::lang::Class::isAnonymousClass()
1581 {
1582   int offset = findInnerClassAttribute();
1583   if (offset == -1)
1584     return false;
1585
1586   unsigned char *bytes = reflection_data + offset;
1587   int len = read_4 (bytes);
1588   unsigned char *next = bytes + len;
1589   // Skip a byte.
1590   read_u1 (bytes, next);
1591   int n_classes = read_u2 (bytes, next);
1592   for (int i = 0; i < n_classes; ++i)
1593     {
1594       int inner_class_index = read_u2 (bytes, next);
1595       /*int outer_class_index = */read_u2 (bytes, next);
1596       int inner_name_index = read_u2 (bytes, next);
1597       /*int inner_flags = */read_u2 (bytes, next);
1598
1599       if (inner_class_index == 0)
1600         continue;
1601       if (resolve_class_constant (this, &constants, inner_class_index) == this)
1602         return inner_name_index == 0;
1603     }
1604
1605   return false;
1606 }
1607
1608 jboolean
1609 java::lang::Class::isLocalClass()
1610 {
1611   _Jv_word indexes;
1612   indexes.i = getEnclosingMethodData();
1613   return indexes.i != 0;
1614 }
1615
1616 jboolean
1617 java::lang::Class::isMemberClass()
1618 {
1619   // FIXME: is this correct?
1620   return !isLocalClass() && getDeclaringClass() != NULL;
1621 }
1622
1623 \f
1624
1625 //
1626 // Some class-related convenience functions.
1627 //
1628
1629 // Find a method declared in the class.  If it is not declared locally
1630 // (or if it is inherited), return NULL.
1631 _Jv_Method *
1632 _Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
1633                     _Jv_Utf8Const *signature)
1634 {
1635   for (int i = 0; i < klass->method_count; ++i)
1636     {
1637       if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
1638           && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
1639         return &klass->methods[i];
1640     }
1641   return NULL;
1642 }
1643
1644 _Jv_Method *
1645 _Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
1646                           _Jv_Utf8Const *signature,
1647                           jclass *declarer_result)
1648 {
1649   for (; klass; klass = klass->getSuperclass())
1650     {
1651       _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
1652
1653       if (meth)
1654         {
1655           if (declarer_result)
1656             *declarer_result = klass;
1657           return meth;
1658         }
1659     }
1660
1661   return NULL;
1662 }
1663
1664 java::lang::reflect::Method *
1665 _Jv_GetReflectedMethod (jclass klass, _Jv_Utf8Const *name,
1666                        _Jv_Utf8Const *signature)
1667 {
1668   for (; klass; klass = klass->getSuperclass())
1669     {
1670       _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
1671       if (meth)
1672         {
1673           using namespace java::lang::reflect;
1674           Method *rmethod = new Method ();
1675           rmethod->offset = (char*) meth - (char*) klass->methods;
1676           rmethod->declaringClass = klass;
1677           return rmethod;
1678         }
1679     }
1680   
1681   return NULL;
1682 }
1683
1684 #ifdef HAVE_TLS
1685
1686 // NOTE: MCACHE_SIZE should be a power of 2 minus one.
1687 #define MCACHE_SIZE 31
1688
1689 struct _Jv_mcache
1690 {
1691   jclass klass;
1692   _Jv_Method *method;
1693 };
1694
1695 static __thread _Jv_mcache *method_cache;
1696 #endif // HAVE_TLS
1697
1698 static void *
1699 _Jv_FindMethodInCache (jclass klass MAYBE_UNUSED,
1700                        _Jv_Utf8Const *name MAYBE_UNUSED,
1701                        _Jv_Utf8Const *signature MAYBE_UNUSED)
1702 {
1703 #ifdef HAVE_TLS
1704   _Jv_mcache *cache = method_cache;
1705   if (cache)
1706     {
1707       int index = name->hash16 () & MCACHE_SIZE;
1708       _Jv_mcache *mc = &cache[index];
1709       _Jv_Method *m = mc->method;
1710
1711       if (mc->klass == klass
1712           && _Jv_equalUtf8Consts (m->name, name)
1713           && _Jv_equalUtf8Consts (m->signature, signature))
1714         return mc->method->ncode;
1715     }
1716 #endif // HAVE_TLS
1717   return NULL;
1718 }
1719
1720 static void
1721 _Jv_AddMethodToCache (jclass klass MAYBE_UNUSED,
1722                       _Jv_Method *method MAYBE_UNUSED)
1723 {
1724 #ifdef HAVE_TLS
1725   if (method_cache == NULL)
1726     method_cache = (_Jv_mcache *) _Jv_MallocUnchecked((MCACHE_SIZE + 1)
1727                                                       * sizeof (_Jv_mcache));
1728   // If the allocation failed, just keep going.
1729   if (method_cache != NULL)
1730     {
1731       int index = method->name->hash16 () & MCACHE_SIZE;
1732       method_cache[index].method = method;
1733       method_cache[index].klass = klass;
1734     }
1735 #endif // HAVE_TLS
1736 }
1737
1738 // Free this thread's method cache.  We explicitly manage this memory
1739 // as the GC does not yet know how to scan TLS on all platforms.
1740 void
1741 _Jv_FreeMethodCache ()
1742 {
1743 #ifdef HAVE_TLS
1744   if (method_cache != NULL)
1745     {
1746       _Jv_Free(method_cache);
1747       method_cache = NULL;
1748     }
1749 #endif // HAVE_TLS
1750 }
1751
1752 void *
1753 _Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
1754                            _Jv_Utf8Const *signature)
1755 {
1756   using namespace java::lang::reflect;
1757
1758   void *ncode = _Jv_FindMethodInCache (klass, name, signature);
1759   if (ncode != 0)
1760     return ncode;
1761
1762   for (; klass; klass = klass->getSuperclass())
1763     {
1764       _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
1765       if (! meth)
1766         continue;
1767
1768       if (Modifier::isStatic(meth->accflags))
1769         throw new java::lang::IncompatibleClassChangeError
1770           (_Jv_GetMethodString (klass, meth));
1771       if (Modifier::isAbstract(meth->accflags))
1772         throw new java::lang::AbstractMethodError
1773           (_Jv_GetMethodString (klass, meth));
1774       if (! Modifier::isPublic(meth->accflags))
1775         throw new java::lang::IllegalAccessError
1776           (_Jv_GetMethodString (klass, meth));
1777
1778       _Jv_AddMethodToCache (klass, meth);
1779
1780       return meth->ncode;
1781     }
1782   throw new java::lang::IncompatibleClassChangeError;
1783 }
1784
1785 // Fast interface method lookup by index.
1786 void *
1787 _Jv_LookupInterfaceMethodIdx (jclass klass, jclass iface, int method_idx)
1788 {
1789   _Jv_IDispatchTable *cldt = klass->idt;
1790   int idx = iface->ioffsets[cldt->iindex] + method_idx;
1791   return cldt->itable[idx];
1792 }
1793
1794 jboolean
1795 _Jv_IsAssignableFrom (jclass source, jclass target)
1796 {
1797   if (source == target)
1798     return true;
1799
1800   // If target is array, so must source be.  
1801   while (target->isArray ())
1802     {
1803       if (! source->isArray())
1804         return false;
1805       target = target->getComponentType();
1806       source = source->getComponentType();
1807     }
1808
1809   if (target->isInterface())
1810     {
1811       // Abstract classes have no IDT, and IDTs provide no way to check
1812       // two interfaces for assignability.
1813       if (__builtin_expect 
1814           (source->idt == NULL || source->isInterface(), false))
1815         return _Jv_InterfaceAssignableFrom (source, target);
1816
1817       _Jv_IDispatchTable *cl_idt = source->idt;
1818
1819       if (__builtin_expect ((target->ioffsets == NULL), false))
1820         return false; // No class implementing TARGET has been loaded.    
1821       jshort cl_iindex = cl_idt->iindex;
1822       if (cl_iindex < target->ioffsets[0])
1823         {
1824           jshort offset = target->ioffsets[cl_iindex];
1825           if (offset != -1 && offset < cl_idt->itable_length
1826               && cl_idt->itable[offset] == target)
1827             return true;
1828         }
1829       return false;
1830     }
1831
1832   // Primitive TYPE classes are only assignable to themselves.
1833   if (__builtin_expect (target->isPrimitive() || source->isPrimitive(), false))
1834     return false;
1835
1836   if (target == &java::lang::Object::class$)
1837     return true;
1838   else if (source->ancestors == NULL || target->ancestors == NULL)
1839     {
1840       // We need this case when either SOURCE or TARGET has not has
1841       // its constant-time tables prepared.
1842
1843       // At this point we know that TARGET can't be Object, so it is
1844       // safe to use that as the termination point.
1845       while (source && source != &java::lang::Object::class$)
1846         {
1847           if (source == target)
1848             return true;
1849           source = source->getSuperclass();
1850         }
1851     }
1852   else if (source->depth >= target->depth
1853            && source->ancestors[source->depth - target->depth] == target)
1854     return true;
1855
1856   return false;
1857 }
1858
1859 // Interface type checking, the slow way. Returns TRUE if IFACE is a 
1860 // superinterface of SOURCE. This is used when SOURCE is also an interface,
1861 // or a class with no interface dispatch table.
1862 jboolean
1863 _Jv_InterfaceAssignableFrom (jclass source, jclass iface)
1864 {
1865   for (int i = 0; i < source->interface_count; i++)
1866     {
1867       jclass interface = source->interfaces[i];
1868       if (iface == interface
1869           || _Jv_InterfaceAssignableFrom (interface, iface))
1870         return true;      
1871     }
1872     
1873   if (!source->isInterface()
1874       && source->superclass 
1875       && _Jv_InterfaceAssignableFrom (source->superclass, iface))
1876     return true;
1877         
1878   return false;
1879 }
1880
1881 jboolean
1882 _Jv_IsInstanceOf(jobject obj, jclass cl)
1883 {
1884   if (__builtin_expect (!obj, false))
1885     return false;
1886   return _Jv_IsAssignableFrom (JV_CLASS (obj), cl);
1887 }
1888
1889 void *
1890 _Jv_CheckCast (jclass c, jobject obj)
1891 {
1892   if (__builtin_expect 
1893       (obj != NULL && ! _Jv_IsAssignableFrom(JV_CLASS (obj), c), false))
1894     throw new java::lang::ClassCastException
1895       ((new java::lang::StringBuffer
1896         (obj->getClass()->getName()))->append
1897        (JvNewStringUTF(" cannot be cast to "))->append
1898        (c->getName())->toString());
1899
1900   return obj;
1901 }
1902
1903 void
1904 _Jv_CheckArrayStore (jobject arr, jobject obj)
1905 {
1906   if (obj)
1907     {
1908       JvAssert (arr != NULL);
1909       jclass elt_class = (JV_CLASS (arr))->getComponentType();
1910       if (elt_class == &java::lang::Object::class$)
1911         return;
1912       jclass obj_class = JV_CLASS (obj);
1913       if (__builtin_expect 
1914           (! _Jv_IsAssignableFrom (obj_class, elt_class), false))
1915         throw new java::lang::ArrayStoreException
1916                 ((new java::lang::StringBuffer
1917                  (JvNewStringUTF("Cannot store ")))->append
1918                  (obj_class->getName())->append
1919                  (JvNewStringUTF(" in array of type "))->append
1920                  (elt_class->getName())->toString());
1921     }
1922 }
1923
1924 jboolean
1925 _Jv_IsAssignableFromSlow (jclass source, jclass target)
1926 {
1927   // First, strip arrays.
1928   while (target->isArray ())
1929     {
1930       // If target is array, source must be as well.
1931       if (! source->isArray ())
1932        return false;
1933       target = target->getComponentType ();
1934       source = source->getComponentType ();
1935     }
1936
1937   // Quick success.
1938   if (target == &java::lang::Object::class$)
1939     return true;
1940
1941   // Ensure that the classes have their supers installed.
1942   _Jv_Linker::wait_for_state (source, JV_STATE_LOADING);
1943   _Jv_Linker::wait_for_state (target, JV_STATE_LOADING);
1944
1945   do
1946     {
1947       if (source == target)
1948        return true;
1949
1950       if (target->isPrimitive () || source->isPrimitive ())
1951        return false;
1952
1953       if (target->isInterface ())
1954        {
1955          for (int i = 0; i < source->interface_count; ++i)
1956            {
1957              // We use a recursive call because we also need to
1958              // check superinterfaces.
1959              if (_Jv_IsAssignableFromSlow (source->getInterface (i), target))
1960                return true;
1961            }
1962        }
1963       source = source->getSuperclass ();
1964     }
1965   while (source != NULL);
1966
1967   return false;
1968 }
1969
1970 // Lookup an interface method by name.  This is very similar to
1971 // purpose to _getMethod, but the interfaces are quite different.  It
1972 // might be a good idea for _getMethod to call this function.
1973 //
1974 // Return true of the method is found, with the class in FOUND_CLASS
1975 // and the index in INDEX.
1976 bool
1977 _Jv_getInterfaceMethod (jclass search_class, jclass &found_class, int &index,
1978                         const _Jv_Utf8Const *utf_name,  
1979                         const _Jv_Utf8Const *utf_sig)
1980 {
1981    for (jclass klass = search_class; klass; klass = klass->getSuperclass())
1982     {
1983       // FIXME: Throw an exception?
1984       if (!klass->isInterface ())
1985         return false;
1986       
1987       int max = klass->method_count;
1988       int offset = 0;
1989       for (int i = 0; i < max; ++i)
1990         {
1991           // Skip <clinit> here, as it will not be in the IDT.
1992           if (klass->methods[i].name->first() == '<')
1993             continue;
1994
1995           if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
1996               && _Jv_equalUtf8Consts (klass->methods[i].signature, utf_sig))
1997             {
1998               // Found it.
1999               using namespace java::lang::reflect;
2000
2001               // FIXME: Method must be public.  Throw an exception?
2002               if (! Modifier::isPublic (klass->methods[i].accflags))
2003                 break;
2004
2005               found_class = klass;
2006               // Interface method indexes count from 1.
2007               index = offset + 1;
2008               return true;
2009             }
2010
2011           ++offset;
2012         }
2013     }
2014
2015   // If we haven't found a match, and this class is an interface, then
2016   // check all the superinterfaces.
2017   if (search_class->isInterface())
2018     {
2019       for (int i = 0; i < search_class->interface_count; ++i)
2020         {
2021           using namespace java::lang::reflect;
2022           bool found = _Jv_getInterfaceMethod (search_class->interfaces[i], 
2023                                                found_class, index,
2024                                                utf_name, utf_sig);
2025           if (found)
2026             return true;
2027         }
2028     }
2029
2030   return false;
2031 }
2032
2033 #ifdef INTERPRETER
2034 _Jv_MethodBase *
2035 _Jv_FindInterpreterMethod (jclass klass, jmethodID desired_method)
2036 {
2037   using namespace java::lang::reflect;
2038
2039   _Jv_InterpClass *iclass
2040     = reinterpret_cast<_Jv_InterpClass *> (klass->aux_info);
2041   _Jv_MethodBase **imethods = _Jv_GetFirstMethod (iclass);
2042
2043   for (int i = 0; i < JvNumMethods (klass); ++i)
2044     {
2045       _Jv_MethodBase *imeth = imethods[i];
2046       if (imeth->get_method () == desired_method)
2047         return imeth;
2048     }
2049
2050   return NULL;
2051 }
2052 #endif
2053
2054 // Return Utf8 name of a class. This function is here for code that
2055 // can't access klass->name directly.
2056 _Jv_Utf8Const*
2057 _Jv_GetClassNameUtf8 (jclass klass)
2058 {
2059   return klass->name;
2060 }
2061
2062 jclass
2063 _Jv_GetMethodDeclaringClass (jmethodID method)
2064 {
2065   _Jv_StackTrace::UpdateNCodeMap ();
2066   jobject obj = reinterpret_cast<jobject> (method->ncode);
2067   return reinterpret_cast<jclass> (_Jv_StackTrace::ncodeMap->get (obj));
2068 }
2069
2070 jbyte
2071 _Jv_GetClassState (jclass klass)
2072 {
2073   return klass->state;
2074 }
2075
2076 #ifdef INTERPRETER
2077 jstring
2078 _Jv_GetInterpClassSourceFile (jclass klass)
2079 {
2080   if (_Jv_IsInterpretedClass (klass))
2081     {
2082       _Jv_InterpClass *iclass =
2083         reinterpret_cast<_Jv_InterpClass *> (klass->aux_info);
2084       return iclass->source_file_name;
2085     }
2086
2087   return NULL;
2088 }
2089 #endif