1 // natClass.cc - Implementation of java.lang.Class native methods.
3 /* Copyright (C) 1998, 1999, 2000 Cygnus Solutions
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/lang/Class.h>
21 #include <java/lang/ClassLoader.h>
22 #include <java/lang/String.h>
23 #include <java/lang/reflect/Modifier.h>
24 #include <java/lang/reflect/Member.h>
25 #include <java/lang/reflect/Method.h>
26 #include <java/lang/reflect/Field.h>
27 #include <java/lang/reflect/Constructor.h>
28 #include <java/lang/AbstractMethodError.h>
29 #include <java/lang/ClassNotFoundException.h>
30 #include <java/lang/IllegalAccessException.h>
31 #include <java/lang/IllegalAccessError.h>
32 #include <java/lang/IncompatibleClassChangeError.h>
33 #include <java/lang/InstantiationException.h>
34 #include <java/lang/NoClassDefFoundError.h>
35 #include <java/lang/NoSuchFieldException.h>
36 #include <java/lang/NoSuchMethodException.h>
37 #include <java/lang/Thread.h>
38 #include <java/lang/NullPointerException.h>
39 #include <java/lang/System.h>
40 #include <java/lang/SecurityManager.h>
41 #include <java/lang/StringBuffer.h>
43 #include <java-cpool.h>
47 #define CloneableClass _CL_Q34java4lang9Cloneable
48 extern java::lang::Class CloneableClass;
49 #define ObjectClass _CL_Q34java4lang6Object
50 extern java::lang::Class ObjectClass;
51 #define ErrorClass _CL_Q34java4lang5Error
52 extern java::lang::Class ErrorClass;
53 #define ClassClass _CL_Q34java4lang5Class
54 extern java::lang::Class ClassClass;
55 #define MethodClass _CL_Q44java4lang7reflect6Method
56 extern java::lang::Class MethodClass;
57 #define FieldClass _CL_Q44java4lang7reflect5Field
58 extern java::lang::Class FieldClass;
59 #define ConstructorClass _CL_Q44java4lang7reflect11Constructor
60 extern java::lang::Class ConstructorClass;
62 // Some constants we use to look up the class initializer.
63 static _Jv_Utf8Const *void_signature = _Jv_makeUtf8Const ("()V", 3);
64 static _Jv_Utf8Const *clinit_name = _Jv_makeUtf8Const ("<clinit>", 8);
65 static _Jv_Utf8Const *init_name = _Jv_makeUtf8Const ("<init>", 6);
66 static _Jv_Utf8Const *finit_name = _Jv_makeUtf8Const ("$finit$", 7);
71 java::lang::Class::forName (jstring className)
74 JvThrow (new java::lang::NullPointerException);
77 // FIXME: should check syntax of CLASSNAME and throw
78 // IllegalArgumentException on failure.
80 // FIXME: should use class loader from calling method.
81 jclass klass = _Jv_FindClass (className, NULL);
83 jsize length = _Jv_GetStringUTFLength (className);
85 _Jv_GetStringUTFRegion (className, 0, length, buffer);
87 // FIXME: should check syntax of CLASSNAME and throw
88 // IllegalArgumentException on failure.
89 _Jv_Utf8Const *name = _Jv_makeUtf8Const (buffer, length);
91 // FIXME: should use class loader from calling method.
92 jclass klass = (buffer[0] == '['
93 ? _Jv_FindClassFromSignature (name->data, NULL)
94 : _Jv_FindClass (name, NULL));
97 JvThrow (new java::lang::ClassNotFoundException (className));
102 java::lang::reflect::Constructor *
103 java::lang::Class::getConstructor (JArray<jclass> *param_types)
105 jstring partial_sig = getSignature (param_types, true);
106 jint hash = partial_sig->hashCode ();
108 int i = isPrimitive () ? 0 : method_count;
111 // FIXME: access checks.
112 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
113 && _Jv_equal (methods[i].signature, partial_sig, hash))
115 // Found it. For getConstructor, the constructor must be
117 using namespace java::lang::reflect;
118 if (! Modifier::isPublic(methods[i].accflags))
120 Constructor *cons = new Constructor ();
121 cons->offset = (char *) (&methods[i]) - (char *) methods;
122 cons->declaringClass = this;
126 JvThrow (new java::lang::NoSuchMethodException);
129 JArray<java::lang::reflect::Constructor *> *
130 java::lang::Class::_getConstructors (jboolean declared)
132 // FIXME: this method needs access checks.
134 int numConstructors = 0;
135 int max = isPrimitive () ? 0 : method_count;
137 for (i = max; --i >= 0; )
139 _Jv_Method *method = &methods[i];
140 if (method->name == NULL
141 && ! _Jv_equalUtf8Consts (method->name, init_name))
144 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
148 JArray<java::lang::reflect::Constructor *> *result
149 = (JArray<java::lang::reflect::Constructor *> *)
150 JvNewObjectArray (numConstructors, &ConstructorClass, NULL);
151 java::lang::reflect::Constructor** cptr = elements (result);
152 for (i = 0; i < max; i++)
154 _Jv_Method *method = &methods[i];
155 if (method->name == NULL
156 && ! _Jv_equalUtf8Consts (method->name, init_name))
159 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
161 java::lang::reflect::Constructor *cons
162 = new java::lang::reflect::Constructor ();
163 cons->offset = (char *) method - (char *) methods;
164 cons->declaringClass = this;
170 java::lang::reflect::Constructor *
171 java::lang::Class::getDeclaredConstructor (JArray<jclass> *param_types)
173 jstring partial_sig = getSignature (param_types, true);
174 jint hash = partial_sig->hashCode ();
176 int i = isPrimitive () ? 0 : method_count;
179 // FIXME: access checks.
180 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
181 && _Jv_equal (methods[i].signature, partial_sig, hash))
184 using namespace java::lang::reflect;
185 Constructor *cons = new Constructor ();
186 cons->offset = (char *) (&methods[i]) - (char *) methods;
187 cons->declaringClass = this;
191 JvThrow (new java::lang::NoSuchMethodException);
194 java::lang::reflect::Field *
195 java::lang::Class::getField (jstring name, jint hash)
197 java::lang::reflect::Field* rfield;
198 for (int i = 0; i < field_count; i++)
200 _Jv_Field *field = &fields[i];
201 if (! _Jv_equal (field->name, name, hash))
203 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
205 rfield = new java::lang::reflect::Field ();
206 rfield->offset = (char*) field - (char*) fields;
207 rfield->declaringClass = this;
211 jclass superclass = getSuperclass();
212 if (superclass == NULL)
214 rfield = superclass->getField(name, hash);
215 for (int i = 0; i < interface_count && rfield == NULL; ++i)
216 rfield = interfaces[i]->getField (name, hash);
220 java::lang::reflect::Field *
221 java::lang::Class::getDeclaredField (jstring name)
223 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
225 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
226 int hash = name->hashCode();
227 for (int i = 0; i < field_count; i++)
229 _Jv_Field *field = &fields[i];
230 if (! _Jv_equal (field->name, name, hash))
232 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
233 rfield->offset = (char*) field - (char*) fields;
234 rfield->declaringClass = this;
238 JvThrow (new java::lang::NoSuchFieldException (name));
241 JArray<java::lang::reflect::Field *> *
242 java::lang::Class::getDeclaredFields (void)
244 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
246 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
247 JArray<java::lang::reflect::Field *> *result
248 = (JArray<java::lang::reflect::Field *> *)
249 JvNewObjectArray (field_count, &FieldClass, NULL);
250 java::lang::reflect::Field** fptr = elements (result);
251 for (int i = 0; i < field_count; i++)
253 _Jv_Field *field = &fields[i];
254 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
255 rfield->offset = (char*) field - (char*) fields;
256 rfield->declaringClass = this;
263 java::lang::Class::getSignature (java::lang::StringBuffer *buffer)
266 buffer->append((jchar) method_count);
269 jstring name = getName();
270 if (name->charAt(0) != '[')
271 buffer->append((jchar) 'L');
272 buffer->append(name);
273 if (name->charAt(0) != '[')
274 buffer->append((jchar) ';');
278 // This doesn't have to be native. It is an implementation detail
279 // only called from the C++ code, though, so maybe this is clearer.
281 java::lang::Class::getSignature (JArray<jclass> *param_types,
282 jboolean is_constructor)
284 java::lang::StringBuffer *buf = new java::lang::StringBuffer ();
285 buf->append((jchar) '(');
286 jclass *v = elements (param_types);
287 for (int i = 0; i < param_types->length; ++i)
288 v[i]->getSignature(buf);
289 buf->append((jchar) ')');
291 buf->append((jchar) 'V');
292 return buf->toString();
295 java::lang::reflect::Method *
296 java::lang::Class::getDeclaredMethod (jstring name,
297 JArray<jclass> *param_types)
299 jstring partial_sig = getSignature (param_types, false);
300 jint p_len = partial_sig->length();
301 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
302 int i = isPrimitive () ? 0 : method_count;
305 // FIXME: access checks.
306 if (_Jv_equalUtf8Consts (methods[i].name, utf_name)
307 && _Jv_equaln (methods[i].signature, partial_sig, p_len))
310 using namespace java::lang::reflect;
311 Method *rmethod = new Method ();
312 rmethod->offset = (char*) (&methods[i]) - (char*) methods;
313 rmethod->declaringClass = this;
317 JvThrow (new java::lang::NoSuchMethodException);
320 JArray<java::lang::reflect::Method *> *
321 java::lang::Class::getDeclaredMethods (void)
324 int max = isPrimitive () ? 0 : method_count;
326 for (i = max; --i >= 0; )
328 _Jv_Method *method = &methods[i];
329 if (method->name == NULL
330 || _Jv_equalUtf8Consts (method->name, clinit_name)
331 || _Jv_equalUtf8Consts (method->name, init_name)
332 || _Jv_equalUtf8Consts (method->name, finit_name))
336 JArray<java::lang::reflect::Method *> *result
337 = (JArray<java::lang::reflect::Method *> *)
338 JvNewObjectArray (numMethods, &MethodClass, NULL);
339 java::lang::reflect::Method** mptr = elements (result);
340 for (i = 0; i < max; i++)
342 _Jv_Method *method = &methods[i];
343 if (method->name == NULL
344 || _Jv_equalUtf8Consts (method->name, clinit_name)
345 || _Jv_equalUtf8Consts (method->name, init_name)
346 || _Jv_equalUtf8Consts (method->name, finit_name))
348 java::lang::reflect::Method* rmethod
349 = new java::lang::reflect::Method ();
350 rmethod->offset = (char*) method - (char*) methods;
351 rmethod->declaringClass = this;
358 java::lang::Class::getName (void)
360 char buffer[name->length + 1];
361 memcpy (buffer, name->data, name->length);
362 buffer[name->length] = '\0';
363 return _Jv_NewStringUTF (buffer);
367 java::lang::Class::getClasses (void)
374 java::lang::Class::getDeclaredClasses (void)
376 checkMemberAccess (java::lang::reflect::Member::DECLARED);
377 // Until we have inner classes, it always makes sense to return an
379 JArray<jclass> *result
380 = (JArray<jclass> *) JvNewObjectArray (0, &ClassClass, NULL);
385 java::lang::Class::getDeclaringClass (void)
387 // Until we have inner classes, it makes sense to always return
393 java::lang::Class::_getFields (JArray<java::lang::reflect::Field *> *result,
397 for (int i = 0; i < field_count; i++)
399 _Jv_Field *field = &fields[i];
400 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
406 java::lang::reflect::Field *rfield
407 = new java::lang::reflect::Field ();
408 rfield->offset = (char *) field - (char *) fields;
409 rfield->declaringClass = this;
410 rfield->name = _Jv_NewStringUtf8Const (field->name);
411 (elements (result))[offset + i] = rfield;
414 jclass superclass = getSuperclass();
415 if (superclass != NULL)
417 int s_count = superclass->_getFields (result, offset);
421 for (int i = 0; i < interface_count; ++i)
423 int f_count = interfaces[i]->_getFields (result, offset);
430 JArray<java::lang::reflect::Field *> *
431 java::lang::Class::getFields (void)
433 using namespace java::lang::reflect;
435 int count = _getFields (NULL, 0);
437 JArray<java::lang::reflect::Field *> *result
438 = ((JArray<java::lang::reflect::Field *> *)
439 JvNewObjectArray (count, &FieldClass, NULL));
441 _getFields (result, 0);
447 java::lang::Class::getInterfaces (void)
449 jobjectArray r = JvNewObjectArray (interface_count, getClass (), NULL);
450 jobject *data = elements (r);
451 for (int i = 0; i < interface_count; ++i)
452 data[i] = interfaces[i];
453 return reinterpret_cast<JArray<jclass> *> (r);
456 java::lang::reflect::Method *
457 java::lang::Class::getMethod (jstring name, JArray<jclass> *param_types)
459 jstring partial_sig = getSignature (param_types, false);
460 jint p_len = partial_sig->length();
461 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
462 for (Class *klass = this; klass; klass = klass->getSuperclass())
464 int i = klass->isPrimitive () ? 0 : klass->method_count;
467 // FIXME: access checks.
468 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
469 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
472 using namespace java::lang::reflect;
474 // Method must be public.
475 if (! Modifier::isPublic (methods[i].accflags))
478 Method *rmethod = new Method ();
479 rmethod->offset = (char*) (&klass->methods[i]) - (char*) methods;
480 rmethod->declaringClass = klass;
485 JvThrow (new java::lang::NoSuchMethodException);
488 // This is a very slow implementation, since it re-scans all the
489 // methods we've already listed to make sure we haven't duplicated a
490 // method. It also over-estimates the required size, so we have to
491 // shrink the result array later.
493 java::lang::Class::_getMethods (JArray<java::lang::reflect::Method *> *result,
498 // First examine all local methods
499 for (int i = isPrimitive () ? 0 : method_count; --i >= 0; )
501 _Jv_Method *method = &methods[i];
502 if (method->name == NULL
503 || _Jv_equalUtf8Consts (method->name, clinit_name)
504 || _Jv_equalUtf8Consts (method->name, init_name)
505 || _Jv_equalUtf8Consts (method->name, finit_name))
507 // Only want public methods.
508 if (! java::lang::reflect::Modifier::isPublic (method->accflags))
511 // This is where we over-count the slots required if we aren't
512 // filling the result for real.
516 java::lang::reflect::Method **mp = elements (result);
517 // If we already have a method with this name and signature,
518 // then ignore this one. This can happen with virtual
520 for (int j = 0; j < offset; ++j)
522 _Jv_Method *meth_2 = _Jv_FromReflectedMethod (mp[j]);
523 if (_Jv_equalUtf8Consts (method->name, meth_2->name)
524 && _Jv_equalUtf8Consts (method->signature,
537 using namespace java::lang::reflect;
538 Method *rmethod = new Method ();
539 rmethod->offset = (char *) method - (char *) methods;
540 rmethod->declaringClass = this;
541 Method **mp = elements (result);
542 mp[offset + count] = rmethod;
548 // Now examine superclasses.
549 if (getSuperclass () != NULL)
551 jint s_count = getSuperclass()->_getMethods (result, offset);
556 // Finally, examine interfaces.
557 for (int i = 0; i < interface_count; ++i)
559 int f_count = interfaces[i]->_getMethods (result, offset);
567 JArray<java::lang::reflect::Method *> *
568 java::lang::Class::getMethods (void)
570 using namespace java::lang::reflect;
572 // FIXME: security checks.
574 // This will overestimate the size we need.
575 jint count = _getMethods (NULL, 0);
577 JArray<Method *> *result
578 = ((JArray<Method *> *) JvNewObjectArray (count, &MethodClass, NULL));
580 // When filling the array for real, we get the actual count. Then
581 // we resize the array.
582 jint real_count = _getMethods (result, 0);
584 if (real_count != count)
587 = ((JArray<Method *> *) JvNewObjectArray (real_count, &MethodClass,
590 Method **destp = elements (r2);
591 Method **srcp = elements (result);
593 for (int i = 0; i < real_count; ++i)
603 java::lang::Class::isAssignableFrom (jclass klass)
607 // Primitive types must be equal, which we just tested for.
608 if (isPrimitive () || ! klass || klass->isPrimitive())
611 // If target is array, so must source be.
614 if (! klass->isArray())
616 return getComponentType()->isAssignableFrom(klass->getComponentType());
619 if (isAssignableFrom (klass->getSuperclass()))
624 // See if source implements this interface.
625 for (int i = 0; i < klass->interface_count; ++i)
627 jclass interface = klass->interfaces[i];
628 // FIXME: ensure that class is prepared here.
630 if (isAssignableFrom (interface))
639 java::lang::Class::isInstance (jobject obj)
641 if (! obj || isPrimitive ())
643 return isAssignableFrom (obj->getClass());
647 java::lang::Class::isInterface (void)
649 return (accflags & java::lang::reflect::Modifier::INTERFACE) != 0;
653 java::lang::Class::newInstance (void)
655 // FIXME: do accessibility checks here. There currently doesn't
656 // seem to be any way to do these.
657 // FIXME: we special-case one check here just to pass a Plum Hall
658 // test. Once access checking is implemented, remove this.
659 if (this == &ClassClass)
660 JvThrow (new java::lang::IllegalAccessException);
665 || java::lang::reflect::Modifier::isAbstract(accflags))
666 JvThrow (new java::lang::InstantiationException);
668 _Jv_InitClass (this);
670 _Jv_Method *meth = _Jv_GetMethodLocal (this, init_name, void_signature);
672 JvThrow (new java::lang::NoSuchMethodException);
674 jobject r = JvAllocObject (this);
675 ((void (*) (jobject)) meth->ncode) (r);
680 java::lang::Class::finalize (void)
683 JvAssert (_Jv_IsInterpretedClass (this));
684 _Jv_UnregisterClass (this);
690 java::lang::Class::hackRunInitializers (void)
692 _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name, void_signature);
694 ((void (*) (void)) meth->ncode) ();
697 // This implements the initialization process for a class. From Spec
700 java::lang::Class::initializeClass (void)
702 // Short-circuit to avoid needless locking.
703 if (state == JV_STATE_DONE)
706 // do this before we enter the monitor below, since this can cause
707 // exceptions. Here we assume, that reading "state" is an atomic
708 // operation, I pressume that is true? --Kresten
709 if (state < JV_STATE_LINKED)
712 if (_Jv_IsInterpretedClass (this))
714 java::lang::ClassLoader::resolveClass0 (this);
717 _Jv_MonitorEnter (this);
723 _Jv_MonitorEnter (this);
724 _Jv_PrepareCompiledClass (this);
730 _Jv_MonitorEnter (this);
734 java::lang::Thread *self = java::lang::Thread::currentThread();
735 // FIXME: `self' can be null at startup. Hence this nasty trick.
736 self = (java::lang::Thread *) ((long) self | 1);
737 while (state == JV_STATE_IN_PROGRESS && thread && thread != self)
741 if (state == JV_STATE_DONE || state == JV_STATE_IN_PROGRESS || thread == self)
743 _Jv_MonitorExit (this);
748 if (state == JV_STATE_ERROR)
750 _Jv_MonitorExit (this);
751 JvThrow (new java::lang::NoClassDefFoundError);
756 state = JV_STATE_IN_PROGRESS;
757 _Jv_MonitorExit (this);
760 if (! isInterface () && superclass)
762 // FIXME: We can't currently catch a Java exception in C++ code.
763 // So instead we call a Java trampoline. It returns an
764 // exception, or null.
765 jobject except = superclass->hackTrampoline(0, NULL);
768 // Caught an exception.
769 _Jv_MonitorEnter (this);
770 state = JV_STATE_ERROR;
772 _Jv_MonitorExit (this);
778 // FIXME: once again we have to go through a trampoline.
779 java::lang::Throwable *except = hackTrampoline (1, NULL);
784 _Jv_MonitorEnter (this);
785 state = JV_STATE_DONE;
789 if (! ErrorClass.isInstance(except))
791 // Once again we must use the trampoline. In this case we
792 // have to detect an OutOfMemoryError.
793 except = hackTrampoline(2, except);
795 _Jv_MonitorEnter (this);
796 state = JV_STATE_ERROR;
799 _Jv_MonitorExit (this);
807 // Some class-related convenience functions.
810 // Find a method declared in the class. If it is not declared locally
811 // (or if it is inherited), return NULL.
813 _Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
814 _Jv_Utf8Const *signature)
816 for (int i = 0; i < klass->method_count; ++i)
818 if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
819 && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
820 return &klass->methods[i];
826 _Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
827 _Jv_Utf8Const *signature)
829 for (; klass; klass = klass->getSuperclass())
831 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
840 // NOTE: MCACHE_SIZE should be a power of 2 minus one.
841 #define MCACHE_SIZE 1023
849 static _Jv_mcache method_cache[MCACHE_SIZE + 1];
852 _Jv_FindMethodInCache (jclass klass,
854 _Jv_Utf8Const *signature)
856 int index = name->hash & MCACHE_SIZE;
857 _Jv_mcache *mc = method_cache + index;
858 _Jv_Method *m = mc->method;
860 if (mc->klass == klass
861 && m != NULL // thread safe check
862 && _Jv_equalUtf8Consts (m->name, name)
863 && _Jv_equalUtf8Consts (m->signature, signature))
864 return mc->method->ncode;
869 _Jv_AddMethodToCache (jclass klass,
872 _Jv_MonitorEnter (&ClassClass);
874 int index = method->name->hash & MCACHE_SIZE;
876 method_cache[index].method = method;
877 method_cache[index].klass = klass;
879 _Jv_MonitorExit (&ClassClass);
883 _Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
884 _Jv_Utf8Const *signature)
886 void *ncode = _Jv_FindMethodInCache (klass, name, signature);
890 for (; klass; klass = klass->getSuperclass())
892 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
896 if (java::lang::reflect::Modifier::isStatic(meth->accflags))
897 JvThrow (new java::lang::IncompatibleClassChangeError);
898 if (java::lang::reflect::Modifier::isAbstract(meth->accflags))
899 JvThrow (new java::lang::AbstractMethodError);
900 if (! java::lang::reflect::Modifier::isPublic(meth->accflags))
901 JvThrow (new java::lang::IllegalAccessError);
903 _Jv_AddMethodToCache (klass, meth);
907 JvThrow (new java::lang::IncompatibleClassChangeError);
908 return NULL; // Placate compiler.
912 _Jv_InitClass (jclass klass)
914 klass->initializeClass();
918 _Jv_IsInstanceOf(jobject obj, jclass cl)
920 return cl->isInstance(obj);