0960649e71cb5a2835473d42a04d873221c8910c
[gcc.git] / libjava / java / lang / natClass.cc
1 // natClass.cc - Implementation of java.lang.Class native methods.
2
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation
4
5 This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
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/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>
55
56 #include <java-cpool.h>
57
58 \f
59
60 using namespace gcj;
61
62 jclass
63 java::lang::Class::forName (jstring className, jboolean initialize,
64 java::lang::ClassLoader *loader)
65 {
66 if (! className)
67 throw new java::lang::NullPointerException;
68
69 jsize length = _Jv_GetStringUTFLength (className);
70 char buffer[length];
71 _Jv_GetStringUTFRegion (className, 0, length, buffer);
72
73 _Jv_Utf8Const *name = _Jv_makeUtf8Const (buffer, length);
74
75 if (! _Jv_VerifyClassName (name))
76 throw new java::lang::ClassNotFoundException (className);
77
78 jclass klass = (buffer[0] == '['
79 ? _Jv_FindClassFromSignature (name->data, loader)
80 : _Jv_FindClass (name, loader));
81
82 if (klass == NULL)
83 throw new java::lang::ClassNotFoundException (className);
84
85 if (initialize)
86 _Jv_InitClass (klass);
87
88 return klass;
89 }
90
91 jclass
92 java::lang::Class::forName (jstring className)
93 {
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
99 {
100 for (int i = 1; !klass; i++)
101 {
102 klass = t->classAt (i);
103 }
104 loader = klass->getClassLoader();
105 }
106 catch (::java::lang::ArrayIndexOutOfBoundsException *e)
107 {
108 }
109
110 return forName (className, true, loader);
111 }
112
113 java::lang::ClassLoader *
114 java::lang::Class::getClassLoader (void)
115 {
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
123
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 ();
134 }
135
136 java::lang::reflect::Constructor *
137 java::lang::Class::getConstructor (JArray<jclass> *param_types)
138 {
139 jstring partial_sig = getSignature (param_types, true);
140 jint hash = partial_sig->hashCode ();
141
142 int i = isPrimitive () ? 0 : method_count;
143 while (--i >= 0)
144 {
145 // FIXME: access checks.
146 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
147 && _Jv_equal (methods[i].signature, partial_sig, hash))
148 {
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;
158 }
159 }
160 throw new java::lang::NoSuchMethodException;
161 }
162
163 JArray<java::lang::reflect::Constructor *> *
164 java::lang::Class::_getConstructors (jboolean declared)
165 {
166 // FIXME: this method needs access checks.
167
168 int numConstructors = 0;
169 int max = isPrimitive () ? 0 : method_count;
170 int i;
171 for (i = max; --i >= 0; )
172 {
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++;
181 }
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++)
189 {
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;
202 }
203 return result;
204 }
205
206 java::lang::reflect::Constructor *
207 java::lang::Class::getDeclaredConstructor (JArray<jclass> *param_types)
208 {
209 jstring partial_sig = getSignature (param_types, true);
210 jint hash = partial_sig->hashCode ();
211
212 int i = isPrimitive () ? 0 : method_count;
213 while (--i >= 0)
214 {
215 // FIXME: access checks.
216 if (_Jv_equalUtf8Consts (methods[i].name, init_name)
217 && _Jv_equal (methods[i].signature, partial_sig, hash))
218 {
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;
225 }
226 }
227 throw new java::lang::NoSuchMethodException;
228 }
229
230 java::lang::reflect::Field *
231 java::lang::Class::getField (jstring name, jint hash)
232 {
233 java::lang::reflect::Field* rfield;
234 for (int i = 0; i < field_count; i++)
235 {
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;
246 }
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;
254 }
255
256 java::lang::reflect::Field *
257 java::lang::Class::getDeclaredField (jstring name)
258 {
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++)
264 {
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;
273 }
274 throw new java::lang::NoSuchFieldException (name);
275 }
276
277 JArray<java::lang::reflect::Field *> *
278 java::lang::Class::getDeclaredFields (void)
279 {
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++)
288 {
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;
294 }
295 return result;
296 }
297
298 void
299 java::lang::Class::getSignature (java::lang::StringBuffer *buffer)
300 {
301 if (isPrimitive())
302 buffer->append((jchar) method_count);
303 else
304 {
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) ';');
311 }
312 }
313
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)
319 {
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)
324 {
325 jclass *v = elements (param_types);
326 for (int i = 0; i < param_types->length; ++i)
327 v[i]->getSignature(buf);
328 }
329 buf->append((jchar) ')');
330 if (is_constructor)
331 buf->append((jchar) 'V');
332 return buf->toString();
333 }
334
335 java::lang::reflect::Method *
336 java::lang::Class::_getDeclaredMethod (jstring name,
337 JArray<jclass> *param_types)
338 {
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)
344 {
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)
349 {
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;
356 }
357 }
358 return NULL;
359 }
360
361 JArray<java::lang::reflect::Method *> *
362 java::lang::Class::getDeclaredMethods (void)
363 {
364 int numMethods = 0;
365 int max = isPrimitive () ? 0 : method_count;
366 int i;
367 for (i = max; --i >= 0; )
368 {
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++;
378 }
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++)
384 {
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;
398 }
399 return result;
400 }
401
402 jstring
403 java::lang::Class::getName (void)
404 {
405 char buffer[name->length + 1];
406 memcpy (buffer, name->data, name->length);
407 buffer[name->length] = '\0';
408 return _Jv_NewStringUTF (buffer);
409 }
410
411 JArray<jclass> *
412 java::lang::Class::getClasses (void)
413 {
414 // FIXME: security checking.
415
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;
422 }
423
424 JArray<jclass> *
425 java::lang::Class::getDeclaredClasses (void)
426 {
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;
434 }
435
436 jclass
437 java::lang::Class::getDeclaringClass (void)
438 {
439 // Until we have inner classes, it makes sense to always return
440 // NULL.
441 return NULL;
442 }
443
444 jint
445 java::lang::Class::_getFields (JArray<java::lang::reflect::Field *> *result,
446 jint offset)
447 {
448 int count = 0;
449 for (int i = 0; i < field_count; i++)
450 {
451 _Jv_Field *field = &fields[i];
452 if (! (field->getModifiers() & java::lang::reflect::Modifier::PUBLIC))
453 continue;
454 ++count;
455
456 if (result != NULL)
457 {
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;
464 }
465 }
466 jclass superclass = getSuperclass();
467 if (superclass != NULL)
468 {
469 int s_count = superclass->_getFields (result, offset);
470 count += s_count;
471 offset += s_count;
472 }
473 for (int i = 0; i < interface_count; ++i)
474 {
475 int f_count = interfaces[i]->_getFields (result, offset);
476 count += f_count;
477 offset += f_count;
478 }
479 return count;
480 }
481
482 JArray<java::lang::reflect::Field *> *
483 java::lang::Class::getFields (void)
484 {
485 // FIXME: security checking.
486
487 using namespace java::lang::reflect;
488
489 int count = _getFields (NULL, 0);
490
491 JArray<java::lang::reflect::Field *> *result
492 = ((JArray<java::lang::reflect::Field *> *)
493 JvNewObjectArray (count, &java::lang::reflect::Field::class$, NULL));
494
495 _getFields (result, 0);
496
497 return result;
498 }
499
500 JArray<jclass> *
501 java::lang::Class::getInterfaces (void)
502 {
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);
508 }
509
510 java::lang::reflect::Method *
511 java::lang::Class::_getMethod (jstring name, JArray<jclass> *param_types)
512 {
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())
517 {
518 int i = klass->isPrimitive () ? 0 : klass->method_count;
519 while (--i >= 0)
520 {
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)
526 {
527 // Found it.
528 using namespace java::lang::reflect;
529
530 // Method must be public.
531 if (! Modifier::isPublic (klass->methods[i].accflags))
532 break;
533
534 Method *rmethod = new Method ();
535 rmethod->offset = ((char *) (&klass->methods[i])
536 - (char *) klass->methods);
537 rmethod->declaringClass = klass;
538 return rmethod;
539 }
540 }
541 }
542
543 // If we haven't found a match, and this class is an interface, then
544 // check all the superinterfaces.
545 if (isInterface())
546 {
547 for (int i = 0; i < interface_count; ++i)
548 {
549 using namespace java::lang::reflect;
550 Method *rmethod = interfaces[i]->_getMethod (name, param_types);
551 if (rmethod != NULL)
552 return rmethod;
553 }
554 }
555
556 return NULL;
557 }
558
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)
566 {
567 jint count = 0;
568
569 // First examine all local methods
570 for (int i = isPrimitive () ? 0 : method_count; --i >= 0; )
571 {
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;
583
584 // This is where we over-count the slots required if we aren't
585 // filling the result for real.
586 if (result != NULL)
587 {
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)
594 {
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))
599 {
600 add = false;
601 break;
602 }
603 }
604 if (! add)
605 continue;
606 }
607
608 if (result != NULL)
609 {
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;
616 }
617 ++count;
618 }
619 offset += count;
620
621 // Now examine superclasses.
622 if (getSuperclass () != NULL)
623 {
624 jint s_count = getSuperclass()->_getMethods (result, offset);
625 offset += s_count;
626 count += s_count;
627 }
628
629 // Finally, examine interfaces.
630 for (int i = 0; i < interface_count; ++i)
631 {
632 int f_count = interfaces[i]->_getMethods (result, offset);
633 count += f_count;
634 offset += f_count;
635 }
636
637 return count;
638 }
639
640 JArray<java::lang::reflect::Method *> *
641 java::lang::Class::getMethods (void)
642 {
643 using namespace java::lang::reflect;
644
645 // FIXME: security checks.
646
647 // This will overestimate the size we need.
648 jint count = _getMethods (NULL, 0);
649
650 JArray<Method *> *result
651 = ((JArray<Method *> *) JvNewObjectArray (count,
652 &Method::class$,
653 NULL));
654
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);
658
659 if (real_count != count)
660 {
661 JArray<Method *> *r2
662 = ((JArray<Method *> *) JvNewObjectArray (real_count,
663 &Method::class$,
664 NULL));
665
666 Method **destp = elements (r2);
667 Method **srcp = elements (result);
668
669 for (int i = 0; i < real_count; ++i)
670 *destp++ = *srcp++;
671
672 result = r2;
673 }
674
675 return result;
676 }
677
678 jboolean
679 java::lang::Class::isAssignableFrom (jclass klass)
680 {
681 // Arguments may not have been initialized, given ".class" syntax.
682 _Jv_InitClass (this);
683 _Jv_InitClass (klass);
684 return _Jv_IsAssignableFrom (this, klass);
685 }
686
687 jboolean
688 java::lang::Class::isInstance (jobject obj)
689 {
690 if (! obj)
691 return false;
692 _Jv_InitClass (this);
693 return _Jv_IsAssignableFrom (this, JV_CLASS (obj));
694 }
695
696 jobject
697 java::lang::Class::newInstance (void)
698 {
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;
705
706 if (isPrimitive ()
707 || isInterface ()
708 || isArray ()
709 || java::lang::reflect::Modifier::isAbstract(accflags))
710 throw new java::lang::InstantiationException;
711
712 _Jv_InitClass (this);
713
714 _Jv_Method *meth = _Jv_GetMethodLocal (this, init_name, void_signature);
715 if (! meth)
716 throw new java::lang::NoSuchMethodException;
717
718 jobject r = JvAllocObject (this);
719 ((void (*) (jobject)) meth->ncode) (r);
720 return r;
721 }
722
723 void
724 java::lang::Class::finalize (void)
725 {
726 #ifdef INTERPRETER
727 JvAssert (_Jv_IsInterpretedClass (this));
728 _Jv_UnregisterClass (this);
729 #endif
730 }
731
732 // This implements the initialization process for a class. From Spec
733 // section 12.4.2.
734 void
735 java::lang::Class::initializeClass (void)
736 {
737 // short-circuit to avoid needless locking.
738 if (state == JV_STATE_DONE)
739 return;
740
741 // Step 1.
742 _Jv_MonitorEnter (this);
743
744 if (state < JV_STATE_LINKED)
745 {
746 #ifdef INTERPRETER
747 if (_Jv_IsInterpretedClass (this))
748 {
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);
753 }
754 else
755 #endif
756 {
757 _Jv_PrepareCompiledClass (this);
758 }
759 }
760
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 ();
767
768 // Steps 3 & 4.
769 if (state == JV_STATE_DONE || state == JV_STATE_IN_PROGRESS)
770 {
771 _Jv_MonitorExit (this);
772 return;
773 }
774
775 // Step 5.
776 if (state == JV_STATE_ERROR)
777 {
778 _Jv_MonitorExit (this);
779 throw new java::lang::NoClassDefFoundError (getName());
780 }
781
782 // Step 6.
783 thread = self;
784 state = JV_STATE_IN_PROGRESS;
785 _Jv_MonitorExit (this);
786
787 // Step 7.
788 if (! isInterface () && superclass)
789 {
790 try
791 {
792 _Jv_InitClass (superclass);
793 }
794 catch (java::lang::Throwable *except)
795 {
796 // Caught an exception.
797 _Jv_MonitorEnter (this);
798 state = JV_STATE_ERROR;
799 notifyAll ();
800 _Jv_MonitorExit (this);
801 throw except;
802 }
803 }
804
805 _Jv_PrepareConstantTimeTables (this);
806
807 if (vtable == NULL)
808 _Jv_MakeVTable(this);
809
810 if (otable != NULL && otable->state == 0)
811 _Jv_LinkOffsetTable(this);
812
813 // Steps 8, 9, 10, 11.
814 try
815 {
816 _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name,
817 void_signature);
818 if (meth)
819 ((void (*) (void)) meth->ncode) ();
820 }
821 catch (java::lang::Throwable *except)
822 {
823 if (! java::lang::Error::class$.isInstance(except))
824 {
825 try
826 {
827 except = new ExceptionInInitializerError (except);
828 }
829 catch (java::lang::Throwable *t)
830 {
831 except = t;
832 }
833 }
834 _Jv_MonitorEnter (this);
835 state = JV_STATE_ERROR;
836 notifyAll ();
837 _Jv_MonitorExit (this);
838 throw except;
839 }
840
841 _Jv_MonitorEnter (this);
842 state = JV_STATE_DONE;
843 notifyAll ();
844 _Jv_MonitorExit (this);
845 }
846
847 \f
848
849 //
850 // Some class-related convenience functions.
851 //
852
853 // Find a method declared in the class. If it is not declared locally
854 // (or if it is inherited), return NULL.
855 _Jv_Method *
856 _Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
857 _Jv_Utf8Const *signature)
858 {
859 for (int i = 0; i < klass->method_count; ++i)
860 {
861 if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
862 && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
863 return &klass->methods[i];
864 }
865 return NULL;
866 }
867
868 _Jv_Method *
869 _Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
870 _Jv_Utf8Const *signature)
871 {
872 for (; klass; klass = klass->getSuperclass())
873 {
874 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
875
876 if (meth)
877 return meth;
878 }
879
880 return NULL;
881 }
882
883 // NOTE: MCACHE_SIZE should be a power of 2 minus one.
884 #define MCACHE_SIZE 1023
885
886 struct _Jv_mcache
887 {
888 jclass klass;
889 _Jv_Method *method;
890 };
891
892 static _Jv_mcache method_cache[MCACHE_SIZE + 1];
893
894 static void *
895 _Jv_FindMethodInCache (jclass klass,
896 _Jv_Utf8Const *name,
897 _Jv_Utf8Const *signature)
898 {
899 int index = name->hash & MCACHE_SIZE;
900 _Jv_mcache *mc = method_cache + index;
901 _Jv_Method *m = mc->method;
902
903 if (mc->klass == klass
904 && m != NULL // thread safe check
905 && _Jv_equalUtf8Consts (m->name, name)
906 && _Jv_equalUtf8Consts (m->signature, signature))
907 return mc->method->ncode;
908 return NULL;
909 }
910
911 static void
912 _Jv_AddMethodToCache (jclass klass,
913 _Jv_Method *method)
914 {
915 _Jv_MonitorEnter (&java::lang::Class::class$);
916
917 int index = method->name->hash & MCACHE_SIZE;
918
919 method_cache[index].method = method;
920 method_cache[index].klass = klass;
921
922 _Jv_MonitorExit (&java::lang::Class::class$);
923 }
924
925 void *
926 _Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
927 _Jv_Utf8Const *signature)
928 {
929 using namespace java::lang::reflect;
930
931 void *ncode = _Jv_FindMethodInCache (klass, name, signature);
932 if (ncode != 0)
933 return ncode;
934
935 for (; klass; klass = klass->getSuperclass())
936 {
937 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
938 if (! meth)
939 continue;
940
941 if (Modifier::isStatic(meth->accflags))
942 throw new java::lang::IncompatibleClassChangeError
943 (_Jv_GetMethodString (klass, meth->name));
944 if (Modifier::isAbstract(meth->accflags))
945 throw new java::lang::AbstractMethodError
946 (_Jv_GetMethodString (klass, meth->name));
947 if (! Modifier::isPublic(meth->accflags))
948 throw new java::lang::IllegalAccessError
949 (_Jv_GetMethodString (klass, meth->name));
950
951 _Jv_AddMethodToCache (klass, meth);
952
953 return meth->ncode;
954 }
955 throw new java::lang::IncompatibleClassChangeError;
956 }
957
958 // Fast interface method lookup by index.
959 void *
960 _Jv_LookupInterfaceMethodIdx (jclass klass, jclass iface, int method_idx)
961 {
962 _Jv_IDispatchTable *cldt = klass->idt;
963 int idx = iface->idt->iface.ioffsets[cldt->cls.iindex] + method_idx;
964 return cldt->cls.itable[idx];
965 }
966
967 jboolean
968 _Jv_IsAssignableFrom (jclass target, jclass source)
969 {
970 if (source == target)
971 return true;
972
973 // If target is array, so must source be.
974 if (target->isArray ())
975 {
976 if (! source->isArray())
977 return false;
978 return _Jv_IsAssignableFrom(target->getComponentType(),
979 source->getComponentType());
980 }
981
982 if (target->isInterface())
983 {
984 // Abstract classes have no IDT, and IDTs provide no way to check
985 // two interfaces for assignability.
986 if (__builtin_expect
987 (source->idt == NULL || source->isInterface(), false))
988 return _Jv_InterfaceAssignableFrom (target, source);
989
990 _Jv_IDispatchTable *cl_idt = source->idt;
991 _Jv_IDispatchTable *if_idt = target->idt;
992
993 if (__builtin_expect ((if_idt == NULL), false))
994 return false; // No class implementing TARGET has been loaded.
995 jshort cl_iindex = cl_idt->cls.iindex;
996 if (cl_iindex < if_idt->iface.ioffsets[0])
997 {
998 jshort offset = if_idt->iface.ioffsets[cl_iindex];
999 if (offset != -1 && offset < cl_idt->cls.itable_length
1000 && cl_idt->cls.itable[offset] == target)
1001 return true;
1002 }
1003 return false;
1004 }
1005
1006 // Primitive TYPE classes are only assignable to themselves.
1007 if (__builtin_expect (target->isPrimitive(), false))
1008 return false;
1009
1010 if (target == &java::lang::Object::class$)
1011 {
1012 if (source->isPrimitive())
1013 return false;
1014 return true;
1015 }
1016 else if (source->ancestors != NULL
1017 && target->ancestors != NULL
1018 && source->depth >= target->depth
1019 && source->ancestors[source->depth - target->depth] == target)
1020 return true;
1021
1022 return false;
1023 }
1024
1025 // Interface type checking, the slow way. Returns TRUE if IFACE is a
1026 // superinterface of SOURCE. This is used when SOURCE is also an interface,
1027 // or a class with no interface dispatch table.
1028 jboolean
1029 _Jv_InterfaceAssignableFrom (jclass iface, jclass source)
1030 {
1031 for (int i = 0; i < source->interface_count; i++)
1032 {
1033 jclass interface = source->interfaces[i];
1034 if (iface == interface
1035 || _Jv_InterfaceAssignableFrom (iface, interface))
1036 return true;
1037 }
1038
1039 if (!source->isInterface()
1040 && source->superclass
1041 && _Jv_InterfaceAssignableFrom (iface, source->superclass))
1042 return true;
1043
1044 return false;
1045 }
1046
1047 jboolean
1048 _Jv_IsInstanceOf(jobject obj, jclass cl)
1049 {
1050 if (__builtin_expect (!obj, false))
1051 return false;
1052 return (_Jv_IsAssignableFrom (cl, JV_CLASS (obj)));
1053 }
1054
1055 void *
1056 _Jv_CheckCast (jclass c, jobject obj)
1057 {
1058 if (__builtin_expect
1059 (obj != NULL && ! _Jv_IsAssignableFrom(c, JV_CLASS (obj)), false))
1060 throw new java::lang::ClassCastException
1061 ((new java::lang::StringBuffer
1062 (obj->getClass()->getName()))->append
1063 (JvNewStringUTF(" cannot be cast to "))->append
1064 (c->getName())->toString());
1065
1066 return obj;
1067 }
1068
1069 void
1070 _Jv_CheckArrayStore (jobject arr, jobject obj)
1071 {
1072 if (obj)
1073 {
1074 JvAssert (arr != NULL);
1075 jclass elt_class = (JV_CLASS (arr))->getComponentType();
1076 if (elt_class == &java::lang::Object::class$)
1077 return;
1078 jclass obj_class = JV_CLASS (obj);
1079 if (__builtin_expect
1080 (! _Jv_IsAssignableFrom (elt_class, obj_class), false))
1081 throw new java::lang::ArrayStoreException
1082 ((new java::lang::StringBuffer
1083 (JvNewStringUTF("Cannot store ")))->append
1084 (obj_class->getName())->append
1085 (JvNewStringUTF(" in array of type "))->append
1086 (elt_class->getName())->toString());
1087 }
1088 }
1089
1090 #define INITIAL_IOFFSETS_LEN 4
1091 #define INITIAL_IFACES_LEN 4
1092
1093 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
1094
1095 // Generate tables for constant-time assignment testing and interface
1096 // method lookup. This implements the technique described by Per Bothner
1097 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
1098 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
1099 void
1100 _Jv_PrepareConstantTimeTables (jclass klass)
1101 {
1102 if (klass->isPrimitive () || klass->isInterface ())
1103 return;
1104
1105 // Short-circuit in case we've been called already.
1106 if ((klass->idt != NULL) || klass->depth != 0)
1107 return;
1108
1109 // Calculate the class depth and ancestor table. The depth of a class
1110 // is how many "extends" it is removed from Object. Thus the depth of
1111 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
1112 // is 2. Depth is defined for all regular and array classes, but not
1113 // interfaces or primitive types.
1114
1115 jclass klass0 = klass;
1116 jboolean has_interfaces = 0;
1117 while (klass0 != &java::lang::Object::class$)
1118 {
1119 has_interfaces += klass0->interface_count;
1120 klass0 = klass0->superclass;
1121 klass->depth++;
1122 }
1123
1124 // We do class member testing in constant time by using a small table
1125 // of all the ancestor classes within each class. The first element is
1126 // a pointer to the current class, and the rest are pointers to the
1127 // classes ancestors, ordered from the current class down by decreasing
1128 // depth. We do not include java.lang.Object in the table of ancestors,
1129 // since it is redundant.
1130
1131 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth * sizeof (jclass));
1132 klass0 = klass;
1133 for (int index = 0; index < klass->depth; index++)
1134 {
1135 klass->ancestors[index] = klass0;
1136 klass0 = klass0->superclass;
1137 }
1138
1139 if (java::lang::reflect::Modifier::isAbstract (klass->accflags))
1140 return;
1141
1142 // Optimization: If class implements no interfaces, use a common
1143 // predefined interface table.
1144 if (!has_interfaces)
1145 {
1146 klass->idt = &null_idt;
1147 return;
1148 }
1149
1150 klass->idt =
1151 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1152
1153 _Jv_ifaces ifaces;
1154
1155 ifaces.count = 0;
1156 ifaces.len = INITIAL_IFACES_LEN;
1157 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
1158
1159 int itable_size = _Jv_GetInterfaces (klass, &ifaces);
1160
1161 if (ifaces.count > 0)
1162 {
1163 klass->idt->cls.itable =
1164 (void **) _Jv_Malloc (itable_size * sizeof (void *));
1165 klass->idt->cls.itable_length = itable_size;
1166
1167 jshort *itable_offsets =
1168 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
1169
1170 _Jv_GenerateITable (klass, &ifaces, itable_offsets);
1171
1172 jshort cls_iindex =
1173 _Jv_FindIIndex (ifaces.list, itable_offsets, ifaces.count);
1174
1175 for (int i=0; i < ifaces.count; i++)
1176 {
1177 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
1178 itable_offsets[i];
1179 }
1180
1181 klass->idt->cls.iindex = cls_iindex;
1182
1183 _Jv_Free (ifaces.list);
1184 _Jv_Free (itable_offsets);
1185 }
1186 else
1187 {
1188 klass->idt->cls.iindex = SHRT_MAX;
1189 }
1190 }
1191
1192 // Return index of item in list, or -1 if item is not present.
1193 inline jshort
1194 _Jv_IndexOf (void *item, void **list, jshort list_len)
1195 {
1196 for (int i=0; i < list_len; i++)
1197 {
1198 if (list[i] == item)
1199 return i;
1200 }
1201 return -1;
1202 }
1203
1204 // Find all unique interfaces directly or indirectly implemented by klass.
1205 // Returns the size of the interface dispatch table (itable) for klass, which
1206 // is the number of unique interfaces plus the total number of methods that
1207 // those interfaces declare. May extend ifaces if required.
1208 jshort
1209 _Jv_GetInterfaces (jclass klass, _Jv_ifaces *ifaces)
1210 {
1211 jshort result = 0;
1212
1213 for (int i=0; i < klass->interface_count; i++)
1214 {
1215 jclass iface = klass->interfaces[i];
1216 if (_Jv_IndexOf (iface, (void **) ifaces->list, ifaces->count) == -1)
1217 {
1218 if (ifaces->count + 1 >= ifaces->len)
1219 {
1220 /* Resize ifaces list */
1221 ifaces->len = ifaces->len * 2;
1222 ifaces->list = (jclass *) _Jv_Realloc (ifaces->list,
1223 ifaces->len * sizeof(jclass));
1224 }
1225 ifaces->list[ifaces->count] = iface;
1226 ifaces->count++;
1227
1228 result += _Jv_GetInterfaces (klass->interfaces[i], ifaces);
1229 }
1230 }
1231
1232 if (klass->isInterface())
1233 {
1234 result += klass->method_count + 1;
1235 }
1236 else
1237 {
1238 if (klass->superclass)
1239 {
1240 result += _Jv_GetInterfaces (klass->superclass, ifaces);
1241 }
1242 }
1243 return result;
1244 }
1245
1246 // Fill out itable in klass, resolving method declarations in each ifaces.
1247 // itable_offsets is filled out with the position of each iface in itable,
1248 // such that itable[itable_offsets[n]] == ifaces.list[n].
1249 void
1250 _Jv_GenerateITable (jclass klass, _Jv_ifaces *ifaces, jshort *itable_offsets)
1251 {
1252 void **itable = klass->idt->cls.itable;
1253 jshort itable_pos = 0;
1254
1255 for (int i=0; i < ifaces->count; i++)
1256 {
1257 jclass iface = ifaces->list[i];
1258 itable_offsets[i] = itable_pos;
1259 itable_pos = _Jv_AppendPartialITable (klass, iface, itable, itable_pos);
1260
1261 /* Create interface dispatch table for iface */
1262 if (iface->idt == NULL)
1263 {
1264 iface->idt =
1265 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1266
1267 // The first element of ioffsets is its length (itself included).
1268 jshort *ioffsets =
1269 (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN * sizeof (jshort));
1270 ioffsets[0] = INITIAL_IOFFSETS_LEN;
1271 for (int i=1; i < INITIAL_IOFFSETS_LEN; i++)
1272 ioffsets[i] = -1;
1273
1274 iface->idt->iface.ioffsets = ioffsets;
1275 }
1276 }
1277 }
1278
1279 // Format method name for use in error messages.
1280 jstring
1281 _Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
1282 {
1283 jstring r = JvNewStringUTF (klass->name->data);
1284 r = r->concat (JvNewStringUTF ("."));
1285 r = r->concat (JvNewStringUTF (name->data));
1286 return r;
1287 }
1288
1289 void
1290 _Jv_ThrowNoSuchMethodError ()
1291 {
1292 throw new java::lang::NoSuchMethodError;
1293 }
1294
1295 // Each superinterface of a class (i.e. each interface that the class
1296 // directly or indirectly implements) has a corresponding "Partial
1297 // Interface Dispatch Table" whose size is (number of methods + 1) words.
1298 // The first word is a pointer to the interface (i.e. the java.lang.Class
1299 // instance for that interface). The remaining words are pointers to the
1300 // actual methods that implement the methods declared in the interface,
1301 // in order of declaration.
1302 //
1303 // Append partial interface dispatch table for "iface" to "itable", at
1304 // position itable_pos.
1305 // Returns the offset at which the next partial ITable should be appended.
1306 jshort
1307 _Jv_AppendPartialITable (jclass klass, jclass iface, void **itable,
1308 jshort pos)
1309 {
1310 using namespace java::lang::reflect;
1311
1312 itable[pos++] = (void *) iface;
1313 _Jv_Method *meth;
1314
1315 for (int j=0; j < iface->method_count; j++)
1316 {
1317 meth = NULL;
1318 for (jclass cl = klass; cl; cl = cl->getSuperclass())
1319 {
1320 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
1321 iface->methods[j].signature);
1322
1323 if (meth)
1324 break;
1325 }
1326
1327 if (meth && (meth->name->data[0] == '<'))
1328 {
1329 // leave a placeholder in the itable for hidden init methods.
1330 itable[pos] = NULL;
1331 }
1332 else if (meth)
1333 {
1334 if (Modifier::isStatic(meth->accflags))
1335 throw new java::lang::IncompatibleClassChangeError
1336 (_Jv_GetMethodString (klass, meth->name));
1337 if (Modifier::isAbstract(meth->accflags))
1338 throw new java::lang::AbstractMethodError
1339 (_Jv_GetMethodString (klass, meth->name));
1340 if (! Modifier::isPublic(meth->accflags))
1341 throw new java::lang::IllegalAccessError
1342 (_Jv_GetMethodString (klass, meth->name));
1343
1344 itable[pos] = meth->ncode;
1345 }
1346 else
1347 {
1348 // The method doesn't exist in klass. Binary compatibility rules
1349 // permit this, so we delay the error until runtime using a pointer
1350 // to a method which throws an exception.
1351 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
1352 }
1353 pos++;
1354 }
1355
1356 return pos;
1357 }
1358
1359 static _Jv_Mutex_t iindex_mutex;
1360 bool iindex_mutex_initialized = false;
1361
1362 // We need to find the correct offset in the Class Interface Dispatch
1363 // Table for a given interface. Once we have that, invoking an interface
1364 // method just requires combining the Method's index in the interface
1365 // (known at compile time) to get the correct method. Doing a type test
1366 // (cast or instanceof) is the same problem: Once we have a possible Partial
1367 // Interface Dispatch Table, we just compare the first element to see if it
1368 // matches the desired interface. So how can we find the correct offset?
1369 // Our solution is to keep a vector of candiate offsets in each interface
1370 // (idt->iface.ioffsets), and in each class we have an index
1371 // (idt->cls.iindex) used to select the correct offset from ioffsets.
1372 //
1373 // Calculate and return iindex for a new class.
1374 // ifaces is a vector of num interfaces that the class implements.
1375 // offsets[j] is the offset in the interface dispatch table for the
1376 // interface corresponding to ifaces[j].
1377 // May extend the interface ioffsets if required.
1378 jshort
1379 _Jv_FindIIndex (jclass *ifaces, jshort *offsets, jshort num)
1380 {
1381 int i;
1382 int j;
1383
1384 // Acquire a global lock to prevent itable corruption in case of multiple
1385 // classes that implement an intersecting set of interfaces being linked
1386 // simultaneously. We can assume that the mutex will be initialized
1387 // single-threaded.
1388 if (! iindex_mutex_initialized)
1389 {
1390 _Jv_MutexInit (&iindex_mutex);
1391 iindex_mutex_initialized = true;
1392 }
1393
1394 _Jv_MutexLock (&iindex_mutex);
1395
1396 for (i=1;; i++) /* each potential position in ioffsets */
1397 {
1398 for (j=0;; j++) /* each iface */
1399 {
1400 if (j >= num)
1401 goto found;
1402 if (i >= ifaces[j]->idt->iface.ioffsets[0])
1403 continue;
1404 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
1405 /* We can potentially share this position with another class. */
1406 if (ioffset >= 0 && ioffset != offsets[j])
1407 break; /* Nope. Try next i. */
1408 }
1409 }
1410 found:
1411 for (j = 0; j < num; j++)
1412 {
1413 int len = ifaces[j]->idt->iface.ioffsets[0];
1414 if (i >= len)
1415 {
1416 /* Resize ioffsets. */
1417 int newlen = 2 * len;
1418 if (i >= newlen)
1419 newlen = i + 3;
1420 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
1421 jshort *new_ioffsets = (jshort *) _Jv_Realloc (old_ioffsets,
1422 newlen * sizeof(jshort));
1423 new_ioffsets[0] = newlen;
1424
1425 while (len < newlen)
1426 new_ioffsets[len++] = -1;
1427
1428 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
1429 }
1430 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
1431 }
1432
1433 _Jv_MutexUnlock (&iindex_mutex);
1434
1435 return i;
1436 }
1437
1438 // Only used by serialization
1439 java::lang::reflect::Field *
1440 java::lang::Class::getPrivateField (jstring name)
1441 {
1442 int hash = name->hashCode ();
1443
1444 java::lang::reflect::Field* rfield;
1445 for (int i = 0; i < field_count; i++)
1446 {
1447 _Jv_Field *field = &fields[i];
1448 if (! _Jv_equal (field->name, name, hash))
1449 continue;
1450 rfield = new java::lang::reflect::Field ();
1451 rfield->offset = (char*) field - (char*) fields;
1452 rfield->declaringClass = this;
1453 rfield->name = name;
1454 return rfield;
1455 }
1456 jclass superclass = getSuperclass();
1457 if (superclass == NULL)
1458 return NULL;
1459 rfield = superclass->getPrivateField(name);
1460 for (int i = 0; i < interface_count && rfield == NULL; ++i)
1461 rfield = interfaces[i]->getPrivateField (name);
1462 return rfield;
1463 }
1464
1465 // Only used by serialization
1466 java::lang::reflect::Method *
1467 java::lang::Class::getPrivateMethod (jstring name, JArray<jclass> *param_types)
1468 {
1469 jstring partial_sig = getSignature (param_types, false);
1470 jint p_len = partial_sig->length();
1471 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
1472 for (Class *klass = this; klass; klass = klass->getSuperclass())
1473 {
1474 int i = klass->isPrimitive () ? 0 : klass->method_count;
1475 while (--i >= 0)
1476 {
1477 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
1478 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
1479 {
1480 // Found it.
1481 using namespace java::lang::reflect;
1482
1483 Method *rmethod = new Method ();
1484 rmethod->offset = ((char *) (&klass->methods[i])
1485 - (char *) klass->methods);
1486 rmethod->declaringClass = klass;
1487 return rmethod;
1488 }
1489 }
1490 }
1491 throw new java::lang::NoSuchMethodException;
1492 }
1493
1494 // Private accessor method for Java code to retrieve the protection domain.
1495 java::security::ProtectionDomain *
1496 java::lang::Class::getProtectionDomain0 ()
1497 {
1498 return protectionDomain;
1499 }
1500
1501 // Functions for indirect dispatch (symbolic virtual method binding) support.
1502
1503 // Resolve entries in the virtual method offset symbol table
1504 // (klass->otable_syms). The vtable offset (in bytes) for each resolved method
1505 // is placed at the corresponding position in the virtual method offset table
1506 // (klass->otable). A single otable and otable_syms pair may be shared by many
1507 // classes.
1508 void
1509 _Jv_LinkOffsetTable(jclass klass)
1510 {
1511 //// FIXME: Need to lock the otable ////
1512
1513 if (klass->otable == NULL
1514 || klass->otable->state != 0)
1515 return;
1516
1517 klass->otable->state = 1;
1518
1519 int index = 0;
1520 _Jv_MethodSymbol sym = klass->otable_syms[0];
1521
1522 while (sym.name != NULL)
1523 {
1524 jclass target_class = _Jv_FindClass (sym.class_name, NULL);
1525 _Jv_Method *meth = NULL;
1526
1527 if (target_class != NULL)
1528 if (target_class->isInterface())
1529 {
1530 // FIXME: This does not yet fully conform to binary compatibility
1531 // rules. It will break if a declaration is moved into a
1532 // superinterface.
1533 for (int i=0; i < target_class->method_count; i++)
1534 {
1535 meth = &target_class->methods[i];
1536 if (_Jv_equalUtf8Consts (sym.name, meth->name)
1537 && _Jv_equalUtf8Consts (sym.signature, meth->signature))
1538 {
1539 klass->otable->offsets[index] = i + 1;
1540 break;
1541 }
1542 }
1543 }
1544 else
1545 {
1546 // If the target class does not have a vtable_method_count yet,
1547 // then we can't tell the offsets for its methods, so we must lay
1548 // it out now.
1549 if (target_class->vtable_method_count == -1)
1550 {
1551 JvSynchronize sync (target_class);
1552 _Jv_LayoutVTableMethods (target_class);
1553 }
1554
1555 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1556 sym.signature);
1557
1558 if (meth != NULL)
1559 {
1560 klass->otable->offsets[index] =
1561 _Jv_VTable::idx_to_offset (meth->index);
1562 }
1563 }
1564
1565 if (meth == NULL)
1566 // FIXME: This should be special index for ThrowNoSuchMethod().
1567 klass->otable->offsets[index] = -1;
1568
1569 sym = klass->otable_syms[++index];
1570 }
1571 }
1572
1573 // Returns true if METH should get an entry in a VTable.
1574 static jboolean
1575 isVirtualMethod (_Jv_Method *meth)
1576 {
1577 using namespace java::lang::reflect;
1578 return (((meth->accflags & (Modifier::STATIC | Modifier::PRIVATE)) == 0)
1579 && meth->name->data[0] != '<');
1580 }
1581
1582 // This is put in empty vtable slots.
1583 static void
1584 _Jv_abstractMethodError (void)
1585 {
1586 throw new java::lang::AbstractMethodError();
1587 }
1588
1589 // Prepare virtual method declarations in KLASS, and any superclasses as
1590 // required, by determining their vtable index, setting method->index, and
1591 // finally setting the class's vtable_method_count. Must be called with the
1592 // lock for KLASS held.
1593 void
1594 _Jv_LayoutVTableMethods (jclass klass)
1595 {
1596 if (klass->vtable != NULL || klass->isInterface()
1597 || klass->vtable_method_count != -1)
1598 return;
1599
1600 jclass superclass = klass->superclass;
1601
1602 if (superclass != NULL && superclass->vtable_method_count == -1)
1603 {
1604 JvSynchronize sync (superclass);
1605 _Jv_LayoutVTableMethods (superclass);
1606 }
1607
1608 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1609
1610 for (int i = 0; i < klass->method_count; ++i)
1611 {
1612 _Jv_Method *meth = &klass->methods[i];
1613 _Jv_Method *super_meth = NULL;
1614
1615 if (! isVirtualMethod (meth))
1616 continue;
1617
1618 if (superclass != NULL)
1619 {
1620 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1621 meth->signature);
1622 }
1623
1624 if (super_meth)
1625 meth->index = super_meth->index;
1626 else if (! (meth->accflags & java::lang::reflect::Modifier::FINAL)
1627 && ! (klass->accflags & java::lang::reflect::Modifier::FINAL))
1628 meth->index = index++;
1629 }
1630
1631 klass->vtable_method_count = index;
1632 }
1633
1634 // Set entries in VTABLE for virtual methods declared in KLASS. If
1635 // KLASS has an immediate abstract parent, recursively do its methods
1636 // first. FLAGS is used to determine which slots we've actually set.
1637 void
1638 _Jv_SetVTableEntries (jclass klass, _Jv_VTable *vtable, jboolean *flags)
1639 {
1640 using namespace java::lang::reflect;
1641
1642 jclass superclass = klass->getSuperclass();
1643
1644 if (superclass != NULL && (superclass->getModifiers() & Modifier::ABSTRACT))
1645 _Jv_SetVTableEntries (superclass, vtable, flags);
1646
1647 for (int i = klass->method_count - 1; i >= 0; i--)
1648 {
1649 _Jv_Method *meth = &klass->methods[i];
1650 if (meth->index == (_Jv_ushort) -1)
1651 continue;
1652 if ((meth->accflags & Modifier::ABSTRACT))
1653 {
1654 vtable->set_method(meth->index, (void *) &_Jv_abstractMethodError);
1655 flags[meth->index] = false;
1656 }
1657 else
1658 {
1659 vtable->set_method(meth->index, meth->ncode);
1660 flags[meth->index] = true;
1661 }
1662 }
1663 }
1664
1665 // Allocate and lay out the virtual method table for KLASS. This will also
1666 // cause vtables to be generated for any non-abstract superclasses, and
1667 // virtual method layout to occur for any abstract superclasses. Must be
1668 // called with monitor lock for KLASS held.
1669 void
1670 _Jv_MakeVTable (jclass klass)
1671 {
1672 using namespace java::lang::reflect;
1673
1674 if (klass->vtable != NULL || klass->isInterface()
1675 || (klass->accflags & Modifier::ABSTRACT))
1676 return;
1677
1678 // out before we can create a vtable.
1679 if (klass->vtable_method_count == -1)
1680 _Jv_LayoutVTableMethods (klass);
1681
1682 // Allocate the new vtable.
1683 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1684 klass->vtable = vtable;
1685
1686 jboolean flags[klass->vtable_method_count];
1687 for (int i = 0; i < klass->vtable_method_count; ++i)
1688 flags[i] = false;
1689
1690 // Copy the vtable of the closest non-abstract superclass.
1691 jclass superclass = klass->superclass;
1692 if (superclass != NULL)
1693 {
1694 while ((superclass->accflags & Modifier::ABSTRACT) != 0)
1695 superclass = superclass->superclass;
1696
1697 if (superclass->vtable == NULL)
1698 {
1699 JvSynchronize sync (superclass);
1700 _Jv_MakeVTable (superclass);
1701 }
1702
1703 for (int i = 0; i < superclass->vtable_method_count; ++i)
1704 {
1705 vtable->set_method (i, superclass->vtable->get_method (i));
1706 flags[i] = true;
1707 }
1708 }
1709
1710 // Set the class pointer and GC descriptor.
1711 vtable->clas = klass;
1712 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1713
1714 // For each virtual declared in klass and any immediate abstract
1715 // superclasses, set new vtable entry or override an old one.
1716 _Jv_SetVTableEntries (klass, vtable, flags);
1717
1718 // It is an error to have an abstract method in a concrete class.
1719 if (! (klass->accflags & Modifier::ABSTRACT))
1720 {
1721 for (int i = 0; i < klass->vtable_method_count; ++i)
1722 if (! flags[i])
1723 // FIXME: messsage.
1724 throw new java::lang::AbstractMethodError ();
1725 }
1726 }