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