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>
42 #include <gcj/method.h>
44 #include <java-cpool.h>
48 #define CloneableClass _CL_Q34java4lang9Cloneable
49 extern java::lang::Class CloneableClass;
50 #define ObjectClass _CL_Q34java4lang6Object
51 extern java::lang::Class ObjectClass;
52 #define ErrorClass _CL_Q34java4lang5Error
53 extern java::lang::Class ErrorClass;
54 #define ClassClass _CL_Q34java4lang5Class
55 extern java::lang::Class ClassClass;
56 #define MethodClass _CL_Q44java4lang7reflect6Method
57 extern java::lang::Class MethodClass;
58 #define FieldClass _CL_Q44java4lang7reflect5Field
59 extern java::lang::Class FieldClass;
60 #define ConstructorClass _CL_Q44java4lang7reflect11Constructor
61 extern java::lang::Class ConstructorClass;
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$", 7);
72 java::lang::Class::forName (jstring className)
75 JvThrow (new java::lang::NullPointerException);
78 // FIXME: should check syntax of CLASSNAME and throw
79 // IllegalArgumentException on failure.
81 // FIXME: should use class loader from calling method.
82 jclass klass = _Jv_FindClass (className, NULL);
84 jsize length = _Jv_GetStringUTFLength (className);
86 _Jv_GetStringUTFRegion (className, 0, length, buffer);
88 // FIXME: should check syntax of CLASSNAME and throw
89 // IllegalArgumentException on failure.
90 _Jv_Utf8Const *name = _Jv_makeUtf8Const (buffer, length);
92 // FIXME: should use class loader from calling method.
93 jclass klass = (buffer[0] == '['
94 ? _Jv_FindClassFromSignature (name->data, NULL)
95 : _Jv_FindClass (name, NULL));
98 JvThrow (new java::lang::ClassNotFoundException (className));
103 java::lang::reflect::Constructor *
104 java::lang::Class::getConstructor (JArray<jclass> *param_types)
106 jstring partial_sig = getSignature (param_types, true);
107 jint hash = partial_sig->hashCode ();
109 int i = isPrimitive () ? 0 : method_count;
112 // FIXME: access checks.
113 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
114 && _Jv_equal (methods[i].signature, partial_sig, hash))
116 // Found it. For getConstructor, the constructor must be
118 using namespace java::lang::reflect;
119 if (! Modifier::isPublic(methods[i].accflags))
121 Constructor *cons = new Constructor ();
122 cons->offset = (char *) (&methods[i]) - (char *) methods;
123 cons->declaringClass = this;
127 JvThrow (new java::lang::NoSuchMethodException);
130 JArray<java::lang::reflect::Constructor *> *
131 java::lang::Class::_getConstructors (jboolean declared)
133 // FIXME: this method needs access checks.
135 int numConstructors = 0;
136 int max = isPrimitive () ? 0 : method_count;
138 for (i = max; --i >= 0; )
140 _Jv_Method *method = &methods[i];
141 if (method->name == NULL
142 || ! _Jv_equalUtf8Consts (method->name, init_name))
145 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
149 JArray<java::lang::reflect::Constructor *> *result
150 = (JArray<java::lang::reflect::Constructor *> *)
151 JvNewObjectArray (numConstructors, &ConstructorClass, NULL);
152 java::lang::reflect::Constructor** cptr = elements (result);
153 for (i = 0; i < max; i++)
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))
162 java::lang::reflect::Constructor *cons
163 = new java::lang::reflect::Constructor ();
164 cons->offset = (char *) method - (char *) methods;
165 cons->declaringClass = this;
171 java::lang::reflect::Constructor *
172 java::lang::Class::getDeclaredConstructor (JArray<jclass> *param_types)
174 jstring partial_sig = getSignature (param_types, true);
175 jint hash = partial_sig->hashCode ();
177 int i = isPrimitive () ? 0 : method_count;
180 // FIXME: access checks.
181 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
182 && _Jv_equal (methods[i].signature, partial_sig, hash))
185 using namespace java::lang::reflect;
186 Constructor *cons = new Constructor ();
187 cons->offset = (char *) (&methods[i]) - (char *) methods;
188 cons->declaringClass = this;
192 JvThrow (new java::lang::NoSuchMethodException);
195 java::lang::reflect::Field *
196 java::lang::Class::getField (jstring name, jint hash)
198 java::lang::reflect::Field* rfield;
199 for (int i = 0; i < field_count; i++)
201 _Jv_Field *field = &fields[i];
202 if (! _Jv_equal (field->name, name, hash))
204 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
206 rfield = new java::lang::reflect::Field ();
207 rfield->offset = (char*) field - (char*) fields;
208 rfield->declaringClass = this;
212 jclass superclass = getSuperclass();
213 if (superclass == NULL)
215 rfield = superclass->getField(name, hash);
216 for (int i = 0; i < interface_count && rfield == NULL; ++i)
217 rfield = interfaces[i]->getField (name, hash);
221 java::lang::reflect::Field *
222 java::lang::Class::getDeclaredField (jstring name)
224 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
226 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
227 int hash = name->hashCode();
228 for (int i = 0; i < field_count; i++)
230 _Jv_Field *field = &fields[i];
231 if (! _Jv_equal (field->name, name, hash))
233 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
234 rfield->offset = (char*) field - (char*) fields;
235 rfield->declaringClass = this;
239 JvThrow (new java::lang::NoSuchFieldException (name));
242 JArray<java::lang::reflect::Field *> *
243 java::lang::Class::getDeclaredFields (void)
245 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
247 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
248 JArray<java::lang::reflect::Field *> *result
249 = (JArray<java::lang::reflect::Field *> *)
250 JvNewObjectArray (field_count, &FieldClass, NULL);
251 java::lang::reflect::Field** fptr = elements (result);
252 for (int i = 0; i < field_count; i++)
254 _Jv_Field *field = &fields[i];
255 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
256 rfield->offset = (char*) field - (char*) fields;
257 rfield->declaringClass = this;
264 java::lang::Class::getSignature (java::lang::StringBuffer *buffer)
267 buffer->append((jchar) method_count);
270 jstring name = getName();
271 if (name->charAt(0) != '[')
272 buffer->append((jchar) 'L');
273 buffer->append(name);
274 if (name->charAt(0) != '[')
275 buffer->append((jchar) ';');
279 // This doesn't have to be native. It is an implementation detail
280 // only called from the C++ code, though, so maybe this is clearer.
282 java::lang::Class::getSignature (JArray<jclass> *param_types,
283 jboolean is_constructor)
285 java::lang::StringBuffer *buf = new java::lang::StringBuffer ();
286 buf->append((jchar) '(');
287 jclass *v = elements (param_types);
288 for (int i = 0; i < param_types->length; ++i)
289 v[i]->getSignature(buf);
290 buf->append((jchar) ')');
292 buf->append((jchar) 'V');
293 return buf->toString();
296 java::lang::reflect::Method *
297 java::lang::Class::getDeclaredMethod (jstring name,
298 JArray<jclass> *param_types)
300 jstring partial_sig = getSignature (param_types, false);
301 jint p_len = partial_sig->length();
302 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
303 int i = isPrimitive () ? 0 : method_count;
306 // FIXME: access checks.
307 if (_Jv_equalUtf8Consts (methods[i].name, utf_name)
308 && _Jv_equaln (methods[i].signature, partial_sig, p_len))
311 using namespace java::lang::reflect;
312 Method *rmethod = new Method ();
313 rmethod->offset = (char*) (&methods[i]) - (char*) methods;
314 rmethod->declaringClass = this;
318 JvThrow (new java::lang::NoSuchMethodException);
321 JArray<java::lang::reflect::Method *> *
322 java::lang::Class::getDeclaredMethods (void)
325 int max = isPrimitive () ? 0 : method_count;
327 for (i = max; --i >= 0; )
329 _Jv_Method *method = &methods[i];
330 if (method->name == NULL
331 || _Jv_equalUtf8Consts (method->name, clinit_name)
332 || _Jv_equalUtf8Consts (method->name, init_name)
333 || _Jv_equalUtf8Consts (method->name, finit_name))
337 JArray<java::lang::reflect::Method *> *result
338 = (JArray<java::lang::reflect::Method *> *)
339 JvNewObjectArray (numMethods, &MethodClass, NULL);
340 java::lang::reflect::Method** mptr = elements (result);
341 for (i = 0; i < max; i++)
343 _Jv_Method *method = &methods[i];
344 if (method->name == NULL
345 || _Jv_equalUtf8Consts (method->name, clinit_name)
346 || _Jv_equalUtf8Consts (method->name, init_name)
347 || _Jv_equalUtf8Consts (method->name, finit_name))
349 java::lang::reflect::Method* rmethod
350 = new java::lang::reflect::Method ();
351 rmethod->offset = (char*) method - (char*) methods;
352 rmethod->declaringClass = this;
359 java::lang::Class::getName (void)
361 char buffer[name->length + 1];
362 memcpy (buffer, name->data, name->length);
363 buffer[name->length] = '\0';
364 return _Jv_NewStringUTF (buffer);
368 java::lang::Class::getClasses (void)
370 // Until we have inner classes, it always makes sense to return an
372 JArray<jclass> *result
373 = (JArray<jclass> *) JvNewObjectArray (0, &ClassClass, NULL);
378 java::lang::Class::getDeclaredClasses (void)
380 checkMemberAccess (java::lang::reflect::Member::DECLARED);
381 // Until we have inner classes, it always makes sense to return an
383 JArray<jclass> *result
384 = (JArray<jclass> *) JvNewObjectArray (0, &ClassClass, NULL);
389 java::lang::Class::getDeclaringClass (void)
391 // Until we have inner classes, it makes sense to always return
397 java::lang::Class::_getFields (JArray<java::lang::reflect::Field *> *result,
401 for (int i = 0; i < field_count; i++)
403 _Jv_Field *field = &fields[i];
404 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
410 java::lang::reflect::Field *rfield
411 = new java::lang::reflect::Field ();
412 rfield->offset = (char *) field - (char *) fields;
413 rfield->declaringClass = this;
414 rfield->name = _Jv_NewStringUtf8Const (field->name);
415 (elements (result))[offset + i] = rfield;
418 jclass superclass = getSuperclass();
419 if (superclass != NULL)
421 int s_count = superclass->_getFields (result, offset);
425 for (int i = 0; i < interface_count; ++i)
427 int f_count = interfaces[i]->_getFields (result, offset);
434 JArray<java::lang::reflect::Field *> *
435 java::lang::Class::getFields (void)
437 using namespace java::lang::reflect;
439 int count = _getFields (NULL, 0);
441 JArray<java::lang::reflect::Field *> *result
442 = ((JArray<java::lang::reflect::Field *> *)
443 JvNewObjectArray (count, &FieldClass, NULL));
445 _getFields (result, 0);
451 java::lang::Class::getInterfaces (void)
453 jobjectArray r = JvNewObjectArray (interface_count, getClass (), NULL);
454 jobject *data = elements (r);
455 for (int i = 0; i < interface_count; ++i)
456 data[i] = interfaces[i];
457 return reinterpret_cast<JArray<jclass> *> (r);
460 java::lang::reflect::Method *
461 java::lang::Class::getMethod (jstring name, JArray<jclass> *param_types)
463 jstring partial_sig = getSignature (param_types, false);
464 jint p_len = partial_sig->length();
465 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
466 for (Class *klass = this; klass; klass = klass->getSuperclass())
468 int i = klass->isPrimitive () ? 0 : klass->method_count;
471 // FIXME: access checks.
472 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
473 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
476 using namespace java::lang::reflect;
478 // Method must be public.
479 if (! Modifier::isPublic (klass->methods[i].accflags))
482 Method *rmethod = new Method ();
483 rmethod->offset = ((char *) (&klass->methods[i])
484 - (char *) klass->methods);
485 rmethod->declaringClass = klass;
490 JvThrow (new java::lang::NoSuchMethodException);
493 // This is a very slow implementation, since it re-scans all the
494 // methods we've already listed to make sure we haven't duplicated a
495 // method. It also over-estimates the required size, so we have to
496 // shrink the result array later.
498 java::lang::Class::_getMethods (JArray<java::lang::reflect::Method *> *result,
503 // First examine all local methods
504 for (int i = isPrimitive () ? 0 : method_count; --i >= 0; )
506 _Jv_Method *method = &methods[i];
507 if (method->name == NULL
508 || _Jv_equalUtf8Consts (method->name, clinit_name)
509 || _Jv_equalUtf8Consts (method->name, init_name)
510 || _Jv_equalUtf8Consts (method->name, finit_name))
512 // Only want public methods.
513 if (! java::lang::reflect::Modifier::isPublic (method->accflags))
516 // This is where we over-count the slots required if we aren't
517 // filling the result for real.
521 java::lang::reflect::Method **mp = elements (result);
522 // If we already have a method with this name and signature,
523 // then ignore this one. This can happen with virtual
525 for (int j = 0; j < offset; ++j)
527 _Jv_Method *meth_2 = _Jv_FromReflectedMethod (mp[j]);
528 if (_Jv_equalUtf8Consts (method->name, meth_2->name)
529 && _Jv_equalUtf8Consts (method->signature,
542 using namespace java::lang::reflect;
543 Method *rmethod = new Method ();
544 rmethod->offset = (char *) method - (char *) methods;
545 rmethod->declaringClass = this;
546 Method **mp = elements (result);
547 mp[offset + count] = rmethod;
553 // Now examine superclasses.
554 if (getSuperclass () != NULL)
556 jint s_count = getSuperclass()->_getMethods (result, offset);
561 // Finally, examine interfaces.
562 for (int i = 0; i < interface_count; ++i)
564 int f_count = interfaces[i]->_getMethods (result, offset);
572 JArray<java::lang::reflect::Method *> *
573 java::lang::Class::getMethods (void)
575 using namespace java::lang::reflect;
577 // FIXME: security checks.
579 // This will overestimate the size we need.
580 jint count = _getMethods (NULL, 0);
582 JArray<Method *> *result
583 = ((JArray<Method *> *) JvNewObjectArray (count, &MethodClass, NULL));
585 // When filling the array for real, we get the actual count. Then
586 // we resize the array.
587 jint real_count = _getMethods (result, 0);
589 if (real_count != count)
592 = ((JArray<Method *> *) JvNewObjectArray (real_count, &MethodClass,
595 Method **destp = elements (r2);
596 Method **srcp = elements (result);
598 for (int i = 0; i < real_count; ++i)
608 java::lang::Class::isAssignableFrom (jclass klass)
612 // Primitive types must be equal, which we just tested for.
613 if (isPrimitive () || ! klass || klass->isPrimitive())
616 // If target is array, so must source be.
619 if (! klass->isArray())
621 return getComponentType()->isAssignableFrom(klass->getComponentType());
624 if (isAssignableFrom (klass->getSuperclass()))
629 // See if source implements this interface.
630 for (int i = 0; i < klass->interface_count; ++i)
632 jclass interface = klass->interfaces[i];
633 // FIXME: ensure that class is prepared here.
635 if (isAssignableFrom (interface))
644 java::lang::Class::isInstance (jobject obj)
646 if (! obj || isPrimitive ())
648 return isAssignableFrom (obj->getClass());
652 java::lang::Class::isInterface (void)
654 return (accflags & java::lang::reflect::Modifier::INTERFACE) != 0;
658 java::lang::Class::newInstance (void)
660 // FIXME: do accessibility checks here. There currently doesn't
661 // seem to be any way to do these.
662 // FIXME: we special-case one check here just to pass a Plum Hall
663 // test. Once access checking is implemented, remove this.
664 if (this == &ClassClass)
665 JvThrow (new java::lang::IllegalAccessException);
670 || java::lang::reflect::Modifier::isAbstract(accflags))
671 JvThrow (new java::lang::InstantiationException);
673 _Jv_InitClass (this);
675 _Jv_Method *meth = _Jv_GetMethodLocal (this, init_name, void_signature);
677 JvThrow (new java::lang::NoSuchMethodException);
679 jobject r = JvAllocObject (this);
680 ((void (*) (jobject)) meth->ncode) (r);
685 java::lang::Class::finalize (void)
688 JvAssert (_Jv_IsInterpretedClass (this));
689 _Jv_UnregisterClass (this);
695 java::lang::Class::hackRunInitializers (void)
697 _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name, void_signature);
699 ((void (*) (void)) meth->ncode) ();
702 // This implements the initialization process for a class. From Spec
705 java::lang::Class::initializeClass (void)
707 // Short-circuit to avoid needless locking.
708 if (state == JV_STATE_DONE)
711 // do this before we enter the monitor below, since this can cause
712 // exceptions. Here we assume, that reading "state" is an atomic
713 // operation, I pressume that is true? --Kresten
714 if (state < JV_STATE_LINKED)
717 if (_Jv_IsInterpretedClass (this))
719 java::lang::ClassLoader::resolveClass0 (this);
722 _Jv_MonitorEnter (this);
728 _Jv_MonitorEnter (this);
729 _Jv_PrepareCompiledClass (this);
735 _Jv_MonitorEnter (this);
739 java::lang::Thread *self = java::lang::Thread::currentThread();
740 // FIXME: `self' can be null at startup. Hence this nasty trick.
741 self = (java::lang::Thread *) ((long) self | 1);
742 while (state == JV_STATE_IN_PROGRESS && thread && thread != self)
746 if (state == JV_STATE_DONE || state == JV_STATE_IN_PROGRESS || thread == self)
748 _Jv_MonitorExit (this);
753 if (state == JV_STATE_ERROR)
755 _Jv_MonitorExit (this);
756 JvThrow (new java::lang::NoClassDefFoundError);
761 state = JV_STATE_IN_PROGRESS;
762 _Jv_MonitorExit (this);
765 if (! isInterface () && superclass)
767 // FIXME: We can't currently catch a Java exception in C++ code.
768 // So instead we call a Java trampoline. It returns an
769 // exception, or null.
770 jobject except = superclass->hackTrampoline(0, NULL);
773 // Caught an exception.
774 _Jv_MonitorEnter (this);
775 state = JV_STATE_ERROR;
777 _Jv_MonitorExit (this);
783 // FIXME: once again we have to go through a trampoline.
784 java::lang::Throwable *except = hackTrampoline (1, NULL);
789 _Jv_MonitorEnter (this);
790 state = JV_STATE_DONE;
794 if (! ErrorClass.isInstance(except))
796 // Once again we must use the trampoline. In this case we
797 // have to detect an OutOfMemoryError.
798 except = hackTrampoline(2, except);
800 _Jv_MonitorEnter (this);
801 state = JV_STATE_ERROR;
804 _Jv_MonitorExit (this);
812 // Some class-related convenience functions.
815 // Find a method declared in the class. If it is not declared locally
816 // (or if it is inherited), return NULL.
818 _Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
819 _Jv_Utf8Const *signature)
821 for (int i = 0; i < klass->method_count; ++i)
823 if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
824 && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
825 return &klass->methods[i];
831 _Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
832 _Jv_Utf8Const *signature)
834 for (; klass; klass = klass->getSuperclass())
836 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
845 // NOTE: MCACHE_SIZE should be a power of 2 minus one.
846 #define MCACHE_SIZE 1023
854 static _Jv_mcache method_cache[MCACHE_SIZE + 1];
857 _Jv_FindMethodInCache (jclass klass,
859 _Jv_Utf8Const *signature)
861 int index = name->hash & MCACHE_SIZE;
862 _Jv_mcache *mc = method_cache + index;
863 _Jv_Method *m = mc->method;
865 if (mc->klass == klass
866 && m != NULL // thread safe check
867 && _Jv_equalUtf8Consts (m->name, name)
868 && _Jv_equalUtf8Consts (m->signature, signature))
869 return mc->method->ncode;
874 _Jv_AddMethodToCache (jclass klass,
877 _Jv_MonitorEnter (&ClassClass);
879 int index = method->name->hash & MCACHE_SIZE;
881 method_cache[index].method = method;
882 method_cache[index].klass = klass;
884 _Jv_MonitorExit (&ClassClass);
888 _Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
889 _Jv_Utf8Const *signature)
891 void *ncode = _Jv_FindMethodInCache (klass, name, signature);
895 for (; klass; klass = klass->getSuperclass())
897 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
901 if (java::lang::reflect::Modifier::isStatic(meth->accflags))
902 JvThrow (new java::lang::IncompatibleClassChangeError);
903 if (java::lang::reflect::Modifier::isAbstract(meth->accflags))
904 JvThrow (new java::lang::AbstractMethodError);
905 if (! java::lang::reflect::Modifier::isPublic(meth->accflags))
906 JvThrow (new java::lang::IllegalAccessError);
908 _Jv_AddMethodToCache (klass, meth);
912 JvThrow (new java::lang::IncompatibleClassChangeError);
913 return NULL; // Placate compiler.
917 _Jv_InitClass (jclass klass)
919 klass->initializeClass();
923 _Jv_IsInstanceOf(jobject obj, jclass cl)
925 return cl->isInstance(obj);