1 // natClass.cc - Implementation of java.lang.Class native methods.
3 /* Copyright (C) 1998, 1999, 2000 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
16 #pragma implementation "Class.h"
20 #include <java-threads.h>
22 #include <java/lang/Class.h>
23 #include <java/lang/ClassLoader.h>
24 #include <java/lang/String.h>
25 #include <java/lang/reflect/Modifier.h>
26 #include <java/lang/reflect/Member.h>
27 #include <java/lang/reflect/Method.h>
28 #include <java/lang/reflect/Field.h>
29 #include <java/lang/reflect/Constructor.h>
30 #include <java/lang/AbstractMethodError.h>
31 #include <java/lang/ArrayStoreException.h>
32 #include <java/lang/ClassCastException.h>
33 #include <java/lang/ClassNotFoundException.h>
34 #include <java/lang/ExceptionInInitializerError.h>
35 #include <java/lang/IllegalAccessException.h>
36 #include <java/lang/IllegalAccessError.h>
37 #include <java/lang/IncompatibleClassChangeError.h>
38 #include <java/lang/InstantiationException.h>
39 #include <java/lang/NoClassDefFoundError.h>
40 #include <java/lang/NoSuchFieldException.h>
41 #include <java/lang/NoSuchMethodError.h>
42 #include <java/lang/NoSuchMethodException.h>
43 #include <java/lang/Thread.h>
44 #include <java/lang/NullPointerException.h>
45 #include <java/lang/System.h>
46 #include <java/lang/SecurityManager.h>
47 #include <java/lang/StringBuffer.h>
48 #include <gcj/method.h>
50 #include <java-cpool.h>
54 // FIXME: remove these.
55 #define CloneableClass java::lang::Cloneable::class$
56 #define ObjectClass java::lang::Object::class$
57 #define ErrorClass java::lang::Error::class$
58 #define ClassClass java::lang::Class::class$
59 #define MethodClass java::lang::reflect::Method::class$
60 #define FieldClass java::lang::reflect::Field::class$
61 #define ConstructorClass java::lang::reflect::Constructor::class$
63 // Some constants we use to look up the class initializer.
64 static _Jv_Utf8Const *void_signature = _Jv_makeUtf8Const ("()V", 3);
65 static _Jv_Utf8Const *clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
66 static _Jv_Utf8Const *init_name = _Jv_makeUtf8Const ("<init>", 6);
67 static _Jv_Utf8Const *finit_name = _Jv_makeUtf8Const ("finit$", 6);
68 // The legacy `$finit$' method name, which still needs to be
69 // recognized as equivalent to the now prefered `finit$' name.
70 static _Jv_Utf8Const *finit_leg_name = _Jv_makeUtf8Const ("$finit$", 7);
75 java::lang::Class::forName (jstring className, java::lang::ClassLoader *loader)
78 JvThrow (new java::lang::NullPointerException);
80 jsize length = _Jv_GetStringUTFLength (className);
82 _Jv_GetStringUTFRegion (className, 0, length, buffer);
84 // FIXME: should check syntax of CLASSNAME and throw
85 // IllegalArgumentException on failure.
86 _Jv_Utf8Const *name = _Jv_makeUtf8Const (buffer, length);
88 // FIXME: should use bootstrap class loader if loader is null.
89 jclass klass = (buffer[0] == '['
90 ? _Jv_FindClassFromSignature (name->data, loader)
91 : _Jv_FindClass (name, loader));
94 _Jv_InitClass (klass);
96 JvThrow (new java::lang::ClassNotFoundException (className));
102 java::lang::Class::forName (jstring className)
104 // FIXME: should use class loader from calling method.
105 return forName (className, NULL);
108 java::lang::reflect::Constructor *
109 java::lang::Class::getConstructor (JArray<jclass> *param_types)
111 jstring partial_sig = getSignature (param_types, true);
112 jint hash = partial_sig->hashCode ();
114 int i = isPrimitive () ? 0 : method_count;
117 // FIXME: access checks.
118 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
119 && _Jv_equal (methods[i].signature, partial_sig, hash))
121 // Found it. For getConstructor, the constructor must be
123 using namespace java::lang::reflect;
124 if (! Modifier::isPublic(methods[i].accflags))
126 Constructor *cons = new Constructor ();
127 cons->offset = (char *) (&methods[i]) - (char *) methods;
128 cons->declaringClass = this;
132 JvThrow (new java::lang::NoSuchMethodException);
135 JArray<java::lang::reflect::Constructor *> *
136 java::lang::Class::_getConstructors (jboolean declared)
138 // FIXME: this method needs access checks.
140 int numConstructors = 0;
141 int max = isPrimitive () ? 0 : method_count;
143 for (i = max; --i >= 0; )
145 _Jv_Method *method = &methods[i];
146 if (method->name == NULL
147 || ! _Jv_equalUtf8Consts (method->name, init_name))
150 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
154 JArray<java::lang::reflect::Constructor *> *result
155 = (JArray<java::lang::reflect::Constructor *> *)
156 JvNewObjectArray (numConstructors, &ConstructorClass, NULL);
157 java::lang::reflect::Constructor** cptr = elements (result);
158 for (i = 0; i < max; i++)
160 _Jv_Method *method = &methods[i];
161 if (method->name == NULL
162 || ! _Jv_equalUtf8Consts (method->name, init_name))
165 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
167 java::lang::reflect::Constructor *cons
168 = new java::lang::reflect::Constructor ();
169 cons->offset = (char *) method - (char *) methods;
170 cons->declaringClass = this;
176 java::lang::reflect::Constructor *
177 java::lang::Class::getDeclaredConstructor (JArray<jclass> *param_types)
179 jstring partial_sig = getSignature (param_types, true);
180 jint hash = partial_sig->hashCode ();
182 int i = isPrimitive () ? 0 : method_count;
185 // FIXME: access checks.
186 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
187 && _Jv_equal (methods[i].signature, partial_sig, hash))
190 using namespace java::lang::reflect;
191 Constructor *cons = new Constructor ();
192 cons->offset = (char *) (&methods[i]) - (char *) methods;
193 cons->declaringClass = this;
197 JvThrow (new java::lang::NoSuchMethodException);
200 java::lang::reflect::Field *
201 java::lang::Class::getField (jstring name, jint hash)
203 java::lang::reflect::Field* rfield;
204 for (int i = 0; i < field_count; i++)
206 _Jv_Field *field = &fields[i];
207 if (! _Jv_equal (field->name, name, hash))
209 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
211 rfield = new java::lang::reflect::Field ();
212 rfield->offset = (char*) field - (char*) fields;
213 rfield->declaringClass = this;
217 jclass superclass = getSuperclass();
218 if (superclass == NULL)
220 rfield = superclass->getField(name, hash);
221 for (int i = 0; i < interface_count && rfield == NULL; ++i)
222 rfield = interfaces[i]->getField (name, hash);
226 java::lang::reflect::Field *
227 java::lang::Class::getDeclaredField (jstring name)
229 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
231 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
232 int hash = name->hashCode();
233 for (int i = 0; i < field_count; i++)
235 _Jv_Field *field = &fields[i];
236 if (! _Jv_equal (field->name, name, hash))
238 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
239 rfield->offset = (char*) field - (char*) fields;
240 rfield->declaringClass = this;
244 JvThrow (new java::lang::NoSuchFieldException (name));
247 JArray<java::lang::reflect::Field *> *
248 java::lang::Class::getDeclaredFields (void)
250 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
252 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
253 JArray<java::lang::reflect::Field *> *result
254 = (JArray<java::lang::reflect::Field *> *)
255 JvNewObjectArray (field_count, &FieldClass, NULL);
256 java::lang::reflect::Field** fptr = elements (result);
257 for (int i = 0; i < field_count; i++)
259 _Jv_Field *field = &fields[i];
260 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
261 rfield->offset = (char*) field - (char*) fields;
262 rfield->declaringClass = this;
269 java::lang::Class::getSignature (java::lang::StringBuffer *buffer)
272 buffer->append((jchar) method_count);
275 jstring name = getName();
276 if (name->charAt(0) != '[')
277 buffer->append((jchar) 'L');
278 buffer->append(name);
279 if (name->charAt(0) != '[')
280 buffer->append((jchar) ';');
284 // This doesn't have to be native. It is an implementation detail
285 // only called from the C++ code, though, so maybe this is clearer.
287 java::lang::Class::getSignature (JArray<jclass> *param_types,
288 jboolean is_constructor)
290 java::lang::StringBuffer *buf = new java::lang::StringBuffer ();
291 buf->append((jchar) '(');
292 jclass *v = elements (param_types);
293 for (int i = 0; i < param_types->length; ++i)
294 v[i]->getSignature(buf);
295 buf->append((jchar) ')');
297 buf->append((jchar) 'V');
298 return buf->toString();
301 java::lang::reflect::Method *
302 java::lang::Class::getDeclaredMethod (jstring name,
303 JArray<jclass> *param_types)
305 jstring partial_sig = getSignature (param_types, false);
306 jint p_len = partial_sig->length();
307 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
308 int i = isPrimitive () ? 0 : method_count;
311 // FIXME: access checks.
312 if (_Jv_equalUtf8Consts (methods[i].name, utf_name)
313 && _Jv_equaln (methods[i].signature, partial_sig, p_len))
316 using namespace java::lang::reflect;
317 Method *rmethod = new Method ();
318 rmethod->offset = (char*) (&methods[i]) - (char*) methods;
319 rmethod->declaringClass = this;
323 JvThrow (new java::lang::NoSuchMethodException);
326 JArray<java::lang::reflect::Method *> *
327 java::lang::Class::getDeclaredMethods (void)
330 int max = isPrimitive () ? 0 : method_count;
332 for (i = max; --i >= 0; )
334 _Jv_Method *method = &methods[i];
335 if (method->name == NULL
336 || _Jv_equalUtf8Consts (method->name, clinit_name)
337 || _Jv_equalUtf8Consts (method->name, init_name)
338 || _Jv_equalUtf8Consts (method->name, finit_name)
339 // Backward compatibility hack: match the legacy `$finit$' name
340 || _Jv_equalUtf8Consts (method->name, finit_leg_name))
344 JArray<java::lang::reflect::Method *> *result
345 = (JArray<java::lang::reflect::Method *> *)
346 JvNewObjectArray (numMethods, &MethodClass, NULL);
347 java::lang::reflect::Method** mptr = elements (result);
348 for (i = 0; i < max; i++)
350 _Jv_Method *method = &methods[i];
351 if (method->name == NULL
352 || _Jv_equalUtf8Consts (method->name, clinit_name)
353 || _Jv_equalUtf8Consts (method->name, init_name)
354 || _Jv_equalUtf8Consts (method->name, finit_name)
355 // Backward compatibility hack: match the legacy `$finit$' name
356 || _Jv_equalUtf8Consts (method->name, finit_leg_name))
358 java::lang::reflect::Method* rmethod
359 = new java::lang::reflect::Method ();
360 rmethod->offset = (char*) method - (char*) methods;
361 rmethod->declaringClass = this;
368 java::lang::Class::getName (void)
370 char buffer[name->length + 1];
371 memcpy (buffer, name->data, name->length);
372 buffer[name->length] = '\0';
373 return _Jv_NewStringUTF (buffer);
377 java::lang::Class::getClasses (void)
379 // Until we have inner classes, it always makes sense to return an
381 JArray<jclass> *result
382 = (JArray<jclass> *) JvNewObjectArray (0, &ClassClass, NULL);
387 java::lang::Class::getDeclaredClasses (void)
389 checkMemberAccess (java::lang::reflect::Member::DECLARED);
390 // Until we have inner classes, it always makes sense to return an
392 JArray<jclass> *result
393 = (JArray<jclass> *) JvNewObjectArray (0, &ClassClass, NULL);
398 java::lang::Class::getDeclaringClass (void)
400 // Until we have inner classes, it makes sense to always return
406 java::lang::Class::_getFields (JArray<java::lang::reflect::Field *> *result,
410 for (int i = 0; i < field_count; i++)
412 _Jv_Field *field = &fields[i];
413 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
419 java::lang::reflect::Field *rfield
420 = new java::lang::reflect::Field ();
421 rfield->offset = (char *) field - (char *) fields;
422 rfield->declaringClass = this;
423 rfield->name = _Jv_NewStringUtf8Const (field->name);
424 (elements (result))[offset++] = rfield;
427 jclass superclass = getSuperclass();
428 if (superclass != NULL)
430 int s_count = superclass->_getFields (result, offset);
434 for (int i = 0; i < interface_count; ++i)
436 int f_count = interfaces[i]->_getFields (result, offset);
443 JArray<java::lang::reflect::Field *> *
444 java::lang::Class::getFields (void)
446 using namespace java::lang::reflect;
448 int count = _getFields (NULL, 0);
450 JArray<java::lang::reflect::Field *> *result
451 = ((JArray<java::lang::reflect::Field *> *)
452 JvNewObjectArray (count, &FieldClass, NULL));
454 _getFields (result, 0);
460 java::lang::Class::getInterfaces (void)
462 jobjectArray r = JvNewObjectArray (interface_count, getClass (), NULL);
463 jobject *data = elements (r);
464 for (int i = 0; i < interface_count; ++i)
465 data[i] = interfaces[i];
466 return reinterpret_cast<JArray<jclass> *> (r);
469 java::lang::reflect::Method *
470 java::lang::Class::getMethod (jstring name, JArray<jclass> *param_types)
472 jstring partial_sig = getSignature (param_types, false);
473 jint p_len = partial_sig->length();
474 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
475 for (Class *klass = this; klass; klass = klass->getSuperclass())
477 int i = klass->isPrimitive () ? 0 : klass->method_count;
480 // FIXME: access checks.
481 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
482 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
485 using namespace java::lang::reflect;
487 // Method must be public.
488 if (! Modifier::isPublic (klass->methods[i].accflags))
491 Method *rmethod = new Method ();
492 rmethod->offset = ((char *) (&klass->methods[i])
493 - (char *) klass->methods);
494 rmethod->declaringClass = klass;
499 JvThrow (new java::lang::NoSuchMethodException);
502 // This is a very slow implementation, since it re-scans all the
503 // methods we've already listed to make sure we haven't duplicated a
504 // method. It also over-estimates the required size, so we have to
505 // shrink the result array later.
507 java::lang::Class::_getMethods (JArray<java::lang::reflect::Method *> *result,
512 // First examine all local methods
513 for (int i = isPrimitive () ? 0 : method_count; --i >= 0; )
515 _Jv_Method *method = &methods[i];
516 if (method->name == NULL
517 || _Jv_equalUtf8Consts (method->name, clinit_name)
518 || _Jv_equalUtf8Consts (method->name, init_name)
519 || _Jv_equalUtf8Consts (method->name, finit_name)
520 // Backward compatibility hack: match the legacy `$finit$' name
521 || _Jv_equalUtf8Consts (method->name, finit_leg_name))
523 // Only want public methods.
524 if (! java::lang::reflect::Modifier::isPublic (method->accflags))
527 // This is where we over-count the slots required if we aren't
528 // filling the result for real.
532 java::lang::reflect::Method **mp = elements (result);
533 // If we already have a method with this name and signature,
534 // then ignore this one. This can happen with virtual
536 for (int j = 0; j < offset; ++j)
538 _Jv_Method *meth_2 = _Jv_FromReflectedMethod (mp[j]);
539 if (_Jv_equalUtf8Consts (method->name, meth_2->name)
540 && _Jv_equalUtf8Consts (method->signature,
553 using namespace java::lang::reflect;
554 Method *rmethod = new Method ();
555 rmethod->offset = (char *) method - (char *) methods;
556 rmethod->declaringClass = this;
557 Method **mp = elements (result);
558 mp[offset + count] = rmethod;
564 // Now examine superclasses.
565 if (getSuperclass () != NULL)
567 jint s_count = getSuperclass()->_getMethods (result, offset);
572 // Finally, examine interfaces.
573 for (int i = 0; i < interface_count; ++i)
575 int f_count = interfaces[i]->_getMethods (result, offset);
583 JArray<java::lang::reflect::Method *> *
584 java::lang::Class::getMethods (void)
586 using namespace java::lang::reflect;
588 // FIXME: security checks.
590 // This will overestimate the size we need.
591 jint count = _getMethods (NULL, 0);
593 JArray<Method *> *result
594 = ((JArray<Method *> *) JvNewObjectArray (count, &MethodClass, NULL));
596 // When filling the array for real, we get the actual count. Then
597 // we resize the array.
598 jint real_count = _getMethods (result, 0);
600 if (real_count != count)
603 = ((JArray<Method *> *) JvNewObjectArray (real_count, &MethodClass,
606 Method **destp = elements (r2);
607 Method **srcp = elements (result);
609 for (int i = 0; i < real_count; ++i)
619 java::lang::Class::isAssignableFrom (jclass klass)
621 // Arguments may not have been initialized, given ".class" syntax.
622 _Jv_InitClass (this);
623 _Jv_InitClass (klass);
624 return _Jv_IsAssignableFrom (this, klass);
628 java::lang::Class::isInstance (jobject obj)
630 if (__builtin_expect (! obj || isPrimitive (), false))
632 _Jv_InitClass (this);
633 return _Jv_IsAssignableFrom (this, JV_CLASS (obj));
637 java::lang::Class::isInterface (void)
639 return (accflags & java::lang::reflect::Modifier::INTERFACE) != 0;
643 java::lang::Class::newInstance (void)
645 // FIXME: do accessibility checks here. There currently doesn't
646 // seem to be any way to do these.
647 // FIXME: we special-case one check here just to pass a Plum Hall
648 // test. Once access checking is implemented, remove this.
649 if (this == &ClassClass)
650 JvThrow (new java::lang::IllegalAccessException);
655 || java::lang::reflect::Modifier::isAbstract(accflags))
656 JvThrow (new java::lang::InstantiationException);
658 _Jv_InitClass (this);
660 _Jv_Method *meth = _Jv_GetMethodLocal (this, init_name, void_signature);
662 JvThrow (new java::lang::NoSuchMethodException);
664 jobject r = JvAllocObject (this);
665 ((void (*) (jobject)) meth->ncode) (r);
670 java::lang::Class::finalize (void)
673 JvAssert (_Jv_IsInterpretedClass (this));
674 _Jv_UnregisterClass (this);
678 // This implements the initialization process for a class. From Spec
681 java::lang::Class::initializeClass (void)
683 // jshort-circuit to avoid needless locking.
684 if (state == JV_STATE_DONE)
688 _Jv_MonitorEnter (this);
690 if (state < JV_STATE_LINKED)
693 if (_Jv_IsInterpretedClass (this))
695 // this can throw exceptions, so exit the monitor as a precaution.
696 _Jv_MonitorExit (this);
697 java::lang::ClassLoader::resolveClass0 (this);
698 _Jv_MonitorEnter (this);
703 _Jv_PrepareCompiledClass (this);
707 if (state <= JV_STATE_LINKED)
708 _Jv_PrepareConstantTimeTables (this);
711 java::lang::Thread *self = java::lang::Thread::currentThread();
712 // FIXME: `self' can be null at startup. Hence this nasty trick.
713 self = (java::lang::Thread *) ((long) self | 1);
714 while (state == JV_STATE_IN_PROGRESS && thread && thread != self)
718 if (state == JV_STATE_DONE || state == JV_STATE_IN_PROGRESS || thread == self)
720 _Jv_MonitorExit (this);
725 if (state == JV_STATE_ERROR)
727 _Jv_MonitorExit (this);
728 JvThrow (new java::lang::NoClassDefFoundError);
733 state = JV_STATE_IN_PROGRESS;
734 _Jv_MonitorExit (this);
737 if (! isInterface () && superclass)
741 superclass->initializeClass ();
743 catch (java::lang::Throwable *except)
745 // Caught an exception.
746 _Jv_MonitorEnter (this);
747 state = JV_STATE_ERROR;
749 _Jv_MonitorExit (this);
754 // Steps 8, 9, 10, 11.
757 _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name,
760 ((void (*) (void)) meth->ncode) ();
762 catch (java::lang::Throwable *except)
764 if (! ErrorClass.isInstance(except))
768 except = new ExceptionInInitializerError (except);
770 catch (java::lang::Throwable *t)
775 _Jv_MonitorEnter (this);
776 state = JV_STATE_ERROR;
778 _Jv_MonitorExit (this);
782 _Jv_MonitorEnter (this);
783 state = JV_STATE_DONE;
785 _Jv_MonitorExit (this);
791 // Some class-related convenience functions.
794 // Find a method declared in the class. If it is not declared locally
795 // (or if it is inherited), return NULL.
797 _Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
798 _Jv_Utf8Const *signature)
800 for (int i = 0; i < klass->method_count; ++i)
802 if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
803 && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
804 return &klass->methods[i];
810 _Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
811 _Jv_Utf8Const *signature)
813 for (; klass; klass = klass->getSuperclass())
815 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
824 // NOTE: MCACHE_SIZE should be a power of 2 minus one.
825 #define MCACHE_SIZE 1023
833 static _Jv_mcache method_cache[MCACHE_SIZE + 1];
836 _Jv_FindMethodInCache (jclass klass,
838 _Jv_Utf8Const *signature)
840 int index = name->hash & MCACHE_SIZE;
841 _Jv_mcache *mc = method_cache + index;
842 _Jv_Method *m = mc->method;
844 if (mc->klass == klass
845 && m != NULL // thread safe check
846 && _Jv_equalUtf8Consts (m->name, name)
847 && _Jv_equalUtf8Consts (m->signature, signature))
848 return mc->method->ncode;
853 _Jv_AddMethodToCache (jclass klass,
856 _Jv_MonitorEnter (&ClassClass);
858 int index = method->name->hash & MCACHE_SIZE;
860 method_cache[index].method = method;
861 method_cache[index].klass = klass;
863 _Jv_MonitorExit (&ClassClass);
867 _Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
868 _Jv_Utf8Const *signature)
870 using namespace java::lang::reflect;
872 void *ncode = _Jv_FindMethodInCache (klass, name, signature);
876 for (; klass; klass = klass->getSuperclass())
878 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
882 if (Modifier::isStatic(meth->accflags))
883 JvThrow (new java::lang::IncompatibleClassChangeError
884 (_Jv_GetMethodString (klass, meth->name)));
885 if (Modifier::isAbstract(meth->accflags))
886 JvThrow (new java::lang::AbstractMethodError
887 (_Jv_GetMethodString (klass, meth->name)));
888 if (! Modifier::isPublic(meth->accflags))
889 JvThrow (new java::lang::IllegalAccessError
890 (_Jv_GetMethodString (klass, meth->name)));
892 _Jv_AddMethodToCache (klass, meth);
896 JvThrow (new java::lang::IncompatibleClassChangeError);
897 return NULL; // Placate compiler.
900 // Fast interface method lookup by index.
902 _Jv_LookupInterfaceMethodIdx (jclass klass, jclass iface, int method_idx)
904 _Jv_IDispatchTable *cldt = klass->idt;
905 int idx = iface->idt->iface.ioffsets[cldt->cls.iindex] + method_idx;
906 return cldt->cls.itable[idx];
910 _Jv_IsAssignableFrom (jclass target, jclass source)
913 || (target == &ObjectClass && !source->isPrimitive())
914 || (source->ancestors != NULL
915 && source->ancestors[source->depth - target->depth] == target))
918 // If target is array, so must source be.
919 if (target->isArray ())
921 if (! source->isArray())
923 return _Jv_IsAssignableFrom(target->getComponentType(),
924 source->getComponentType());
927 if (target->isInterface())
929 // Abstract classes have no IDT, and IDTs provide no way to check
930 // two interfaces for assignability.
932 (source->idt == NULL || source->isInterface(), false))
933 return _Jv_InterfaceAssignableFrom (target, source);
935 _Jv_IDispatchTable *cl_idt = source->idt;
936 _Jv_IDispatchTable *if_idt = target->idt;
938 if (__builtin_expect ((if_idt == NULL), false))
939 return false; // No class implementing TARGET has been loaded.
940 jshort cl_iindex = cl_idt->cls.iindex;
941 if (cl_iindex <= if_idt->iface.ioffsets[0])
943 jshort offset = if_idt->iface.ioffsets[cl_iindex];
944 if (offset < cl_idt->cls.itable_length
945 && cl_idt->cls.itable[offset] == target)
953 // Interface type checking, the slow way. Returns TRUE if IFACE is a
954 // superinterface of SOURCE. This is used when SOURCE is also an interface,
955 // or a class with no interface dispatch table.
957 _Jv_InterfaceAssignableFrom (jclass iface, jclass source)
959 for (int i = 0; i < source->interface_count; i++)
961 jclass interface = source->interfaces[i];
962 if (iface == interface
963 || _Jv_InterfaceAssignableFrom (iface, interface))
967 if (!source->isInterface()
968 && source->superclass
969 && _Jv_InterfaceAssignableFrom (iface, source->superclass))
976 _Jv_IsInstanceOf(jobject obj, jclass cl)
978 if (__builtin_expect (!obj, false))
980 return (_Jv_IsAssignableFrom (cl, JV_CLASS (obj)));
984 _Jv_CheckCast (jclass c, jobject obj)
987 (obj != NULL && ! _Jv_IsAssignableFrom(c, JV_CLASS (obj)), false))
988 JvThrow (new java::lang::ClassCastException);
993 _Jv_CheckArrayStore (jobject arr, jobject obj)
997 JvAssert (arr != NULL);
998 jclass elt_class = (JV_CLASS (arr))->getComponentType();
999 jclass obj_class = JV_CLASS (obj);
1000 if (__builtin_expect
1001 (! _Jv_IsAssignableFrom (elt_class, obj_class), false))
1002 JvThrow (new java::lang::ArrayStoreException);
1006 #define INITIAL_IOFFSETS_LEN 4
1007 #define INITIAL_IFACES_LEN 4
1009 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
1011 // Generate tables for constant-time assignment testing and interface
1012 // method lookup. This implements the technique described by Per Bothner
1013 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
1014 // http://sourceware.cygnus.com/ml/java-discuss/1999-q3/msg00377.html
1016 _Jv_PrepareConstantTimeTables (jclass klass)
1018 if (klass->isPrimitive () || klass->isInterface ())
1021 // Short-circuit in case we've been called already.
1022 if ((klass->idt != NULL) || klass->depth != 0)
1025 // Calculate the class depth and ancestor table. The depth of a class
1026 // is how many "extends" it is removed from Object. Thus the depth of
1027 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
1028 // is 2. Depth is defined for all regular and array classes, but not
1029 // interfaces or primitive types.
1031 jclass klass0 = klass;
1032 jboolean has_interfaces = 0;
1033 while (klass0 != &ObjectClass)
1035 has_interfaces += klass0->interface_count;
1036 klass0 = klass0->superclass;
1040 // We do class member testing in constant time by using a small table
1041 // of all the ancestor classes within each class. The first element is
1042 // a pointer to the current class, and the rest are pointers to the
1043 // classes ancestors, ordered from the current class down by decreasing
1044 // depth. We do not include java.lang.Object in the table of ancestors,
1045 // since it is redundant.
1047 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth * sizeof (jclass));
1049 for (int index = 0; index < klass->depth; index++)
1051 klass->ancestors[index] = klass0;
1052 klass0 = klass0->superclass;
1055 if (java::lang::reflect::Modifier::isAbstract (klass->accflags))
1058 // Optimization: If class implements no interfaces, use a common
1059 // predefined interface table.
1060 if (!has_interfaces)
1062 klass->idt = &null_idt;
1067 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1072 ifaces.len = INITIAL_IFACES_LEN;
1073 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
1075 int itable_size = _Jv_GetInterfaces (klass, &ifaces);
1077 if (ifaces.count > 0)
1079 klass->idt->cls.itable =
1080 (void **) _Jv_Malloc (itable_size * sizeof (void *));
1081 klass->idt->cls.itable_length = itable_size;
1083 jshort *itable_offsets =
1084 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
1086 _Jv_GenerateITable (klass, &ifaces, itable_offsets);
1089 _Jv_FindIIndex (ifaces.list, itable_offsets, ifaces.count);
1091 for (int i=0; i < ifaces.count; i++)
1093 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
1097 klass->idt->cls.iindex = cls_iindex;
1099 _Jv_Free (ifaces.list);
1100 _Jv_Free (itable_offsets);
1104 klass->idt->cls.iindex = SHRT_MAX;
1108 // Return index of item in list, or -1 if item is not present.
1110 _Jv_IndexOf (void *item, void **list, jshort list_len)
1112 for (int i=0; i < list_len; i++)
1114 if (list[i] == item)
1120 // Find all unique interfaces directly or indirectly implemented by klass.
1121 // Returns the size of the interface dispatch table (itable) for klass, which
1122 // is the number of unique interfaces plus the total number of methods that
1123 // those interfaces declare. May extend ifaces if required.
1125 _Jv_GetInterfaces (jclass klass, _Jv_ifaces *ifaces)
1129 for (int i=0; i < klass->interface_count; i++)
1131 jclass iface = klass->interfaces[i];
1132 if (_Jv_IndexOf (iface, (void **) ifaces->list, ifaces->count) == -1)
1134 if (ifaces->count + 1 >= ifaces->len)
1136 /* Resize ifaces list */
1137 ifaces->len = ifaces->len * 2;
1138 ifaces->list = (jclass *) _Jv_Realloc (ifaces->list,
1139 ifaces->len * sizeof(jclass));
1141 ifaces->list[ifaces->count] = iface;
1144 result += _Jv_GetInterfaces (klass->interfaces[i], ifaces);
1148 if (klass->isInterface())
1150 result += klass->method_count + 1;
1154 if (klass->superclass)
1156 result += _Jv_GetInterfaces (klass->superclass, ifaces);
1162 // Fill out itable in klass, resolving method declarations in each ifaces.
1163 // itable_offsets is filled out with the position of each iface in itable,
1164 // such that itable[itable_offsets[n]] == ifaces.list[n].
1166 _Jv_GenerateITable (jclass klass, _Jv_ifaces *ifaces, jshort *itable_offsets)
1168 void **itable = klass->idt->cls.itable;
1169 jshort itable_pos = 0;
1171 for (int i=0; i < ifaces->count; i++)
1173 jclass iface = ifaces->list[i];
1174 itable_offsets[i] = itable_pos;
1175 itable_pos = _Jv_AppendPartialITable (klass, iface, itable,
1178 /* Create interface dispatch table for iface */
1179 if (iface->idt == NULL)
1182 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1184 // The first element of ioffsets is its length (itself included).
1186 (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN * sizeof (jshort));
1187 ioffsets[0] = INITIAL_IOFFSETS_LEN;
1188 for (int i=1; i < INITIAL_IOFFSETS_LEN; i++)
1191 iface->idt->iface.ioffsets = ioffsets;
1196 // Format method name for use in error messages.
1198 _Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
1200 jstring r = JvNewStringUTF (klass->name->data);
1201 r = r->concat (JvNewStringUTF ("."));
1202 r = r->concat (JvNewStringUTF (name->data));
1207 _Jv_ThrowNoSuchMethodError ()
1209 JvThrow (new java::lang::NoSuchMethodError ());
1212 // Each superinterface of a class (i.e. each interface that the class
1213 // directly or indirectly implements) has a corresponding "Partial
1214 // Interface Dispatch Table" whose size is (number of methods + 1) words.
1215 // The first word is a pointer to the interface (i.e. the java.lang.Class
1216 // instance for that interface). The remaining words are pointers to the
1217 // actual methods that implement the methods declared in the interface,
1218 // in order of declaration.
1220 // Append partial interface dispatch table for "iface" to "itable", at
1221 // position itable_pos.
1222 // Returns the offset at which the next partial ITable should be appended.
1224 _Jv_AppendPartialITable (jclass klass, jclass iface, void **itable,
1227 using namespace java::lang::reflect;
1229 itable[pos++] = (void *) iface;
1232 for (int j=0; j < iface->method_count; j++)
1235 for (jclass cl = klass; cl; cl = cl->getSuperclass())
1237 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
1238 iface->methods[j].signature);
1244 if (meth && (meth->name->data[0] == '<'))
1246 // leave a placeholder in the itable for hidden init methods.
1251 if (Modifier::isStatic(meth->accflags))
1252 JvThrow (new java::lang::IncompatibleClassChangeError
1253 (_Jv_GetMethodString (klass, meth->name)));
1254 if (Modifier::isAbstract(meth->accflags))
1255 JvThrow (new java::lang::AbstractMethodError
1256 (_Jv_GetMethodString (klass, meth->name)));
1257 if (! Modifier::isPublic(meth->accflags))
1258 JvThrow (new java::lang::IllegalAccessError
1259 (_Jv_GetMethodString (klass, meth->name)));
1261 itable[pos] = meth->ncode;
1265 // The method doesn't exist in klass. Binary compatibility rules
1266 // permit this, so we delay the error until runtime using a pointer
1267 // to a method which throws an exception.
1268 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
1276 static _Jv_Mutex_t iindex_mutex;
1277 bool iindex_mutex_initialized = false;
1279 // We need to find the correct offset in the Class Interface Dispatch
1280 // Table for a given interface. Once we have that, invoking an interface
1281 // method just requires combining the Method's index in the interface
1282 // (known at compile time) to get the correct method. Doing a type test
1283 // (cast or instanceof) is the same problem: Once we have a possible Partial
1284 // Interface Dispatch Table, we just compare the first element to see if it
1285 // matches the desired interface. So how can we find the correct offset?
1286 // Our solution is to keep a vector of candiate offsets in each interface
1287 // (idt->iface.ioffsets), and in each class we have an index
1288 // (idt->cls.iindex) used to select the correct offset from ioffsets.
1290 // Calculate and return iindex for a new class.
1291 // ifaces is a vector of num interfaces that the class implements.
1292 // offsets[j] is the offset in the interface dispatch table for the
1293 // interface corresponding to ifaces[j].
1294 // May extend the interface ioffsets if required.
1296 _Jv_FindIIndex (jclass *ifaces, jshort *offsets, jshort num)
1301 // Acquire a global lock to prevent itable corruption in case of multiple
1302 // classes that implement an intersecting set of interfaces being linked
1303 // simultaneously. We can assume that the mutex will be initialized
1305 if (! iindex_mutex_initialized)
1307 _Jv_MutexInit (&iindex_mutex);
1308 iindex_mutex_initialized = true;
1311 _Jv_MutexLock (&iindex_mutex);
1313 for (i=1;; i++) /* each potential position in ioffsets */
1315 for (j=0;; j++) /* each iface */
1319 if (i > ifaces[j]->idt->iface.ioffsets[0])
1321 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
1322 /* We can potentially share this position with another class. */
1323 if (ioffset >= 0 && ioffset != offsets[j])
1324 break; /* Nope. Try next i. */
1328 for (j = 0; j < num; j++)
1330 int len = ifaces[j]->idt->iface.ioffsets[0];
1333 /* Resize ioffsets. */
1334 int newlen = 2 * len;
1337 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
1338 jshort *new_ioffsets = (jshort *) _Jv_Realloc (old_ioffsets,
1339 newlen * sizeof(jshort));
1340 new_ioffsets[0] = newlen;
1342 while (len < newlen)
1343 new_ioffsets[len++] = -1;
1345 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
1347 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
1350 _Jv_MutexUnlock (&iindex_mutex);
1355 // Only used by serialization
1356 java::lang::reflect::Field *
1357 java::lang::Class::getPrivateField (jstring name)
1359 int hash = name->hashCode ();
1361 java::lang::reflect::Field* rfield;
1362 for (int i = 0; i < field_count; i++)
1364 _Jv_Field *field = &fields[i];
1365 if (! _Jv_equal (field->name, name, hash))
1367 rfield = new java::lang::reflect::Field ();
1368 rfield->offset = (char*) field - (char*) fields;
1369 rfield->declaringClass = this;
1370 rfield->name = name;
1373 jclass superclass = getSuperclass();
1374 if (superclass == NULL)
1376 rfield = superclass->getPrivateField(name);
1377 for (int i = 0; i < interface_count && rfield == NULL; ++i)
1378 rfield = interfaces[i]->getPrivateField (name);
1382 // Only used by serialization
1383 java::lang::reflect::Method *
1384 java::lang::Class::getPrivateMethod (jstring name, JArray<jclass> *param_types)
1386 jstring partial_sig = getSignature (param_types, false);
1387 jint p_len = partial_sig->length();
1388 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
1389 for (Class *klass = this; klass; klass = klass->getSuperclass())
1391 int i = klass->isPrimitive () ? 0 : klass->method_count;
1394 // FIXME: access checks.
1395 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
1396 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
1399 using namespace java::lang::reflect;
1401 Method *rmethod = new Method ();
1402 rmethod->offset = ((char *) (&klass->methods[i])
1403 - (char *) klass->methods);
1404 rmethod->declaringClass = klass;
1409 JvThrow (new java::lang::NoSuchMethodException);