c-decl.c (c_finish_incomplete_decl): Don't use xxx_with_decl.
[official-gcc.git] / libjava / java / lang / natClass.cc
blob0db8228d63bb727ab04e8c303006dc64cb3568a6
1 // natClass.cc - Implementation of java.lang.Class native methods.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 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
9 details. */
11 #include <config.h>
13 #include <limits.h>
14 #include <string.h>
16 #pragma implementation "Class.h"
18 #include <gcj/cni.h>
19 #include <jvm.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/ArrayIndexOutOfBoundsException.h>
40 #include <java/lang/InstantiationException.h>
41 #include <java/lang/NoClassDefFoundError.h>
42 #include <java/lang/NoSuchFieldException.h>
43 #include <java/lang/NoSuchMethodError.h>
44 #include <java/lang/NoSuchMethodException.h>
45 #include <java/lang/Thread.h>
46 #include <java/lang/NullPointerException.h>
47 #include <java/lang/RuntimePermission.h>
48 #include <java/lang/System.h>
49 #include <java/lang/SecurityManager.h>
50 #include <java/lang/StringBuffer.h>
51 #include <gnu/gcj/runtime/StackTrace.h>
52 #include <gcj/method.h>
53 #include <gnu/gcj/runtime/MethodRef.h>
54 #include <gnu/gcj/RawData.h>
56 #include <java-cpool.h>
60 using namespace gcj;
62 jclass
63 java::lang::Class::forName (jstring className, jboolean initialize,
64 java::lang::ClassLoader *loader)
66 if (! className)
67 throw new java::lang::NullPointerException;
69 jsize length = _Jv_GetStringUTFLength (className);
70 char buffer[length];
71 _Jv_GetStringUTFRegion (className, 0, length, buffer);
73 _Jv_Utf8Const *name = _Jv_makeUtf8Const (buffer, length);
75 if (! _Jv_VerifyClassName (name))
76 throw new java::lang::ClassNotFoundException (className);
78 jclass klass = (buffer[0] == '['
79 ? _Jv_FindClassFromSignature (name->data, loader)
80 : _Jv_FindClass (name, loader));
82 if (klass == NULL)
83 throw new java::lang::ClassNotFoundException (className);
85 if (initialize)
86 _Jv_InitClass (klass);
88 return klass;
91 jclass
92 java::lang::Class::forName (jstring className)
94 java::lang::ClassLoader *loader = NULL;
95 gnu::gcj::runtime::StackTrace *t
96 = new gnu::gcj::runtime::StackTrace(4);
97 java::lang::Class *klass = NULL;
98 try
100 for (int i = 1; !klass; i++)
102 klass = t->classAt (i);
104 loader = klass->getClassLoader();
106 catch (::java::lang::ArrayIndexOutOfBoundsException *e)
110 return forName (className, true, loader);
113 java::lang::ClassLoader *
114 java::lang::Class::getClassLoader (void)
116 #if 0
117 // FIXME: the checks we need to do are more complex. See the spec.
118 // Currently we can't implement them.
119 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
120 if (s != NULL)
121 s->checkPermission (new RuntimePermission (JvNewStringLatin1 ("getClassLoader")));
122 #endif
124 // The spec requires us to return `null' for primitive classes. In
125 // other cases we have the option of returning `null' for classes
126 // loaded with the bootstrap loader. All gcj-compiled classes which
127 // are linked into the application used to return `null' here, but
128 // that confuses some poorly-written applications. It is a useful
129 // and apparently harmless compatibility hack to simply never return
130 // `null' instead.
131 if (isPrimitive ())
132 return NULL;
133 return loader ? loader : ClassLoader::getSystemClassLoader ();
136 java::lang::reflect::Constructor *
137 java::lang::Class::getConstructor (JArray<jclass> *param_types)
139 jstring partial_sig = getSignature (param_types, true);
140 jint hash = partial_sig->hashCode ();
142 int i = isPrimitive () ? 0 : method_count;
143 while (--i >= 0)
145 // FIXME: access checks.
146 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
147 && _Jv_equal (methods[i].signature, partial_sig, hash))
149 // Found it. For getConstructor, the constructor must be
150 // public.
151 using namespace java::lang::reflect;
152 if (! Modifier::isPublic(methods[i].accflags))
153 break;
154 Constructor *cons = new Constructor ();
155 cons->offset = (char *) (&methods[i]) - (char *) methods;
156 cons->declaringClass = this;
157 return cons;
160 throw new java::lang::NoSuchMethodException (_Jv_NewStringUtf8Const (init_name));
163 JArray<java::lang::reflect::Constructor *> *
164 java::lang::Class::_getConstructors (jboolean declared)
166 // FIXME: this method needs access checks.
168 int numConstructors = 0;
169 int max = isPrimitive () ? 0 : method_count;
170 int i;
171 for (i = max; --i >= 0; )
173 _Jv_Method *method = &methods[i];
174 if (method->name == NULL
175 || ! _Jv_equalUtf8Consts (method->name, init_name))
176 continue;
177 if (! declared
178 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
179 continue;
180 numConstructors++;
182 JArray<java::lang::reflect::Constructor *> *result
183 = (JArray<java::lang::reflect::Constructor *> *)
184 JvNewObjectArray (numConstructors,
185 &java::lang::reflect::Constructor::class$,
186 NULL);
187 java::lang::reflect::Constructor** cptr = elements (result);
188 for (i = 0; i < max; i++)
190 _Jv_Method *method = &methods[i];
191 if (method->name == NULL
192 || ! _Jv_equalUtf8Consts (method->name, init_name))
193 continue;
194 if (! declared
195 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
196 continue;
197 java::lang::reflect::Constructor *cons
198 = new java::lang::reflect::Constructor ();
199 cons->offset = (char *) method - (char *) methods;
200 cons->declaringClass = this;
201 *cptr++ = cons;
203 return result;
206 java::lang::reflect::Constructor *
207 java::lang::Class::getDeclaredConstructor (JArray<jclass> *param_types)
209 jstring partial_sig = getSignature (param_types, true);
210 jint hash = partial_sig->hashCode ();
212 int i = isPrimitive () ? 0 : method_count;
213 while (--i >= 0)
215 // FIXME: access checks.
216 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
217 && _Jv_equal (methods[i].signature, partial_sig, hash))
219 // Found it.
220 using namespace java::lang::reflect;
221 Constructor *cons = new Constructor ();
222 cons->offset = (char *) (&methods[i]) - (char *) methods;
223 cons->declaringClass = this;
224 return cons;
227 throw new java::lang::NoSuchMethodException (_Jv_NewStringUtf8Const (init_name));
230 java::lang::reflect::Field *
231 java::lang::Class::getField (jstring name, jint hash)
233 java::lang::reflect::Field* rfield;
234 for (int i = 0; i < field_count; i++)
236 _Jv_Field *field = &fields[i];
237 if (! _Jv_equal (field->name, name, hash))
238 continue;
239 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
240 continue;
241 rfield = new java::lang::reflect::Field ();
242 rfield->offset = (char*) field - (char*) fields;
243 rfield->declaringClass = this;
244 rfield->name = name;
245 return rfield;
247 jclass superclass = getSuperclass();
248 if (superclass == NULL)
249 return NULL;
250 rfield = superclass->getField(name, hash);
251 for (int i = 0; i < interface_count && rfield == NULL; ++i)
252 rfield = interfaces[i]->getField (name, hash);
253 return rfield;
256 java::lang::reflect::Field *
257 java::lang::Class::getDeclaredField (jstring name)
259 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
260 if (s != NULL)
261 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
262 int hash = name->hashCode();
263 for (int i = 0; i < field_count; i++)
265 _Jv_Field *field = &fields[i];
266 if (! _Jv_equal (field->name, name, hash))
267 continue;
268 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
269 rfield->offset = (char*) field - (char*) fields;
270 rfield->declaringClass = this;
271 rfield->name = name;
272 return rfield;
274 throw new java::lang::NoSuchFieldException (name);
277 JArray<java::lang::reflect::Field *> *
278 java::lang::Class::getDeclaredFields (void)
280 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
281 if (s != NULL)
282 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
283 JArray<java::lang::reflect::Field *> *result
284 = (JArray<java::lang::reflect::Field *> *)
285 JvNewObjectArray (field_count, &java::lang::reflect::Field::class$, NULL);
286 java::lang::reflect::Field** fptr = elements (result);
287 for (int i = 0; i < field_count; i++)
289 _Jv_Field *field = &fields[i];
290 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
291 rfield->offset = (char*) field - (char*) fields;
292 rfield->declaringClass = this;
293 *fptr++ = rfield;
295 return result;
298 void
299 java::lang::Class::getSignature (java::lang::StringBuffer *buffer)
301 if (isPrimitive())
302 buffer->append((jchar) method_count);
303 else
305 jstring name = getName();
306 if (name->charAt(0) != '[')
307 buffer->append((jchar) 'L');
308 buffer->append(name);
309 if (name->charAt(0) != '[')
310 buffer->append((jchar) ';');
314 // This doesn't have to be native. It is an implementation detail
315 // only called from the C++ code, though, so maybe this is clearer.
316 jstring
317 java::lang::Class::getSignature (JArray<jclass> *param_types,
318 jboolean is_constructor)
320 java::lang::StringBuffer *buf = new java::lang::StringBuffer ();
321 buf->append((jchar) '(');
322 // A NULL param_types means "no parameters".
323 if (param_types != NULL)
325 jclass *v = elements (param_types);
326 for (int i = 0; i < param_types->length; ++i)
327 v[i]->getSignature(buf);
329 buf->append((jchar) ')');
330 if (is_constructor)
331 buf->append((jchar) 'V');
332 return buf->toString();
335 java::lang::reflect::Method *
336 java::lang::Class::_getDeclaredMethod (jstring name,
337 JArray<jclass> *param_types)
339 jstring partial_sig = getSignature (param_types, false);
340 jint p_len = partial_sig->length();
341 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
342 int i = isPrimitive () ? 0 : method_count;
343 while (--i >= 0)
345 if (_Jv_equalUtf8Consts (methods[i].name, utf_name)
346 && _Jv_equaln (methods[i].signature, partial_sig, p_len)
347 && (methods[i].accflags
348 & java::lang::reflect::Modifier::INVISIBLE) == 0)
350 // Found it.
351 using namespace java::lang::reflect;
352 Method *rmethod = new Method ();
353 rmethod->offset = (char*) (&methods[i]) - (char*) methods;
354 rmethod->declaringClass = this;
355 return rmethod;
358 return NULL;
361 JArray<java::lang::reflect::Method *> *
362 java::lang::Class::getDeclaredMethods (void)
364 int numMethods = 0;
365 int max = isPrimitive () ? 0 : method_count;
366 int i;
367 for (i = max; --i >= 0; )
369 _Jv_Method *method = &methods[i];
370 if (method->name == NULL
371 || _Jv_equalUtf8Consts (method->name, clinit_name)
372 || _Jv_equalUtf8Consts (method->name, init_name)
373 || _Jv_equalUtf8Consts (method->name, finit_name)
374 || (methods[i].accflags
375 & java::lang::reflect::Modifier::INVISIBLE) != 0)
376 continue;
377 numMethods++;
379 JArray<java::lang::reflect::Method *> *result
380 = (JArray<java::lang::reflect::Method *> *)
381 JvNewObjectArray (numMethods, &java::lang::reflect::Method::class$, NULL);
382 java::lang::reflect::Method** mptr = elements (result);
383 for (i = 0; i < max; i++)
385 _Jv_Method *method = &methods[i];
386 if (method->name == NULL
387 || _Jv_equalUtf8Consts (method->name, clinit_name)
388 || _Jv_equalUtf8Consts (method->name, init_name)
389 || _Jv_equalUtf8Consts (method->name, finit_name)
390 || (methods[i].accflags
391 & java::lang::reflect::Modifier::INVISIBLE) != 0)
392 continue;
393 java::lang::reflect::Method* rmethod
394 = new java::lang::reflect::Method ();
395 rmethod->offset = (char*) method - (char*) methods;
396 rmethod->declaringClass = this;
397 *mptr++ = rmethod;
399 return result;
402 jstring
403 java::lang::Class::getName (void)
405 char buffer[name->length + 1];
406 memcpy (buffer, name->data, name->length);
407 buffer[name->length] = '\0';
408 return _Jv_NewStringUTF (buffer);
411 JArray<jclass> *
412 java::lang::Class::getClasses (void)
414 // FIXME: security checking.
416 // Until we have inner classes, it always makes sense to return an
417 // empty array.
418 JArray<jclass> *result
419 = (JArray<jclass> *) JvNewObjectArray (0, &java::lang::Class::class$,
420 NULL);
421 return result;
424 JArray<jclass> *
425 java::lang::Class::getDeclaredClasses (void)
427 checkMemberAccess (java::lang::reflect::Member::DECLARED);
428 // Until we have inner classes, it always makes sense to return an
429 // empty array.
430 JArray<jclass> *result
431 = (JArray<jclass> *) JvNewObjectArray (0, &java::lang::Class::class$,
432 NULL);
433 return result;
436 jclass
437 java::lang::Class::getDeclaringClass (void)
439 // Until we have inner classes, it makes sense to always return
440 // NULL.
441 return NULL;
444 jint
445 java::lang::Class::_getFields (JArray<java::lang::reflect::Field *> *result,
446 jint offset)
448 int count = 0;
449 for (int i = 0; i < field_count; i++)
451 _Jv_Field *field = &fields[i];
452 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
453 continue;
454 ++count;
456 if (result != NULL)
458 java::lang::reflect::Field *rfield
459 = new java::lang::reflect::Field ();
460 rfield->offset = (char *) field - (char *) fields;
461 rfield->declaringClass = this;
462 rfield->name = _Jv_NewStringUtf8Const (field->name);
463 (elements (result))[offset++] = rfield;
466 jclass superclass = getSuperclass();
467 if (superclass != NULL)
469 int s_count = superclass->_getFields (result, offset);
470 count += s_count;
471 offset += s_count;
473 for (int i = 0; i < interface_count; ++i)
475 int f_count = interfaces[i]->_getFields (result, offset);
476 count += f_count;
477 offset += f_count;
479 return count;
482 JArray<java::lang::reflect::Field *> *
483 java::lang::Class::getFields (void)
485 // FIXME: security checking.
487 using namespace java::lang::reflect;
489 int count = _getFields (NULL, 0);
491 JArray<java::lang::reflect::Field *> *result
492 = ((JArray<java::lang::reflect::Field *> *)
493 JvNewObjectArray (count, &java::lang::reflect::Field::class$, NULL));
495 _getFields (result, 0);
497 return result;
500 JArray<jclass> *
501 java::lang::Class::getInterfaces (void)
503 jobjectArray r = JvNewObjectArray (interface_count, getClass (), NULL);
504 jobject *data = elements (r);
505 for (int i = 0; i < interface_count; ++i)
506 data[i] = interfaces[i];
507 return reinterpret_cast<JArray<jclass> *> (r);
510 java::lang::reflect::Method *
511 java::lang::Class::_getMethod (jstring name, JArray<jclass> *param_types)
513 jstring partial_sig = getSignature (param_types, false);
514 jint p_len = partial_sig->length();
515 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
516 for (Class *klass = this; klass; klass = klass->getSuperclass())
518 int i = klass->isPrimitive () ? 0 : klass->method_count;
519 while (--i >= 0)
521 // FIXME: access checks.
522 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
523 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len)
524 && (klass->methods[i].accflags
525 & java::lang::reflect::Modifier::INVISIBLE) == 0)
527 // Found it.
528 using namespace java::lang::reflect;
530 // Method must be public.
531 if (! Modifier::isPublic (klass->methods[i].accflags))
532 break;
534 Method *rmethod = new Method ();
535 rmethod->offset = ((char *) (&klass->methods[i])
536 - (char *) klass->methods);
537 rmethod->declaringClass = klass;
538 return rmethod;
543 // If we haven't found a match, and this class is an interface, then
544 // check all the superinterfaces.
545 if (isInterface())
547 for (int i = 0; i < interface_count; ++i)
549 using namespace java::lang::reflect;
550 Method *rmethod = interfaces[i]->_getMethod (name, param_types);
551 if (rmethod != NULL)
552 return rmethod;
556 return NULL;
559 // This is a very slow implementation, since it re-scans all the
560 // methods we've already listed to make sure we haven't duplicated a
561 // method. It also over-estimates the required size, so we have to
562 // shrink the result array later.
563 jint
564 java::lang::Class::_getMethods (JArray<java::lang::reflect::Method *> *result,
565 jint offset)
567 jint count = 0;
569 // First examine all local methods
570 for (int i = isPrimitive () ? 0 : method_count; --i >= 0; )
572 _Jv_Method *method = &methods[i];
573 if (method->name == NULL
574 || _Jv_equalUtf8Consts (method->name, clinit_name)
575 || _Jv_equalUtf8Consts (method->name, init_name)
576 || _Jv_equalUtf8Consts (method->name, finit_name)
577 || (method->accflags
578 & java::lang::reflect::Modifier::INVISIBLE) != 0)
579 continue;
580 // Only want public methods.
581 if (! java::lang::reflect::Modifier::isPublic (method->accflags))
582 continue;
584 // This is where we over-count the slots required if we aren't
585 // filling the result for real.
586 if (result != NULL)
588 jboolean add = true;
589 java::lang::reflect::Method **mp = elements (result);
590 // If we already have a method with this name and signature,
591 // then ignore this one. This can happen with virtual
592 // methods.
593 for (int j = 0; j < offset; ++j)
595 _Jv_Method *meth_2 = _Jv_FromReflectedMethod (mp[j]);
596 if (_Jv_equalUtf8Consts (method->name, meth_2->name)
597 && _Jv_equalUtf8Consts (method->signature,
598 meth_2->signature))
600 add = false;
601 break;
604 if (! add)
605 continue;
608 if (result != NULL)
610 using namespace java::lang::reflect;
611 Method *rmethod = new Method ();
612 rmethod->offset = (char *) method - (char *) methods;
613 rmethod->declaringClass = this;
614 Method **mp = elements (result);
615 mp[offset + count] = rmethod;
617 ++count;
619 offset += count;
621 // Now examine superclasses.
622 if (getSuperclass () != NULL)
624 jint s_count = getSuperclass()->_getMethods (result, offset);
625 offset += s_count;
626 count += s_count;
629 // Finally, examine interfaces.
630 for (int i = 0; i < interface_count; ++i)
632 int f_count = interfaces[i]->_getMethods (result, offset);
633 count += f_count;
634 offset += f_count;
637 return count;
640 JArray<java::lang::reflect::Method *> *
641 java::lang::Class::getMethods (void)
643 using namespace java::lang::reflect;
645 // FIXME: security checks.
647 // This will overestimate the size we need.
648 jint count = _getMethods (NULL, 0);
650 JArray<Method *> *result
651 = ((JArray<Method *> *) JvNewObjectArray (count,
652 &Method::class$,
653 NULL));
655 // When filling the array for real, we get the actual count. Then
656 // we resize the array.
657 jint real_count = _getMethods (result, 0);
659 if (real_count != count)
661 JArray<Method *> *r2
662 = ((JArray<Method *> *) JvNewObjectArray (real_count,
663 &Method::class$,
664 NULL));
666 Method **destp = elements (r2);
667 Method **srcp = elements (result);
669 for (int i = 0; i < real_count; ++i)
670 *destp++ = *srcp++;
672 result = r2;
675 return result;
678 jboolean
679 java::lang::Class::isAssignableFrom (jclass klass)
681 // Arguments may not have been initialized, given ".class" syntax.
682 _Jv_InitClass (this);
683 _Jv_InitClass (klass);
684 return _Jv_IsAssignableFrom (this, klass);
687 jboolean
688 java::lang::Class::isInstance (jobject obj)
690 if (! obj)
691 return false;
692 _Jv_InitClass (this);
693 return _Jv_IsAssignableFrom (this, JV_CLASS (obj));
696 jobject
697 java::lang::Class::newInstance (void)
699 // FIXME: do accessibility checks here. There currently doesn't
700 // seem to be any way to do these.
701 // FIXME: we special-case one check here just to pass a Plum Hall
702 // test. Once access checking is implemented, remove this.
703 if (this == &java::lang::Class::class$)
704 throw new java::lang::IllegalAccessException;
706 if (isPrimitive ()
707 || isInterface ()
708 || isArray ()
709 || java::lang::reflect::Modifier::isAbstract(accflags))
710 throw new java::lang::InstantiationException (getName ());
712 _Jv_InitClass (this);
714 _Jv_Method *meth = _Jv_GetMethodLocal (this, init_name, void_signature);
715 if (! meth)
716 throw new java::lang::NoSuchMethodException (_Jv_NewStringUtf8Const (init_name));
718 jobject r = JvAllocObject (this);
719 ((void (*) (jobject)) meth->ncode) (r);
720 return r;
723 void
724 java::lang::Class::finalize (void)
726 #ifdef INTERPRETER
727 JvAssert (_Jv_IsInterpretedClass (this));
728 _Jv_UnregisterClass (this);
729 #endif
732 // This implements the initialization process for a class. From Spec
733 // section 12.4.2.
734 void
735 java::lang::Class::initializeClass (void)
737 // short-circuit to avoid needless locking.
738 if (state == JV_STATE_DONE)
739 return;
741 // Step 1.
742 _Jv_MonitorEnter (this);
744 if (state < JV_STATE_LINKED)
746 #ifdef INTERPRETER
747 if (_Jv_IsInterpretedClass (this))
749 // this can throw exceptions, so exit the monitor as a precaution.
750 _Jv_MonitorExit (this);
751 java::lang::ClassLoader::resolveClass0 (this);
752 _Jv_MonitorEnter (this);
754 else
755 #endif
757 _Jv_PrepareCompiledClass (this);
761 // Step 2.
762 java::lang::Thread *self = java::lang::Thread::currentThread();
763 // FIXME: `self' can be null at startup. Hence this nasty trick.
764 self = (java::lang::Thread *) ((long) self | 1);
765 while (state == JV_STATE_IN_PROGRESS && thread && thread != self)
766 wait ();
768 // Steps 3 & 4.
769 if (state == JV_STATE_DONE)
771 _Jv_MonitorExit (this);
772 return;
774 if (state == JV_STATE_IN_PROGRESS)
776 _Jv_MonitorExit (this);
778 /* Initialization in progress. The class is linked now,
779 so ensure internal tables are built. */
780 _Jv_PrepareConstantTimeTables (this);
781 _Jv_MakeVTable(this);
782 _Jv_LinkOffsetTable(this);
784 return;
787 // Step 5.
788 if (state == JV_STATE_ERROR)
790 _Jv_MonitorExit (this);
791 throw new java::lang::NoClassDefFoundError (getName());
794 // Step 6.
795 thread = self;
796 state = JV_STATE_IN_PROGRESS;
797 _Jv_MonitorExit (this);
799 // Step 7.
800 if (! isInterface () && superclass)
804 _Jv_InitClass (superclass);
806 catch (java::lang::Throwable *except)
808 // Caught an exception.
809 _Jv_MonitorEnter (this);
810 state = JV_STATE_ERROR;
811 notifyAll ();
812 _Jv_MonitorExit (this);
813 throw except;
817 _Jv_PrepareConstantTimeTables (this);
819 if (vtable == NULL)
820 _Jv_MakeVTable(this);
822 if (otable != NULL && otable->state == 0)
823 _Jv_LinkOffsetTable(this);
825 // Steps 8, 9, 10, 11.
828 _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name,
829 void_signature);
830 if (meth)
831 ((void (*) (void)) meth->ncode) ();
833 catch (java::lang::Throwable *except)
835 if (! java::lang::Error::class$.isInstance(except))
839 except = new ExceptionInInitializerError (except);
841 catch (java::lang::Throwable *t)
843 except = t;
846 _Jv_MonitorEnter (this);
847 state = JV_STATE_ERROR;
848 notifyAll ();
849 _Jv_MonitorExit (this);
850 throw except;
853 _Jv_MonitorEnter (this);
854 state = JV_STATE_DONE;
855 notifyAll ();
856 _Jv_MonitorExit (this);
862 // Some class-related convenience functions.
865 // Find a method declared in the class. If it is not declared locally
866 // (or if it is inherited), return NULL.
867 _Jv_Method *
868 _Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
869 _Jv_Utf8Const *signature)
871 for (int i = 0; i < klass->method_count; ++i)
873 if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
874 && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
875 return &klass->methods[i];
877 return NULL;
880 _Jv_Method *
881 _Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
882 _Jv_Utf8Const *signature)
884 for (; klass; klass = klass->getSuperclass())
886 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
888 if (meth)
889 return meth;
892 return NULL;
895 // NOTE: MCACHE_SIZE should be a power of 2 minus one.
896 #define MCACHE_SIZE 1023
898 struct _Jv_mcache
900 jclass klass;
901 _Jv_Method *method;
904 static _Jv_mcache method_cache[MCACHE_SIZE + 1];
906 static void *
907 _Jv_FindMethodInCache (jclass klass,
908 _Jv_Utf8Const *name,
909 _Jv_Utf8Const *signature)
911 int index = name->hash & MCACHE_SIZE;
912 _Jv_mcache *mc = method_cache + index;
913 _Jv_Method *m = mc->method;
915 if (mc->klass == klass
916 && m != NULL // thread safe check
917 && _Jv_equalUtf8Consts (m->name, name)
918 && _Jv_equalUtf8Consts (m->signature, signature))
919 return mc->method->ncode;
920 return NULL;
923 static void
924 _Jv_AddMethodToCache (jclass klass,
925 _Jv_Method *method)
927 _Jv_MonitorEnter (&java::lang::Class::class$);
929 int index = method->name->hash & MCACHE_SIZE;
931 method_cache[index].method = method;
932 method_cache[index].klass = klass;
934 _Jv_MonitorExit (&java::lang::Class::class$);
937 void *
938 _Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
939 _Jv_Utf8Const *signature)
941 using namespace java::lang::reflect;
943 void *ncode = _Jv_FindMethodInCache (klass, name, signature);
944 if (ncode != 0)
945 return ncode;
947 for (; klass; klass = klass->getSuperclass())
949 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
950 if (! meth)
951 continue;
953 if (Modifier::isStatic(meth->accflags))
954 throw new java::lang::IncompatibleClassChangeError
955 (_Jv_GetMethodString (klass, meth->name));
956 if (Modifier::isAbstract(meth->accflags))
957 throw new java::lang::AbstractMethodError
958 (_Jv_GetMethodString (klass, meth->name));
959 if (! Modifier::isPublic(meth->accflags))
960 throw new java::lang::IllegalAccessError
961 (_Jv_GetMethodString (klass, meth->name));
963 _Jv_AddMethodToCache (klass, meth);
965 return meth->ncode;
967 throw new java::lang::IncompatibleClassChangeError;
970 // Fast interface method lookup by index.
971 void *
972 _Jv_LookupInterfaceMethodIdx (jclass klass, jclass iface, int method_idx)
974 _Jv_IDispatchTable *cldt = klass->idt;
975 int idx = iface->idt->iface.ioffsets[cldt->cls.iindex] + method_idx;
976 return cldt->cls.itable[idx];
979 jboolean
980 _Jv_IsAssignableFrom (jclass target, jclass source)
982 if (source == target)
983 return true;
985 // If target is array, so must source be.
986 while (target->isArray ())
988 if (! source->isArray())
989 return false;
990 target = target->getComponentType();
991 source = source->getComponentType();
994 if (target->isInterface())
996 // Abstract classes have no IDT, and IDTs provide no way to check
997 // two interfaces for assignability.
998 if (__builtin_expect
999 (source->idt == NULL || source->isInterface(), false))
1000 return _Jv_InterfaceAssignableFrom (target, source);
1002 _Jv_IDispatchTable *cl_idt = source->idt;
1003 _Jv_IDispatchTable *if_idt = target->idt;
1005 if (__builtin_expect ((if_idt == NULL), false))
1006 return false; // No class implementing TARGET has been loaded.
1007 jshort cl_iindex = cl_idt->cls.iindex;
1008 if (cl_iindex < if_idt->iface.ioffsets[0])
1010 jshort offset = if_idt->iface.ioffsets[cl_iindex];
1011 if (offset != -1 && offset < cl_idt->cls.itable_length
1012 && cl_idt->cls.itable[offset] == target)
1013 return true;
1015 return false;
1018 // Primitive TYPE classes are only assignable to themselves.
1019 if (__builtin_expect (target->isPrimitive() || source->isPrimitive(), false))
1020 return false;
1022 if (target == &java::lang::Object::class$)
1023 return true;
1024 else if (source->ancestors == NULL || target->ancestors == NULL)
1026 // We need this case when either SOURCE or TARGET has not has
1027 // its constant-time tables prepared.
1029 // At this point we know that TARGET can't be Object, so it is
1030 // safe to use that as the termination point.
1031 while (source && source != &java::lang::Object::class$)
1033 if (source == target)
1034 return true;
1035 source = source->getSuperclass();
1038 else if (source->depth >= target->depth
1039 && source->ancestors[source->depth - target->depth] == target)
1040 return true;
1042 return false;
1045 // Interface type checking, the slow way. Returns TRUE if IFACE is a
1046 // superinterface of SOURCE. This is used when SOURCE is also an interface,
1047 // or a class with no interface dispatch table.
1048 jboolean
1049 _Jv_InterfaceAssignableFrom (jclass iface, jclass source)
1051 for (int i = 0; i < source->interface_count; i++)
1053 jclass interface = source->interfaces[i];
1054 if (iface == interface
1055 || _Jv_InterfaceAssignableFrom (iface, interface))
1056 return true;
1059 if (!source->isInterface()
1060 && source->superclass
1061 && _Jv_InterfaceAssignableFrom (iface, source->superclass))
1062 return true;
1064 return false;
1067 jboolean
1068 _Jv_IsInstanceOf(jobject obj, jclass cl)
1070 if (__builtin_expect (!obj, false))
1071 return false;
1072 return (_Jv_IsAssignableFrom (cl, JV_CLASS (obj)));
1075 void *
1076 _Jv_CheckCast (jclass c, jobject obj)
1078 if (__builtin_expect
1079 (obj != NULL && ! _Jv_IsAssignableFrom(c, JV_CLASS (obj)), false))
1080 throw new java::lang::ClassCastException
1081 ((new java::lang::StringBuffer
1082 (obj->getClass()->getName()))->append
1083 (JvNewStringUTF(" cannot be cast to "))->append
1084 (c->getName())->toString());
1086 return obj;
1089 void
1090 _Jv_CheckArrayStore (jobject arr, jobject obj)
1092 if (obj)
1094 JvAssert (arr != NULL);
1095 jclass elt_class = (JV_CLASS (arr))->getComponentType();
1096 if (elt_class == &java::lang::Object::class$)
1097 return;
1098 jclass obj_class = JV_CLASS (obj);
1099 if (__builtin_expect
1100 (! _Jv_IsAssignableFrom (elt_class, obj_class), false))
1101 throw new java::lang::ArrayStoreException
1102 ((new java::lang::StringBuffer
1103 (JvNewStringUTF("Cannot store ")))->append
1104 (obj_class->getName())->append
1105 (JvNewStringUTF(" in array of type "))->append
1106 (elt_class->getName())->toString());
1110 #define INITIAL_IOFFSETS_LEN 4
1111 #define INITIAL_IFACES_LEN 4
1113 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
1115 // Generate tables for constant-time assignment testing and interface
1116 // method lookup. This implements the technique described by Per Bothner
1117 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
1118 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
1119 void
1120 _Jv_PrepareConstantTimeTables (jclass klass)
1122 if (klass->isPrimitive () || klass->isInterface ())
1123 return;
1125 // Short-circuit in case we've been called already.
1126 if ((klass->idt != NULL) || klass->depth != 0)
1127 return;
1129 // Calculate the class depth and ancestor table. The depth of a class
1130 // is how many "extends" it is removed from Object. Thus the depth of
1131 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
1132 // is 2. Depth is defined for all regular and array classes, but not
1133 // interfaces or primitive types.
1135 jclass klass0 = klass;
1136 jboolean has_interfaces = 0;
1137 while (klass0 != &java::lang::Object::class$)
1139 has_interfaces += klass0->interface_count;
1140 klass0 = klass0->superclass;
1141 klass->depth++;
1144 // We do class member testing in constant time by using a small table
1145 // of all the ancestor classes within each class. The first element is
1146 // a pointer to the current class, and the rest are pointers to the
1147 // classes ancestors, ordered from the current class down by decreasing
1148 // depth. We do not include java.lang.Object in the table of ancestors,
1149 // since it is redundant.
1151 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth * sizeof (jclass));
1152 klass0 = klass;
1153 for (int index = 0; index < klass->depth; index++)
1155 klass->ancestors[index] = klass0;
1156 klass0 = klass0->superclass;
1159 if (java::lang::reflect::Modifier::isAbstract (klass->accflags))
1160 return;
1162 // Optimization: If class implements no interfaces, use a common
1163 // predefined interface table.
1164 if (!has_interfaces)
1166 klass->idt = &null_idt;
1167 return;
1170 klass->idt =
1171 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1173 _Jv_ifaces ifaces;
1175 ifaces.count = 0;
1176 ifaces.len = INITIAL_IFACES_LEN;
1177 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
1179 int itable_size = _Jv_GetInterfaces (klass, &ifaces);
1181 if (ifaces.count > 0)
1183 klass->idt->cls.itable =
1184 (void **) _Jv_Malloc (itable_size * sizeof (void *));
1185 klass->idt->cls.itable_length = itable_size;
1187 jshort *itable_offsets =
1188 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
1190 _Jv_GenerateITable (klass, &ifaces, itable_offsets);
1192 jshort cls_iindex =
1193 _Jv_FindIIndex (ifaces.list, itable_offsets, ifaces.count);
1195 for (int i=0; i < ifaces.count; i++)
1197 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
1198 itable_offsets[i];
1201 klass->idt->cls.iindex = cls_iindex;
1203 _Jv_Free (ifaces.list);
1204 _Jv_Free (itable_offsets);
1206 else
1208 klass->idt->cls.iindex = SHRT_MAX;
1212 // Return index of item in list, or -1 if item is not present.
1213 inline jshort
1214 _Jv_IndexOf (void *item, void **list, jshort list_len)
1216 for (int i=0; i < list_len; i++)
1218 if (list[i] == item)
1219 return i;
1221 return -1;
1224 // Find all unique interfaces directly or indirectly implemented by klass.
1225 // Returns the size of the interface dispatch table (itable) for klass, which
1226 // is the number of unique interfaces plus the total number of methods that
1227 // those interfaces declare. May extend ifaces if required.
1228 jshort
1229 _Jv_GetInterfaces (jclass klass, _Jv_ifaces *ifaces)
1231 jshort result = 0;
1233 for (int i=0; i < klass->interface_count; i++)
1235 jclass iface = klass->interfaces[i];
1237 /* Make sure interface is linked. */
1238 _Jv_WaitForState(iface, JV_STATE_LINKED);
1240 if (_Jv_IndexOf (iface, (void **) ifaces->list, ifaces->count) == -1)
1242 if (ifaces->count + 1 >= ifaces->len)
1244 /* Resize ifaces list */
1245 ifaces->len = ifaces->len * 2;
1246 ifaces->list = (jclass *) _Jv_Realloc (ifaces->list,
1247 ifaces->len * sizeof(jclass));
1249 ifaces->list[ifaces->count] = iface;
1250 ifaces->count++;
1252 result += _Jv_GetInterfaces (klass->interfaces[i], ifaces);
1256 if (klass->isInterface())
1258 result += klass->method_count + 1;
1260 else
1262 if (klass->superclass)
1264 result += _Jv_GetInterfaces (klass->superclass, ifaces);
1267 return result;
1270 // Fill out itable in klass, resolving method declarations in each ifaces.
1271 // itable_offsets is filled out with the position of each iface in itable,
1272 // such that itable[itable_offsets[n]] == ifaces.list[n].
1273 void
1274 _Jv_GenerateITable (jclass klass, _Jv_ifaces *ifaces, jshort *itable_offsets)
1276 void **itable = klass->idt->cls.itable;
1277 jshort itable_pos = 0;
1279 for (int i=0; i < ifaces->count; i++)
1281 jclass iface = ifaces->list[i];
1282 itable_offsets[i] = itable_pos;
1283 itable_pos = _Jv_AppendPartialITable (klass, iface, itable, itable_pos);
1285 /* Create interface dispatch table for iface */
1286 if (iface->idt == NULL)
1288 iface->idt =
1289 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1291 // The first element of ioffsets is its length (itself included).
1292 jshort *ioffsets =
1293 (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN * sizeof (jshort));
1294 ioffsets[0] = INITIAL_IOFFSETS_LEN;
1295 for (int i=1; i < INITIAL_IOFFSETS_LEN; i++)
1296 ioffsets[i] = -1;
1298 iface->idt->iface.ioffsets = ioffsets;
1303 // Format method name for use in error messages.
1304 jstring
1305 _Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
1307 jstring r = JvNewStringUTF (klass->name->data);
1308 r = r->concat (JvNewStringUTF ("."));
1309 r = r->concat (JvNewStringUTF (name->data));
1310 return r;
1313 void
1314 _Jv_ThrowNoSuchMethodError ()
1316 throw new java::lang::NoSuchMethodError;
1319 // Each superinterface of a class (i.e. each interface that the class
1320 // directly or indirectly implements) has a corresponding "Partial
1321 // Interface Dispatch Table" whose size is (number of methods + 1) words.
1322 // The first word is a pointer to the interface (i.e. the java.lang.Class
1323 // instance for that interface). The remaining words are pointers to the
1324 // actual methods that implement the methods declared in the interface,
1325 // in order of declaration.
1327 // Append partial interface dispatch table for "iface" to "itable", at
1328 // position itable_pos.
1329 // Returns the offset at which the next partial ITable should be appended.
1330 jshort
1331 _Jv_AppendPartialITable (jclass klass, jclass iface, void **itable,
1332 jshort pos)
1334 using namespace java::lang::reflect;
1336 itable[pos++] = (void *) iface;
1337 _Jv_Method *meth;
1339 for (int j=0; j < iface->method_count; j++)
1341 meth = NULL;
1342 for (jclass cl = klass; cl; cl = cl->getSuperclass())
1344 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
1345 iface->methods[j].signature);
1347 if (meth)
1348 break;
1351 if (meth && (meth->name->data[0] == '<'))
1353 // leave a placeholder in the itable for hidden init methods.
1354 itable[pos] = NULL;
1356 else if (meth)
1358 if (Modifier::isStatic(meth->accflags))
1359 throw new java::lang::IncompatibleClassChangeError
1360 (_Jv_GetMethodString (klass, meth->name));
1361 if (Modifier::isAbstract(meth->accflags))
1362 throw new java::lang::AbstractMethodError
1363 (_Jv_GetMethodString (klass, meth->name));
1364 if (! Modifier::isPublic(meth->accflags))
1365 throw new java::lang::IllegalAccessError
1366 (_Jv_GetMethodString (klass, meth->name));
1368 itable[pos] = meth->ncode;
1370 else
1372 // The method doesn't exist in klass. Binary compatibility rules
1373 // permit this, so we delay the error until runtime using a pointer
1374 // to a method which throws an exception.
1375 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
1377 pos++;
1380 return pos;
1383 static _Jv_Mutex_t iindex_mutex;
1384 static bool iindex_mutex_initialized = false;
1386 // We need to find the correct offset in the Class Interface Dispatch
1387 // Table for a given interface. Once we have that, invoking an interface
1388 // method just requires combining the Method's index in the interface
1389 // (known at compile time) to get the correct method. Doing a type test
1390 // (cast or instanceof) is the same problem: Once we have a possible Partial
1391 // Interface Dispatch Table, we just compare the first element to see if it
1392 // matches the desired interface. So how can we find the correct offset?
1393 // Our solution is to keep a vector of candiate offsets in each interface
1394 // (idt->iface.ioffsets), and in each class we have an index
1395 // (idt->cls.iindex) used to select the correct offset from ioffsets.
1397 // Calculate and return iindex for a new class.
1398 // ifaces is a vector of num interfaces that the class implements.
1399 // offsets[j] is the offset in the interface dispatch table for the
1400 // interface corresponding to ifaces[j].
1401 // May extend the interface ioffsets if required.
1402 jshort
1403 _Jv_FindIIndex (jclass *ifaces, jshort *offsets, jshort num)
1405 int i;
1406 int j;
1408 // Acquire a global lock to prevent itable corruption in case of multiple
1409 // classes that implement an intersecting set of interfaces being linked
1410 // simultaneously. We can assume that the mutex will be initialized
1411 // single-threaded.
1412 if (! iindex_mutex_initialized)
1414 _Jv_MutexInit (&iindex_mutex);
1415 iindex_mutex_initialized = true;
1418 _Jv_MutexLock (&iindex_mutex);
1420 for (i=1;; i++) /* each potential position in ioffsets */
1422 for (j=0;; j++) /* each iface */
1424 if (j >= num)
1425 goto found;
1426 if (i >= ifaces[j]->idt->iface.ioffsets[0])
1427 continue;
1428 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
1429 /* We can potentially share this position with another class. */
1430 if (ioffset >= 0 && ioffset != offsets[j])
1431 break; /* Nope. Try next i. */
1434 found:
1435 for (j = 0; j < num; j++)
1437 int len = ifaces[j]->idt->iface.ioffsets[0];
1438 if (i >= len)
1440 /* Resize ioffsets. */
1441 int newlen = 2 * len;
1442 if (i >= newlen)
1443 newlen = i + 3;
1444 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
1445 jshort *new_ioffsets = (jshort *) _Jv_Realloc (old_ioffsets,
1446 newlen * sizeof(jshort));
1447 new_ioffsets[0] = newlen;
1449 while (len < newlen)
1450 new_ioffsets[len++] = -1;
1452 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
1454 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
1457 _Jv_MutexUnlock (&iindex_mutex);
1459 return i;
1462 // Only used by serialization
1463 java::lang::reflect::Field *
1464 java::lang::Class::getPrivateField (jstring name)
1466 int hash = name->hashCode ();
1468 java::lang::reflect::Field* rfield;
1469 for (int i = 0; i < field_count; i++)
1471 _Jv_Field *field = &fields[i];
1472 if (! _Jv_equal (field->name, name, hash))
1473 continue;
1474 rfield = new java::lang::reflect::Field ();
1475 rfield->offset = (char*) field - (char*) fields;
1476 rfield->declaringClass = this;
1477 rfield->name = name;
1478 return rfield;
1480 jclass superclass = getSuperclass();
1481 if (superclass == NULL)
1482 return NULL;
1483 rfield = superclass->getPrivateField(name);
1484 for (int i = 0; i < interface_count && rfield == NULL; ++i)
1485 rfield = interfaces[i]->getPrivateField (name);
1486 return rfield;
1489 // Only used by serialization
1490 java::lang::reflect::Method *
1491 java::lang::Class::getPrivateMethod (jstring name, JArray<jclass> *param_types)
1493 jstring partial_sig = getSignature (param_types, false);
1494 jint p_len = partial_sig->length();
1495 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
1496 for (Class *klass = this; klass; klass = klass->getSuperclass())
1498 int i = klass->isPrimitive () ? 0 : klass->method_count;
1499 while (--i >= 0)
1501 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
1502 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
1504 // Found it.
1505 using namespace java::lang::reflect;
1507 Method *rmethod = new Method ();
1508 rmethod->offset = ((char *) (&klass->methods[i])
1509 - (char *) klass->methods);
1510 rmethod->declaringClass = klass;
1511 return rmethod;
1515 throw new java::lang::NoSuchMethodException (name);
1518 // Private accessor method for Java code to retrieve the protection domain.
1519 java::security::ProtectionDomain *
1520 java::lang::Class::getProtectionDomain0 ()
1522 return protectionDomain;
1525 // Functions for indirect dispatch (symbolic virtual method binding) support.
1527 // Resolve entries in the virtual method offset symbol table
1528 // (klass->otable_syms). The vtable offset (in bytes) for each resolved method
1529 // is placed at the corresponding position in the virtual method offset table
1530 // (klass->otable). A single otable and otable_syms pair may be shared by many
1531 // classes.
1532 void
1533 _Jv_LinkOffsetTable(jclass klass)
1535 //// FIXME: Need to lock the otable ////
1537 if (klass->otable == NULL
1538 || klass->otable->state != 0)
1539 return;
1541 klass->otable->state = 1;
1543 int index = 0;
1544 _Jv_MethodSymbol sym = klass->otable_syms[0];
1546 while (sym.name != NULL)
1548 jclass target_class = _Jv_FindClass (sym.class_name, NULL);
1549 _Jv_Method *meth = NULL;
1551 if (target_class != NULL)
1552 if (target_class->isInterface())
1554 // FIXME: This does not yet fully conform to binary compatibility
1555 // rules. It will break if a declaration is moved into a
1556 // superinterface.
1557 for (int i=0; i < target_class->method_count; i++)
1559 meth = &target_class->methods[i];
1560 if (_Jv_equalUtf8Consts (sym.name, meth->name)
1561 && _Jv_equalUtf8Consts (sym.signature, meth->signature))
1563 klass->otable->offsets[index] = i + 1;
1564 break;
1568 else
1570 // If the target class does not have a vtable_method_count yet,
1571 // then we can't tell the offsets for its methods, so we must lay
1572 // it out now.
1573 if (target_class->vtable_method_count == -1)
1575 JvSynchronize sync (target_class);
1576 _Jv_LayoutVTableMethods (target_class);
1579 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1580 sym.signature);
1582 if (meth != NULL)
1584 klass->otable->offsets[index] =
1585 _Jv_VTable::idx_to_offset (meth->index);
1589 if (meth == NULL)
1590 // FIXME: This should be special index for ThrowNoSuchMethod().
1591 klass->otable->offsets[index] = -1;
1593 sym = klass->otable_syms[++index];
1597 // Returns true if METH should get an entry in a VTable.
1598 static jboolean
1599 isVirtualMethod (_Jv_Method *meth)
1601 using namespace java::lang::reflect;
1602 return (((meth->accflags & (Modifier::STATIC | Modifier::PRIVATE)) == 0)
1603 && meth->name->data[0] != '<');
1606 // This is put in empty vtable slots.
1607 static void
1608 _Jv_abstractMethodError (void)
1610 throw new java::lang::AbstractMethodError();
1613 // Prepare virtual method declarations in KLASS, and any superclasses as
1614 // required, by determining their vtable index, setting method->index, and
1615 // finally setting the class's vtable_method_count. Must be called with the
1616 // lock for KLASS held.
1617 void
1618 _Jv_LayoutVTableMethods (jclass klass)
1620 if (klass->vtable != NULL || klass->isInterface()
1621 || klass->vtable_method_count != -1)
1622 return;
1624 jclass superclass = klass->superclass;
1626 if (superclass != NULL && superclass->vtable_method_count == -1)
1628 JvSynchronize sync (superclass);
1629 _Jv_LayoutVTableMethods (superclass);
1632 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1634 for (int i = 0; i < klass->method_count; ++i)
1636 _Jv_Method *meth = &klass->methods[i];
1637 _Jv_Method *super_meth = NULL;
1639 if (! isVirtualMethod (meth))
1640 continue;
1642 if (superclass != NULL)
1644 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1645 meth->signature);
1648 if (super_meth)
1649 meth->index = super_meth->index;
1650 else if (! (meth->accflags & java::lang::reflect::Modifier::FINAL)
1651 && ! (klass->accflags & java::lang::reflect::Modifier::FINAL))
1652 meth->index = index++;
1655 klass->vtable_method_count = index;
1658 // Set entries in VTABLE for virtual methods declared in KLASS. If
1659 // KLASS has an immediate abstract parent, recursively do its methods
1660 // first. FLAGS is used to determine which slots we've actually set.
1661 void
1662 _Jv_SetVTableEntries (jclass klass, _Jv_VTable *vtable, jboolean *flags)
1664 using namespace java::lang::reflect;
1666 jclass superclass = klass->getSuperclass();
1668 if (superclass != NULL && (superclass->getModifiers() & Modifier::ABSTRACT))
1669 _Jv_SetVTableEntries (superclass, vtable, flags);
1671 for (int i = klass->method_count - 1; i >= 0; i--)
1673 _Jv_Method *meth = &klass->methods[i];
1674 if (meth->index == (_Jv_ushort) -1)
1675 continue;
1676 if ((meth->accflags & Modifier::ABSTRACT))
1678 vtable->set_method(meth->index, (void *) &_Jv_abstractMethodError);
1679 flags[meth->index] = false;
1681 else
1683 vtable->set_method(meth->index, meth->ncode);
1684 flags[meth->index] = true;
1689 // Allocate and lay out the virtual method table for KLASS. This will also
1690 // cause vtables to be generated for any non-abstract superclasses, and
1691 // virtual method layout to occur for any abstract superclasses. Must be
1692 // called with monitor lock for KLASS held.
1693 void
1694 _Jv_MakeVTable (jclass klass)
1696 using namespace java::lang::reflect;
1698 if (klass->vtable != NULL || klass->isInterface()
1699 || (klass->accflags & Modifier::ABSTRACT))
1700 return;
1702 // out before we can create a vtable.
1703 if (klass->vtable_method_count == -1)
1704 _Jv_LayoutVTableMethods (klass);
1706 // Allocate the new vtable.
1707 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1708 klass->vtable = vtable;
1710 jboolean flags[klass->vtable_method_count];
1711 for (int i = 0; i < klass->vtable_method_count; ++i)
1712 flags[i] = false;
1714 // Copy the vtable of the closest non-abstract superclass.
1715 jclass superclass = klass->superclass;
1716 if (superclass != NULL)
1718 while ((superclass->accflags & Modifier::ABSTRACT) != 0)
1719 superclass = superclass->superclass;
1721 if (superclass->vtable == NULL)
1723 JvSynchronize sync (superclass);
1724 _Jv_MakeVTable (superclass);
1727 for (int i = 0; i < superclass->vtable_method_count; ++i)
1729 vtable->set_method (i, superclass->vtable->get_method (i));
1730 flags[i] = true;
1734 // Set the class pointer and GC descriptor.
1735 vtable->clas = klass;
1736 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1738 // For each virtual declared in klass and any immediate abstract
1739 // superclasses, set new vtable entry or override an old one.
1740 _Jv_SetVTableEntries (klass, vtable, flags);
1742 // It is an error to have an abstract method in a concrete class.
1743 if (! (klass->accflags & Modifier::ABSTRACT))
1745 for (int i = 0; i < klass->vtable_method_count; ++i)
1746 if (! flags[i])
1747 // FIXME: messsage.
1748 throw new java::lang::AbstractMethodError ();