* config/rs6000/rs6000.c (rs6000_return_in_memory): Allow Altivec
[official-gcc.git] / libjava / java / lang / natClass.cc
blob920245cd586f6587835932f46cc6f645b678413c
1 // natClass.cc - Implementation of java.lang.Class native methods.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004
4 Free Software Foundation
6 This file is part of libgcj.
8 This software is copyrighted work licensed under the terms of the
9 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
10 details. */
12 #include <config.h>
14 #include <limits.h>
15 #include <string.h>
16 #include <stddef.h>
18 #pragma implementation "Class.h"
20 #include <gcj/cni.h>
21 #include <jvm.h>
22 #include <java-threads.h>
24 #include <java/lang/Class.h>
25 #include <java/lang/ClassLoader.h>
26 #include <java/lang/String.h>
27 #include <java/lang/reflect/Modifier.h>
28 #include <java/lang/reflect/Member.h>
29 #include <java/lang/reflect/Method.h>
30 #include <java/lang/reflect/Field.h>
31 #include <java/lang/reflect/Constructor.h>
32 #include <java/lang/AbstractMethodError.h>
33 #include <java/lang/ArrayStoreException.h>
34 #include <java/lang/ClassCastException.h>
35 #include <java/lang/ClassNotFoundException.h>
36 #include <java/lang/ExceptionInInitializerError.h>
37 #include <java/lang/IllegalAccessException.h>
38 #include <java/lang/IllegalAccessError.h>
39 #include <java/lang/IllegalArgumentException.h>
40 #include <java/lang/IncompatibleClassChangeError.h>
41 #include <java/lang/NoSuchFieldError.h>
42 #include <java/lang/ArrayIndexOutOfBoundsException.h>
43 #include <java/lang/InstantiationException.h>
44 #include <java/lang/NoClassDefFoundError.h>
45 #include <java/lang/NoSuchFieldException.h>
46 #include <java/lang/NoSuchMethodError.h>
47 #include <java/lang/NoSuchMethodException.h>
48 #include <java/lang/Thread.h>
49 #include <java/lang/NullPointerException.h>
50 #include <java/lang/RuntimePermission.h>
51 #include <java/lang/System.h>
52 #include <java/lang/SecurityManager.h>
53 #include <java/lang/StringBuffer.h>
54 #include <java/lang/VMClassLoader.h>
55 #include <gnu/gcj/runtime/StackTrace.h>
56 #include <gcj/method.h>
57 #include <gnu/gcj/runtime/MethodRef.h>
58 #include <gnu/gcj/RawData.h>
60 #include <java-cpool.h>
61 #include <java-interp.h>
65 using namespace gcj;
67 bool gcj::verbose_class_flag;
69 jclass
70 java::lang::Class::forName (jstring className, jboolean initialize,
71 java::lang::ClassLoader *loader)
73 if (! className)
74 throw new java::lang::NullPointerException;
76 jsize length = _Jv_GetStringUTFLength (className);
77 char buffer[length];
78 _Jv_GetStringUTFRegion (className, 0, className->length(), buffer);
80 _Jv_Utf8Const *name = _Jv_makeUtf8Const (buffer, length);
82 if (! _Jv_VerifyClassName (name))
83 throw new java::lang::ClassNotFoundException (className);
85 jclass klass = (buffer[0] == '['
86 ? _Jv_FindClassFromSignature (name->chars(), loader)
87 : _Jv_FindClass (name, loader));
89 if (klass == NULL)
90 throw new java::lang::ClassNotFoundException (className);
92 if (initialize)
93 _Jv_InitClass (klass);
95 return klass;
98 jclass
99 java::lang::Class::forName (jstring className)
101 java::lang::ClassLoader *loader = NULL;
102 gnu::gcj::runtime::StackTrace *t
103 = new gnu::gcj::runtime::StackTrace(4);
104 java::lang::Class *klass = NULL;
107 for (int i = 1; !klass; i++)
109 klass = t->classAt (i);
111 loader = klass->getClassLoaderInternal();
113 catch (::java::lang::ArrayIndexOutOfBoundsException *e)
117 return forName (className, true, loader);
120 java::lang::ClassLoader *
121 java::lang::Class::getClassLoader (void)
123 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
124 if (s != NULL)
126 gnu::gcj::runtime::StackTrace *t
127 = new gnu::gcj::runtime::StackTrace(4);
128 Class *caller = NULL;
129 ClassLoader *caller_loader = NULL;
132 for (int i = 1; !caller; i++)
134 caller = t->classAt (i);
136 caller_loader = caller->getClassLoaderInternal();
138 catch (::java::lang::ArrayIndexOutOfBoundsException *e)
142 // If the caller has a non-null class loader, and that loader
143 // is not this class' loader or an ancestor thereof, then do a
144 // security check.
145 if (caller_loader != NULL && ! caller_loader->isAncestorOf(loader))
146 s->checkPermission (new RuntimePermission (JvNewStringLatin1 ("getClassLoader")));
149 // The spec requires us to return `null' for primitive classes. In
150 // other cases we have the option of returning `null' for classes
151 // loaded with the bootstrap loader. All gcj-compiled classes which
152 // are linked into the application used to return `null' here, but
153 // that confuses some poorly-written applications. It is a useful
154 // and apparently harmless compatibility hack to simply never return
155 // `null' instead.
156 if (isPrimitive ())
157 return NULL;
158 return loader ? loader : ClassLoader::systemClassLoader;
161 java::lang::reflect::Constructor *
162 java::lang::Class::getConstructor (JArray<jclass> *param_types)
164 memberAccessCheck(java::lang::reflect::Member::PUBLIC);
166 jstring partial_sig = getSignature (param_types, true);
167 jint hash = partial_sig->hashCode ();
169 int i = isPrimitive () ? 0 : method_count;
170 while (--i >= 0)
172 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
173 && _Jv_equal (methods[i].signature, partial_sig, hash))
175 // Found it. For getConstructor, the constructor must be
176 // public.
177 using namespace java::lang::reflect;
178 if (! Modifier::isPublic(methods[i].accflags))
179 break;
180 Constructor *cons = new Constructor ();
181 cons->offset = (char *) (&methods[i]) - (char *) methods;
182 cons->declaringClass = this;
183 return cons;
186 throw new java::lang::NoSuchMethodException (_Jv_NewStringUtf8Const (init_name));
189 JArray<java::lang::reflect::Constructor *> *
190 java::lang::Class::_getConstructors (jboolean declared)
192 memberAccessCheck(java::lang::reflect::Member::PUBLIC);
194 int numConstructors = 0;
195 int max = isPrimitive () ? 0 : method_count;
196 int i;
197 for (i = max; --i >= 0; )
199 _Jv_Method *method = &methods[i];
200 if (method->name == NULL
201 || ! _Jv_equalUtf8Consts (method->name, init_name))
202 continue;
203 if (! declared
204 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
205 continue;
206 numConstructors++;
208 JArray<java::lang::reflect::Constructor *> *result
209 = (JArray<java::lang::reflect::Constructor *> *)
210 JvNewObjectArray (numConstructors,
211 &java::lang::reflect::Constructor::class$,
212 NULL);
213 java::lang::reflect::Constructor** cptr = elements (result);
214 for (i = 0; i < max; i++)
216 _Jv_Method *method = &methods[i];
217 if (method->name == NULL
218 || ! _Jv_equalUtf8Consts (method->name, init_name))
219 continue;
220 if (! declared
221 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
222 continue;
223 java::lang::reflect::Constructor *cons
224 = new java::lang::reflect::Constructor ();
225 cons->offset = (char *) method - (char *) methods;
226 cons->declaringClass = this;
227 *cptr++ = cons;
229 return result;
232 java::lang::reflect::Constructor *
233 java::lang::Class::getDeclaredConstructor (JArray<jclass> *param_types)
235 memberAccessCheck(java::lang::reflect::Member::DECLARED);
237 jstring partial_sig = getSignature (param_types, true);
238 jint hash = partial_sig->hashCode ();
240 int i = isPrimitive () ? 0 : method_count;
241 while (--i >= 0)
243 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
244 && _Jv_equal (methods[i].signature, partial_sig, hash))
246 // Found it.
247 using namespace java::lang::reflect;
248 Constructor *cons = new Constructor ();
249 cons->offset = (char *) (&methods[i]) - (char *) methods;
250 cons->declaringClass = this;
251 return cons;
254 throw new java::lang::NoSuchMethodException (_Jv_NewStringUtf8Const (init_name));
257 java::lang::reflect::Field *
258 java::lang::Class::getField (jstring name, jint hash)
260 java::lang::reflect::Field* rfield;
261 for (int i = 0; i < field_count; i++)
263 _Jv_Field *field = &fields[i];
264 if (! _Jv_equal (field->name, name, hash))
265 continue;
266 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
267 continue;
268 rfield = new java::lang::reflect::Field ();
269 rfield->offset = (char*) field - (char*) fields;
270 rfield->declaringClass = this;
271 rfield->name = name;
272 return rfield;
274 jclass superclass = getSuperclass();
275 if (superclass == NULL)
276 return NULL;
277 rfield = superclass->getField(name, hash);
278 for (int i = 0; i < interface_count && rfield == NULL; ++i)
279 rfield = interfaces[i]->getField (name, hash);
280 return rfield;
283 java::lang::reflect::Field *
284 java::lang::Class::getDeclaredField (jstring name)
286 memberAccessCheck(java::lang::reflect::Member::DECLARED);
287 int hash = name->hashCode();
288 for (int i = 0; i < field_count; i++)
290 _Jv_Field *field = &fields[i];
291 if (! _Jv_equal (field->name, name, hash))
292 continue;
293 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
294 rfield->offset = (char*) field - (char*) fields;
295 rfield->declaringClass = this;
296 rfield->name = name;
297 return rfield;
299 throw new java::lang::NoSuchFieldException (name);
302 JArray<java::lang::reflect::Field *> *
303 java::lang::Class::getDeclaredFields (jboolean public_only)
305 int size;
306 if (public_only)
308 size = 0;
309 for (int i = 0; i < field_count; ++i)
311 _Jv_Field *field = &fields[i];
312 if ((field->flags & java::lang::reflect::Modifier::PUBLIC))
313 ++size;
316 else
317 size = field_count;
319 JArray<java::lang::reflect::Field *> *result
320 = (JArray<java::lang::reflect::Field *> *)
321 JvNewObjectArray (size, &java::lang::reflect::Field::class$, NULL);
322 java::lang::reflect::Field** fptr = elements (result);
323 for (int i = 0; i < field_count; i++)
325 _Jv_Field *field = &fields[i];
326 if (public_only
327 && ! (field->flags & java::lang::reflect::Modifier::PUBLIC))
328 continue;
329 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
330 rfield->offset = (char*) field - (char*) fields;
331 rfield->declaringClass = this;
332 *fptr++ = rfield;
334 return result;
337 void
338 java::lang::Class::getSignature (java::lang::StringBuffer *buffer)
340 if (isPrimitive())
341 buffer->append((jchar) method_count);
342 else
344 jstring name = getName();
345 if (name->charAt(0) != '[')
346 buffer->append((jchar) 'L');
347 buffer->append(name);
348 if (name->charAt(0) != '[')
349 buffer->append((jchar) ';');
353 // This doesn't have to be native. It is an implementation detail
354 // only called from the C++ code, though, so maybe this is clearer.
355 jstring
356 java::lang::Class::getSignature (JArray<jclass> *param_types,
357 jboolean is_constructor)
359 java::lang::StringBuffer *buf = new java::lang::StringBuffer ();
360 buf->append((jchar) '(');
361 // A NULL param_types means "no parameters".
362 if (param_types != NULL)
364 jclass *v = elements (param_types);
365 for (int i = 0; i < param_types->length; ++i)
366 v[i]->getSignature(buf);
368 buf->append((jchar) ')');
369 if (is_constructor)
370 buf->append((jchar) 'V');
371 return buf->toString();
374 java::lang::reflect::Method *
375 java::lang::Class::_getDeclaredMethod (jstring name,
376 JArray<jclass> *param_types)
378 jstring partial_sig = getSignature (param_types, false);
379 jint p_len = partial_sig->length();
380 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
381 int i = isPrimitive () ? 0 : method_count;
382 while (--i >= 0)
384 if (_Jv_equalUtf8Consts (methods[i].name, utf_name)
385 && _Jv_equaln (methods[i].signature, partial_sig, p_len)
386 && (methods[i].accflags
387 & java::lang::reflect::Modifier::INVISIBLE) == 0)
389 // Found it.
390 using namespace java::lang::reflect;
391 Method *rmethod = new Method ();
392 rmethod->offset = (char*) (&methods[i]) - (char*) methods;
393 rmethod->declaringClass = this;
394 return rmethod;
397 return NULL;
400 JArray<java::lang::reflect::Method *> *
401 java::lang::Class::getDeclaredMethods (void)
403 memberAccessCheck(java::lang::reflect::Member::DECLARED);
405 int numMethods = 0;
406 int max = isPrimitive () ? 0 : method_count;
407 int i;
408 for (i = max; --i >= 0; )
410 _Jv_Method *method = &methods[i];
411 if (method->name == NULL
412 || _Jv_equalUtf8Consts (method->name, clinit_name)
413 || _Jv_equalUtf8Consts (method->name, init_name)
414 || _Jv_equalUtf8Consts (method->name, finit_name)
415 || (methods[i].accflags
416 & java::lang::reflect::Modifier::INVISIBLE) != 0)
417 continue;
418 numMethods++;
420 JArray<java::lang::reflect::Method *> *result
421 = (JArray<java::lang::reflect::Method *> *)
422 JvNewObjectArray (numMethods, &java::lang::reflect::Method::class$, NULL);
423 java::lang::reflect::Method** mptr = elements (result);
424 for (i = 0; i < max; i++)
426 _Jv_Method *method = &methods[i];
427 if (method->name == NULL
428 || _Jv_equalUtf8Consts (method->name, clinit_name)
429 || _Jv_equalUtf8Consts (method->name, init_name)
430 || _Jv_equalUtf8Consts (method->name, finit_name)
431 || (methods[i].accflags
432 & java::lang::reflect::Modifier::INVISIBLE) != 0)
433 continue;
434 java::lang::reflect::Method* rmethod
435 = new java::lang::reflect::Method ();
436 rmethod->offset = (char*) method - (char*) methods;
437 rmethod->declaringClass = this;
438 *mptr++ = rmethod;
440 return result;
443 jstring
444 java::lang::Class::getName (void)
446 return name->toString();
449 JArray<jclass> *
450 java::lang::Class::getClasses (void)
452 // FIXME: security checking.
454 // Until we have inner classes, it always makes sense to return an
455 // empty array.
456 JArray<jclass> *result
457 = (JArray<jclass> *) JvNewObjectArray (0, &java::lang::Class::class$,
458 NULL);
459 return result;
462 JArray<jclass> *
463 java::lang::Class::getDeclaredClasses (void)
465 memberAccessCheck (java::lang::reflect::Member::DECLARED);
466 // Until we have inner classes, it always makes sense to return an
467 // empty array.
468 JArray<jclass> *result
469 = (JArray<jclass> *) JvNewObjectArray (0, &java::lang::Class::class$,
470 NULL);
471 return result;
474 jclass
475 java::lang::Class::getDeclaringClass (void)
477 // Until we have inner classes, it makes sense to always return
478 // NULL.
479 return NULL;
482 JArray<jclass> *
483 java::lang::Class::getInterfaces (void)
485 jobjectArray r = JvNewObjectArray (interface_count, getClass (), NULL);
486 jobject *data = elements (r);
487 for (int i = 0; i < interface_count; ++i)
488 data[i] = interfaces[i];
489 return reinterpret_cast<JArray<jclass> *> (r);
492 java::lang::reflect::Method *
493 java::lang::Class::_getMethod (jstring name, JArray<jclass> *param_types)
495 jstring partial_sig = getSignature (param_types, false);
496 jint p_len = partial_sig->length();
497 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
498 for (Class *klass = this; klass; klass = klass->getSuperclass())
500 int i = klass->isPrimitive () ? 0 : klass->method_count;
501 while (--i >= 0)
503 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
504 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len)
505 && (klass->methods[i].accflags
506 & java::lang::reflect::Modifier::INVISIBLE) == 0)
508 // Found it.
509 using namespace java::lang::reflect;
511 // Method must be public.
512 if (! Modifier::isPublic (klass->methods[i].accflags))
513 break;
515 Method *rmethod = new Method ();
516 rmethod->offset = ((char *) (&klass->methods[i])
517 - (char *) klass->methods);
518 rmethod->declaringClass = klass;
519 return rmethod;
524 // If we haven't found a match, and this class is an interface, then
525 // check all the superinterfaces.
526 if (isInterface())
528 for (int i = 0; i < interface_count; ++i)
530 using namespace java::lang::reflect;
531 Method *rmethod = interfaces[i]->_getMethod (name, param_types);
532 if (rmethod != NULL)
533 return rmethod;
537 return NULL;
540 // This is a very slow implementation, since it re-scans all the
541 // methods we've already listed to make sure we haven't duplicated a
542 // method. It also over-estimates the required size, so we have to
543 // shrink the result array later.
544 jint
545 java::lang::Class::_getMethods (JArray<java::lang::reflect::Method *> *result,
546 jint offset)
548 jint count = 0;
550 // First examine all local methods
551 for (int i = isPrimitive () ? 0 : method_count; --i >= 0; )
553 _Jv_Method *method = &methods[i];
554 if (method->name == NULL
555 || _Jv_equalUtf8Consts (method->name, clinit_name)
556 || _Jv_equalUtf8Consts (method->name, init_name)
557 || _Jv_equalUtf8Consts (method->name, finit_name)
558 || (method->accflags
559 & java::lang::reflect::Modifier::INVISIBLE) != 0)
560 continue;
561 // Only want public methods.
562 if (! java::lang::reflect::Modifier::isPublic (method->accflags))
563 continue;
565 // This is where we over-count the slots required if we aren't
566 // filling the result for real.
567 if (result != NULL)
569 jboolean add = true;
570 java::lang::reflect::Method **mp = elements (result);
571 // If we already have a method with this name and signature,
572 // then ignore this one. This can happen with virtual
573 // methods.
574 for (int j = 0; j < offset; ++j)
576 _Jv_Method *meth_2 = _Jv_FromReflectedMethod (mp[j]);
577 if (_Jv_equalUtf8Consts (method->name, meth_2->name)
578 && _Jv_equalUtf8Consts (method->signature,
579 meth_2->signature))
581 add = false;
582 break;
585 if (! add)
586 continue;
589 if (result != NULL)
591 using namespace java::lang::reflect;
592 Method *rmethod = new Method ();
593 rmethod->offset = (char *) method - (char *) methods;
594 rmethod->declaringClass = this;
595 Method **mp = elements (result);
596 mp[offset + count] = rmethod;
598 ++count;
600 offset += count;
602 // Now examine superclasses.
603 if (getSuperclass () != NULL)
605 jint s_count = getSuperclass()->_getMethods (result, offset);
606 offset += s_count;
607 count += s_count;
610 // Finally, examine interfaces.
611 for (int i = 0; i < interface_count; ++i)
613 int f_count = interfaces[i]->_getMethods (result, offset);
614 count += f_count;
615 offset += f_count;
618 return count;
621 JArray<java::lang::reflect::Method *> *
622 java::lang::Class::getMethods (void)
624 using namespace java::lang::reflect;
626 memberAccessCheck(Member::PUBLIC);
628 // This will overestimate the size we need.
629 jint count = _getMethods (NULL, 0);
631 JArray<Method *> *result
632 = ((JArray<Method *> *) JvNewObjectArray (count,
633 &Method::class$,
634 NULL));
636 // When filling the array for real, we get the actual count. Then
637 // we resize the array.
638 jint real_count = _getMethods (result, 0);
640 if (real_count != count)
642 JArray<Method *> *r2
643 = ((JArray<Method *> *) JvNewObjectArray (real_count,
644 &Method::class$,
645 NULL));
647 Method **destp = elements (r2);
648 Method **srcp = elements (result);
650 for (int i = 0; i < real_count; ++i)
651 *destp++ = *srcp++;
653 result = r2;
656 return result;
659 jboolean
660 java::lang::Class::isAssignableFrom (jclass klass)
662 // Arguments may not have been initialized, given ".class" syntax.
663 _Jv_InitClass (this);
664 _Jv_InitClass (klass);
665 return _Jv_IsAssignableFrom (this, klass);
668 jboolean
669 java::lang::Class::isInstance (jobject obj)
671 if (! obj)
672 return false;
673 _Jv_InitClass (this);
674 return _Jv_IsAssignableFrom (this, JV_CLASS (obj));
677 jobject
678 java::lang::Class::newInstance (void)
680 memberAccessCheck(java::lang::reflect::Member::PUBLIC);
682 if (isPrimitive ()
683 || isInterface ()
684 || isArray ()
685 || java::lang::reflect::Modifier::isAbstract(accflags))
686 throw new java::lang::InstantiationException (getName ());
688 _Jv_InitClass (this);
690 _Jv_Method *meth = _Jv_GetMethodLocal (this, init_name, void_signature);
691 if (! meth)
692 throw new java::lang::InstantiationException (getName());
694 jobject r = _Jv_AllocObject (this);
695 ((void (*) (jobject)) meth->ncode) (r);
696 return r;
699 void
700 java::lang::Class::finalize (void)
702 #ifdef INTERPRETER
703 JvAssert (_Jv_IsInterpretedClass (this));
704 _Jv_UnregisterClass (this);
705 #endif
708 // This implements the initialization process for a class. From Spec
709 // section 12.4.2.
710 void
711 java::lang::Class::initializeClass (void)
713 // short-circuit to avoid needless locking.
714 if (state == JV_STATE_DONE)
715 return;
717 // Step 1.
718 _Jv_MonitorEnter (this);
720 if (state < JV_STATE_LINKED)
722 #ifdef INTERPRETER
723 if (_Jv_IsInterpretedClass (this))
725 // this can throw exceptions, so exit the monitor as a precaution.
726 _Jv_MonitorExit (this);
727 java::lang::VMClassLoader::resolveClass (this);
728 _Jv_MonitorEnter (this);
730 else
731 #endif
733 _Jv_PrepareCompiledClass (this);
737 // Step 2.
738 java::lang::Thread *self = java::lang::Thread::currentThread();
739 // FIXME: `self' can be null at startup. Hence this nasty trick.
740 self = (java::lang::Thread *) ((long) self | 1);
741 while (state == JV_STATE_IN_PROGRESS && thread && thread != self)
742 wait ();
744 // Steps 3 & 4.
745 if (state == JV_STATE_DONE)
747 _Jv_MonitorExit (this);
748 return;
750 if (state == JV_STATE_IN_PROGRESS)
752 _Jv_MonitorExit (this);
754 /* Initialization in progress. The class is linked now,
755 so ensure internal tables are built. */
756 _Jv_PrepareConstantTimeTables (this);
757 _Jv_MakeVTable(this);
758 _Jv_LinkSymbolTable(this);
760 return;
763 // Step 5.
764 if (state == JV_STATE_ERROR)
766 _Jv_MonitorExit (this);
767 throw new java::lang::NoClassDefFoundError (getName());
770 // Step 6.
771 thread = self;
772 state = JV_STATE_IN_PROGRESS;
773 _Jv_MonitorExit (this);
775 // Step 7.
776 if (! isInterface () && superclass)
780 _Jv_InitClass (superclass);
782 catch (java::lang::Throwable *except)
784 // Caught an exception.
785 _Jv_MonitorEnter (this);
786 state = JV_STATE_ERROR;
787 notifyAll ();
788 _Jv_MonitorExit (this);
789 throw except;
793 _Jv_PrepareConstantTimeTables (this);
795 if (vtable == NULL)
796 _Jv_MakeVTable(this);
798 if (otable || atable)
799 _Jv_LinkSymbolTable(this);
801 _Jv_linkExceptionClassTable (this);
803 // Steps 8, 9, 10, 11.
806 _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name,
807 void_signature);
808 if (meth)
809 ((void (*) (void)) meth->ncode) ();
811 catch (java::lang::Throwable *except)
813 if (! java::lang::Error::class$.isInstance(except))
817 except = new ExceptionInInitializerError (except);
819 catch (java::lang::Throwable *t)
821 except = t;
824 _Jv_MonitorEnter (this);
825 state = JV_STATE_ERROR;
826 notifyAll ();
827 _Jv_MonitorExit (this);
828 throw except;
831 _Jv_MonitorEnter (this);
832 state = JV_STATE_DONE;
833 notifyAll ();
834 _Jv_MonitorExit (this);
840 // Some class-related convenience functions.
843 // Find a method declared in the class. If it is not declared locally
844 // (or if it is inherited), return NULL.
845 _Jv_Method *
846 _Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
847 _Jv_Utf8Const *signature)
849 for (int i = 0; i < klass->method_count; ++i)
851 if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
852 && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
853 return &klass->methods[i];
855 return NULL;
858 _Jv_Method *
859 _Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
860 _Jv_Utf8Const *signature)
862 for (; klass; klass = klass->getSuperclass())
864 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
866 if (meth)
867 return meth;
870 return NULL;
873 // NOTE: MCACHE_SIZE should be a power of 2 minus one.
874 #define MCACHE_SIZE 1023
876 struct _Jv_mcache
878 jclass klass;
879 _Jv_Method *method;
882 static _Jv_mcache method_cache[MCACHE_SIZE + 1];
884 static void *
885 _Jv_FindMethodInCache (jclass klass,
886 _Jv_Utf8Const *name,
887 _Jv_Utf8Const *signature)
889 int index = name->hash16() & MCACHE_SIZE;
890 _Jv_mcache *mc = method_cache + index;
891 _Jv_Method *m = mc->method;
893 if (mc->klass == klass
894 && m != NULL // thread safe check
895 && _Jv_equalUtf8Consts (m->name, name)
896 && _Jv_equalUtf8Consts (m->signature, signature))
897 return mc->method->ncode;
898 return NULL;
901 static void
902 _Jv_AddMethodToCache (jclass klass,
903 _Jv_Method *method)
905 _Jv_MonitorEnter (&java::lang::Class::class$);
907 int index = method->name->hash16() & MCACHE_SIZE;
909 method_cache[index].method = method;
910 method_cache[index].klass = klass;
912 _Jv_MonitorExit (&java::lang::Class::class$);
915 void *
916 _Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
917 _Jv_Utf8Const *signature)
919 using namespace java::lang::reflect;
921 void *ncode = _Jv_FindMethodInCache (klass, name, signature);
922 if (ncode != 0)
923 return ncode;
925 for (; klass; klass = klass->getSuperclass())
927 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
928 if (! meth)
929 continue;
931 if (Modifier::isStatic(meth->accflags))
932 throw new java::lang::IncompatibleClassChangeError
933 (_Jv_GetMethodString (klass, meth->name));
934 if (Modifier::isAbstract(meth->accflags))
935 throw new java::lang::AbstractMethodError
936 (_Jv_GetMethodString (klass, meth->name));
937 if (! Modifier::isPublic(meth->accflags))
938 throw new java::lang::IllegalAccessError
939 (_Jv_GetMethodString (klass, meth->name));
941 _Jv_AddMethodToCache (klass, meth);
943 return meth->ncode;
945 throw new java::lang::IncompatibleClassChangeError;
948 // Fast interface method lookup by index.
949 void *
950 _Jv_LookupInterfaceMethodIdx (jclass klass, jclass iface, int method_idx)
952 _Jv_IDispatchTable *cldt = klass->idt;
953 int idx = iface->idt->iface.ioffsets[cldt->cls.iindex] + method_idx;
954 return cldt->cls.itable[idx];
957 jboolean
958 _Jv_IsAssignableFrom (jclass target, jclass source)
960 if (source == target)
961 return true;
963 // If target is array, so must source be.
964 while (target->isArray ())
966 if (! source->isArray())
967 return false;
968 target = target->getComponentType();
969 source = source->getComponentType();
972 if (target->isInterface())
974 // Abstract classes have no IDT, and IDTs provide no way to check
975 // two interfaces for assignability.
976 if (__builtin_expect
977 (source->idt == NULL || source->isInterface(), false))
978 return _Jv_InterfaceAssignableFrom (target, source);
980 _Jv_IDispatchTable *cl_idt = source->idt;
981 _Jv_IDispatchTable *if_idt = target->idt;
983 if (__builtin_expect ((if_idt == NULL), false))
984 return false; // No class implementing TARGET has been loaded.
985 jshort cl_iindex = cl_idt->cls.iindex;
986 if (cl_iindex < if_idt->iface.ioffsets[0])
988 jshort offset = if_idt->iface.ioffsets[cl_iindex];
989 if (offset != -1 && offset < cl_idt->cls.itable_length
990 && cl_idt->cls.itable[offset] == target)
991 return true;
993 return false;
996 // Primitive TYPE classes are only assignable to themselves.
997 if (__builtin_expect (target->isPrimitive() || source->isPrimitive(), false))
998 return false;
1000 if (target == &java::lang::Object::class$)
1001 return true;
1002 else if (source->ancestors == NULL || target->ancestors == NULL)
1004 // We need this case when either SOURCE or TARGET has not has
1005 // its constant-time tables prepared.
1007 // At this point we know that TARGET can't be Object, so it is
1008 // safe to use that as the termination point.
1009 while (source && source != &java::lang::Object::class$)
1011 if (source == target)
1012 return true;
1013 source = source->getSuperclass();
1016 else if (source->depth >= target->depth
1017 && source->ancestors[source->depth - target->depth] == target)
1018 return true;
1020 return false;
1023 // Interface type checking, the slow way. Returns TRUE if IFACE is a
1024 // superinterface of SOURCE. This is used when SOURCE is also an interface,
1025 // or a class with no interface dispatch table.
1026 jboolean
1027 _Jv_InterfaceAssignableFrom (jclass iface, jclass source)
1029 for (int i = 0; i < source->interface_count; i++)
1031 jclass interface = source->interfaces[i];
1032 if (iface == interface
1033 || _Jv_InterfaceAssignableFrom (iface, interface))
1034 return true;
1037 if (!source->isInterface()
1038 && source->superclass
1039 && _Jv_InterfaceAssignableFrom (iface, source->superclass))
1040 return true;
1042 return false;
1045 jboolean
1046 _Jv_IsInstanceOf(jobject obj, jclass cl)
1048 if (__builtin_expect (!obj, false))
1049 return false;
1050 return (_Jv_IsAssignableFrom (cl, JV_CLASS (obj)));
1053 void *
1054 _Jv_CheckCast (jclass c, jobject obj)
1056 if (__builtin_expect
1057 (obj != NULL && ! _Jv_IsAssignableFrom(c, JV_CLASS (obj)), false))
1058 throw new java::lang::ClassCastException
1059 ((new java::lang::StringBuffer
1060 (obj->getClass()->getName()))->append
1061 (JvNewStringUTF(" cannot be cast to "))->append
1062 (c->getName())->toString());
1064 return obj;
1067 void
1068 _Jv_CheckArrayStore (jobject arr, jobject obj)
1070 if (obj)
1072 JvAssert (arr != NULL);
1073 jclass elt_class = (JV_CLASS (arr))->getComponentType();
1074 if (elt_class == &java::lang::Object::class$)
1075 return;
1076 jclass obj_class = JV_CLASS (obj);
1077 if (__builtin_expect
1078 (! _Jv_IsAssignableFrom (elt_class, obj_class), false))
1079 throw new java::lang::ArrayStoreException
1080 ((new java::lang::StringBuffer
1081 (JvNewStringUTF("Cannot store ")))->append
1082 (obj_class->getName())->append
1083 (JvNewStringUTF(" in array of type "))->append
1084 (elt_class->getName())->toString());
1088 #define INITIAL_IOFFSETS_LEN 4
1089 #define INITIAL_IFACES_LEN 4
1091 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
1093 // Generate tables for constant-time assignment testing and interface
1094 // method lookup. This implements the technique described by Per Bothner
1095 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
1096 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
1097 void
1098 _Jv_PrepareConstantTimeTables (jclass klass)
1100 if (klass->isPrimitive () || klass->isInterface ())
1101 return;
1103 // Short-circuit in case we've been called already.
1104 if ((klass->idt != NULL) || klass->depth != 0)
1105 return;
1107 // Calculate the class depth and ancestor table. The depth of a class
1108 // is how many "extends" it is removed from Object. Thus the depth of
1109 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
1110 // is 2. Depth is defined for all regular and array classes, but not
1111 // interfaces or primitive types.
1113 jclass klass0 = klass;
1114 jboolean has_interfaces = 0;
1115 while (klass0 != &java::lang::Object::class$)
1117 has_interfaces += klass0->interface_count;
1118 klass0 = klass0->superclass;
1119 klass->depth++;
1122 // We do class member testing in constant time by using a small table
1123 // of all the ancestor classes within each class. The first element is
1124 // a pointer to the current class, and the rest are pointers to the
1125 // classes ancestors, ordered from the current class down by decreasing
1126 // depth. We do not include java.lang.Object in the table of ancestors,
1127 // since it is redundant.
1129 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth * sizeof (jclass));
1130 klass0 = klass;
1131 for (int index = 0; index < klass->depth; index++)
1133 klass->ancestors[index] = klass0;
1134 klass0 = klass0->superclass;
1137 if (java::lang::reflect::Modifier::isAbstract (klass->accflags))
1138 return;
1140 // Optimization: If class implements no interfaces, use a common
1141 // predefined interface table.
1142 if (!has_interfaces)
1144 klass->idt = &null_idt;
1145 return;
1148 klass->idt =
1149 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1151 _Jv_ifaces ifaces;
1153 ifaces.count = 0;
1154 ifaces.len = INITIAL_IFACES_LEN;
1155 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
1157 int itable_size = _Jv_GetInterfaces (klass, &ifaces);
1159 if (ifaces.count > 0)
1161 klass->idt->cls.itable =
1162 (void **) _Jv_Malloc (itable_size * sizeof (void *));
1163 klass->idt->cls.itable_length = itable_size;
1165 jshort *itable_offsets =
1166 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
1168 _Jv_GenerateITable (klass, &ifaces, itable_offsets);
1170 jshort cls_iindex =
1171 _Jv_FindIIndex (ifaces.list, itable_offsets, ifaces.count);
1173 for (int i=0; i < ifaces.count; i++)
1175 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
1176 itable_offsets[i];
1179 klass->idt->cls.iindex = cls_iindex;
1181 _Jv_Free (ifaces.list);
1182 _Jv_Free (itable_offsets);
1184 else
1186 klass->idt->cls.iindex = SHRT_MAX;
1190 // Return index of item in list, or -1 if item is not present.
1191 inline jshort
1192 _Jv_IndexOf (void *item, void **list, jshort list_len)
1194 for (int i=0; i < list_len; i++)
1196 if (list[i] == item)
1197 return i;
1199 return -1;
1202 // Find all unique interfaces directly or indirectly implemented by klass.
1203 // Returns the size of the interface dispatch table (itable) for klass, which
1204 // is the number of unique interfaces plus the total number of methods that
1205 // those interfaces declare. May extend ifaces if required.
1206 jshort
1207 _Jv_GetInterfaces (jclass klass, _Jv_ifaces *ifaces)
1209 jshort result = 0;
1211 for (int i=0; i < klass->interface_count; i++)
1213 jclass iface = klass->interfaces[i];
1215 /* Make sure interface is linked. */
1216 _Jv_WaitForState(iface, JV_STATE_LINKED);
1218 if (_Jv_IndexOf (iface, (void **) ifaces->list, ifaces->count) == -1)
1220 if (ifaces->count + 1 >= ifaces->len)
1222 /* Resize ifaces list */
1223 ifaces->len = ifaces->len * 2;
1224 ifaces->list = (jclass *) _Jv_Realloc (ifaces->list,
1225 ifaces->len * sizeof(jclass));
1227 ifaces->list[ifaces->count] = iface;
1228 ifaces->count++;
1230 result += _Jv_GetInterfaces (klass->interfaces[i], ifaces);
1234 if (klass->isInterface())
1236 result += klass->method_count + 1;
1238 else
1240 if (klass->superclass)
1242 result += _Jv_GetInterfaces (klass->superclass, ifaces);
1245 return result;
1248 // Fill out itable in klass, resolving method declarations in each ifaces.
1249 // itable_offsets is filled out with the position of each iface in itable,
1250 // such that itable[itable_offsets[n]] == ifaces.list[n].
1251 void
1252 _Jv_GenerateITable (jclass klass, _Jv_ifaces *ifaces, jshort *itable_offsets)
1254 void **itable = klass->idt->cls.itable;
1255 jshort itable_pos = 0;
1257 for (int i=0; i < ifaces->count; i++)
1259 jclass iface = ifaces->list[i];
1260 itable_offsets[i] = itable_pos;
1261 itable_pos = _Jv_AppendPartialITable (klass, iface, itable, itable_pos);
1263 /* Create interface dispatch table for iface */
1264 if (iface->idt == NULL)
1266 iface->idt =
1267 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1269 // The first element of ioffsets is its length (itself included).
1270 jshort *ioffsets =
1271 (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN * sizeof (jshort));
1272 ioffsets[0] = INITIAL_IOFFSETS_LEN;
1273 for (int i=1; i < INITIAL_IOFFSETS_LEN; i++)
1274 ioffsets[i] = -1;
1276 iface->idt->iface.ioffsets = ioffsets;
1281 // Format method name for use in error messages.
1282 jstring
1283 _Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
1285 jstring r = klass->name->toString();
1286 r = r->concat (JvNewStringUTF ("."));
1287 r = r->concat (name->toString());
1288 return r;
1291 void
1292 _Jv_ThrowNoSuchMethodError ()
1294 throw new java::lang::NoSuchMethodError;
1297 // Each superinterface of a class (i.e. each interface that the class
1298 // directly or indirectly implements) has a corresponding "Partial
1299 // Interface Dispatch Table" whose size is (number of methods + 1) words.
1300 // The first word is a pointer to the interface (i.e. the java.lang.Class
1301 // instance for that interface). The remaining words are pointers to the
1302 // actual methods that implement the methods declared in the interface,
1303 // in order of declaration.
1305 // Append partial interface dispatch table for "iface" to "itable", at
1306 // position itable_pos.
1307 // Returns the offset at which the next partial ITable should be appended.
1308 jshort
1309 _Jv_AppendPartialITable (jclass klass, jclass iface, void **itable,
1310 jshort pos)
1312 using namespace java::lang::reflect;
1314 itable[pos++] = (void *) iface;
1315 _Jv_Method *meth;
1317 for (int j=0; j < iface->method_count; j++)
1319 meth = NULL;
1320 for (jclass cl = klass; cl; cl = cl->getSuperclass())
1322 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
1323 iface->methods[j].signature);
1325 if (meth)
1326 break;
1329 if (meth && (meth->name->first() == '<'))
1331 // leave a placeholder in the itable for hidden init methods.
1332 itable[pos] = NULL;
1334 else if (meth)
1336 if (Modifier::isStatic(meth->accflags))
1337 throw new java::lang::IncompatibleClassChangeError
1338 (_Jv_GetMethodString (klass, meth->name));
1339 if (Modifier::isAbstract(meth->accflags))
1340 throw new java::lang::AbstractMethodError
1341 (_Jv_GetMethodString (klass, meth->name));
1342 if (! Modifier::isPublic(meth->accflags))
1343 throw new java::lang::IllegalAccessError
1344 (_Jv_GetMethodString (klass, meth->name));
1346 itable[pos] = meth->ncode;
1348 else
1350 // The method doesn't exist in klass. Binary compatibility rules
1351 // permit this, so we delay the error until runtime using a pointer
1352 // to a method which throws an exception.
1353 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
1355 pos++;
1358 return pos;
1361 static _Jv_Mutex_t iindex_mutex;
1362 static bool iindex_mutex_initialized = false;
1364 // We need to find the correct offset in the Class Interface Dispatch
1365 // Table for a given interface. Once we have that, invoking an interface
1366 // method just requires combining the Method's index in the interface
1367 // (known at compile time) to get the correct method. Doing a type test
1368 // (cast or instanceof) is the same problem: Once we have a possible Partial
1369 // Interface Dispatch Table, we just compare the first element to see if it
1370 // matches the desired interface. So how can we find the correct offset?
1371 // Our solution is to keep a vector of candiate offsets in each interface
1372 // (idt->iface.ioffsets), and in each class we have an index
1373 // (idt->cls.iindex) used to select the correct offset from ioffsets.
1375 // Calculate and return iindex for a new class.
1376 // ifaces is a vector of num interfaces that the class implements.
1377 // offsets[j] is the offset in the interface dispatch table for the
1378 // interface corresponding to ifaces[j].
1379 // May extend the interface ioffsets if required.
1380 jshort
1381 _Jv_FindIIndex (jclass *ifaces, jshort *offsets, jshort num)
1383 int i;
1384 int j;
1386 // Acquire a global lock to prevent itable corruption in case of multiple
1387 // classes that implement an intersecting set of interfaces being linked
1388 // simultaneously. We can assume that the mutex will be initialized
1389 // single-threaded.
1390 if (! iindex_mutex_initialized)
1392 _Jv_MutexInit (&iindex_mutex);
1393 iindex_mutex_initialized = true;
1396 _Jv_MutexLock (&iindex_mutex);
1398 for (i=1;; i++) /* each potential position in ioffsets */
1400 for (j=0;; j++) /* each iface */
1402 if (j >= num)
1403 goto found;
1404 if (i >= ifaces[j]->idt->iface.ioffsets[0])
1405 continue;
1406 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
1407 /* We can potentially share this position with another class. */
1408 if (ioffset >= 0 && ioffset != offsets[j])
1409 break; /* Nope. Try next i. */
1412 found:
1413 for (j = 0; j < num; j++)
1415 int len = ifaces[j]->idt->iface.ioffsets[0];
1416 if (i >= len)
1418 /* Resize ioffsets. */
1419 int newlen = 2 * len;
1420 if (i >= newlen)
1421 newlen = i + 3;
1422 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
1423 jshort *new_ioffsets = (jshort *) _Jv_Realloc (old_ioffsets,
1424 newlen * sizeof(jshort));
1425 new_ioffsets[0] = newlen;
1427 while (len < newlen)
1428 new_ioffsets[len++] = -1;
1430 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
1432 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
1435 _Jv_MutexUnlock (&iindex_mutex);
1437 return i;
1440 // Only used by serialization
1441 java::lang::reflect::Field *
1442 java::lang::Class::getPrivateField (jstring name)
1444 int hash = name->hashCode ();
1446 java::lang::reflect::Field* rfield;
1447 for (int i = 0; i < field_count; i++)
1449 _Jv_Field *field = &fields[i];
1450 if (! _Jv_equal (field->name, name, hash))
1451 continue;
1452 rfield = new java::lang::reflect::Field ();
1453 rfield->offset = (char*) field - (char*) fields;
1454 rfield->declaringClass = this;
1455 rfield->name = name;
1456 return rfield;
1458 jclass superclass = getSuperclass();
1459 if (superclass == NULL)
1460 return NULL;
1461 rfield = superclass->getPrivateField(name);
1462 for (int i = 0; i < interface_count && rfield == NULL; ++i)
1463 rfield = interfaces[i]->getPrivateField (name);
1464 return rfield;
1467 // Only used by serialization
1468 java::lang::reflect::Method *
1469 java::lang::Class::getPrivateMethod (jstring name, JArray<jclass> *param_types)
1471 jstring partial_sig = getSignature (param_types, false);
1472 jint p_len = partial_sig->length();
1473 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
1474 for (Class *klass = this; klass; klass = klass->getSuperclass())
1476 int i = klass->isPrimitive () ? 0 : klass->method_count;
1477 while (--i >= 0)
1479 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
1480 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
1482 // Found it.
1483 using namespace java::lang::reflect;
1485 Method *rmethod = new Method ();
1486 rmethod->offset = ((char *) (&klass->methods[i])
1487 - (char *) klass->methods);
1488 rmethod->declaringClass = klass;
1489 return rmethod;
1493 throw new java::lang::NoSuchMethodException (name);
1496 // Private accessor method for Java code to retrieve the protection domain.
1497 java::security::ProtectionDomain *
1498 java::lang::Class::getProtectionDomain0 ()
1500 return protectionDomain;
1503 JArray<jobject> *
1504 java::lang::Class::getSigners()
1506 return hack_signers;
1509 void
1510 java::lang::Class::setSigners(JArray<jobject> *s)
1512 hack_signers = s;
1515 // Functions for indirect dispatch (symbolic virtual binding) support.
1517 // There are two tables, atable and otable. atable is an array of
1518 // addresses, and otable is an array of offsets, and these are used
1519 // for static and virtual members respectively.
1521 // {a,o}table_syms is an array of _Jv_MethodSymbols. Each such symbol
1522 // is a tuple of {classname, member name, signature}.
1523 // _Jv_LinkSymbolTable() scans these two arrays and fills in the
1524 // corresponding atable and otable with the addresses of static
1525 // members and the offsets of virtual members.
1527 // The offset (in bytes) for each resolved method or field is placed
1528 // at the corresponding position in the virtual method offset table
1529 // (klass->otable).
1531 // The same otable and atable may be shared by many classes.
1533 void
1534 _Jv_LinkSymbolTable(jclass klass)
1536 //// FIXME: Need to lock the tables ////
1538 int index = 0;
1539 _Jv_MethodSymbol sym;
1540 if (klass->otable == NULL
1541 || klass->otable->state != 0)
1542 goto atable;
1544 klass->otable->state = 1;
1546 for (index = 0; sym = klass->otable_syms[index], sym.name != NULL; index++)
1548 // FIXME: Why are we passing NULL as the class loader?
1549 jclass target_class = _Jv_FindClass (sym.class_name, NULL);
1550 _Jv_Method *meth = NULL;
1552 const _Jv_Utf8Const *signature = sym.signature;
1555 static char *bounce = (char *)_Jv_ThrowNoSuchMethodError;
1556 ptrdiff_t offset = (char *)(klass->vtable) - bounce;
1557 klass->otable->offsets[index] = offset;
1560 if (target_class == NULL)
1561 continue;
1563 if (target_class->isInterface())
1565 // FIXME: This does not yet fully conform to binary compatibility
1566 // rules. It will break if a declaration is moved into a
1567 // superinterface.
1568 for (jclass cls = target_class; cls != 0; cls = cls->getSuperclass ())
1570 for (int i=0; i < cls->method_count; i++)
1572 meth = &cls->methods[i];
1573 if (_Jv_equalUtf8Consts (sym.name, meth->name)
1574 && _Jv_equalUtf8Consts (signature, meth->signature))
1576 klass->otable->offsets[index] = i + 1;
1577 goto found;
1582 found:
1583 continue;
1586 // We're looking for a field or a method, and we can tell
1587 // which is needed by looking at the signature.
1588 if (signature->first() == '(' && signature->len() >= 2)
1590 // If the target class does not have a vtable_method_count yet,
1591 // then we can't tell the offsets for its methods, so we must lay
1592 // it out now.
1593 if (target_class->vtable_method_count == -1)
1595 JvSynchronize sync (target_class);
1596 _Jv_LayoutVTableMethods (target_class);
1599 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1600 sym.signature);
1602 if (meth != NULL)
1604 klass->otable->offsets[index] =
1605 _Jv_VTable::idx_to_offset (meth->index);
1608 continue;
1611 // try fields
1613 _Jv_Field *the_field = NULL;
1615 for (jclass cls = target_class; cls != 0; cls = cls->getSuperclass ())
1617 for (int i = 0; i < cls->field_count; i++)
1619 _Jv_Field *field = &cls->fields[i];
1620 if (! _Jv_equalUtf8Consts (field->name, sym.name))
1621 continue;
1623 // FIXME: What access checks should we perform here?
1624 // if (_Jv_CheckAccess (klass, cls, field->flags))
1625 // {
1627 if (!field->isResolved ())
1628 _Jv_ResolveField (field, cls->loader);
1630 // if (field_type != 0 && field->type != field_type)
1631 // throw new java::lang::LinkageError
1632 // (JvNewStringLatin1
1633 // ("field type mismatch with different loaders"));
1635 the_field = field;
1636 goto end_of_field_search;
1639 end_of_field_search:
1640 if (the_field != NULL)
1642 if (the_field->flags & 0x0008 /* Modifier::STATIC */)
1644 throw new java::lang::IncompatibleClassChangeError;
1646 else
1648 klass->otable->offsets[index] = the_field->u.boffset;
1651 else
1653 throw new java::lang::NoSuchFieldError
1654 (_Jv_NewStringUtf8Const (sym.name));
1659 atable:
1660 if (klass->atable == NULL
1661 || klass->atable->state != 0)
1662 return;
1664 klass->atable->state = 1;
1666 for (index = 0; sym = klass->atable_syms[index], sym.name != NULL; index++)
1668 // FIXME: Why are we passing NULL as the class loader?
1669 jclass target_class = _Jv_FindClass (sym.class_name, NULL);
1670 _Jv_Method *meth = NULL;
1671 const _Jv_Utf8Const *signature = sym.signature;
1673 // ??? Setting this pointer to null will at least get us a
1674 // NullPointerException
1675 klass->atable->addresses[index] = NULL;
1677 if (target_class == NULL)
1678 continue;
1680 // We're looking for a static field or a static method, and we
1681 // can tell which is needed by looking at the signature.
1682 if (signature->first() == '(' && signature->len() >= 2)
1684 // If the target class does not have a vtable_method_count yet,
1685 // then we can't tell the offsets for its methods, so we must lay
1686 // it out now.
1687 if (target_class->vtable_method_count == -1)
1689 JvSynchronize sync (target_class);
1690 _Jv_LayoutVTableMethods (target_class);
1693 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1694 sym.signature);
1696 if (meth != NULL)
1698 if (meth->ncode) // Maybe abstract?
1699 klass->atable->addresses[index] = meth->ncode;
1700 #ifdef INTERPRETER
1701 else if (_Jv_IsInterpretedClass (target_class))
1702 _Jv_Defer_Resolution (target_class, meth,
1703 &klass->atable->addresses[index]);
1704 #endif
1706 else
1707 klass->atable->addresses[index] = (void *)_Jv_ThrowNoSuchMethodError;
1709 continue;
1712 // try fields
1714 _Jv_Field *the_field = NULL;
1716 for (jclass cls = target_class; cls != 0; cls = cls->getSuperclass ())
1718 for (int i = 0; i < cls->field_count; i++)
1720 _Jv_Field *field = &cls->fields[i];
1721 if (! _Jv_equalUtf8Consts (field->name, sym.name))
1722 continue;
1724 // FIXME: What access checks should we perform here?
1725 // if (_Jv_CheckAccess (klass, cls, field->flags))
1726 // {
1728 if (!field->isResolved ())
1729 _Jv_ResolveField (field, cls->loader);
1731 // if (field_type != 0 && field->type != field_type)
1732 // throw new java::lang::LinkageError
1733 // (JvNewStringLatin1
1734 // ("field type mismatch with different loaders"));
1736 the_field = field;
1737 goto end_of_static_field_search;
1740 end_of_static_field_search:
1741 if (the_field != NULL)
1743 if (the_field->flags & 0x0008 /* Modifier::STATIC */)
1745 klass->atable->addresses[index] = the_field->u.addr;
1747 else
1749 throw new java::lang::IncompatibleClassChangeError;
1752 else
1754 throw new java::lang::NoSuchFieldError
1755 (_Jv_NewStringUtf8Const (sym.name));
1762 // For each catch_record in the list of caught classes, fill in the
1763 // address field.
1764 void
1765 _Jv_linkExceptionClassTable (jclass self)
1767 struct _Jv_CatchClass *catch_record = self->catch_classes;
1768 if (!catch_record || catch_record->classname)
1769 return;
1770 catch_record++;
1771 while (catch_record->classname)
1773 jclass target_class = _Jv_FindClass (catch_record->classname,
1774 self->getClassLoaderInternal ());
1775 *catch_record->address = target_class;
1776 catch_record++;
1778 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1781 // This is put in empty vtable slots.
1782 static void
1783 _Jv_abstractMethodError (void)
1785 throw new java::lang::AbstractMethodError();
1788 // Set itable method indexes for members of interface IFACE.
1789 void
1790 _Jv_LayoutInterfaceMethods (jclass iface)
1792 if (! iface->isInterface())
1793 return;
1795 // itable indexes start at 1.
1796 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1797 // itable so they are also assigned an index here.
1798 for (int i = 0; i < iface->method_count; i++)
1799 iface->methods[i].index = i + 1;
1802 // Prepare virtual method declarations in KLASS, and any superclasses as
1803 // required, by determining their vtable index, setting method->index, and
1804 // finally setting the class's vtable_method_count. Must be called with the
1805 // lock for KLASS held.
1806 void
1807 _Jv_LayoutVTableMethods (jclass klass)
1809 if (klass->vtable != NULL || klass->isInterface()
1810 || klass->vtable_method_count != -1)
1811 return;
1813 jclass superclass = klass->superclass;
1815 typedef unsigned int uaddr __attribute__ ((mode (pointer)));
1817 // If superclass looks like a constant pool entry,
1818 // resolve it now.
1819 if ((uaddr) superclass < (uaddr) klass->constants.size)
1821 if (klass->state < JV_STATE_LINKED)
1823 _Jv_Utf8Const *name = klass->constants.data[(uaddr) superclass].utf8;
1824 superclass = _Jv_FindClass (name, klass->loader);
1825 if (! superclass)
1827 throw new java::lang::NoClassDefFoundError (name->toString());
1830 else
1831 superclass = klass->constants.data[(uaddr) superclass].clazz;
1834 if (superclass != NULL && superclass->vtable_method_count == -1)
1836 JvSynchronize sync (superclass);
1837 _Jv_LayoutVTableMethods (superclass);
1840 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1842 for (int i = 0; i < klass->method_count; ++i)
1844 _Jv_Method *meth = &klass->methods[i];
1845 _Jv_Method *super_meth = NULL;
1847 if (! _Jv_isVirtualMethod (meth))
1848 continue;
1850 // FIXME: Must check that we don't override:
1851 // - Package-private method where superclass is in different package.
1852 // - Final or less-accessible declaration in superclass (check binary
1853 // spec, do we allocate new vtable entry or put throw node in vtable?)
1854 // - Static or private method in superclass.
1856 if (superclass != NULL)
1858 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1859 meth->signature);
1862 if (super_meth)
1863 meth->index = super_meth->index;
1864 else
1865 meth->index = index++;
1868 klass->vtable_method_count = index;
1871 // Set entries in VTABLE for virtual methods declared in KLASS. If
1872 // KLASS has an immediate abstract parent, recursively do its methods
1873 // first. FLAGS is used to determine which slots we've actually set.
1874 void
1875 _Jv_SetVTableEntries (jclass klass, _Jv_VTable *vtable, jboolean *flags)
1877 using namespace java::lang::reflect;
1879 jclass superclass = klass->getSuperclass();
1881 if (superclass != NULL && (superclass->getModifiers() & Modifier::ABSTRACT))
1882 _Jv_SetVTableEntries (superclass, vtable, flags);
1884 for (int i = klass->method_count - 1; i >= 0; i--)
1886 _Jv_Method *meth = &klass->methods[i];
1887 if (meth->index == (_Jv_ushort) -1)
1888 continue;
1889 if ((meth->accflags & Modifier::ABSTRACT))
1891 vtable->set_method(meth->index, (void *) &_Jv_abstractMethodError);
1892 flags[meth->index] = false;
1894 else
1896 vtable->set_method(meth->index, meth->ncode);
1897 flags[meth->index] = true;
1902 // Allocate and lay out the virtual method table for KLASS. This will also
1903 // cause vtables to be generated for any non-abstract superclasses, and
1904 // virtual method layout to occur for any abstract superclasses. Must be
1905 // called with monitor lock for KLASS held.
1906 void
1907 _Jv_MakeVTable (jclass klass)
1909 using namespace java::lang::reflect;
1911 if (klass->vtable != NULL || klass->isInterface()
1912 || (klass->accflags & Modifier::ABSTRACT))
1913 return;
1915 // Class must be laid out before we can create a vtable.
1916 if (klass->vtable_method_count == -1)
1917 _Jv_LayoutVTableMethods (klass);
1919 // Allocate the new vtable.
1920 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1921 klass->vtable = vtable;
1923 jboolean flags[klass->vtable_method_count];
1924 for (int i = 0; i < klass->vtable_method_count; ++i)
1925 flags[i] = false;
1927 // Copy the vtable of the closest non-abstract superclass.
1928 jclass superclass = klass->superclass;
1929 if (superclass != NULL)
1931 while ((superclass->accflags & Modifier::ABSTRACT) != 0)
1932 superclass = superclass->superclass;
1934 if (superclass->vtable == NULL)
1936 JvSynchronize sync (superclass);
1937 _Jv_MakeVTable (superclass);
1940 for (int i = 0; i < superclass->vtable_method_count; ++i)
1942 vtable->set_method (i, superclass->vtable->get_method (i));
1943 flags[i] = true;
1947 // Set the class pointer and GC descriptor.
1948 vtable->clas = klass;
1949 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1951 // For each virtual declared in klass and any immediate abstract
1952 // superclasses, set new vtable entry or override an old one.
1953 _Jv_SetVTableEntries (klass, vtable, flags);
1955 // It is an error to have an abstract method in a concrete class.
1956 if (! (klass->accflags & Modifier::ABSTRACT))
1958 for (int i = 0; i < klass->vtable_method_count; ++i)
1959 if (! flags[i])
1961 using namespace java::lang;
1962 while (klass != NULL)
1964 for (int j = 0; j < klass->method_count; ++j)
1966 if (klass->methods[i].index == i)
1968 StringBuffer *buf = new StringBuffer ();
1969 buf->append (_Jv_NewStringUtf8Const (klass->methods[i].name));
1970 buf->append ((jchar) ' ');
1971 buf->append (_Jv_NewStringUtf8Const (klass->methods[i].signature));
1972 throw new AbstractMethodError (buf->toString ());
1975 klass = klass->getSuperclass ();
1977 // Couldn't find the name, which is weird.
1978 // But we still must throw the error.
1979 throw new AbstractMethodError ();