1 // natClass.cc - Implementation of java.lang.Class native methods.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002 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/IllegalArgumentException.h>
38 #include <java/lang/IncompatibleClassChangeError.h>
39 #include <java/lang/InstantiationException.h>
40 #include <java/lang/NoClassDefFoundError.h>
41 #include <java/lang/NoSuchFieldException.h>
42 #include <java/lang/NoSuchMethodError.h>
43 #include <java/lang/NoSuchMethodException.h>
44 #include <java/lang/Thread.h>
45 #include <java/lang/NullPointerException.h>
46 #include <java/lang/RuntimePermission.h>
47 #include <java/lang/System.h>
48 #include <java/lang/SecurityManager.h>
49 #include <java/lang/StringBuffer.h>
50 #include <gcj/method.h>
52 #include <java-cpool.h>
59 java::lang::Class::forName (jstring className, jboolean initialize,
60 java::lang::ClassLoader *loader)
63 throw new java::lang::NullPointerException;
65 jsize length = _Jv_GetStringUTFLength (className);
67 _Jv_GetStringUTFRegion (className, 0, length, buffer);
69 _Jv_Utf8Const *name = _Jv_makeUtf8Const (buffer, length);
71 if (! _Jv_VerifyClassName (name))
72 throw new java::lang::ClassNotFoundException (className);
74 // FIXME: should use bootstrap class loader if loader is null.
75 jclass klass = (buffer[0] == '['
76 ? _Jv_FindClassFromSignature (name->data, loader)
77 : _Jv_FindClass (name, loader));
80 throw new java::lang::ClassNotFoundException (className);
83 _Jv_InitClass (klass);
89 java::lang::Class::forName (jstring className)
91 // FIXME: should use class loader from calling method.
92 return forName (className, true, NULL);
95 java::lang::ClassLoader *
96 java::lang::Class::getClassLoader (void)
99 // FIXME: the checks we need to do are more complex. See the spec.
100 // Currently we can't implement them.
101 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
103 s->checkPermission (new RuntimePermission (JvNewStringLatin1 ("getClassLoader")));
106 // The spec requires us to return `null' for primitive classes. In
107 // other cases we have the option of returning `null' for classes
108 // loaded with the bootstrap loader. All gcj-compiled classes which
109 // are linked into the application used to return `null' here, but
110 // that confuses some poorly-written applications. It is a useful
111 // and apparently harmless compatibility hack to simply never return
115 return loader ? loader : ClassLoader::getSystemClassLoader ();
118 java::lang::reflect::Constructor *
119 java::lang::Class::getConstructor (JArray<jclass> *param_types)
121 jstring partial_sig = getSignature (param_types, true);
122 jint hash = partial_sig->hashCode ();
124 int i = isPrimitive () ? 0 : method_count;
127 // FIXME: access checks.
128 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
129 && _Jv_equal (methods[i].signature, partial_sig, hash))
131 // Found it. For getConstructor, the constructor must be
133 using namespace java::lang::reflect;
134 if (! Modifier::isPublic(methods[i].accflags))
136 Constructor *cons = new Constructor ();
137 cons->offset = (char *) (&methods[i]) - (char *) methods;
138 cons->declaringClass = this;
142 throw new java::lang::NoSuchMethodException;
145 JArray<java::lang::reflect::Constructor *> *
146 java::lang::Class::_getConstructors (jboolean declared)
148 // FIXME: this method needs access checks.
150 int numConstructors = 0;
151 int max = isPrimitive () ? 0 : method_count;
153 for (i = max; --i >= 0; )
155 _Jv_Method *method = &methods[i];
156 if (method->name == NULL
157 || ! _Jv_equalUtf8Consts (method->name, init_name))
160 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
164 JArray<java::lang::reflect::Constructor *> *result
165 = (JArray<java::lang::reflect::Constructor *> *)
166 JvNewObjectArray (numConstructors,
167 &java::lang::reflect::Constructor::class$,
169 java::lang::reflect::Constructor** cptr = elements (result);
170 for (i = 0; i < max; i++)
172 _Jv_Method *method = &methods[i];
173 if (method->name == NULL
174 || ! _Jv_equalUtf8Consts (method->name, init_name))
177 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
179 java::lang::reflect::Constructor *cons
180 = new java::lang::reflect::Constructor ();
181 cons->offset = (char *) method - (char *) methods;
182 cons->declaringClass = this;
188 java::lang::reflect::Constructor *
189 java::lang::Class::getDeclaredConstructor (JArray<jclass> *param_types)
191 jstring partial_sig = getSignature (param_types, true);
192 jint hash = partial_sig->hashCode ();
194 int i = isPrimitive () ? 0 : method_count;
197 // FIXME: access checks.
198 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
199 && _Jv_equal (methods[i].signature, partial_sig, hash))
202 using namespace java::lang::reflect;
203 Constructor *cons = new Constructor ();
204 cons->offset = (char *) (&methods[i]) - (char *) methods;
205 cons->declaringClass = this;
209 throw new java::lang::NoSuchMethodException;
212 java::lang::reflect::Field *
213 java::lang::Class::getField (jstring name, jint hash)
215 java::lang::reflect::Field* rfield;
216 for (int i = 0; i < field_count; i++)
218 _Jv_Field *field = &fields[i];
219 if (! _Jv_equal (field->name, name, hash))
221 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
223 rfield = new java::lang::reflect::Field ();
224 rfield->offset = (char*) field - (char*) fields;
225 rfield->declaringClass = this;
229 jclass superclass = getSuperclass();
230 if (superclass == NULL)
232 rfield = superclass->getField(name, hash);
233 for (int i = 0; i < interface_count && rfield == NULL; ++i)
234 rfield = interfaces[i]->getField (name, hash);
238 java::lang::reflect::Field *
239 java::lang::Class::getDeclaredField (jstring name)
241 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
243 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
244 int hash = name->hashCode();
245 for (int i = 0; i < field_count; i++)
247 _Jv_Field *field = &fields[i];
248 if (! _Jv_equal (field->name, name, hash))
250 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
251 rfield->offset = (char*) field - (char*) fields;
252 rfield->declaringClass = this;
256 throw new java::lang::NoSuchFieldException (name);
259 JArray<java::lang::reflect::Field *> *
260 java::lang::Class::getDeclaredFields (void)
262 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
264 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
265 JArray<java::lang::reflect::Field *> *result
266 = (JArray<java::lang::reflect::Field *> *)
267 JvNewObjectArray (field_count, &java::lang::reflect::Field::class$, NULL);
268 java::lang::reflect::Field** fptr = elements (result);
269 for (int i = 0; i < field_count; i++)
271 _Jv_Field *field = &fields[i];
272 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
273 rfield->offset = (char*) field - (char*) fields;
274 rfield->declaringClass = this;
281 java::lang::Class::getSignature (java::lang::StringBuffer *buffer)
284 buffer->append((jchar) method_count);
287 jstring name = getName();
288 if (name->charAt(0) != '[')
289 buffer->append((jchar) 'L');
290 buffer->append(name);
291 if (name->charAt(0) != '[')
292 buffer->append((jchar) ';');
296 // This doesn't have to be native. It is an implementation detail
297 // only called from the C++ code, though, so maybe this is clearer.
299 java::lang::Class::getSignature (JArray<jclass> *param_types,
300 jboolean is_constructor)
302 java::lang::StringBuffer *buf = new java::lang::StringBuffer ();
303 buf->append((jchar) '(');
304 // A NULL param_types means "no parameters".
305 if (param_types != NULL)
307 jclass *v = elements (param_types);
308 for (int i = 0; i < param_types->length; ++i)
309 v[i]->getSignature(buf);
311 buf->append((jchar) ')');
313 buf->append((jchar) 'V');
314 return buf->toString();
317 java::lang::reflect::Method *
318 java::lang::Class::_getDeclaredMethod (jstring name,
319 JArray<jclass> *param_types)
321 jstring partial_sig = getSignature (param_types, false);
322 jint p_len = partial_sig->length();
323 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
324 int i = isPrimitive () ? 0 : method_count;
327 if (_Jv_equalUtf8Consts (methods[i].name, utf_name)
328 && _Jv_equaln (methods[i].signature, partial_sig, p_len))
331 using namespace java::lang::reflect;
332 Method *rmethod = new Method ();
333 rmethod->offset = (char*) (&methods[i]) - (char*) methods;
334 rmethod->declaringClass = this;
341 JArray<java::lang::reflect::Method *> *
342 java::lang::Class::getDeclaredMethods (void)
345 int max = isPrimitive () ? 0 : method_count;
347 for (i = max; --i >= 0; )
349 _Jv_Method *method = &methods[i];
350 if (method->name == NULL
351 || _Jv_equalUtf8Consts (method->name, clinit_name)
352 || _Jv_equalUtf8Consts (method->name, init_name)
353 || _Jv_equalUtf8Consts (method->name, finit_name))
357 JArray<java::lang::reflect::Method *> *result
358 = (JArray<java::lang::reflect::Method *> *)
359 JvNewObjectArray (numMethods, &java::lang::reflect::Method::class$, NULL);
360 java::lang::reflect::Method** mptr = elements (result);
361 for (i = 0; i < max; i++)
363 _Jv_Method *method = &methods[i];
364 if (method->name == NULL
365 || _Jv_equalUtf8Consts (method->name, clinit_name)
366 || _Jv_equalUtf8Consts (method->name, init_name)
367 || _Jv_equalUtf8Consts (method->name, finit_name))
369 java::lang::reflect::Method* rmethod
370 = new java::lang::reflect::Method ();
371 rmethod->offset = (char*) method - (char*) methods;
372 rmethod->declaringClass = this;
379 java::lang::Class::getName (void)
381 char buffer[name->length + 1];
382 memcpy (buffer, name->data, name->length);
383 buffer[name->length] = '\0';
384 return _Jv_NewStringUTF (buffer);
388 java::lang::Class::getClasses (void)
390 // FIXME: security checking.
392 // Until we have inner classes, it always makes sense to return an
394 JArray<jclass> *result
395 = (JArray<jclass> *) JvNewObjectArray (0, &java::lang::Class::class$,
401 java::lang::Class::getDeclaredClasses (void)
403 checkMemberAccess (java::lang::reflect::Member::DECLARED);
404 // Until we have inner classes, it always makes sense to return an
406 JArray<jclass> *result
407 = (JArray<jclass> *) JvNewObjectArray (0, &java::lang::Class::class$,
413 java::lang::Class::getDeclaringClass (void)
415 // Until we have inner classes, it makes sense to always return
421 java::lang::Class::_getFields (JArray<java::lang::reflect::Field *> *result,
425 for (int i = 0; i < field_count; i++)
427 _Jv_Field *field = &fields[i];
428 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
434 java::lang::reflect::Field *rfield
435 = new java::lang::reflect::Field ();
436 rfield->offset = (char *) field - (char *) fields;
437 rfield->declaringClass = this;
438 rfield->name = _Jv_NewStringUtf8Const (field->name);
439 (elements (result))[offset++] = rfield;
442 jclass superclass = getSuperclass();
443 if (superclass != NULL)
445 int s_count = superclass->_getFields (result, offset);
449 for (int i = 0; i < interface_count; ++i)
451 int f_count = interfaces[i]->_getFields (result, offset);
458 JArray<java::lang::reflect::Field *> *
459 java::lang::Class::getFields (void)
461 // FIXME: security checking.
463 using namespace java::lang::reflect;
465 int count = _getFields (NULL, 0);
467 JArray<java::lang::reflect::Field *> *result
468 = ((JArray<java::lang::reflect::Field *> *)
469 JvNewObjectArray (count, &java::lang::reflect::Field::class$, NULL));
471 _getFields (result, 0);
477 java::lang::Class::getInterfaces (void)
479 jobjectArray r = JvNewObjectArray (interface_count, getClass (), NULL);
480 jobject *data = elements (r);
481 for (int i = 0; i < interface_count; ++i)
482 data[i] = interfaces[i];
483 return reinterpret_cast<JArray<jclass> *> (r);
486 java::lang::reflect::Method *
487 java::lang::Class::_getMethod (jstring name, JArray<jclass> *param_types)
489 jstring partial_sig = getSignature (param_types, false);
490 jint p_len = partial_sig->length();
491 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
492 for (Class *klass = this; klass; klass = klass->getSuperclass())
494 int i = klass->isPrimitive () ? 0 : klass->method_count;
497 // FIXME: access checks.
498 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
499 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
502 using namespace java::lang::reflect;
504 // Method must be public.
505 if (! Modifier::isPublic (klass->methods[i].accflags))
508 Method *rmethod = new Method ();
509 rmethod->offset = ((char *) (&klass->methods[i])
510 - (char *) klass->methods);
511 rmethod->declaringClass = klass;
517 // If we haven't found a match, and this class is an interface, then
518 // check all the superinterfaces.
521 for (int i = 0; i < interface_count; ++i)
523 using namespace java::lang::reflect;
524 Method *rmethod = interfaces[i]->_getMethod (name, param_types);
533 // This is a very slow implementation, since it re-scans all the
534 // methods we've already listed to make sure we haven't duplicated a
535 // method. It also over-estimates the required size, so we have to
536 // shrink the result array later.
538 java::lang::Class::_getMethods (JArray<java::lang::reflect::Method *> *result,
543 // First examine all local methods
544 for (int i = isPrimitive () ? 0 : method_count; --i >= 0; )
546 _Jv_Method *method = &methods[i];
547 if (method->name == NULL
548 || _Jv_equalUtf8Consts (method->name, clinit_name)
549 || _Jv_equalUtf8Consts (method->name, init_name)
550 || _Jv_equalUtf8Consts (method->name, finit_name))
552 // Only want public methods.
553 if (! java::lang::reflect::Modifier::isPublic (method->accflags))
556 // This is where we over-count the slots required if we aren't
557 // filling the result for real.
561 java::lang::reflect::Method **mp = elements (result);
562 // If we already have a method with this name and signature,
563 // then ignore this one. This can happen with virtual
565 for (int j = 0; j < offset; ++j)
567 _Jv_Method *meth_2 = _Jv_FromReflectedMethod (mp[j]);
568 if (_Jv_equalUtf8Consts (method->name, meth_2->name)
569 && _Jv_equalUtf8Consts (method->signature,
582 using namespace java::lang::reflect;
583 Method *rmethod = new Method ();
584 rmethod->offset = (char *) method - (char *) methods;
585 rmethod->declaringClass = this;
586 Method **mp = elements (result);
587 mp[offset + count] = rmethod;
593 // Now examine superclasses.
594 if (getSuperclass () != NULL)
596 jint s_count = getSuperclass()->_getMethods (result, offset);
601 // Finally, examine interfaces.
602 for (int i = 0; i < interface_count; ++i)
604 int f_count = interfaces[i]->_getMethods (result, offset);
612 JArray<java::lang::reflect::Method *> *
613 java::lang::Class::getMethods (void)
615 using namespace java::lang::reflect;
617 // FIXME: security checks.
619 // This will overestimate the size we need.
620 jint count = _getMethods (NULL, 0);
622 JArray<Method *> *result
623 = ((JArray<Method *> *) JvNewObjectArray (count,
627 // When filling the array for real, we get the actual count. Then
628 // we resize the array.
629 jint real_count = _getMethods (result, 0);
631 if (real_count != count)
634 = ((JArray<Method *> *) JvNewObjectArray (real_count,
638 Method **destp = elements (r2);
639 Method **srcp = elements (result);
641 for (int i = 0; i < real_count; ++i)
651 java::lang::Class::isAssignableFrom (jclass klass)
653 // Arguments may not have been initialized, given ".class" syntax.
654 _Jv_InitClass (this);
655 _Jv_InitClass (klass);
656 return _Jv_IsAssignableFrom (this, klass);
660 java::lang::Class::isInstance (jobject obj)
664 _Jv_InitClass (this);
665 return _Jv_IsAssignableFrom (this, JV_CLASS (obj));
669 java::lang::Class::newInstance (void)
671 // FIXME: do accessibility checks here. There currently doesn't
672 // seem to be any way to do these.
673 // FIXME: we special-case one check here just to pass a Plum Hall
674 // test. Once access checking is implemented, remove this.
675 if (this == &java::lang::Class::class$)
676 throw new java::lang::IllegalAccessException;
681 || java::lang::reflect::Modifier::isAbstract(accflags))
682 throw new java::lang::InstantiationException;
684 _Jv_InitClass (this);
686 _Jv_Method *meth = _Jv_GetMethodLocal (this, init_name, void_signature);
688 throw new java::lang::NoSuchMethodException;
690 jobject r = JvAllocObject (this);
691 ((void (*) (jobject)) meth->ncode) (r);
696 java::lang::Class::finalize (void)
699 JvAssert (_Jv_IsInterpretedClass (this));
700 _Jv_UnregisterClass (this);
704 // This implements the initialization process for a class. From Spec
707 java::lang::Class::initializeClass (void)
709 // short-circuit to avoid needless locking.
710 if (state == JV_STATE_DONE)
714 _Jv_MonitorEnter (this);
716 if (state < JV_STATE_LINKED)
719 if (_Jv_IsInterpretedClass (this))
721 // this can throw exceptions, so exit the monitor as a precaution.
722 _Jv_MonitorExit (this);
723 java::lang::ClassLoader::resolveClass0 (this);
724 _Jv_MonitorEnter (this);
729 _Jv_PrepareCompiledClass (this);
733 if (state <= JV_STATE_LINKED)
734 _Jv_PrepareConstantTimeTables (this);
737 java::lang::Thread *self = java::lang::Thread::currentThread();
738 // FIXME: `self' can be null at startup. Hence this nasty trick.
739 self = (java::lang::Thread *) ((long) self | 1);
740 while (state == JV_STATE_IN_PROGRESS && thread && thread != self)
744 if (state == JV_STATE_DONE
745 || state == JV_STATE_IN_PROGRESS
748 _Jv_MonitorExit (this);
753 if (state == JV_STATE_ERROR)
755 _Jv_MonitorExit (this);
756 throw new java::lang::NoClassDefFoundError;
761 state = JV_STATE_IN_PROGRESS;
762 _Jv_MonitorExit (this);
765 if (! isInterface () && superclass)
769 _Jv_InitClass (superclass);
771 catch (java::lang::Throwable *except)
773 // Caught an exception.
774 _Jv_MonitorEnter (this);
775 state = JV_STATE_ERROR;
777 _Jv_MonitorExit (this);
782 // Steps 8, 9, 10, 11.
785 _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name,
788 ((void (*) (void)) meth->ncode) ();
790 catch (java::lang::Throwable *except)
792 if (! java::lang::Error::class$.isInstance(except))
796 except = new ExceptionInInitializerError (except);
798 catch (java::lang::Throwable *t)
803 _Jv_MonitorEnter (this);
804 state = JV_STATE_ERROR;
806 _Jv_MonitorExit (this);
810 _Jv_MonitorEnter (this);
811 state = JV_STATE_DONE;
813 _Jv_MonitorExit (this);
819 // Some class-related convenience functions.
822 // Find a method declared in the class. If it is not declared locally
823 // (or if it is inherited), return NULL.
825 _Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
826 _Jv_Utf8Const *signature)
828 for (int i = 0; i < klass->method_count; ++i)
830 if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
831 && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
832 return &klass->methods[i];
838 _Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
839 _Jv_Utf8Const *signature)
841 for (; klass; klass = klass->getSuperclass())
843 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
852 // NOTE: MCACHE_SIZE should be a power of 2 minus one.
853 #define MCACHE_SIZE 1023
861 static _Jv_mcache method_cache[MCACHE_SIZE + 1];
864 _Jv_FindMethodInCache (jclass klass,
866 _Jv_Utf8Const *signature)
868 int index = name->hash & MCACHE_SIZE;
869 _Jv_mcache *mc = method_cache + index;
870 _Jv_Method *m = mc->method;
872 if (mc->klass == klass
873 && m != NULL // thread safe check
874 && _Jv_equalUtf8Consts (m->name, name)
875 && _Jv_equalUtf8Consts (m->signature, signature))
876 return mc->method->ncode;
881 _Jv_AddMethodToCache (jclass klass,
884 _Jv_MonitorEnter (&java::lang::Class::class$);
886 int index = method->name->hash & MCACHE_SIZE;
888 method_cache[index].method = method;
889 method_cache[index].klass = klass;
891 _Jv_MonitorExit (&java::lang::Class::class$);
895 _Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
896 _Jv_Utf8Const *signature)
898 using namespace java::lang::reflect;
900 void *ncode = _Jv_FindMethodInCache (klass, name, signature);
904 for (; klass; klass = klass->getSuperclass())
906 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
910 if (Modifier::isStatic(meth->accflags))
911 throw new java::lang::IncompatibleClassChangeError
912 (_Jv_GetMethodString (klass, meth->name));
913 if (Modifier::isAbstract(meth->accflags))
914 throw new java::lang::AbstractMethodError
915 (_Jv_GetMethodString (klass, meth->name));
916 if (! Modifier::isPublic(meth->accflags))
917 throw new java::lang::IllegalAccessError
918 (_Jv_GetMethodString (klass, meth->name));
920 _Jv_AddMethodToCache (klass, meth);
924 throw new java::lang::IncompatibleClassChangeError;
927 // Fast interface method lookup by index.
929 _Jv_LookupInterfaceMethodIdx (jclass klass, jclass iface, int method_idx)
931 _Jv_IDispatchTable *cldt = klass->idt;
932 int idx = iface->idt->iface.ioffsets[cldt->cls.iindex] + method_idx;
933 return cldt->cls.itable[idx];
937 _Jv_IsAssignableFrom (jclass target, jclass source)
939 if (source == target)
942 // If target is array, so must source be.
943 if (target->isArray ())
945 if (! source->isArray())
947 return _Jv_IsAssignableFrom(target->getComponentType(),
948 source->getComponentType());
951 if (target->isInterface())
953 // Abstract classes have no IDT, and IDTs provide no way to check
954 // two interfaces for assignability.
956 (source->idt == NULL || source->isInterface(), false))
957 return _Jv_InterfaceAssignableFrom (target, source);
959 _Jv_IDispatchTable *cl_idt = source->idt;
960 _Jv_IDispatchTable *if_idt = target->idt;
962 if (__builtin_expect ((if_idt == NULL), false))
963 return false; // No class implementing TARGET has been loaded.
964 jshort cl_iindex = cl_idt->cls.iindex;
965 if (cl_iindex < if_idt->iface.ioffsets[0])
967 jshort offset = if_idt->iface.ioffsets[cl_iindex];
968 if (offset != -1 && offset < cl_idt->cls.itable_length
969 && cl_idt->cls.itable[offset] == target)
975 // Primitive TYPE classes are only assignable to themselves.
976 if (__builtin_expect (target->isPrimitive(), false))
979 if (target == &java::lang::Object::class$)
981 if (source->isPrimitive())
985 else if (source->ancestors != NULL
986 && target->ancestors != NULL
987 && source->depth >= target->depth
988 && source->ancestors[source->depth - target->depth] == target)
994 // Interface type checking, the slow way. Returns TRUE if IFACE is a
995 // superinterface of SOURCE. This is used when SOURCE is also an interface,
996 // or a class with no interface dispatch table.
998 _Jv_InterfaceAssignableFrom (jclass iface, jclass source)
1000 for (int i = 0; i < source->interface_count; i++)
1002 jclass interface = source->interfaces[i];
1003 if (iface == interface
1004 || _Jv_InterfaceAssignableFrom (iface, interface))
1008 if (!source->isInterface()
1009 && source->superclass
1010 && _Jv_InterfaceAssignableFrom (iface, source->superclass))
1017 _Jv_IsInstanceOf(jobject obj, jclass cl)
1019 if (__builtin_expect (!obj, false))
1021 return (_Jv_IsAssignableFrom (cl, JV_CLASS (obj)));
1025 _Jv_CheckCast (jclass c, jobject obj)
1027 if (__builtin_expect
1028 (obj != NULL && ! _Jv_IsAssignableFrom(c, JV_CLASS (obj)), false))
1029 throw new java::lang::ClassCastException
1030 ((new java::lang::StringBuffer
1031 (obj->getClass()->getName()))->append
1032 (JvNewStringUTF(" cannot be cast to "))->append
1033 (c->getName())->toString());
1039 _Jv_CheckArrayStore (jobject arr, jobject obj)
1043 JvAssert (arr != NULL);
1044 jclass elt_class = (JV_CLASS (arr))->getComponentType();
1045 jclass obj_class = JV_CLASS (obj);
1046 if (__builtin_expect
1047 (! _Jv_IsAssignableFrom (elt_class, obj_class), false))
1048 throw new java::lang::ArrayStoreException;
1052 #define INITIAL_IOFFSETS_LEN 4
1053 #define INITIAL_IFACES_LEN 4
1055 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
1057 // Generate tables for constant-time assignment testing and interface
1058 // method lookup. This implements the technique described by Per Bothner
1059 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
1060 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
1062 _Jv_PrepareConstantTimeTables (jclass klass)
1064 if (klass->isPrimitive () || klass->isInterface ())
1067 // Short-circuit in case we've been called already.
1068 if ((klass->idt != NULL) || klass->depth != 0)
1071 // Calculate the class depth and ancestor table. The depth of a class
1072 // is how many "extends" it is removed from Object. Thus the depth of
1073 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
1074 // is 2. Depth is defined for all regular and array classes, but not
1075 // interfaces or primitive types.
1077 jclass klass0 = klass;
1078 jboolean has_interfaces = 0;
1079 while (klass0 != &java::lang::Object::class$)
1081 has_interfaces += klass0->interface_count;
1082 klass0 = klass0->superclass;
1086 // We do class member testing in constant time by using a small table
1087 // of all the ancestor classes within each class. The first element is
1088 // a pointer to the current class, and the rest are pointers to the
1089 // classes ancestors, ordered from the current class down by decreasing
1090 // depth. We do not include java.lang.Object in the table of ancestors,
1091 // since it is redundant.
1093 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth * sizeof (jclass));
1095 for (int index = 0; index < klass->depth; index++)
1097 klass->ancestors[index] = klass0;
1098 klass0 = klass0->superclass;
1101 if (java::lang::reflect::Modifier::isAbstract (klass->accflags))
1104 // Optimization: If class implements no interfaces, use a common
1105 // predefined interface table.
1106 if (!has_interfaces)
1108 klass->idt = &null_idt;
1113 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1118 ifaces.len = INITIAL_IFACES_LEN;
1119 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
1121 int itable_size = _Jv_GetInterfaces (klass, &ifaces);
1123 if (ifaces.count > 0)
1125 klass->idt->cls.itable =
1126 (void **) _Jv_Malloc (itable_size * sizeof (void *));
1127 klass->idt->cls.itable_length = itable_size;
1129 jshort *itable_offsets =
1130 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
1132 _Jv_GenerateITable (klass, &ifaces, itable_offsets);
1135 _Jv_FindIIndex (ifaces.list, itable_offsets, ifaces.count);
1137 for (int i=0; i < ifaces.count; i++)
1139 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
1143 klass->idt->cls.iindex = cls_iindex;
1145 _Jv_Free (ifaces.list);
1146 _Jv_Free (itable_offsets);
1150 klass->idt->cls.iindex = SHRT_MAX;
1154 // Return index of item in list, or -1 if item is not present.
1156 _Jv_IndexOf (void *item, void **list, jshort list_len)
1158 for (int i=0; i < list_len; i++)
1160 if (list[i] == item)
1166 // Find all unique interfaces directly or indirectly implemented by klass.
1167 // Returns the size of the interface dispatch table (itable) for klass, which
1168 // is the number of unique interfaces plus the total number of methods that
1169 // those interfaces declare. May extend ifaces if required.
1171 _Jv_GetInterfaces (jclass klass, _Jv_ifaces *ifaces)
1175 for (int i=0; i < klass->interface_count; i++)
1177 jclass iface = klass->interfaces[i];
1178 if (_Jv_IndexOf (iface, (void **) ifaces->list, ifaces->count) == -1)
1180 if (ifaces->count + 1 >= ifaces->len)
1182 /* Resize ifaces list */
1183 ifaces->len = ifaces->len * 2;
1184 ifaces->list = (jclass *) _Jv_Realloc (ifaces->list,
1185 ifaces->len * sizeof(jclass));
1187 ifaces->list[ifaces->count] = iface;
1190 result += _Jv_GetInterfaces (klass->interfaces[i], ifaces);
1194 if (klass->isInterface())
1196 result += klass->method_count + 1;
1200 if (klass->superclass)
1202 result += _Jv_GetInterfaces (klass->superclass, ifaces);
1208 // Fill out itable in klass, resolving method declarations in each ifaces.
1209 // itable_offsets is filled out with the position of each iface in itable,
1210 // such that itable[itable_offsets[n]] == ifaces.list[n].
1212 _Jv_GenerateITable (jclass klass, _Jv_ifaces *ifaces, jshort *itable_offsets)
1214 void **itable = klass->idt->cls.itable;
1215 jshort itable_pos = 0;
1217 for (int i=0; i < ifaces->count; i++)
1219 jclass iface = ifaces->list[i];
1220 itable_offsets[i] = itable_pos;
1221 itable_pos = _Jv_AppendPartialITable (klass, iface, itable, itable_pos);
1223 /* Create interface dispatch table for iface */
1224 if (iface->idt == NULL)
1227 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1229 // The first element of ioffsets is its length (itself included).
1231 (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN * sizeof (jshort));
1232 ioffsets[0] = INITIAL_IOFFSETS_LEN;
1233 for (int i=1; i < INITIAL_IOFFSETS_LEN; i++)
1236 iface->idt->iface.ioffsets = ioffsets;
1241 // Format method name for use in error messages.
1243 _Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
1245 jstring r = JvNewStringUTF (klass->name->data);
1246 r = r->concat (JvNewStringUTF ("."));
1247 r = r->concat (JvNewStringUTF (name->data));
1252 _Jv_ThrowNoSuchMethodError ()
1254 throw new java::lang::NoSuchMethodError;
1257 // Each superinterface of a class (i.e. each interface that the class
1258 // directly or indirectly implements) has a corresponding "Partial
1259 // Interface Dispatch Table" whose size is (number of methods + 1) words.
1260 // The first word is a pointer to the interface (i.e. the java.lang.Class
1261 // instance for that interface). The remaining words are pointers to the
1262 // actual methods that implement the methods declared in the interface,
1263 // in order of declaration.
1265 // Append partial interface dispatch table for "iface" to "itable", at
1266 // position itable_pos.
1267 // Returns the offset at which the next partial ITable should be appended.
1269 _Jv_AppendPartialITable (jclass klass, jclass iface, void **itable,
1272 using namespace java::lang::reflect;
1274 itable[pos++] = (void *) iface;
1277 for (int j=0; j < iface->method_count; j++)
1280 for (jclass cl = klass; cl; cl = cl->getSuperclass())
1282 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
1283 iface->methods[j].signature);
1289 if (meth && (meth->name->data[0] == '<'))
1291 // leave a placeholder in the itable for hidden init methods.
1296 if (Modifier::isStatic(meth->accflags))
1297 throw new java::lang::IncompatibleClassChangeError
1298 (_Jv_GetMethodString (klass, meth->name));
1299 if (Modifier::isAbstract(meth->accflags))
1300 throw new java::lang::AbstractMethodError
1301 (_Jv_GetMethodString (klass, meth->name));
1302 if (! Modifier::isPublic(meth->accflags))
1303 throw new java::lang::IllegalAccessError
1304 (_Jv_GetMethodString (klass, meth->name));
1306 itable[pos] = meth->ncode;
1310 // The method doesn't exist in klass. Binary compatibility rules
1311 // permit this, so we delay the error until runtime using a pointer
1312 // to a method which throws an exception.
1313 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
1321 static _Jv_Mutex_t iindex_mutex;
1322 bool iindex_mutex_initialized = false;
1324 // We need to find the correct offset in the Class Interface Dispatch
1325 // Table for a given interface. Once we have that, invoking an interface
1326 // method just requires combining the Method's index in the interface
1327 // (known at compile time) to get the correct method. Doing a type test
1328 // (cast or instanceof) is the same problem: Once we have a possible Partial
1329 // Interface Dispatch Table, we just compare the first element to see if it
1330 // matches the desired interface. So how can we find the correct offset?
1331 // Our solution is to keep a vector of candiate offsets in each interface
1332 // (idt->iface.ioffsets), and in each class we have an index
1333 // (idt->cls.iindex) used to select the correct offset from ioffsets.
1335 // Calculate and return iindex for a new class.
1336 // ifaces is a vector of num interfaces that the class implements.
1337 // offsets[j] is the offset in the interface dispatch table for the
1338 // interface corresponding to ifaces[j].
1339 // May extend the interface ioffsets if required.
1341 _Jv_FindIIndex (jclass *ifaces, jshort *offsets, jshort num)
1346 // Acquire a global lock to prevent itable corruption in case of multiple
1347 // classes that implement an intersecting set of interfaces being linked
1348 // simultaneously. We can assume that the mutex will be initialized
1350 if (! iindex_mutex_initialized)
1352 _Jv_MutexInit (&iindex_mutex);
1353 iindex_mutex_initialized = true;
1356 _Jv_MutexLock (&iindex_mutex);
1358 for (i=1;; i++) /* each potential position in ioffsets */
1360 for (j=0;; j++) /* each iface */
1364 if (i >= ifaces[j]->idt->iface.ioffsets[0])
1366 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
1367 /* We can potentially share this position with another class. */
1368 if (ioffset >= 0 && ioffset != offsets[j])
1369 break; /* Nope. Try next i. */
1373 for (j = 0; j < num; j++)
1375 int len = ifaces[j]->idt->iface.ioffsets[0];
1378 /* Resize ioffsets. */
1379 int newlen = 2 * len;
1382 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
1383 jshort *new_ioffsets = (jshort *) _Jv_Realloc (old_ioffsets,
1384 newlen * sizeof(jshort));
1385 new_ioffsets[0] = newlen;
1387 while (len < newlen)
1388 new_ioffsets[len++] = -1;
1390 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
1392 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
1395 _Jv_MutexUnlock (&iindex_mutex);
1400 // Only used by serialization
1401 java::lang::reflect::Field *
1402 java::lang::Class::getPrivateField (jstring name)
1404 int hash = name->hashCode ();
1406 java::lang::reflect::Field* rfield;
1407 for (int i = 0; i < field_count; i++)
1409 _Jv_Field *field = &fields[i];
1410 if (! _Jv_equal (field->name, name, hash))
1412 rfield = new java::lang::reflect::Field ();
1413 rfield->offset = (char*) field - (char*) fields;
1414 rfield->declaringClass = this;
1415 rfield->name = name;
1418 jclass superclass = getSuperclass();
1419 if (superclass == NULL)
1421 rfield = superclass->getPrivateField(name);
1422 for (int i = 0; i < interface_count && rfield == NULL; ++i)
1423 rfield = interfaces[i]->getPrivateField (name);
1427 // Only used by serialization
1428 java::lang::reflect::Method *
1429 java::lang::Class::getPrivateMethod (jstring name, JArray<jclass> *param_types)
1431 jstring partial_sig = getSignature (param_types, false);
1432 jint p_len = partial_sig->length();
1433 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
1434 for (Class *klass = this; klass; klass = klass->getSuperclass())
1436 int i = klass->isPrimitive () ? 0 : klass->method_count;
1439 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
1440 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
1443 using namespace java::lang::reflect;
1445 Method *rmethod = new Method ();
1446 rmethod->offset = ((char *) (&klass->methods[i])
1447 - (char *) klass->methods);
1448 rmethod->declaringClass = klass;
1453 throw new java::lang::NoSuchMethodException;
1456 // Private accessor method for Java code to retrieve the protection domain.
1457 java::security::ProtectionDomain *
1458 java::lang::Class::getProtectionDomain0 ()
1460 return protectionDomain;
1463 // Functions for indirect dispatch (symbolic virtual method binding) support.
1465 // Resolve entries in the virtual method offset symbol table
1466 // (klass->otable_syms). The vtable offset (in bytes) for each resolved method
1467 // is placed at the corresponding position in the virtual method offset table
1468 // (klass->otable). A single otable and otable_syms pair may be shared by many
1471 _Jv_LinkOffsetTable(jclass klass)
1473 //// FIXME: Need to lock the otable ////
1475 if (klass->otable == NULL
1476 || klass->otable->state != 0)
1479 klass->otable->state = 1;
1482 _Jv_MethodSymbol sym = klass->otable_syms[0];
1484 while (sym.name != NULL)
1486 jclass target_class = _Jv_FindClass (sym.class_name, NULL);
1487 _Jv_Method *meth = NULL;
1489 if (target_class != NULL)
1490 if (target_class->isInterface())
1492 // FIXME: This does not yet fully conform to binary compatibility
1493 // rules. It will break if a declaration is moved into a
1495 for (int i=0; i < target_class->method_count; i++)
1497 meth = &target_class->methods[i];
1498 if (_Jv_equalUtf8Consts (sym.name, meth->name)
1499 && _Jv_equalUtf8Consts (sym.signature, meth->signature))
1501 klass->otable->offsets[index] = i + 1;
1508 // If the target class does not have a vtable_method_count yet,
1509 // then we can't tell the offsets for its methods, so we must lay
1511 if (target_class->vtable_method_count == -1)
1513 JvSynchronize sync (target_class);
1514 _Jv_LayoutVTableMethods (target_class);
1517 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1522 klass->otable->offsets[index] =
1523 _Jv_VTable::idx_to_offset (meth->index);
1528 // FIXME: This should be special index for ThrowNoSuchMethod().
1529 klass->otable->offsets[index] = -1;
1531 sym = klass->otable_syms[++index];
1535 // Returns true if METH should get an entry in a VTable.
1537 isVirtualMethod (_Jv_Method *meth)
1539 using namespace java::lang::reflect;
1540 return (((meth->accflags & (Modifier::STATIC | Modifier::PRIVATE)) == 0)
1541 && meth->name->data[0] != '<');
1544 // Prepare virtual method declarations in KLASS, and any superclasses as
1545 // required, by determining their vtable index, setting method->index, and
1546 // finally setting the class's vtable_method_count. Must be called with the
1547 // lock for KLASS held.
1549 _Jv_LayoutVTableMethods (jclass klass)
1551 if (klass->vtable != NULL || klass->isInterface()
1552 || klass->vtable_method_count != -1)
1555 jclass superclass = klass->superclass;
1557 if (superclass != NULL && superclass->vtable_method_count == -1)
1559 JvSynchronize sync (superclass);
1560 _Jv_LayoutVTableMethods (superclass);
1563 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1565 for (int i = 0; i < klass->method_count; ++i)
1567 _Jv_Method *meth = &klass->methods[i];
1568 _Jv_Method *super_meth = NULL;
1570 if (!isVirtualMethod(meth))
1573 if (superclass != NULL)
1574 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1578 meth->index = super_meth->index;
1580 meth->index = index++;
1583 klass->vtable_method_count = index;
1586 // Set entries in VTABLE for virtual methods declared in KLASS. If KLASS has
1587 // an immediate abstract parent, recursivly do its methods first.
1589 _Jv_SetVTableEntries (jclass klass, _Jv_VTable *vtable)
1591 using namespace java::lang::reflect;
1593 jclass superclass = klass->getSuperclass();
1595 if (superclass != NULL && (superclass->getModifiers() & Modifier::ABSTRACT))
1596 _Jv_SetVTableEntries (superclass, vtable);
1598 for (int i = klass->method_count - 1; i >= 0; i--)
1600 _Jv_Method *meth = &klass->methods[i];
1601 if (!isVirtualMethod(meth))
1603 vtable->set_method(meth->index, meth->ncode);
1607 // Allocate and lay out the virtual method table for KLASS. This will also
1608 // cause vtables to be generated for any non-abstract superclasses, and
1609 // virtual method layout to occur for any abstract superclasses. Must be
1610 // called with monitor lock for KLASS held.
1612 _Jv_MakeVTable (jclass klass)
1614 using namespace java::lang::reflect;
1616 if (klass->vtable != NULL || klass->isInterface()
1617 || (klass->accflags & Modifier::ABSTRACT))
1620 // out before we can create a vtable.
1621 if (klass->vtable_method_count == -1)
1622 _Jv_LayoutVTableMethods (klass);
1624 // Allocate the new vtable.
1625 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1626 klass->vtable = vtable;
1628 // Copy the vtable of the closest non-abstract superclass.
1629 jclass superclass = klass->superclass;
1630 if (superclass != NULL)
1632 while ((superclass->accflags & Modifier::ABSTRACT) != 0)
1633 superclass = superclass->superclass;
1635 if (superclass->vtable == NULL)
1637 JvSynchronize sync (superclass);
1638 _Jv_MakeVTable (superclass);
1641 for (int i = 0; i < superclass->vtable_method_count; ++i)
1642 vtable->set_method (i, superclass->vtable->get_method (i));
1645 // Set the class pointer and GC descriptor.
1646 vtable->clas = klass;
1647 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1649 // For each virtual declared in klass and any immediate abstract
1650 // superclasses, set new vtable entry or override an old one.
1651 _Jv_SetVTableEntries (klass, vtable);