768ced611ac2cb9500614c2d8de44e12c1ff5943
[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 if (state <= JV_STATE_LINKED)
762 _Jv_PrepareConstantTimeTables (this);
763
764 // Step 2.
765 java::lang::Thread *self = java::lang::Thread::currentThread();
766 // FIXME: `self' can be null at startup. Hence this nasty trick.
767 self = (java::lang::Thread *) ((long) self | 1);
768 while (state == JV_STATE_IN_PROGRESS && thread && thread != self)
769 wait ();
770
771 // Steps 3 & 4.
772 if (state == JV_STATE_DONE || state == JV_STATE_IN_PROGRESS)
773 {
774 _Jv_MonitorExit (this);
775 return;
776 }
777
778 // Step 5.
779 if (state == JV_STATE_ERROR)
780 {
781 _Jv_MonitorExit (this);
782 throw new java::lang::NoClassDefFoundError (getName());
783 }
784
785 // Step 6.
786 thread = self;
787 state = JV_STATE_IN_PROGRESS;
788 _Jv_MonitorExit (this);
789
790 // Step 7.
791 if (! isInterface () && superclass)
792 {
793 try
794 {
795 _Jv_InitClass (superclass);
796 }
797 catch (java::lang::Throwable *except)
798 {
799 // Caught an exception.
800 _Jv_MonitorEnter (this);
801 state = JV_STATE_ERROR;
802 notifyAll ();
803 _Jv_MonitorExit (this);
804 throw except;
805 }
806 }
807
808 // Steps 8, 9, 10, 11.
809 try
810 {
811 _Jv_Method *meth = _Jv_GetMethodLocal (this, clinit_name,
812 void_signature);
813 if (meth)
814 ((void (*) (void)) meth->ncode) ();
815 }
816 catch (java::lang::Throwable *except)
817 {
818 if (! java::lang::Error::class$.isInstance(except))
819 {
820 try
821 {
822 except = new ExceptionInInitializerError (except);
823 }
824 catch (java::lang::Throwable *t)
825 {
826 except = t;
827 }
828 }
829 _Jv_MonitorEnter (this);
830 state = JV_STATE_ERROR;
831 notifyAll ();
832 _Jv_MonitorExit (this);
833 throw except;
834 }
835
836 _Jv_MonitorEnter (this);
837 state = JV_STATE_DONE;
838 notifyAll ();
839 _Jv_MonitorExit (this);
840 }
841
842 \f
843
844 //
845 // Some class-related convenience functions.
846 //
847
848 // Find a method declared in the class. If it is not declared locally
849 // (or if it is inherited), return NULL.
850 _Jv_Method *
851 _Jv_GetMethodLocal (jclass klass, _Jv_Utf8Const *name,
852 _Jv_Utf8Const *signature)
853 {
854 for (int i = 0; i < klass->method_count; ++i)
855 {
856 if (_Jv_equalUtf8Consts (name, klass->methods[i].name)
857 && _Jv_equalUtf8Consts (signature, klass->methods[i].signature))
858 return &klass->methods[i];
859 }
860 return NULL;
861 }
862
863 _Jv_Method *
864 _Jv_LookupDeclaredMethod (jclass klass, _Jv_Utf8Const *name,
865 _Jv_Utf8Const *signature)
866 {
867 for (; klass; klass = klass->getSuperclass())
868 {
869 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
870
871 if (meth)
872 return meth;
873 }
874
875 return NULL;
876 }
877
878 // NOTE: MCACHE_SIZE should be a power of 2 minus one.
879 #define MCACHE_SIZE 1023
880
881 struct _Jv_mcache
882 {
883 jclass klass;
884 _Jv_Method *method;
885 };
886
887 static _Jv_mcache method_cache[MCACHE_SIZE + 1];
888
889 static void *
890 _Jv_FindMethodInCache (jclass klass,
891 _Jv_Utf8Const *name,
892 _Jv_Utf8Const *signature)
893 {
894 int index = name->hash & MCACHE_SIZE;
895 _Jv_mcache *mc = method_cache + index;
896 _Jv_Method *m = mc->method;
897
898 if (mc->klass == klass
899 && m != NULL // thread safe check
900 && _Jv_equalUtf8Consts (m->name, name)
901 && _Jv_equalUtf8Consts (m->signature, signature))
902 return mc->method->ncode;
903 return NULL;
904 }
905
906 static void
907 _Jv_AddMethodToCache (jclass klass,
908 _Jv_Method *method)
909 {
910 _Jv_MonitorEnter (&java::lang::Class::class$);
911
912 int index = method->name->hash & MCACHE_SIZE;
913
914 method_cache[index].method = method;
915 method_cache[index].klass = klass;
916
917 _Jv_MonitorExit (&java::lang::Class::class$);
918 }
919
920 void *
921 _Jv_LookupInterfaceMethod (jclass klass, _Jv_Utf8Const *name,
922 _Jv_Utf8Const *signature)
923 {
924 using namespace java::lang::reflect;
925
926 void *ncode = _Jv_FindMethodInCache (klass, name, signature);
927 if (ncode != 0)
928 return ncode;
929
930 for (; klass; klass = klass->getSuperclass())
931 {
932 _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
933 if (! meth)
934 continue;
935
936 if (Modifier::isStatic(meth->accflags))
937 throw new java::lang::IncompatibleClassChangeError
938 (_Jv_GetMethodString (klass, meth->name));
939 if (Modifier::isAbstract(meth->accflags))
940 throw new java::lang::AbstractMethodError
941 (_Jv_GetMethodString (klass, meth->name));
942 if (! Modifier::isPublic(meth->accflags))
943 throw new java::lang::IllegalAccessError
944 (_Jv_GetMethodString (klass, meth->name));
945
946 _Jv_AddMethodToCache (klass, meth);
947
948 return meth->ncode;
949 }
950 throw new java::lang::IncompatibleClassChangeError;
951 }
952
953 // Fast interface method lookup by index.
954 void *
955 _Jv_LookupInterfaceMethodIdx (jclass klass, jclass iface, int method_idx)
956 {
957 _Jv_IDispatchTable *cldt = klass->idt;
958 int idx = iface->idt->iface.ioffsets[cldt->cls.iindex] + method_idx;
959 return cldt->cls.itable[idx];
960 }
961
962 jboolean
963 _Jv_IsAssignableFrom (jclass target, jclass source)
964 {
965 if (source == target)
966 return true;
967
968 // If target is array, so must source be.
969 if (target->isArray ())
970 {
971 if (! source->isArray())
972 return false;
973 return _Jv_IsAssignableFrom(target->getComponentType(),
974 source->getComponentType());
975 }
976
977 if (target->isInterface())
978 {
979 // Abstract classes have no IDT, and IDTs provide no way to check
980 // two interfaces for assignability.
981 if (__builtin_expect
982 (source->idt == NULL || source->isInterface(), false))
983 return _Jv_InterfaceAssignableFrom (target, source);
984
985 _Jv_IDispatchTable *cl_idt = source->idt;
986 _Jv_IDispatchTable *if_idt = target->idt;
987
988 if (__builtin_expect ((if_idt == NULL), false))
989 return false; // No class implementing TARGET has been loaded.
990 jshort cl_iindex = cl_idt->cls.iindex;
991 if (cl_iindex < if_idt->iface.ioffsets[0])
992 {
993 jshort offset = if_idt->iface.ioffsets[cl_iindex];
994 if (offset != -1 && offset < cl_idt->cls.itable_length
995 && cl_idt->cls.itable[offset] == target)
996 return true;
997 }
998 return false;
999 }
1000
1001 // Primitive TYPE classes are only assignable to themselves.
1002 if (__builtin_expect (target->isPrimitive(), false))
1003 return false;
1004
1005 if (target == &java::lang::Object::class$)
1006 {
1007 if (source->isPrimitive())
1008 return false;
1009 return true;
1010 }
1011 else if (source->ancestors != NULL
1012 && target->ancestors != NULL
1013 && source->depth >= target->depth
1014 && source->ancestors[source->depth - target->depth] == target)
1015 return true;
1016
1017 return false;
1018 }
1019
1020 // Interface type checking, the slow way. Returns TRUE if IFACE is a
1021 // superinterface of SOURCE. This is used when SOURCE is also an interface,
1022 // or a class with no interface dispatch table.
1023 jboolean
1024 _Jv_InterfaceAssignableFrom (jclass iface, jclass source)
1025 {
1026 for (int i = 0; i < source->interface_count; i++)
1027 {
1028 jclass interface = source->interfaces[i];
1029 if (iface == interface
1030 || _Jv_InterfaceAssignableFrom (iface, interface))
1031 return true;
1032 }
1033
1034 if (!source->isInterface()
1035 && source->superclass
1036 && _Jv_InterfaceAssignableFrom (iface, source->superclass))
1037 return true;
1038
1039 return false;
1040 }
1041
1042 jboolean
1043 _Jv_IsInstanceOf(jobject obj, jclass cl)
1044 {
1045 if (__builtin_expect (!obj, false))
1046 return false;
1047 return (_Jv_IsAssignableFrom (cl, JV_CLASS (obj)));
1048 }
1049
1050 void *
1051 _Jv_CheckCast (jclass c, jobject obj)
1052 {
1053 if (__builtin_expect
1054 (obj != NULL && ! _Jv_IsAssignableFrom(c, JV_CLASS (obj)), false))
1055 throw new java::lang::ClassCastException
1056 ((new java::lang::StringBuffer
1057 (obj->getClass()->getName()))->append
1058 (JvNewStringUTF(" cannot be cast to "))->append
1059 (c->getName())->toString());
1060
1061 return obj;
1062 }
1063
1064 void
1065 _Jv_CheckArrayStore (jobject arr, jobject obj)
1066 {
1067 if (obj)
1068 {
1069 JvAssert (arr != NULL);
1070 jclass elt_class = (JV_CLASS (arr))->getComponentType();
1071 if (elt_class == &java::lang::Object::class$)
1072 return;
1073 jclass obj_class = JV_CLASS (obj);
1074 if (__builtin_expect
1075 (! _Jv_IsAssignableFrom (elt_class, obj_class), false))
1076 throw new java::lang::ArrayStoreException
1077 ((new java::lang::StringBuffer
1078 (JvNewStringUTF("Cannot store ")))->append
1079 (obj_class->getName())->append
1080 (JvNewStringUTF(" in array of type "))->append
1081 (elt_class->getName())->toString());
1082 }
1083 }
1084
1085 #define INITIAL_IOFFSETS_LEN 4
1086 #define INITIAL_IFACES_LEN 4
1087
1088 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
1089
1090 // Generate tables for constant-time assignment testing and interface
1091 // method lookup. This implements the technique described by Per Bothner
1092 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
1093 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
1094 void
1095 _Jv_PrepareConstantTimeTables (jclass klass)
1096 {
1097 if (klass->isPrimitive () || klass->isInterface ())
1098 return;
1099
1100 // Short-circuit in case we've been called already.
1101 if ((klass->idt != NULL) || klass->depth != 0)
1102 return;
1103
1104 // Calculate the class depth and ancestor table. The depth of a class
1105 // is how many "extends" it is removed from Object. Thus the depth of
1106 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
1107 // is 2. Depth is defined for all regular and array classes, but not
1108 // interfaces or primitive types.
1109
1110 jclass klass0 = klass;
1111 jboolean has_interfaces = 0;
1112 while (klass0 != &java::lang::Object::class$)
1113 {
1114 has_interfaces += klass0->interface_count;
1115 klass0 = klass0->superclass;
1116 klass->depth++;
1117 }
1118
1119 // We do class member testing in constant time by using a small table
1120 // of all the ancestor classes within each class. The first element is
1121 // a pointer to the current class, and the rest are pointers to the
1122 // classes ancestors, ordered from the current class down by decreasing
1123 // depth. We do not include java.lang.Object in the table of ancestors,
1124 // since it is redundant.
1125
1126 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth * sizeof (jclass));
1127 klass0 = klass;
1128 for (int index = 0; index < klass->depth; index++)
1129 {
1130 klass->ancestors[index] = klass0;
1131 klass0 = klass0->superclass;
1132 }
1133
1134 if (java::lang::reflect::Modifier::isAbstract (klass->accflags))
1135 return;
1136
1137 // Optimization: If class implements no interfaces, use a common
1138 // predefined interface table.
1139 if (!has_interfaces)
1140 {
1141 klass->idt = &null_idt;
1142 return;
1143 }
1144
1145 klass->idt =
1146 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1147
1148 _Jv_ifaces ifaces;
1149
1150 ifaces.count = 0;
1151 ifaces.len = INITIAL_IFACES_LEN;
1152 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
1153
1154 int itable_size = _Jv_GetInterfaces (klass, &ifaces);
1155
1156 if (ifaces.count > 0)
1157 {
1158 klass->idt->cls.itable =
1159 (void **) _Jv_Malloc (itable_size * sizeof (void *));
1160 klass->idt->cls.itable_length = itable_size;
1161
1162 jshort *itable_offsets =
1163 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
1164
1165 _Jv_GenerateITable (klass, &ifaces, itable_offsets);
1166
1167 jshort cls_iindex =
1168 _Jv_FindIIndex (ifaces.list, itable_offsets, ifaces.count);
1169
1170 for (int i=0; i < ifaces.count; i++)
1171 {
1172 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
1173 itable_offsets[i];
1174 }
1175
1176 klass->idt->cls.iindex = cls_iindex;
1177
1178 _Jv_Free (ifaces.list);
1179 _Jv_Free (itable_offsets);
1180 }
1181 else
1182 {
1183 klass->idt->cls.iindex = SHRT_MAX;
1184 }
1185 }
1186
1187 // Return index of item in list, or -1 if item is not present.
1188 inline jshort
1189 _Jv_IndexOf (void *item, void **list, jshort list_len)
1190 {
1191 for (int i=0; i < list_len; i++)
1192 {
1193 if (list[i] == item)
1194 return i;
1195 }
1196 return -1;
1197 }
1198
1199 // Find all unique interfaces directly or indirectly implemented by klass.
1200 // Returns the size of the interface dispatch table (itable) for klass, which
1201 // is the number of unique interfaces plus the total number of methods that
1202 // those interfaces declare. May extend ifaces if required.
1203 jshort
1204 _Jv_GetInterfaces (jclass klass, _Jv_ifaces *ifaces)
1205 {
1206 jshort result = 0;
1207
1208 for (int i=0; i < klass->interface_count; i++)
1209 {
1210 jclass iface = klass->interfaces[i];
1211 if (_Jv_IndexOf (iface, (void **) ifaces->list, ifaces->count) == -1)
1212 {
1213 if (ifaces->count + 1 >= ifaces->len)
1214 {
1215 /* Resize ifaces list */
1216 ifaces->len = ifaces->len * 2;
1217 ifaces->list = (jclass *) _Jv_Realloc (ifaces->list,
1218 ifaces->len * sizeof(jclass));
1219 }
1220 ifaces->list[ifaces->count] = iface;
1221 ifaces->count++;
1222
1223 result += _Jv_GetInterfaces (klass->interfaces[i], ifaces);
1224 }
1225 }
1226
1227 if (klass->isInterface())
1228 {
1229 result += klass->method_count + 1;
1230 }
1231 else
1232 {
1233 if (klass->superclass)
1234 {
1235 result += _Jv_GetInterfaces (klass->superclass, ifaces);
1236 }
1237 }
1238 return result;
1239 }
1240
1241 // Fill out itable in klass, resolving method declarations in each ifaces.
1242 // itable_offsets is filled out with the position of each iface in itable,
1243 // such that itable[itable_offsets[n]] == ifaces.list[n].
1244 void
1245 _Jv_GenerateITable (jclass klass, _Jv_ifaces *ifaces, jshort *itable_offsets)
1246 {
1247 void **itable = klass->idt->cls.itable;
1248 jshort itable_pos = 0;
1249
1250 for (int i=0; i < ifaces->count; i++)
1251 {
1252 jclass iface = ifaces->list[i];
1253 itable_offsets[i] = itable_pos;
1254 itable_pos = _Jv_AppendPartialITable (klass, iface, itable, itable_pos);
1255
1256 /* Create interface dispatch table for iface */
1257 if (iface->idt == NULL)
1258 {
1259 iface->idt =
1260 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
1261
1262 // The first element of ioffsets is its length (itself included).
1263 jshort *ioffsets =
1264 (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN * sizeof (jshort));
1265 ioffsets[0] = INITIAL_IOFFSETS_LEN;
1266 for (int i=1; i < INITIAL_IOFFSETS_LEN; i++)
1267 ioffsets[i] = -1;
1268
1269 iface->idt->iface.ioffsets = ioffsets;
1270 }
1271 }
1272 }
1273
1274 // Format method name for use in error messages.
1275 jstring
1276 _Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
1277 {
1278 jstring r = JvNewStringUTF (klass->name->data);
1279 r = r->concat (JvNewStringUTF ("."));
1280 r = r->concat (JvNewStringUTF (name->data));
1281 return r;
1282 }
1283
1284 void
1285 _Jv_ThrowNoSuchMethodError ()
1286 {
1287 throw new java::lang::NoSuchMethodError;
1288 }
1289
1290 // Each superinterface of a class (i.e. each interface that the class
1291 // directly or indirectly implements) has a corresponding "Partial
1292 // Interface Dispatch Table" whose size is (number of methods + 1) words.
1293 // The first word is a pointer to the interface (i.e. the java.lang.Class
1294 // instance for that interface). The remaining words are pointers to the
1295 // actual methods that implement the methods declared in the interface,
1296 // in order of declaration.
1297 //
1298 // Append partial interface dispatch table for "iface" to "itable", at
1299 // position itable_pos.
1300 // Returns the offset at which the next partial ITable should be appended.
1301 jshort
1302 _Jv_AppendPartialITable (jclass klass, jclass iface, void **itable,
1303 jshort pos)
1304 {
1305 using namespace java::lang::reflect;
1306
1307 itable[pos++] = (void *) iface;
1308 _Jv_Method *meth;
1309
1310 for (int j=0; j < iface->method_count; j++)
1311 {
1312 meth = NULL;
1313 for (jclass cl = klass; cl; cl = cl->getSuperclass())
1314 {
1315 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
1316 iface->methods[j].signature);
1317
1318 if (meth)
1319 break;
1320 }
1321
1322 if (meth && (meth->name->data[0] == '<'))
1323 {
1324 // leave a placeholder in the itable for hidden init methods.
1325 itable[pos] = NULL;
1326 }
1327 else if (meth)
1328 {
1329 if (Modifier::isStatic(meth->accflags))
1330 throw new java::lang::IncompatibleClassChangeError
1331 (_Jv_GetMethodString (klass, meth->name));
1332 if (Modifier::isAbstract(meth->accflags))
1333 throw new java::lang::AbstractMethodError
1334 (_Jv_GetMethodString (klass, meth->name));
1335 if (! Modifier::isPublic(meth->accflags))
1336 throw new java::lang::IllegalAccessError
1337 (_Jv_GetMethodString (klass, meth->name));
1338
1339 itable[pos] = meth->ncode;
1340 }
1341 else
1342 {
1343 // The method doesn't exist in klass. Binary compatibility rules
1344 // permit this, so we delay the error until runtime using a pointer
1345 // to a method which throws an exception.
1346 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
1347 }
1348 pos++;
1349 }
1350
1351 return pos;
1352 }
1353
1354 static _Jv_Mutex_t iindex_mutex;
1355 bool iindex_mutex_initialized = false;
1356
1357 // We need to find the correct offset in the Class Interface Dispatch
1358 // Table for a given interface. Once we have that, invoking an interface
1359 // method just requires combining the Method's index in the interface
1360 // (known at compile time) to get the correct method. Doing a type test
1361 // (cast or instanceof) is the same problem: Once we have a possible Partial
1362 // Interface Dispatch Table, we just compare the first element to see if it
1363 // matches the desired interface. So how can we find the correct offset?
1364 // Our solution is to keep a vector of candiate offsets in each interface
1365 // (idt->iface.ioffsets), and in each class we have an index
1366 // (idt->cls.iindex) used to select the correct offset from ioffsets.
1367 //
1368 // Calculate and return iindex for a new class.
1369 // ifaces is a vector of num interfaces that the class implements.
1370 // offsets[j] is the offset in the interface dispatch table for the
1371 // interface corresponding to ifaces[j].
1372 // May extend the interface ioffsets if required.
1373 jshort
1374 _Jv_FindIIndex (jclass *ifaces, jshort *offsets, jshort num)
1375 {
1376 int i;
1377 int j;
1378
1379 // Acquire a global lock to prevent itable corruption in case of multiple
1380 // classes that implement an intersecting set of interfaces being linked
1381 // simultaneously. We can assume that the mutex will be initialized
1382 // single-threaded.
1383 if (! iindex_mutex_initialized)
1384 {
1385 _Jv_MutexInit (&iindex_mutex);
1386 iindex_mutex_initialized = true;
1387 }
1388
1389 _Jv_MutexLock (&iindex_mutex);
1390
1391 for (i=1;; i++) /* each potential position in ioffsets */
1392 {
1393 for (j=0;; j++) /* each iface */
1394 {
1395 if (j >= num)
1396 goto found;
1397 if (i >= ifaces[j]->idt->iface.ioffsets[0])
1398 continue;
1399 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
1400 /* We can potentially share this position with another class. */
1401 if (ioffset >= 0 && ioffset != offsets[j])
1402 break; /* Nope. Try next i. */
1403 }
1404 }
1405 found:
1406 for (j = 0; j < num; j++)
1407 {
1408 int len = ifaces[j]->idt->iface.ioffsets[0];
1409 if (i >= len)
1410 {
1411 /* Resize ioffsets. */
1412 int newlen = 2 * len;
1413 if (i >= newlen)
1414 newlen = i + 3;
1415 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
1416 jshort *new_ioffsets = (jshort *) _Jv_Realloc (old_ioffsets,
1417 newlen * sizeof(jshort));
1418 new_ioffsets[0] = newlen;
1419
1420 while (len < newlen)
1421 new_ioffsets[len++] = -1;
1422
1423 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
1424 }
1425 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
1426 }
1427
1428 _Jv_MutexUnlock (&iindex_mutex);
1429
1430 return i;
1431 }
1432
1433 // Only used by serialization
1434 java::lang::reflect::Field *
1435 java::lang::Class::getPrivateField (jstring name)
1436 {
1437 int hash = name->hashCode ();
1438
1439 java::lang::reflect::Field* rfield;
1440 for (int i = 0; i < field_count; i++)
1441 {
1442 _Jv_Field *field = &fields[i];
1443 if (! _Jv_equal (field->name, name, hash))
1444 continue;
1445 rfield = new java::lang::reflect::Field ();
1446 rfield->offset = (char*) field - (char*) fields;
1447 rfield->declaringClass = this;
1448 rfield->name = name;
1449 return rfield;
1450 }
1451 jclass superclass = getSuperclass();
1452 if (superclass == NULL)
1453 return NULL;
1454 rfield = superclass->getPrivateField(name);
1455 for (int i = 0; i < interface_count && rfield == NULL; ++i)
1456 rfield = interfaces[i]->getPrivateField (name);
1457 return rfield;
1458 }
1459
1460 // Only used by serialization
1461 java::lang::reflect::Method *
1462 java::lang::Class::getPrivateMethod (jstring name, JArray<jclass> *param_types)
1463 {
1464 jstring partial_sig = getSignature (param_types, false);
1465 jint p_len = partial_sig->length();
1466 _Jv_Utf8Const *utf_name = _Jv_makeUtf8Const (name);
1467 for (Class *klass = this; klass; klass = klass->getSuperclass())
1468 {
1469 int i = klass->isPrimitive () ? 0 : klass->method_count;
1470 while (--i >= 0)
1471 {
1472 if (_Jv_equalUtf8Consts (klass->methods[i].name, utf_name)
1473 && _Jv_equaln (klass->methods[i].signature, partial_sig, p_len))
1474 {
1475 // Found it.
1476 using namespace java::lang::reflect;
1477
1478 Method *rmethod = new Method ();
1479 rmethod->offset = ((char *) (&klass->methods[i])
1480 - (char *) klass->methods);
1481 rmethod->declaringClass = klass;
1482 return rmethod;
1483 }
1484 }
1485 }
1486 throw new java::lang::NoSuchMethodException;
1487 }
1488
1489 // Private accessor method for Java code to retrieve the protection domain.
1490 java::security::ProtectionDomain *
1491 java::lang::Class::getProtectionDomain0 ()
1492 {
1493 return protectionDomain;
1494 }
1495
1496 // Functions for indirect dispatch (symbolic virtual method binding) support.
1497
1498 // Resolve entries in the virtual method offset symbol table
1499 // (klass->otable_syms). The vtable offset (in bytes) for each resolved method
1500 // is placed at the corresponding position in the virtual method offset table
1501 // (klass->otable). A single otable and otable_syms pair may be shared by many
1502 // classes.
1503 void
1504 _Jv_LinkOffsetTable(jclass klass)
1505 {
1506 //// FIXME: Need to lock the otable ////
1507
1508 if (klass->otable == NULL
1509 || klass->otable->state != 0)
1510 return;
1511
1512 klass->otable->state = 1;
1513
1514 int index = 0;
1515 _Jv_MethodSymbol sym = klass->otable_syms[0];
1516
1517 while (sym.name != NULL)
1518 {
1519 jclass target_class = _Jv_FindClass (sym.class_name, NULL);
1520 _Jv_Method *meth = NULL;
1521
1522 if (target_class != NULL)
1523 if (target_class->isInterface())
1524 {
1525 // FIXME: This does not yet fully conform to binary compatibility
1526 // rules. It will break if a declaration is moved into a
1527 // superinterface.
1528 for (int i=0; i < target_class->method_count; i++)
1529 {
1530 meth = &target_class->methods[i];
1531 if (_Jv_equalUtf8Consts (sym.name, meth->name)
1532 && _Jv_equalUtf8Consts (sym.signature, meth->signature))
1533 {
1534 klass->otable->offsets[index] = i + 1;
1535 break;
1536 }
1537 }
1538 }
1539 else
1540 {
1541 // If the target class does not have a vtable_method_count yet,
1542 // then we can't tell the offsets for its methods, so we must lay
1543 // it out now.
1544 if (target_class->vtable_method_count == -1)
1545 {
1546 JvSynchronize sync (target_class);
1547 _Jv_LayoutVTableMethods (target_class);
1548 }
1549
1550 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1551 sym.signature);
1552
1553 if (meth != NULL)
1554 {
1555 klass->otable->offsets[index] =
1556 _Jv_VTable::idx_to_offset (meth->index);
1557 }
1558 }
1559
1560 if (meth == NULL)
1561 // FIXME: This should be special index for ThrowNoSuchMethod().
1562 klass->otable->offsets[index] = -1;
1563
1564 sym = klass->otable_syms[++index];
1565 }
1566 }
1567
1568 // Returns true if METH should get an entry in a VTable.
1569 static jboolean
1570 isVirtualMethod (_Jv_Method *meth)
1571 {
1572 using namespace java::lang::reflect;
1573 return (((meth->accflags & (Modifier::STATIC | Modifier::PRIVATE)) == 0)
1574 && meth->name->data[0] != '<');
1575 }
1576
1577 // This is put in empty vtable slots.
1578 static void
1579 _Jv_abstractMethodError (void)
1580 {
1581 throw new java::lang::AbstractMethodError();
1582 }
1583
1584 // Prepare virtual method declarations in KLASS, and any superclasses as
1585 // required, by determining their vtable index, setting method->index, and
1586 // finally setting the class's vtable_method_count. Must be called with the
1587 // lock for KLASS held.
1588 void
1589 _Jv_LayoutVTableMethods (jclass klass)
1590 {
1591 if (klass->vtable != NULL || klass->isInterface()
1592 || klass->vtable_method_count != -1)
1593 return;
1594
1595 jclass superclass = klass->superclass;
1596
1597 if (superclass != NULL && superclass->vtable_method_count == -1)
1598 {
1599 JvSynchronize sync (superclass);
1600 _Jv_LayoutVTableMethods (superclass);
1601 }
1602
1603 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1604
1605 for (int i = 0; i < klass->method_count; ++i)
1606 {
1607 _Jv_Method *meth = &klass->methods[i];
1608 _Jv_Method *super_meth = NULL;
1609
1610 if (! isVirtualMethod (meth))
1611 continue;
1612
1613 if (superclass != NULL)
1614 {
1615 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1616 meth->signature);
1617 }
1618
1619 if (super_meth)
1620 meth->index = super_meth->index;
1621 else if (! (meth->accflags & java::lang::reflect::Modifier::FINAL)
1622 && ! (klass->accflags & java::lang::reflect::Modifier::FINAL))
1623 meth->index = index++;
1624 }
1625
1626 klass->vtable_method_count = index;
1627 }
1628
1629 // Set entries in VTABLE for virtual methods declared in KLASS. If
1630 // KLASS has an immediate abstract parent, recursively do its methods
1631 // first. FLAGS is used to determine which slots we've actually set.
1632 void
1633 _Jv_SetVTableEntries (jclass klass, _Jv_VTable *vtable, jboolean *flags)
1634 {
1635 using namespace java::lang::reflect;
1636
1637 jclass superclass = klass->getSuperclass();
1638
1639 if (superclass != NULL && (superclass->getModifiers() & Modifier::ABSTRACT))
1640 _Jv_SetVTableEntries (superclass, vtable, flags);
1641
1642 for (int i = klass->method_count - 1; i >= 0; i--)
1643 {
1644 _Jv_Method *meth = &klass->methods[i];
1645 if (meth->index == (_Jv_ushort) -1)
1646 continue;
1647 if ((meth->accflags & Modifier::ABSTRACT))
1648 {
1649 vtable->set_method(meth->index, (void *) &_Jv_abstractMethodError);
1650 flags[meth->index] = false;
1651 }
1652 else
1653 {
1654 vtable->set_method(meth->index, meth->ncode);
1655 flags[meth->index] = true;
1656 }
1657 }
1658 }
1659
1660 // Allocate and lay out the virtual method table for KLASS. This will also
1661 // cause vtables to be generated for any non-abstract superclasses, and
1662 // virtual method layout to occur for any abstract superclasses. Must be
1663 // called with monitor lock for KLASS held.
1664 void
1665 _Jv_MakeVTable (jclass klass)
1666 {
1667 using namespace java::lang::reflect;
1668
1669 if (klass->vtable != NULL || klass->isInterface()
1670 || (klass->accflags & Modifier::ABSTRACT))
1671 return;
1672
1673 // out before we can create a vtable.
1674 if (klass->vtable_method_count == -1)
1675 _Jv_LayoutVTableMethods (klass);
1676
1677 // Allocate the new vtable.
1678 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1679 klass->vtable = vtable;
1680
1681 jboolean flags[klass->vtable_method_count];
1682 for (int i = 0; i < klass->vtable_method_count; ++i)
1683 flags[i] = false;
1684
1685 // Copy the vtable of the closest non-abstract superclass.
1686 jclass superclass = klass->superclass;
1687 if (superclass != NULL)
1688 {
1689 while ((superclass->accflags & Modifier::ABSTRACT) != 0)
1690 superclass = superclass->superclass;
1691
1692 if (superclass->vtable == NULL)
1693 {
1694 JvSynchronize sync (superclass);
1695 _Jv_MakeVTable (superclass);
1696 }
1697
1698 for (int i = 0; i < superclass->vtable_method_count; ++i)
1699 {
1700 vtable->set_method (i, superclass->vtable->get_method (i));
1701 flags[i] = true;
1702 }
1703 }
1704
1705 // Set the class pointer and GC descriptor.
1706 vtable->clas = klass;
1707 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1708
1709 // For each virtual declared in klass and any immediate abstract
1710 // superclasses, set new vtable entry or override an old one.
1711 _Jv_SetVTableEntries (klass, vtable, flags);
1712
1713 // It is an error to have an abstract method in a concrete class.
1714 if (! (klass->accflags & Modifier::ABSTRACT))
1715 {
1716 for (int i = 0; i < klass->vtable_method_count; ++i)
1717 if (! flags[i])
1718 // FIXME: messsage.
1719 throw new java::lang::AbstractMethodError ();
1720 }
1721 }