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
+ i
] = 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 (java::lang::reflect::Modifier::isAbstract (source
->accflags
)
933 || source
->isInterface(), false))
934 return _Jv_InterfaceAssignableFrom (target
, source
);
936 _Jv_IDispatchTable
*cl_idt
= source
->idt
;
937 _Jv_IDispatchTable
*if_idt
= target
->idt
;
939 if (__builtin_expect ((if_idt
== NULL
), false))
940 return false; // No class implementing TARGET has been loaded.
941 jshort cl_iindex
= cl_idt
->cls
.iindex
;
942 if (cl_iindex
<= if_idt
->iface
.ioffsets
[0])
944 jshort offset
= if_idt
->iface
.ioffsets
[cl_iindex
];
945 if (offset
< cl_idt
->cls
.itable_length
946 && cl_idt
->cls
.itable
[offset
] == target
)
954 // Interface type checking, the slow way. Returns TRUE if IFACE is a
955 // superinterface of SOURCE. This is used when SOURCE is also an interface,
956 // or a class with no interface dispatch table.
958 _Jv_InterfaceAssignableFrom (jclass iface
, jclass source
)
960 for (int i
= 0; i
< source
->interface_count
; i
++)
962 jclass interface
= source
->interfaces
[i
];
963 if (iface
== interface
964 || _Jv_InterfaceAssignableFrom (iface
, interface
))
968 if (!source
->isInterface()
969 && source
->superclass
970 && _Jv_InterfaceAssignableFrom (iface
, source
->superclass
))
977 _Jv_IsInstanceOf(jobject obj
, jclass cl
)
979 if (__builtin_expect (!obj
, false))
981 return (_Jv_IsAssignableFrom (cl
, JV_CLASS (obj
)));
985 _Jv_CheckCast (jclass c
, jobject obj
)
988 (obj
!= NULL
&& ! _Jv_IsAssignableFrom(c
, JV_CLASS (obj
)), false))
989 JvThrow (new java::lang::ClassCastException
);
994 _Jv_CheckArrayStore (jobject arr
, jobject obj
)
998 JvAssert (arr
!= NULL
);
999 jclass elt_class
= (JV_CLASS (arr
))->getComponentType();
1000 jclass obj_class
= JV_CLASS (obj
);
1001 if (__builtin_expect
1002 (! _Jv_IsAssignableFrom (elt_class
, obj_class
), false))
1003 JvThrow (new java::lang::ArrayStoreException
);
1007 #define INITIAL_IOFFSETS_LEN 4
1008 #define INITIAL_IFACES_LEN 4
1010 // Generate tables for constant-time assignment testing and interface
1011 // method lookup. This implements the technique described by Per Bothner
1012 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
1013 // http://sourceware.cygnus.com/ml/java-discuss/1999-q3/msg00377.html
1015 _Jv_PrepareConstantTimeTables (jclass klass
)
1017 if (klass
->isPrimitive () || klass
->isInterface ())
1020 // Short-circuit in case we've been called already.
1021 if ((klass
->idt
!= NULL
) || klass
->depth
!= 0)
1024 // Calculate the class depth and ancestor table. The depth of a class
1025 // is how many "extends" it is removed from Object. Thus the depth of
1026 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
1027 // is 2. Depth is defined for all regular and array classes, but not
1028 // interfaces or primitive types.
1030 jclass klass0
= klass
;
1031 while (klass0
!= &ObjectClass
)
1033 klass0
= klass0
->superclass
;
1037 // We do class member testing in constant time by using a small table
1038 // of all the ancestor classes within each class. The first element is
1039 // a pointer to the current class, and the rest are pointers to the
1040 // classes ancestors, ordered from the current class down by decreasing
1041 // depth. We do not include java.lang.Object in the table of ancestors,
1042 // since it is redundant.
1044 klass
->ancestors
= (jclass
*) _Jv_Malloc (klass
->depth
* sizeof (jclass
));
1046 for (int index
= 0; index
< klass
->depth
; index
++)
1048 klass
->ancestors
[index
] = klass0
;
1049 klass0
= klass0
->superclass
;
1052 if (java::lang::reflect::Modifier::isAbstract (klass
->accflags
))
1056 (_Jv_IDispatchTable
*) _Jv_Malloc (sizeof (_Jv_IDispatchTable
));
1061 ifaces
.len
= INITIAL_IFACES_LEN
;
1062 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
* sizeof (jclass
*));
1064 int itable_size
= _Jv_GetInterfaces (klass
, &ifaces
);
1066 if (ifaces
.count
> 0)
1068 klass
->idt
->cls
.itable
=
1069 (void **) _Jv_Malloc (itable_size
* sizeof (void *));
1070 klass
->idt
->cls
.itable_length
= itable_size
;
1072 jshort
*itable_offsets
=
1073 (jshort
*) _Jv_Malloc (ifaces
.count
* sizeof (jshort
));
1075 _Jv_GenerateITable (klass
, &ifaces
, itable_offsets
);
1078 _Jv_FindIIndex (ifaces
.list
, itable_offsets
, ifaces
.count
);
1080 for (int i
=0; i
< ifaces
.count
; i
++)
1082 ifaces
.list
[i
]->idt
->iface
.ioffsets
[cls_iindex
] =
1086 klass
->idt
->cls
.iindex
= cls_iindex
;
1088 _Jv_Free (ifaces
.list
);
1089 _Jv_Free (itable_offsets
);
1093 klass
->idt
->cls
.iindex
= SHRT_MAX
;
1097 // Return index of item in list, or -1 if item is not present.
1099 _Jv_IndexOf (void *item
, void **list
, jshort list_len
)
1101 for (int i
=0; i
< list_len
; i
++)
1103 if (list
[i
] == item
)
1109 // Find all unique interfaces directly or indirectly implemented by klass.
1110 // Returns the size of the interface dispatch table (itable) for klass, which
1111 // is the number of unique interfaces plus the total number of methods that
1112 // those interfaces declare. May extend ifaces if required.
1114 _Jv_GetInterfaces (jclass klass
, _Jv_ifaces
*ifaces
)
1118 for (int i
=0; i
< klass
->interface_count
; i
++)
1120 jclass iface
= klass
->interfaces
[i
];
1121 if (_Jv_IndexOf (iface
, (void **) ifaces
->list
, ifaces
->count
) == -1)
1123 if (ifaces
->count
+ 1 >= ifaces
->len
)
1125 /* Resize ifaces list */
1126 ifaces
->len
= ifaces
->len
* 2;
1127 ifaces
->list
= (jclass
*) _Jv_Realloc (ifaces
->list
,
1128 ifaces
->len
* sizeof(jclass
));
1130 ifaces
->list
[ifaces
->count
] = iface
;
1133 result
+= _Jv_GetInterfaces (klass
->interfaces
[i
], ifaces
);
1137 if (klass
->isInterface())
1139 result
+= klass
->method_count
+ 1;
1143 if (klass
->superclass
)
1145 result
+= _Jv_GetInterfaces (klass
->superclass
, ifaces
);
1151 // Fill out itable in klass, resolving method declarations in each ifaces.
1152 // itable_offsets is filled out with the position of each iface in itable,
1153 // such that itable[itable_offsets[n]] == ifaces.list[n].
1155 _Jv_GenerateITable (jclass klass
, _Jv_ifaces
*ifaces
, jshort
*itable_offsets
)
1157 void **itable
= klass
->idt
->cls
.itable
;
1158 jshort itable_pos
= 0;
1160 for (int i
=0; i
< ifaces
->count
; i
++)
1162 jclass iface
= ifaces
->list
[i
];
1163 itable_offsets
[i
] = itable_pos
;
1164 itable_pos
= _Jv_AppendPartialITable (klass
, iface
, itable
,
1167 /* Create interface dispatch table for iface */
1168 if (iface
->idt
== NULL
)
1171 (_Jv_IDispatchTable
*) _Jv_Malloc (sizeof (_Jv_IDispatchTable
));
1173 // The first element of ioffsets is its length (itself included).
1175 (jshort
*) _Jv_Malloc (INITIAL_IOFFSETS_LEN
* sizeof (jshort
));
1176 ioffsets
[0] = INITIAL_IOFFSETS_LEN
;
1177 for (int i
=1; i
< INITIAL_IOFFSETS_LEN
; i
++)
1180 iface
->idt
->iface
.ioffsets
= ioffsets
;
1185 // Format method name for use in error messages.
1187 _Jv_GetMethodString (jclass klass
, _Jv_Utf8Const
*name
)
1189 jstring r
= JvNewStringUTF (klass
->name
->data
);
1190 r
= r
->concat (JvNewStringUTF ("."));
1191 r
= r
->concat (JvNewStringUTF (name
->data
));
1196 _Jv_ThrowNoSuchMethodError ()
1198 JvThrow (new java::lang::NoSuchMethodError ());
1201 // Each superinterface of a class (i.e. each interface that the class
1202 // directly or indirectly implements) has a corresponding "Partial
1203 // Interface Dispatch Table" whose size is (number of methods + 1) words.
1204 // The first word is a pointer to the interface (i.e. the java.lang.Class
1205 // instance for that interface). The remaining words are pointers to the
1206 // actual methods that implement the methods declared in the interface,
1207 // in order of declaration.
1209 // Append partial interface dispatch table for "iface" to "itable", at
1210 // position itable_pos.
1211 // Returns the offset at which the next partial ITable should be appended.
1213 _Jv_AppendPartialITable (jclass klass
, jclass iface
, void **itable
,
1216 using namespace java::lang::reflect
;
1218 itable
[pos
++] = (void *) iface
;
1221 for (int j
=0; j
< iface
->method_count
; j
++)
1224 for (jclass cl
= klass
; cl
; cl
= cl
->getSuperclass())
1226 meth
= _Jv_GetMethodLocal (cl
, iface
->methods
[j
].name
,
1227 iface
->methods
[j
].signature
);
1233 if (meth
&& (meth
->name
->data
[0] == '<'))
1235 // leave a placeholder in the itable for hidden init methods.
1240 if (Modifier::isStatic(meth
->accflags
))
1241 JvThrow (new java::lang::IncompatibleClassChangeError
1242 (_Jv_GetMethodString (klass
, meth
->name
)));
1243 if (Modifier::isAbstract(meth
->accflags
))
1244 JvThrow (new java::lang::AbstractMethodError
1245 (_Jv_GetMethodString (klass
, meth
->name
)));
1246 if (! Modifier::isPublic(meth
->accflags
))
1247 JvThrow (new java::lang::IllegalAccessError
1248 (_Jv_GetMethodString (klass
, meth
->name
)));
1250 itable
[pos
] = meth
->ncode
;
1254 // The method doesn't exist in klass. Binary compatibility rules
1255 // permit this, so we delay the error until runtime using a pointer
1256 // to a method which throws an exception.
1257 itable
[pos
] = (void *) _Jv_ThrowNoSuchMethodError
;
1265 static _Jv_Mutex_t iindex_mutex
;
1266 bool iindex_mutex_initialized
= false;
1268 // We need to find the correct offset in the Class Interface Dispatch
1269 // Table for a given interface. Once we have that, invoking an interface
1270 // method just requires combining the Method's index in the interface
1271 // (known at compile time) to get the correct method. Doing a type test
1272 // (cast or instanceof) is the same problem: Once we have a possible Partial
1273 // Interface Dispatch Table, we just compare the first element to see if it
1274 // matches the desired interface. So how can we find the correct offset?
1275 // Our solution is to keep a vector of candiate offsets in each interface
1276 // (idt->iface.ioffsets), and in each class we have an index
1277 // (idt->cls.iindex) used to select the correct offset from ioffsets.
1279 // Calculate and return iindex for a new class.
1280 // ifaces is a vector of num interfaces that the class implements.
1281 // offsets[j] is the offset in the interface dispatch table for the
1282 // interface corresponding to ifaces[j].
1283 // May extend the interface ioffsets if required.
1285 _Jv_FindIIndex (jclass
*ifaces
, jshort
*offsets
, jshort num
)
1290 // Acquire a global lock to prevent itable corruption in case of multiple
1291 // classes that implement an intersecting set of interfaces being linked
1292 // simultaneously. We can assume that the mutex will be initialized
1294 if (! iindex_mutex_initialized
)
1296 _Jv_MutexInit (&iindex_mutex
);
1297 iindex_mutex_initialized
= true;
1300 _Jv_MutexLock (&iindex_mutex
);
1302 for (i
=1;; i
++) /* each potential position in ioffsets */
1304 for (j
=0;; j
++) /* each iface */
1308 if (i
> ifaces
[j
]->idt
->iface
.ioffsets
[0])
1310 int ioffset
= ifaces
[j
]->idt
->iface
.ioffsets
[i
];
1311 /* We can potentially share this position with another class. */
1312 if (ioffset
>= 0 && ioffset
!= offsets
[j
])
1313 break; /* Nope. Try next i. */
1317 for (j
= 0; j
< num
; j
++)
1319 int len
= ifaces
[j
]->idt
->iface
.ioffsets
[0];
1322 /* Resize ioffsets. */
1323 int newlen
= 2 * len
;
1326 jshort
*old_ioffsets
= ifaces
[j
]->idt
->iface
.ioffsets
;
1327 jshort
*new_ioffsets
= (jshort
*) _Jv_Realloc (old_ioffsets
,
1328 newlen
* sizeof(jshort
));
1329 new_ioffsets
[0] = newlen
;
1331 while (len
< newlen
)
1332 new_ioffsets
[len
++] = -1;
1334 ifaces
[j
]->idt
->iface
.ioffsets
= new_ioffsets
;
1336 ifaces
[j
]->idt
->iface
.ioffsets
[i
] = offsets
[j
];
1339 _Jv_MutexUnlock (&iindex_mutex
);
1344 // Only used by serialization
1345 java::lang::reflect::Field
*
1346 java::lang::Class::getPrivateField (jstring name
)
1348 int hash
= name
->hashCode ();
1350 java::lang::reflect::Field
* rfield
;
1351 for (int i
= 0; i
< field_count
; i
++)
1353 _Jv_Field
*field
= &fields
[i
];
1354 if (! _Jv_equal (field
->name
, name
, hash
))
1356 rfield
= new java::lang::reflect::Field ();
1357 rfield
->offset
= (char*) field
- (char*) fields
;
1358 rfield
->declaringClass
= this;
1359 rfield
->name
= name
;
1362 jclass superclass
= getSuperclass();
1363 if (superclass
== NULL
)
1365 rfield
= superclass
->getPrivateField(name
);
1366 for (int i
= 0; i
< interface_count
&& rfield
== NULL
; ++i
)
1367 rfield
= interfaces
[i
]->getPrivateField (name
);
1371 // Only used by serialization
1372 java::lang::reflect::Method
*
1373 java::lang::Class::getPrivateMethod (jstring name
, JArray
<jclass
> *param_types
)
1375 jstring partial_sig
= getSignature (param_types
, false);
1376 jint p_len
= partial_sig
->length();
1377 _Jv_Utf8Const
*utf_name
= _Jv_makeUtf8Const (name
);
1378 for (Class
*klass
= this; klass
; klass
= klass
->getSuperclass())
1380 int i
= klass
->isPrimitive () ? 0 : klass
->method_count
;
1383 // FIXME: access checks.
1384 if (_Jv_equalUtf8Consts (klass
->methods
[i
].name
, utf_name
)
1385 && _Jv_equaln (klass
->methods
[i
].signature
, partial_sig
, p_len
))
1388 using namespace java::lang::reflect
;
1390 Method
*rmethod
= new Method ();
1391 rmethod
->offset
= ((char *) (&klass
->methods
[i
])
1392 - (char *) klass
->methods
);
1393 rmethod
->declaringClass
= klass
;
1398 JvThrow (new java::lang::NoSuchMethodException
);