source: trunk/src/gcc/libjava/java/lang/natClass.cc@ 603

Last change on this file since 603 was 2, checked in by bird, 23 years ago

Initial revision

  • Property cvs2svn:cvs-rev set to 1.1
  • Property svn:eol-style set to native
  • Property svn:executable set to *
File size: 45.7 KB
Line 
1// natClass.cc - Implementation of java.lang.Class native methods.
2
3/* Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation
4
5 This file is part of libgcj.
6
7This software is copyrighted work licensed under the terms of the
8Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9details. */
10
11#include <config.h>
12
13#include <limits.h>
14#include <string.h>
15
16#pragma implementation "Class.h"
17
18#include <gcj/cni.h>
19#include <jvm.h>
20#include <java-threads.h>
21
22#include <java/lang/Class.h>
23#include <java/lang/ClassLoader.h>
24#include <java/lang/String.h>
25#include <java/lang/reflect/Modifier.h>
26#include <java/lang/reflect/Member.h>
27#include <java/lang/reflect/Method.h>
28#include <java/lang/reflect/Field.h>
29#include <java/lang/reflect/Constructor.h>
30#include <java/lang/AbstractMethodError.h>
31#include <java/lang/ArrayStoreException.h>
32#include <java/lang/ClassCastException.h>
33#include <java/lang/ClassNotFoundException.h>
34#include <java/lang/ExceptionInInitializerError.h>
35#include <java/lang/IllegalAccessException.h>
36#include <java/lang/IllegalAccessError.h>
37#include <java/lang/IllegalArgumentException.h>
38#include <java/lang/IncompatibleClassChangeError.h>
39#include <java/lang/InstantiationException.h>
40#include <java/lang/NoClassDefFoundError.h>
41#include <java/lang/NoSuchFieldException.h>
42#include <java/lang/NoSuchMethodError.h>
43#include <java/lang/NoSuchMethodException.h>
44#include <java/lang/Thread.h>
45#include <java/lang/NullPointerException.h>
46#include <java/lang/RuntimePermission.h>
47#include <java/lang/System.h>
48#include <java/lang/SecurityManager.h>
49#include <java/lang/StringBuffer.h>
50#include <gcj/method.h>
51
52#include <java-cpool.h>
53
54
55
56
57// FIXME: remove these.
58#define CloneableClass java::lang::Cloneable::class$
59#define ObjectClass java::lang::Object::class$
60#define ErrorClass java::lang::Error::class$
61#define ClassClass java::lang::Class::class$
62#define MethodClass java::lang::reflect::Method::class$
63#define FieldClass java::lang::reflect::Field::class$
64#define ConstructorClass java::lang::reflect::Constructor::class$
65
66
67
68
69using namespace gcj;
70
71jclass
72java::lang::Class::forName (jstring className, jboolean initialize,
73 java::lang::ClassLoader *loader)
74{
75 if (! className)
76 throw new java::lang::NullPointerException;
77
78 jsize length = _Jv_GetStringUTFLength (className);
79 char buffer[length];
80 _Jv_GetStringUTFRegion (className, 0, length, buffer);
81
82 _Jv_Utf8Const *name = _Jv_makeUtf8Const (buffer, length);
83
84 if (! _Jv_VerifyClassName (name))
85 throw new java::lang::ClassNotFoundException (className);
86
87 // FIXME: should use bootstrap class loader if loader is null.
88 jclass klass = (buffer[0] == '['
89 ? _Jv_FindClassFromSignature (name->data, loader)
90 : _Jv_FindClass (name, loader));
91
92 if (klass == NULL)
93 throw new java::lang::ClassNotFoundException (className);
94
95 if (initialize)
96 _Jv_InitClass (klass);
97
98 return klass;
99}
100
101jclass
102java::lang::Class::forName (jstring className)
103{
104 // FIXME: should use class loader from calling method.
105 return forName (className, true, NULL);
106}
107
108java::lang::ClassLoader *
109java::lang::Class::getClassLoader (void)
110{
111#if 0
112 // FIXME: the checks we need to do are more complex. See the spec.
113 // Currently we can't implement them.
114 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
115 if (s != NULL)
116 s->checkPermission (new RuntimePermission (JvNewStringLatin1 ("getClassLoader")));
117#endif
118
119 // The spec requires us to return `null' for primitive classes. In
120 // other cases we have the option of returning `null' for classes
121 // loaded with the bootstrap loader. All gcj-compiled classes which
122 // are linked into the application used to return `null' here, but
123 // that confuses some poorly-written applications. It is a useful
124 // and apparently harmless compatibility hack to simply never return
125 // `null' instead.
126 if (isPrimitive ())
127 return NULL;
128 return loader ? loader : ClassLoader::getSystemClassLoader ();
129}
130
131java::lang::reflect::Constructor *
132java::lang::Class::getConstructor (JArray<jclass> *param_types)
133{
134 jstring partial_sig = getSignature (param_types, true);
135 jint hash = partial_sig->hashCode ();
136
137 int i = isPrimitive () ? 0 : method_count;
138 while (--i >= 0)
139 {
140 // FIXME: access checks.
141 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
142 && _Jv_equal (methods[i].signature, partial_sig, hash))
143 {
144 // Found it. For getConstructor, the constructor must be
145 // public.
146 using namespace java::lang::reflect;
147 if (! Modifier::isPublic(methods[i].accflags))
148 break;
149 Constructor *cons = new Constructor ();
150 cons->offset = (char *) (&methods[i]) - (char *) methods;
151 cons->declaringClass = this;
152 return cons;
153 }
154 }
155 throw new java::lang::NoSuchMethodException;
156}
157
158JArray<java::lang::reflect::Constructor *> *
159java::lang::Class::_getConstructors (jboolean declared)
160{
161 // FIXME: this method needs access checks.
162
163 int numConstructors = 0;
164 int max = isPrimitive () ? 0 : method_count;
165 int i;
166 for (i = max; --i >= 0; )
167 {
168 _Jv_Method *method = &methods[i];
169 if (method->name == NULL
170 || ! _Jv_equalUtf8Consts (method->name, init_name))
171 continue;
172 if (! declared
173 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
174 continue;
175 numConstructors++;
176 }
177 JArray<java::lang::reflect::Constructor *> *result
178 = (JArray<java::lang::reflect::Constructor *> *)
179 JvNewObjectArray (numConstructors, &ConstructorClass, NULL);
180 java::lang::reflect::Constructor** cptr = elements (result);
181 for (i = 0; i < max; i++)
182 {
183 _Jv_Method *method = &methods[i];
184 if (method->name == NULL
185 || ! _Jv_equalUtf8Consts (method->name, init_name))
186 continue;
187 if (! declared
188 && ! java::lang::reflect::Modifier::isPublic(method->accflags))
189 continue;
190 java::lang::reflect::Constructor *cons
191 = new java::lang::reflect::Constructor ();
192 cons->offset = (char *) method - (char *) methods;
193 cons->declaringClass = this;
194 *cptr++ = cons;
195 }
196 return result;
197}
198
199java::lang::reflect::Constructor *
200java::lang::Class::getDeclaredConstructor (JArray<jclass> *param_types)
201{
202 jstring partial_sig = getSignature (param_types, true);
203 jint hash = partial_sig->hashCode ();
204
205 int i = isPrimitive () ? 0 : method_count;
206 while (--i >= 0)
207 {
208 // FIXME: access checks.
209 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
210 && _Jv_equal (methods[i].signature, partial_sig, hash))
211 {
212 // Found it.
213 using namespace java::lang::reflect;
214 Constructor *cons = new Constructor ();
215 cons->offset = (char *) (&methods[i]) - (char *) methods;
216 cons->declaringClass = this;
217 return cons;
218 }
219 }
220 throw new java::lang::NoSuchMethodException;
221}
222
223java::lang::reflect::Field *
224java::lang::Class::getField (jstring name, jint hash)
225{
226 java::lang::reflect::Field* rfield;
227 for (int i = 0; i < field_count; i++)
228 {
229 _Jv_Field *field = &fields[i];
230 if (! _Jv_equal (field->name, name, hash))
231 continue;
232 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
233 continue;
234 rfield = new java::lang::reflect::Field ();
235 rfield->offset = (char*) field - (char*) fields;
236 rfield->declaringClass = this;
237 rfield->name = name;
238 return rfield;
239 }
240 jclass superclass = getSuperclass();
241 if (superclass == NULL)
242 return NULL;
243 rfield = superclass->getField(name, hash);
244 for (int i = 0; i < interface_count && rfield == NULL; ++i)
245 rfield = interfaces[i]->getField (name, hash);
246 return rfield;
247}
248
249java::lang::reflect::Field *
250java::lang::Class::getDeclaredField (jstring name)
251{
252 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
253 if (s != NULL)
254 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
255 int hash = name->hashCode();
256 for (int i = 0; i < field_count; i++)
257 {
258 _Jv_Field *field = &fields[i];
259 if (! _Jv_equal (field->name, name, hash))
260 continue;
261 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
262 rfield->offset = (char*) field - (char*) fields;
263 rfield->declaringClass = this;
264 rfield->name = name;
265 return rfield;
266 }
267 throw new java::lang::NoSuchFieldException (name);
268}
269
270JArray<java::lang::reflect::Field *> *
271java::lang::Class::getDeclaredFields (void)
272{
273 java::lang::SecurityManager *s = java::lang::System::getSecurityManager();
274 if (s != NULL)
275 s->checkMemberAccess (this, java::lang::reflect::Member::DECLARED);
276 JArray<java::lang::reflect::Field *> *result
277 = (JArray<java::lang::reflect::Field *> *)
278 JvNewObjectArray (field_count, &FieldClass, NULL);
279 java::lang::reflect::Field** fptr = elements (result);
280 for (int i = 0; i < field_count; i++)
281 {
282 _Jv_Field *field = &fields[i];
283 java::lang::reflect::Field* rfield = new java::lang::reflect::Field ();
284 rfield->offset = (char*) field - (char*) fields;
285 rfield->declaringClass = this;
286 *fptr++ = rfield;
287 }
288 return result;
289}
290
291void
292java::lang::Class::getSignature (java::lang::StringBuffer *buffer)
293{
294 if (isPrimitive())
295 buffer->append((jchar) method_count);
296 else
297 {
298 jstring name = getName();
299 if (name->charAt(0) != '[')
300 buffer->append((jchar) 'L');
301 buffer->append(name);
302 if (name->charAt(0) != '[')
303 buffer->append((jchar) ';');
304 }
305}
306
307// This doesn't have to be native. It is an implementation detail
308// only called from the C++ code, though, so maybe this is clearer.
309jstring
310java::lang::Class::getSignature (JArray<jclass> *param_types,
311 jboolean is_constructor)
312{
313 java::lang::StringBuffer *buf = new java::lang::StringBuffer ();
314 buf->append((jchar) '(');
315 // A NULL param_types means "no parameters".
316 if (param_types != NULL)
317 {
318 jclass *v = elements (param_types);
319 for (int i = 0; i < param_types->length; ++i)
320 v[i]->getSignature(buf);
321 }
322 buf->append((jchar) ')');
323 if (is_constructor)
324 buf->append((jchar) 'V');
325 return buf->toString();
326}
327
328java::lang::reflect::Method *
329java::lang::Class::getDeclaredMethod (jstring name,
330 JArray<jclass> *param_types)
331{
332 jstring partial_sig = getSignature (param_types, false);
333 jint p_len = partial_sig->length();
334 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
335 int i = isPrimitive () ? 0 : method_count;
336 while (--i >= 0)
337 {
338 // FIXME: access checks.
339 if (_Jv_equalUtf8Consts (methods[i].name, utf_name)
340 && _Jv_equaln (methods[i].signature, partial_sig, p_len))
341 {
342 // Found it.
343 using namespace java::lang::reflect;
344 Method *rmethod = new Method ();
345 rmethod->offset = (char*) (&methods[i]) - (char*) methods;
346 rmethod->declaringClass = this;
347 return rmethod;
348 }
349 }
350 throw new java::lang::NoSuchMethodException;
351}
352
353JArray<java::lang::reflect::Method *> *
354java::lang::Class::getDeclaredMethods (void)
355{
356 int numMethods = 0;
357 int max = isPrimitive () ? 0 : method_count;
358 int i;
359 for (i = max; --i >= 0; )
360 {
361 _Jv_Method *method = &methods[i];
362 if (method->name == NULL
363 || _Jv_equalUtf8Consts (method->name, clinit_name)
364 || _Jv_equalUtf8Consts (method->name, init_name)
365 || _Jv_equalUtf8Consts (method->name, finit_name))
366 continue;
367 numMethods++;
368 }
369 JArray<java::lang::reflect::Method *> *result
370 = (JArray<java::lang::reflect::Method *> *)
371 JvNewObjectArray (numMethods, &MethodClass, NULL);
372 java::lang::reflect::Method** mptr = elements (result);
373 for (i = 0; i < max; i++)
374 {
375 _Jv_Method *method = &methods[i];
376 if (method->name == NULL
377 || _Jv_equalUtf8Consts (method->name, clinit_name)
378 || _Jv_equalUtf8Consts (method->name, init_name)
379 || _Jv_equalUtf8Consts (method->name, finit_name))
380 continue;
381 java::lang::reflect::Method* rmethod
382 = new java::lang::reflect::Method ();
383 rmethod->offset = (char*) method - (char*) methods;
384 rmethod->declaringClass = this;
385 *mptr++ = rmethod;
386 }
387 return result;
388}
389
390jstring
391java::lang::Class::getName (void)
392{
393 char buffer[name->length + 1];
394 memcpy (buffer, name->data, name->length);
395 buffer[name->length] = '\0';
396 return _Jv_NewStringUTF (buffer);
397}
398
399JArray<jclass> *
400java::lang::Class::getClasses (void)
401{
402 // FIXME: security checking.
403
404 // Until we have inner classes, it always makes sense to return an
405 // empty array.
406 JArray<jclass> *result
407 = (JArray<jclass> *) JvNewObjectArray (0, &ClassClass, NULL);
408 return result;
409}
410
411JArray<jclass> *
412java::lang::Class::getDeclaredClasses (void)
413{
414 checkMemberAccess (java::lang::reflect::Member::DECLARED);
415 // Until we have inner classes, it always makes sense to return an
416 // empty array.
417 JArray<jclass> *result
418 = (JArray<jclass> *) JvNewObjectArray (0, &ClassClass, NULL);
419 return result;
420}
421
422jclass
423java::lang::Class::getDeclaringClass (void)
424{
425 // Until we have inner classes, it makes sense to always return
426 // NULL.
427 return NULL;
428}
429
430jint
431java::lang::Class::_getFields (JArray<java::lang::reflect::Field *> *result,
432 jint offset)
433{
434 int count = 0;
435 for (int i = 0; i < field_count; i++)
436 {
437 _Jv_Field *field = &fields[i];
438 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
439 continue;
440 ++count;
441
442 if (result != NULL)
443 {
444 java::lang::reflect::Field *rfield
445 = new java::lang::reflect::Field ();
446 rfield->offset = (char *) field - (char *) fields;
447 rfield->declaringClass = this;
448 rfield->name = _Jv_NewStringUtf8Const (field->name);
449 (elements (result))[offset++] = rfield;
450 }
451 }
452 jclass superclass = getSuperclass();
453 if (superclass != NULL)
454 {
455 int s_count = superclass->_getFields (result, offset);
456 count += s_count;
457 offset += s_count;
458 }
459 for (int i = 0; i < interface_count; ++i)
460 {
461 int f_count = interfaces[i]->_getFields (result, offset);
462 count += f_count;
463 offset += f_count;
464 }
465 return count;
466}
467
468JArray<java::lang::reflect::Field *> *
469java::lang::Class::getFields (void)
470{
471 // FIXME: security checking.
472
473 using namespace java::lang::reflect;
474
475 int count = _getFields (NULL, 0);
476
477 JArray<java::lang::reflect::Field *> *result
478 = ((JArray<java::lang::reflect::Field *> *)
479 JvNewObjectArray (count, &FieldClass, NULL));
480
481 _getFields (result, 0);
482
483 return result;
484}
485
486JArray<jclass> *
487java::lang::Class::getInterfaces (void)
488{
489 jobjectArray r = JvNewObjectArray (interface_count, getClass (), NULL);
490 jobject *data = elements (r);
491 for (int i = 0; i < interface_count; ++i)
492 data[i] = interfaces[i];
493 return reinterpret_cast<JArray<jclass> *> (r);
494}
495
496java::lang::reflect::Method *
497java::lang::Class::getMethod (jstring name, JArray<jclass> *param_types)
498{
499 jstring partial_sig = getSignature (param_types, false);
500 jint p_len = partial_sig->length();
501 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
502 for (Class *klass = this; klass; klass = klass->getSuperclass())
503 {
504 int i = klass->isPrimitive () ? 0 : klass->method_count;
505 while (--i >= 0)
506 {
507 // FIXME: access checks.
508 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
509 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
510 {
511 // Found it.
512 using namespace java::lang::reflect;
513
514 // Method must be public.
515 if (! Modifier::isPublic (klass->methods[i].accflags))
516 break;
517
518 Method *rmethod = new Method ();
519 rmethod->offset = ((char *) (&klass->methods[i])
520 - (char *) klass->methods);
521 rmethod->declaringClass = klass;
522 return rmethod;
523 }
524 }
525 }
526 throw new java::lang::NoSuchMethodException;
527}
528
529// This is a very slow implementation, since it re-scans all the
530// methods we've already listed to make sure we haven't duplicated a
531// method. It also over-estimates the required size, so we have to
532// shrink the result array later.
533jint
534java::lang::Class::_getMethods (JArray<java::lang::reflect::Method *> *result,
535 jint offset)
536{
537 jint count = 0;
538
539 // First examine all local methods
540 for (int i = isPrimitive () ? 0 : method_count; --i >= 0; )
541 {
542 _Jv_Method *method = &methods[i];
543 if (method->name == NULL
544 || _Jv_equalUtf8Consts (method->name, clinit_name)
545 || _Jv_equalUtf8Consts (method->name, init_name)
546 || _Jv_equalUtf8Consts (method->name, finit_name))
547 continue;
548 // Only want public methods.
549 if (! java::lang::reflect::Modifier::isPublic (method->accflags))
550 continue;
551
552 // This is where we over-count the slots required if we aren't
553 // filling the result for real.
554 if (result != NULL)
555 {
556 jboolean add = true;
557 java::lang::reflect::Method **mp = elements (result);
558 // If we already have a method with this name and signature,
559 // then ignore this one. This can happen with virtual
560 // methods.
561 for (int j = 0; j < offset; ++j)
562 {
563 _Jv_Method *meth_2 = _Jv_FromReflectedMethod (mp[j]);
564 if (_Jv_equalUtf8Consts (method->name, meth_2->name)
565 && _Jv_equalUtf8Consts (method->signature,
566 meth_2->signature))
567 {
568 add = false;
569 break;
570 }
571 }
572 if (! add)
573 continue;
574 }
575
576 if (result != NULL)
577 {
578 using namespace java::lang::reflect;
579 Method *rmethod = new Method ();
580 rmethod->offset = (char *) method - (char *) methods;
581 rmethod->declaringClass = this;
582 Method **mp = elements (result);
583 mp[offset + count] = rmethod;
584 }
585 ++count;
586 }
587 offset += count;
588
589 // Now examine superclasses.
590 if (getSuperclass () != NULL)
591 {
592 jint s_count = getSuperclass()->_getMethods (result, offset);
593 offset += s_count;
594 count += s_count;
595 }
596
597 // Finally, examine interfaces.
598 for (int i = 0; i < interface_count; ++i)
599 {
600 int f_count = interfaces[i]->_getMethods (result, offset);
601 count += f_count;
602 offset += f_count;
603 }
604
605 return count;
606}
607
608JArray<java::lang::reflect::Method *> *
609java::lang::Class::getMethods (void)
610{
611 using namespace java::lang::reflect;
612
613 // FIXME: security checks.
614
615 // This will overestimate the size we need.
616 jint count = _getMethods (NULL, 0);
617
618 JArray<Method *> *result
619 = ((JArray<Method *> *) JvNewObjectArray (count, &MethodClass, NULL));
620
621 // When filling the array for real, we get the actual count. Then
622 // we resize the array.
623 jint real_count = _getMethods (result, 0);
624
625 if (real_count != count)
626 {
627 JArray<Method *> *r2
628 = ((JArray<Method *> *) JvNewObjectArray (real_count, &MethodClass,
629 NULL));
630
631 Method **destp = elements (r2);
632 Method **srcp = elements (result);
633
634 for (int i = 0; i < real_count; ++i)
635 *destp++ = *srcp++;
636
637 result = r2;
638 }
639
640 return result;
641}
642
643jboolean
644java::lang::Class::isAssignableFrom (jclass klass)
645{
646 // Arguments may not have been initialized, given ".class" syntax.
647 _Jv_InitClass (this);
648 _Jv_InitClass (klass);
649 return _Jv_IsAssignableFrom (this, klass);
650}
651
652jboolean
653java::lang::Class::isInstance (jobject obj)
654{
655 if (! obj)
656 return false;
657 _Jv_InitClass (this);
658 return _Jv_IsAssignableFrom (this, JV_CLASS (obj));
659}
660
661jobject
662java::lang::Class::newInstance (void)
663{
664 // FIXME: do accessibility checks here. There currently doesn't
665 // seem to be any way to do these.
666 // FIXME: we special-case one check here just to pass a Plum Hall
667 // test. Once access checking is implemented, remove this.
668 if (this == &ClassClass)
669 throw new java::lang::IllegalAccessException;
670
671 if (isPrimitive ()
672 || isInterface ()
673 || isArray ()
674 || java::lang::reflect::Modifier::isAbstract(accflags))
675 throw new java::lang::InstantiationException;
676
677 _Jv_InitClass (this);
678
679 _Jv_Method *meth = _Jv_GetMethodLocal (this, init_name, void_signature);
680 if (! meth)
681 throw new java::lang::NoSuchMethodException;
682
683 jobject r = JvAllocObject (this);
684 ((void (*) (jobject)) meth->ncode) (r);
685 return r;
686}
687
688void
689java::lang::Class::finalize (void)
690{
691#ifdef INTERPRETER
692 JvAssert (_Jv_IsInterpretedClass (this));
693 _Jv_UnregisterClass (this);
694#endif
695}
696
697// This implements the initialization process for a class. From Spec
698// section 12.4.2.
699void
700java::lang::Class::initializeClass (void)
701{
702 // short-circuit to avoid needless locking.
703 if (state == JV_STATE_DONE)
704 return;
705
706 // Step 1.
707 _Jv_MonitorEnter (this);
708
709 if (state < JV_STATE_LINKED)
710 {
711#ifdef INTERPRETER
712 if (_Jv_IsInterpretedClass (this))
713 {
714 // this can throw exceptions, so exit the monitor as a precaution.
715 _Jv_MonitorExit (this);
716 java::lang::ClassLoader::resolveClass0 (this);
717 _Jv_MonitorEnter (this);
718 }
719 else
720#endif
721 {
722 _Jv_PrepareCompiledClass (this);
723 }
724 }
725
726 if (state <= JV_STATE_LINKED)
727 _Jv_PrepareConstantTimeTables (this);
728
729 // Step 2.
730 java::lang::Thread *self = java::lang::Thread::currentThread();
731 // FIXME: `self' can be null at startup. Hence this nasty trick.
732 self = (java::lang::Thread *) ((long) self | 1);
733 while (state == JV_STATE_IN_PROGRESS && thread && thread != self)
734 wait ();
735
736 // Steps 3 & 4.
737 if (state == JV_STATE_DONE
738 || state == JV_STATE_IN_PROGRESS
739 || thread == self)
740 {
741 _Jv_MonitorExit (this);
742 return;
743 }
744
745 // Step 5.
746 if (state == JV_STATE_ERROR)
747 {
748 _Jv_MonitorExit (this);
749 throw new java::lang::NoClassDefFoundError;
750 }
751
752 // Step 6.
753 thread = self;
754 state = JV_STATE_IN_PROGRESS;
755 _Jv_MonitorExit (this);
756
757 // Step 7.
758 if (! isInterface () && superclass)
759 {
760 try
761 {
762 _Jv_InitClass (superclass);
763 }
764 catch (java::lang::Throwable *except)
765 {
766 // Caught an exception.
767 _Jv_MonitorEnter (this);
768 state = JV_STATE_ERROR;
769 notifyAll ();
770 _Jv_MonitorExit (this);
771 throw except;
772 }
773 }
774
775 // Steps 8, 9, 10, 11.
776 try
777 {
778 _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name,
779 void_signature);
780 if (meth)
781 ((void (*) (void)) meth->ncode) ();
782 }
783 catch (java::lang::Throwable *except)
784 {
785 if (! ErrorClass.isInstance(except))
786 {
787 try
788 {
789 except = new ExceptionInInitializerError (except);
790 }
791 catch (java::lang::Throwable *t)
792 {
793 except = t;
794 }
795 }
796 _Jv_MonitorEnter (this);
797 state = JV_STATE_ERROR;
798 notifyAll ();
799 _Jv_MonitorExit (this);
800 throw except;
801 }
802
803 _Jv_MonitorEnter (this);
804 state = JV_STATE_DONE;
805 notifyAll ();
806 _Jv_MonitorExit (this);
807}
808
809
810
811
812//
813// Some class-related convenience functions.
814//
815
816// Find a method declared in the class. If it is not declared locally
817// (or if it is inherited), return NULL.
818_Jv_Method *
819_Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
820 _Jv_Utf8Const *signature)
821{
822 for (int i = 0; i < klass->method_count; ++i)
823 {
824 if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
825 && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
826 return &klass->methods[i];
827 }
828 return NULL;
829}
830
831_Jv_Method *
832_Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
833 _Jv_Utf8Const *signature)
834{
835 for (; klass; klass = klass->getSuperclass())
836 {
837 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
838
839 if (meth)
840 return meth;
841 }
842
843 return NULL;
844}
845
846// NOTE: MCACHE_SIZE should be a power of 2 minus one.
847#define MCACHE_SIZE 1023
848
849struct _Jv_mcache
850{
851 jclass klass;
852 _Jv_Method *method;
853};
854
855static _Jv_mcache method_cache[MCACHE_SIZE + 1];
856
857static void *
858_Jv_FindMethodInCache (jclass klass,
859 _Jv_Utf8Const *name,
860 _Jv_Utf8Const *signature)
861{
862 int index = name->hash & MCACHE_SIZE;
863 _Jv_mcache *mc = method_cache + index;
864 _Jv_Method *m = mc->method;
865
866 if (mc->klass == klass
867 && m != NULL // thread safe check
868 && _Jv_equalUtf8Consts (m->name, name)
869 && _Jv_equalUtf8Consts (m->signature, signature))
870 return mc->method->ncode;
871 return NULL;
872}
873
874static void
875_Jv_AddMethodToCache (jclass klass,
876 _Jv_Method *method)
877{
878 _Jv_MonitorEnter (&ClassClass);
879
880 int index = method->name->hash & MCACHE_SIZE;
881
882 method_cache[index].method = method;
883 method_cache[index].klass = klass;
884
885 _Jv_MonitorExit (&ClassClass);
886}
887
888void *
889_Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
890 _Jv_Utf8Const *signature)
891{
892 using namespace java::lang::reflect;
893
894 void *ncode = _Jv_FindMethodInCache (klass, name, signature);
895 if (ncode != 0)
896 return ncode;
897
898 for (; klass; klass = klass->getSuperclass())
899 {
900 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
901 if (! meth)
902 continue;
903
904 if (Modifier::isStatic(meth->accflags))
905 throw new java::lang::IncompatibleClassChangeError
906 (_Jv_GetMethodString (klass, meth->name));
907 if (Modifier::isAbstract(meth->accflags))
908 throw new java::lang::AbstractMethodError
909 (_Jv_GetMethodString (klass, meth->name));
910 if (! Modifier::isPublic(meth->accflags))
911 throw new java::lang::IllegalAccessError
912 (_Jv_GetMethodString (klass, meth->name));
913
914 _Jv_AddMethodToCache (klass, meth);
915
916 return meth->ncode;
917 }
918 throw new java::lang::IncompatibleClassChangeError;
919}
920
921// Fast interface method lookup by index.
922void *
923_Jv_LookupInterfaceMethodIdx (jclass klass, jclass iface, int method_idx)
924{
925 _Jv_IDispatchTable *cldt = klass->idt;
926 int idx = iface->idt->iface.ioffsets[cldt->cls.iindex] + method_idx;
927 return cldt->cls.itable[idx];
928}
929
930jboolean
931_Jv_IsAssignableFrom (jclass target, jclass source)
932{
933 if (source == target)
934 return true;
935
936 // If target is array, so must source be.
937 if (target->isArray ())
938 {
939 if (! source->isArray())
940 return false;
941 return _Jv_IsAssignableFrom(target->getComponentType(),
942 source->getComponentType());
943 }
944
945 if (target->isInterface())
946 {
947 // Abstract classes have no IDT, and IDTs provide no way to check
948 // two interfaces for assignability.
949 if (__builtin_expect
950 (source->idt == NULL || source->isInterface(), false))
951 return _Jv_InterfaceAssignableFrom (target, source);
952
953 _Jv_IDispatchTable *cl_idt = source->idt;
954 _Jv_IDispatchTable *if_idt = target->idt;
955
956 if (__builtin_expect ((if_idt == NULL), false))
957 return false; // No class implementing TARGET has been loaded.
958 jshort cl_iindex = cl_idt->cls.iindex;
959 if (cl_iindex < if_idt->iface.ioffsets[0])
960 {
961 jshort offset = if_idt->iface.ioffsets[cl_iindex];
962 if (offset != -1 && offset < cl_idt->cls.itable_length
963 && cl_idt->cls.itable[offset] == target)
964 return true;
965 }
966 return false;
967 }
968
969 // Primitive TYPE classes are only assignable to themselves.
970 if (__builtin_expect (target->isPrimitive(), false))
971 return false;
972
973 if (target == &ObjectClass)
974 {
975 if (source->isPrimitive())
976 return false;
977 return true;
978 }
979 else if (source->ancestors != NULL
980 && target->ancestors != NULL
981 && source->depth >= target->depth
982 && source->ancestors[source->depth - target->depth] == target)
983 return true;
984
985 return false;
986}
987
988// Interface type checking, the slow way. Returns TRUE if IFACE is a
989// superinterface of SOURCE. This is used when SOURCE is also an interface,
990// or a class with no interface dispatch table.
991jboolean
992_Jv_InterfaceAssignableFrom (jclass iface, jclass source)
993{
994 for (int i = 0; i < source->interface_count; i++)
995 {
996 jclass interface = source->interfaces[i];
997 if (iface == interface
998 || _Jv_InterfaceAssignableFrom (iface, interface))
999 return true;
1000 }
1001
1002 if (!source->isInterface()
1003 && source->superclass
1004 && _Jv_InterfaceAssignableFrom (iface, source->superclass))
1005 return true;
1006
1007 return false;
1008}
1009
1010jboolean
1011_Jv_IsInstanceOf(jobject obj, jclass cl)
1012{
1013 if (__builtin_expect (!obj, false))
1014 return false;
1015 return (_Jv_IsAssignableFrom (cl, JV_CLASS (obj)));
1016}
1017
1018void *
1019_Jv_CheckCast (jclass c, jobject obj)
1020{
1021 if (__builtin_expect
1022 (obj != NULL && ! _Jv_IsAssignableFrom(c, JV_CLASS (obj)), false))
1023 throw new java::lang::ClassCastException
1024 ((new java::lang::StringBuffer
1025 (obj->getClass()->getName()))->append
1026 (JvNewStringUTF(" cannot be cast to "))->append
1027 (c->getName())->toString());
1028
1029 return obj;
1030}
1031
1032void
1033_Jv_CheckArrayStore (jobject arr, jobject obj)
1034{
1035 if (obj)
1036 {
1037 JvAssert (arr != NULL);
1038 jclass elt_class = (JV_CLASS (arr))->getComponentType();
1039 jclass obj_class = JV_CLASS (obj);
1040 if (__builtin_expect
1041 (! _Jv_IsAssignableFrom (elt_class, obj_class), false))
1042 throw new java::lang::ArrayStoreException;
1043 }
1044}
1045
1046#define INITIAL_IOFFSETS_LEN 4
1047#define INITIAL_IFACES_LEN 4
1048
1049static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
1050
1051// Generate tables for constant-time assignment testing and interface
1052// method lookup. This implements the technique described by Per Bothner
1053// <[email protected]> on the java-discuss mailing list on 1999-09-02:
1054// http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
1055void
1056_Jv_PrepareConstantTimeTables (jclass klass)
1057{
1058 if (klass->isPrimitive () || klass->isInterface ())
1059 return;
1060
1061 // Short-circuit in case we've been called already.
1062 if ((klass->idt != NULL) || klass->depth != 0)
1063 return;
1064
1065 // Calculate the class depth and ancestor table. The depth of a class
1066 // is how many "extends" it is removed from Object. Thus the depth of
1067 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
1068 // is 2. Depth is defined for all regular and array classes, but not
1069 // interfaces or primitive types.
1070
1071 jclass klass0 = klass;
1072 jboolean has_interfaces = 0;
1073 while (klass0 != &ObjectClass)
1074 {
1075 has_interfaces += klass0->interface_count;
1076 klass0 = klass0->superclass;
1077 klass->depth++;
1078 }
1079
1080 // We do class member testing in constant time by using a small table
1081 // of all the ancestor classes within each class. The first element is
1082 // a pointer to the current class, and the rest are pointers to the
1083 // classes ancestors, ordered from the current class down by decreasing
1084 // depth. We do not include java.lang.Object in the table of ancestors,
1085 // since it is redundant.
1086
1087 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth * sizeof (jclass));
1088 klass0 = klass;
1089 for (int index = 0; index < klass->depth; index++)
1090 {
1091 klass->ancestors[index] = klass0;
1092 klass0 = klass0->superclass;
1093 }
1094
1095 if (java::lang::reflect::Modifier::isAbstract (klass->accflags))
1096 return;
1097
1098 // Optimization: If class implements no interfaces, use a common
1099 // predefined interface table.
1100 if (!has_interfaces)
1101 {
1102 klass->idt = &null_idt;
1103 return;
1104 }
1105
1106 klass->idt =
1107 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1108
1109 _Jv_ifaces ifaces;
1110
1111 ifaces.count = 0;
1112 ifaces.len = INITIAL_IFACES_LEN;
1113 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
1114
1115 int itable_size = _Jv_GetInterfaces (klass, &ifaces);
1116
1117 if (ifaces.count > 0)
1118 {
1119 klass->idt->cls.itable =
1120 (void **) _Jv_Malloc (itable_size * sizeof (void *));
1121 klass->idt->cls.itable_length = itable_size;
1122
1123 jshort *itable_offsets =
1124 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
1125
1126 _Jv_GenerateITable (klass, &ifaces, itable_offsets);
1127
1128 jshort cls_iindex =
1129 _Jv_FindIIndex (ifaces.list, itable_offsets, ifaces.count);
1130
1131 for (int i=0; i < ifaces.count; i++)
1132 {
1133 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
1134 itable_offsets[i];
1135 }
1136
1137 klass->idt->cls.iindex = cls_iindex;
1138
1139 _Jv_Free (ifaces.list);
1140 _Jv_Free (itable_offsets);
1141 }
1142 else
1143 {
1144 klass->idt->cls.iindex = SHRT_MAX;
1145 }
1146}
1147
1148// Return index of item in list, or -1 if item is not present.
1149inline jshort
1150_Jv_IndexOf (void *item, void **list, jshort list_len)
1151{
1152 for (int i=0; i < list_len; i++)
1153 {
1154 if (list[i] == item)
1155 return i;
1156 }
1157 return -1;
1158}
1159
1160// Find all unique interfaces directly or indirectly implemented by klass.
1161// Returns the size of the interface dispatch table (itable) for klass, which
1162// is the number of unique interfaces plus the total number of methods that
1163// those interfaces declare. May extend ifaces if required.
1164jshort
1165_Jv_GetInterfaces (jclass klass, _Jv_ifaces *ifaces)
1166{
1167 jshort result = 0;
1168
1169 for (int i=0; i < klass->interface_count; i++)
1170 {
1171 jclass iface = klass->interfaces[i];
1172 if (_Jv_IndexOf (iface, (void **) ifaces->list, ifaces->count) == -1)
1173 {
1174 if (ifaces->count + 1 >= ifaces->len)
1175 {
1176 /* Resize ifaces list */
1177 ifaces->len = ifaces->len * 2;
1178 ifaces->list = (jclass *) _Jv_Realloc (ifaces->list,
1179 ifaces->len * sizeof(jclass));
1180 }
1181 ifaces->list[ifaces->count] = iface;
1182 ifaces->count++;
1183
1184 result += _Jv_GetInterfaces (klass->interfaces[i], ifaces);
1185 }
1186 }
1187
1188 if (klass->isInterface())
1189 {
1190 result += klass->method_count + 1;
1191 }
1192 else
1193 {
1194 if (klass->superclass)
1195 {
1196 result += _Jv_GetInterfaces (klass->superclass, ifaces);
1197 }
1198 }
1199 return result;
1200}
1201
1202// Fill out itable in klass, resolving method declarations in each ifaces.
1203// itable_offsets is filled out with the position of each iface in itable,
1204// such that itable[itable_offsets[n]] == ifaces.list[n].
1205void
1206_Jv_GenerateITable (jclass klass, _Jv_ifaces *ifaces, jshort *itable_offsets)
1207{
1208 void **itable = klass->idt->cls.itable;
1209 jshort itable_pos = 0;
1210
1211 for (int i=0; i < ifaces->count; i++)
1212 {
1213 jclass iface = ifaces->list[i];
1214 itable_offsets[i] = itable_pos;
1215 itable_pos = _Jv_AppendPartialITable (klass, iface, itable, itable_pos);
1216
1217 /* Create interface dispatch table for iface */
1218 if (iface->idt == NULL)
1219 {
1220 iface->idt =
1221 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1222
1223 // The first element of ioffsets is its length (itself included).
1224 jshort *ioffsets =
1225 (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN * sizeof (jshort));
1226 ioffsets[0] = INITIAL_IOFFSETS_LEN;
1227 for (int i=1; i < INITIAL_IOFFSETS_LEN; i++)
1228 ioffsets[i] = -1;
1229
1230 iface->idt->iface.ioffsets = ioffsets;
1231 }
1232 }
1233}
1234
1235// Format method name for use in error messages.
1236jstring
1237_Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
1238{
1239 jstring r = JvNewStringUTF (klass->name->data);
1240 r = r->concat (JvNewStringUTF ("."));
1241 r = r->concat (JvNewStringUTF (name->data));
1242 return r;
1243}
1244
1245void
1246_Jv_ThrowNoSuchMethodError ()
1247{
1248 throw new java::lang::NoSuchMethodError;
1249}
1250
1251// Each superinterface of a class (i.e. each interface that the class
1252// directly or indirectly implements) has a corresponding "Partial
1253// Interface Dispatch Table" whose size is (number of methods + 1) words.
1254// The first word is a pointer to the interface (i.e. the java.lang.Class
1255// instance for that interface). The remaining words are pointers to the
1256// actual methods that implement the methods declared in the interface,
1257// in order of declaration.
1258//
1259// Append partial interface dispatch table for "iface" to "itable", at
1260// position itable_pos.
1261// Returns the offset at which the next partial ITable should be appended.
1262jshort
1263_Jv_AppendPartialITable (jclass klass, jclass iface, void **itable,
1264 jshort pos)
1265{
1266 using namespace java::lang::reflect;
1267
1268 itable[pos++] = (void *) iface;
1269 _Jv_Method *meth;
1270
1271 for (int j=0; j < iface->method_count; j++)
1272 {
1273 meth = NULL;
1274 for (jclass cl = klass; cl; cl = cl->getSuperclass())
1275 {
1276 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
1277 iface->methods[j].signature);
1278
1279 if (meth)
1280 break;
1281 }
1282
1283 if (meth && (meth->name->data[0] == '<'))
1284 {
1285 // leave a placeholder in the itable for hidden init methods.
1286 itable[pos] = NULL;
1287 }
1288 else if (meth)
1289 {
1290 if (Modifier::isStatic(meth->accflags))
1291 throw new java::lang::IncompatibleClassChangeError
1292 (_Jv_GetMethodString (klass, meth->name));
1293 if (Modifier::isAbstract(meth->accflags))
1294 throw new java::lang::AbstractMethodError
1295 (_Jv_GetMethodString (klass, meth->name));
1296 if (! Modifier::isPublic(meth->accflags))
1297 throw new java::lang::IllegalAccessError
1298 (_Jv_GetMethodString (klass, meth->name));
1299
1300 itable[pos] = meth->ncode;
1301 }
1302 else
1303 {
1304 // The method doesn't exist in klass. Binary compatibility rules
1305 // permit this, so we delay the error until runtime using a pointer
1306 // to a method which throws an exception.
1307 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
1308 }
1309 pos++;
1310 }
1311
1312 return pos;
1313}
1314
1315static _Jv_Mutex_t iindex_mutex;
1316bool iindex_mutex_initialized = false;
1317
1318// We need to find the correct offset in the Class Interface Dispatch
1319// Table for a given interface. Once we have that, invoking an interface
1320// method just requires combining the Method's index in the interface
1321// (known at compile time) to get the correct method. Doing a type test
1322// (cast or instanceof) is the same problem: Once we have a possible Partial
1323// Interface Dispatch Table, we just compare the first element to see if it
1324// matches the desired interface. So how can we find the correct offset?
1325// Our solution is to keep a vector of candiate offsets in each interface
1326// (idt->iface.ioffsets), and in each class we have an index
1327// (idt->cls.iindex) used to select the correct offset from ioffsets.
1328//
1329// Calculate and return iindex for a new class.
1330// ifaces is a vector of num interfaces that the class implements.
1331// offsets[j] is the offset in the interface dispatch table for the
1332// interface corresponding to ifaces[j].
1333// May extend the interface ioffsets if required.
1334jshort
1335_Jv_FindIIndex (jclass *ifaces, jshort *offsets, jshort num)
1336{
1337 int i;
1338 int j;
1339
1340 // Acquire a global lock to prevent itable corruption in case of multiple
1341 // classes that implement an intersecting set of interfaces being linked
1342 // simultaneously. We can assume that the mutex will be initialized
1343 // single-threaded.
1344 if (! iindex_mutex_initialized)
1345 {
1346 _Jv_MutexInit (&iindex_mutex);
1347 iindex_mutex_initialized = true;
1348 }
1349
1350 _Jv_MutexLock (&iindex_mutex);
1351
1352 for (i=1;; i++) /* each potential position in ioffsets */
1353 {
1354 for (j=0;; j++) /* each iface */
1355 {
1356 if (j >= num)
1357 goto found;
1358 if (i >= ifaces[j]->idt->iface.ioffsets[0])
1359 continue;
1360 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
1361 /* We can potentially share this position with another class. */
1362 if (ioffset >= 0 && ioffset != offsets[j])
1363 break; /* Nope. Try next i. */
1364 }
1365 }
1366 found:
1367 for (j = 0; j < num; j++)
1368 {
1369 int len = ifaces[j]->idt->iface.ioffsets[0];
1370 if (i >= len)
1371 {
1372 /* Resize ioffsets. */
1373 int newlen = 2 * len;
1374 if (i >= newlen)
1375 newlen = i + 3;
1376 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
1377 jshort *new_ioffsets = (jshort *) _Jv_Realloc (old_ioffsets,
1378 newlen * sizeof(jshort));
1379 new_ioffsets[0] = newlen;
1380
1381 while (len < newlen)
1382 new_ioffsets[len++] = -1;
1383
1384 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
1385 }
1386 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
1387 }
1388
1389 _Jv_MutexUnlock (&iindex_mutex);
1390
1391 return i;
1392}
1393
1394// Only used by serialization
1395java::lang::reflect::Field *
1396java::lang::Class::getPrivateField (jstring name)
1397{
1398 int hash = name->hashCode ();
1399
1400 java::lang::reflect::Field* rfield;
1401 for (int i = 0; i < field_count; i++)
1402 {
1403 _Jv_Field *field = &fields[i];
1404 if (! _Jv_equal (field->name, name, hash))
1405 continue;
1406 rfield = new java::lang::reflect::Field ();
1407 rfield->offset = (char*) field - (char*) fields;
1408 rfield->declaringClass = this;
1409 rfield->name = name;
1410 return rfield;
1411 }
1412 jclass superclass = getSuperclass();
1413 if (superclass == NULL)
1414 return NULL;
1415 rfield = superclass->getPrivateField(name);
1416 for (int i = 0; i < interface_count && rfield == NULL; ++i)
1417 rfield = interfaces[i]->getPrivateField (name);
1418 return rfield;
1419}
1420
1421// Only used by serialization
1422java::lang::reflect::Method *
1423java::lang::Class::getPrivateMethod (jstring name, JArray<jclass> *param_types)
1424{
1425 jstring partial_sig = getSignature (param_types, false);
1426 jint p_len = partial_sig->length();
1427 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
1428 for (Class *klass = this; klass; klass = klass->getSuperclass())
1429 {
1430 int i = klass->isPrimitive () ? 0 : klass->method_count;
1431 while (--i >= 0)
1432 {
1433 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
1434 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
1435 {
1436 // Found it.
1437 using namespace java::lang::reflect;
1438
1439 Method *rmethod = new Method ();
1440 rmethod->offset = ((char *) (&klass->methods[i])
1441 - (char *) klass->methods);
1442 rmethod->declaringClass = klass;
1443 return rmethod;
1444 }
1445 }
1446 }
1447 throw new java::lang::NoSuchMethodException;
1448}
1449
1450// Private accessor method for Java code to retrieve the protection domain.
1451java::security::ProtectionDomain *
1452java::lang::Class::getProtectionDomain0 ()
1453{
1454 return protectionDomain;
1455}
1456
1457// Functions for indirect dispatch (symbolic virtual method binding) support.
1458
1459// Resolve entries in the virtual method offset symbol table
1460// (klass->otable_syms). The vtable offset (in bytes) for each resolved method
1461// is placed at the corresponding position in the virtual method offset table
1462// (klass->otable). A single otable and otable_syms pair may be shared by many
1463// classes.
1464void
1465_Jv_LinkOffsetTable(jclass klass)
1466{
1467 //// FIXME: Need to lock the otable ////
1468
1469 if (klass->otable == NULL
1470 || klass->otable->state != 0)
1471 return;
1472
1473 klass->otable->state = 1;
1474
1475 int index = 0;
1476 _Jv_MethodSymbol sym = klass->otable_syms[0];
1477
1478 while (sym.name != NULL)
1479 {
1480 jclass target_class = _Jv_FindClass (sym.class_name, NULL);
1481 _Jv_Method *meth = NULL;
1482
1483 if (target_class != NULL)
1484 if (target_class->isInterface())
1485 {
1486 // FIXME: This does not yet fully conform to binary compatibility
1487 // rules. It will break if a declaration is moved into a
1488 // superinterface.
1489 for (int i=0; i < target_class->method_count; i++)
1490 {
1491 meth = &target_class->methods[i];
1492 if (_Jv_equalUtf8Consts (sym.name, meth->name)
1493 && _Jv_equalUtf8Consts (sym.signature, meth->signature))
1494 {
1495 klass->otable->offsets[index] = i + 1;
1496 break;
1497 }
1498 }
1499 }
1500 else
1501 {
1502 // If the target class does not have a vtable_method_count yet,
1503 // then we can't tell the offsets for its methods, so we must lay
1504 // it out now.
1505 if (target_class->vtable_method_count == -1)
1506 {
1507 JvSynchronize sync (target_class);
1508 _Jv_LayoutVTableMethods (target_class);
1509 }
1510
1511 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1512 sym.signature);
1513
1514 if (meth != NULL)
1515 {
1516 klass->otable->offsets[index] =
1517 _Jv_VTable::idx_to_offset (meth->index);
1518 }
1519 }
1520
1521 if (meth == NULL)
1522 // FIXME: This should be special index for ThrowNoSuchMethod().
1523 klass->otable->offsets[index] = -1;
1524
1525 sym = klass->otable_syms[++index];
1526 }
1527}
1528
1529// Returns true if METH should get an entry in a VTable.
1530static bool
1531isVirtualMethod (_Jv_Method *meth)
1532{
1533 using namespace java::lang::reflect;
1534 return (((meth->accflags & (Modifier::STATIC | Modifier::PRIVATE)) == 0)
1535 && meth->name->data[0] != '<');
1536}
1537
1538// Prepare virtual method declarations in KLASS, and any superclasses as
1539// required, by determining their vtable index, setting method->index, and
1540// finally setting the class's vtable_method_count. Must be called with the
1541// lock for KLASS held.
1542void
1543_Jv_LayoutVTableMethods (jclass klass)
1544{
1545 if (klass->vtable != NULL || klass->isInterface()
1546 || klass->vtable_method_count != -1)
1547 return;
1548
1549 jclass superclass = klass->superclass;
1550
1551 if (superclass != NULL && superclass->vtable_method_count == -1)
1552 {
1553 JvSynchronize sync (superclass);
1554 _Jv_LayoutVTableMethods (superclass);
1555 }
1556
1557 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1558
1559 for (int i = 0; i < klass->method_count; ++i)
1560 {
1561 _Jv_Method *meth = &klass->methods[i];
1562 _Jv_Method *super_meth = NULL;
1563
1564 if (!isVirtualMethod(meth))
1565 continue;
1566
1567 if (superclass != NULL)
1568 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1569 meth->signature);
1570
1571 if (super_meth)
1572 meth->index = super_meth->index;
1573 else
1574 meth->index = index++;
1575 }
1576
1577 klass->vtable_method_count = index;
1578}
1579
1580// Set entries in VTABLE for virtual methods declared in KLASS. If KLASS has
1581// an immediate abstract parent, recursivly do its methods first.
1582void
1583_Jv_SetVTableEntries (jclass klass, _Jv_VTable *vtable)
1584{
1585 using namespace java::lang::reflect;
1586
1587 jclass superclass = klass->getSuperclass();
1588
1589 if (superclass != NULL && (superclass->getModifiers() & Modifier::ABSTRACT))
1590 _Jv_SetVTableEntries (superclass, vtable);
1591
1592 for (int i = klass->method_count - 1; i >= 0; i--)
1593 {
1594 _Jv_Method *meth = &klass->methods[i];
1595 if (!isVirtualMethod(meth))
1596 continue;
1597 vtable->set_method(meth->index, meth->ncode);
1598 }
1599}
1600
1601// Allocate and lay out the virtual method table for KLASS. This will also
1602// cause vtables to be generated for any non-abstract superclasses, and
1603// virtual method layout to occur for any abstract superclasses. Must be
1604// called with monitor lock for KLASS held.
1605void
1606_Jv_MakeVTable (jclass klass)
1607{
1608 using namespace java::lang::reflect;
1609
1610 if (klass->vtable != NULL || klass->isInterface()
1611 || (klass->accflags & Modifier::ABSTRACT))
1612 return;
1613
1614 // out before we can create a vtable.
1615 if (klass->vtable_method_count == -1)
1616 _Jv_LayoutVTableMethods (klass);
1617
1618 // Allocate the new vtable.
1619 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1620 klass->vtable = vtable;
1621
1622 // Copy the vtable of the closest non-abstract superclass.
1623 jclass superclass = klass->superclass;
1624 if (superclass != NULL)
1625 {
1626 while ((superclass->accflags & Modifier::ABSTRACT) != 0)
1627 superclass = superclass->superclass;
1628
1629 if (superclass->vtable == NULL)
1630 {
1631 JvSynchronize sync (superclass);
1632 _Jv_MakeVTable (superclass);
1633 }
1634
1635 for (int i = 0; i < superclass->vtable_method_count; ++i)
1636 vtable->set_method (i, superclass->vtable->get_method (i));
1637 }
1638
1639 // Set the class pointer and GC descriptor.
1640 vtable->clas = klass;
1641 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1642
1643 // For each virtual declared in klass and any immediate abstract
1644 // superclasses, set new vtable entry or override an old one.
1645 _Jv_SetVTableEntries (klass, vtable);
1646}
Note: See TracBrowser for help on using the repository browser.