]> git.ipfire.org Git - thirdparty/gcc.git/blob - libjava/link.cc
re PR java/20056 ('verification failed: incompatible type on stack' with --indirect...
[thirdparty/gcc.git] / libjava / link.cc
1 // link.cc - Code for linking and resolving classes and pool entries.
2
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005 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 /* Author: Kresten Krab Thorup <krab@gnu.org> */
12
13 #include <config.h>
14 #include <platform.h>
15
16 #include <stdio.h>
17
18 #include <java-interp.h>
19
20 #include <jvm.h>
21 #include <gcj/cni.h>
22 #include <string.h>
23 #include <limits.h>
24 #include <java-cpool.h>
25 #include <execution.h>
26 #include <java/lang/Class.h>
27 #include <java/lang/String.h>
28 #include <java/lang/StringBuffer.h>
29 #include <java/lang/Thread.h>
30 #include <java/lang/InternalError.h>
31 #include <java/lang/VirtualMachineError.h>
32 #include <java/lang/VerifyError.h>
33 #include <java/lang/NoSuchFieldError.h>
34 #include <java/lang/NoSuchMethodError.h>
35 #include <java/lang/ClassFormatError.h>
36 #include <java/lang/IllegalAccessError.h>
37 #include <java/lang/AbstractMethodError.h>
38 #include <java/lang/NoClassDefFoundError.h>
39 #include <java/lang/IncompatibleClassChangeError.h>
40 #include <java/lang/VerifyError.h>
41 #include <java/lang/VMClassLoader.h>
42 #include <java/lang/reflect/Modifier.h>
43 #include <java/security/CodeSource.h>
44
45 using namespace gcj;
46
47 // When true, print debugging information about class loading.
48 bool gcj::verbose_class_flag;
49
50 typedef unsigned int uaddr __attribute__ ((mode (pointer)));
51
52 template<typename T>
53 struct aligner
54 {
55 char c;
56 T field;
57 };
58
59 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
60
61 // This returns the alignment of a type as it would appear in a
62 // structure. This can be different from the alignment of the type
63 // itself. For instance on x86 double is 8-aligned but struct{double}
64 // is 4-aligned.
65 int
66 _Jv_Linker::get_alignment_from_class (jclass klass)
67 {
68 if (klass == JvPrimClass (byte))
69 return ALIGNOF (jbyte);
70 else if (klass == JvPrimClass (short))
71 return ALIGNOF (jshort);
72 else if (klass == JvPrimClass (int))
73 return ALIGNOF (jint);
74 else if (klass == JvPrimClass (long))
75 return ALIGNOF (jlong);
76 else if (klass == JvPrimClass (boolean))
77 return ALIGNOF (jboolean);
78 else if (klass == JvPrimClass (char))
79 return ALIGNOF (jchar);
80 else if (klass == JvPrimClass (float))
81 return ALIGNOF (jfloat);
82 else if (klass == JvPrimClass (double))
83 return ALIGNOF (jdouble);
84 else
85 return ALIGNOF (jobject);
86 }
87
88 void
89 _Jv_Linker::resolve_field (_Jv_Field *field, java::lang::ClassLoader *loader)
90 {
91 if (! field->isResolved ())
92 {
93 _Jv_Utf8Const *sig = (_Jv_Utf8Const*)field->type;
94 field->type = _Jv_FindClassFromSignature (sig->chars(), loader);
95 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
96 }
97 }
98
99 // A helper for find_field that knows how to recursively search
100 // superclasses and interfaces.
101 _Jv_Field *
102 _Jv_Linker::find_field_helper (jclass search, _Jv_Utf8Const *name,
103 jclass *declarer)
104 {
105 while (search)
106 {
107 // From 5.4.3.2. First search class itself.
108 for (int i = 0; i < search->field_count; ++i)
109 {
110 _Jv_Field *field = &search->fields[i];
111 if (_Jv_equalUtf8Consts (field->name, name))
112 {
113 *declarer = search;
114 return field;
115 }
116 }
117
118 // Next search direct interfaces.
119 for (int i = 0; i < search->interface_count; ++i)
120 {
121 _Jv_Field *result = find_field_helper (search->interfaces[i], name,
122 declarer);
123 if (result)
124 return result;
125 }
126
127 // Now search superclass.
128 search = search->superclass;
129 }
130
131 return NULL;
132 }
133
134 bool
135 _Jv_Linker::has_field_p (jclass search, _Jv_Utf8Const *field_name)
136 {
137 for (int i = 0; i < search->field_count; ++i)
138 {
139 _Jv_Field *field = &search->fields[i];
140 if (_Jv_equalUtf8Consts (field->name, field_name))
141 return true;
142 }
143 return false;
144 }
145
146 // Find a field.
147 // KLASS is the class that is requesting the field.
148 // OWNER is the class in which the field should be found.
149 // FIELD_TYPE_NAME is the type descriptor for the field.
150 // This function does the class loader type checks, and
151 // also access checks. Returns the field, or throws an
152 // exception on error.
153 _Jv_Field *
154 _Jv_Linker::find_field (jclass klass, jclass owner,
155 _Jv_Utf8Const *field_name,
156 _Jv_Utf8Const *field_type_name)
157 {
158 jclass field_type = 0;
159
160 if (owner->loader != klass->loader)
161 {
162 // FIXME: The implementation of this function
163 // (_Jv_FindClassFromSignature) will generate an instance of
164 // _Jv_Utf8Const for each call if the field type is a class name
165 // (Lxx.yy.Z;). This may be too expensive to do for each and
166 // every fieldref being resolved. For now, we fix the problem
167 // by only doing it when we have a loader different from the
168 // class declaring the field.
169 field_type = _Jv_FindClassFromSignature (field_type_name->chars(),
170 klass->loader);
171 }
172
173 jclass found_class = 0;
174 _Jv_Field *the_field = find_field_helper (owner, field_name, &found_class);
175
176 if (the_field == 0)
177 {
178 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
179 sb->append(JvNewStringLatin1("field "));
180 sb->append(owner->getName());
181 sb->append(JvNewStringLatin1("."));
182 sb->append(_Jv_NewStringUTF(field_name->chars()));
183 sb->append(JvNewStringLatin1(" was not found."));
184 throw new java::lang::NoSuchFieldError (sb->toString());
185 }
186
187 if (_Jv_CheckAccess (klass, found_class, the_field->flags))
188 {
189 // Resolve the field using the class' own loader if necessary.
190
191 if (!the_field->isResolved ())
192 resolve_field (the_field, found_class->loader);
193
194 if (field_type != 0 && the_field->type != field_type)
195 throw new java::lang::LinkageError
196 (JvNewStringLatin1
197 ("field type mismatch with different loaders"));
198 }
199 else
200 {
201 java::lang::StringBuffer *sb
202 = new java::lang::StringBuffer ();
203 sb->append(klass->getName());
204 sb->append(JvNewStringLatin1(": "));
205 sb->append(found_class->getName());
206 sb->append(JvNewStringLatin1("."));
207 sb->append(_Jv_NewStringUtf8Const (field_name));
208 throw new java::lang::IllegalAccessError(sb->toString());
209 }
210
211 return the_field;
212 }
213
214 _Jv_word
215 _Jv_Linker::resolve_pool_entry (jclass klass, int index)
216 {
217 using namespace java::lang::reflect;
218
219 _Jv_Constants *pool = &klass->constants;
220
221 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
222 return pool->data[index];
223
224 switch (pool->tags[index])
225 {
226 case JV_CONSTANT_Class:
227 {
228 _Jv_Utf8Const *name = pool->data[index].utf8;
229
230 jclass found;
231 if (name->first() == '[')
232 found = _Jv_FindClassFromSignature (name->chars(),
233 klass->loader);
234 else
235 found = _Jv_FindClass (name, klass->loader);
236
237 if (! found)
238 throw new java::lang::NoClassDefFoundError (name->toString());
239
240 // Check accessibility, but first strip array types as
241 // _Jv_ClassNameSamePackage can't handle arrays.
242 jclass check;
243 for (check = found;
244 check && check->isArray();
245 check = check->getComponentType())
246 ;
247 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
248 || (_Jv_ClassNameSamePackage (check->name,
249 klass->name)))
250 {
251 pool->data[index].clazz = found;
252 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
253 }
254 else
255 {
256 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
257 sb->append(klass->getName());
258 sb->append(JvNewStringLatin1(" can't access class "));
259 sb->append(found->getName());
260 throw new java::lang::IllegalAccessError(sb->toString());
261 }
262 }
263 break;
264
265 case JV_CONSTANT_String:
266 {
267 jstring str;
268 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
269 pool->data[index].o = str;
270 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
271 }
272 break;
273
274 case JV_CONSTANT_Fieldref:
275 {
276 _Jv_ushort class_index, name_and_type_index;
277 _Jv_loadIndexes (&pool->data[index],
278 class_index,
279 name_and_type_index);
280 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
281
282 if (owner != klass)
283 _Jv_InitClass (owner);
284
285 _Jv_ushort name_index, type_index;
286 _Jv_loadIndexes (&pool->data[name_and_type_index],
287 name_index,
288 type_index);
289
290 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
291 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
292
293 _Jv_Field *the_field = find_field (klass, owner, field_name,
294 field_type_name);
295
296 pool->data[index].field = the_field;
297 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
298 }
299 break;
300
301 case JV_CONSTANT_Methodref:
302 case JV_CONSTANT_InterfaceMethodref:
303 {
304 _Jv_ushort class_index, name_and_type_index;
305 _Jv_loadIndexes (&pool->data[index],
306 class_index,
307 name_and_type_index);
308 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
309
310 if (owner != klass)
311 _Jv_InitClass (owner);
312
313 _Jv_ushort name_index, type_index;
314 _Jv_loadIndexes (&pool->data[name_and_type_index],
315 name_index,
316 type_index);
317
318 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
319 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
320
321 _Jv_Method *the_method = 0;
322 jclass found_class = 0;
323
324 // We're going to cache a pointer to the _Jv_Method object
325 // when we find it. So, to ensure this doesn't get moved from
326 // beneath us, we first put all the needed Miranda methods
327 // into the target class.
328 wait_for_state (klass, JV_STATE_LOADED);
329
330 // First search the class itself.
331 the_method = search_method_in_class (owner, klass,
332 method_name, method_signature);
333
334 if (the_method != 0)
335 {
336 found_class = owner;
337 goto end_of_method_search;
338 }
339
340 // If we are resolving an interface method, search the
341 // interface's superinterfaces (A superinterface is not an
342 // interface's superclass - a superinterface is implemented by
343 // the interface).
344 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
345 {
346 _Jv_ifaces ifaces;
347 ifaces.count = 0;
348 ifaces.len = 4;
349 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
350 * sizeof (jclass *));
351
352 get_interfaces (owner, &ifaces);
353
354 for (int i = 0; i < ifaces.count; i++)
355 {
356 jclass cls = ifaces.list[i];
357 the_method = search_method_in_class (cls, klass, method_name,
358 method_signature);
359 if (the_method != 0)
360 {
361 found_class = cls;
362 break;
363 }
364 }
365
366 _Jv_Free (ifaces.list);
367
368 if (the_method != 0)
369 goto end_of_method_search;
370 }
371
372 // Finally, search superclasses.
373 for (jclass cls = owner->getSuperclass (); cls != 0;
374 cls = cls->getSuperclass ())
375 {
376 the_method = search_method_in_class (cls, klass, method_name,
377 method_signature);
378 if (the_method != 0)
379 {
380 found_class = cls;
381 break;
382 }
383 }
384
385 end_of_method_search:
386
387 // FIXME: if (cls->loader != klass->loader), then we
388 // must actually check that the types of arguments
389 // correspond. That is, for each argument type, and
390 // the return type, doing _Jv_FindClassFromSignature
391 // with either loader should produce the same result,
392 // i.e., exactly the same jclass object. JVMS 5.4.3.3
393
394 if (the_method == 0)
395 {
396 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
397 sb->append(JvNewStringLatin1("method "));
398 sb->append(owner->getName());
399 sb->append(JvNewStringLatin1("."));
400 sb->append(_Jv_NewStringUTF(method_name->chars()));
401 sb->append(JvNewStringLatin1(" with signature "));
402 sb->append(_Jv_NewStringUTF(method_signature->chars()));
403 sb->append(JvNewStringLatin1(" was not found."));
404 throw new java::lang::NoSuchMethodError (sb->toString());
405 }
406
407 int vtable_index = -1;
408 if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
409 vtable_index = (jshort)the_method->index;
410
411 pool->data[index].rmethod
412 = klass->engine->resolve_method(the_method,
413 found_class,
414 ((the_method->accflags
415 & Modifier::STATIC) != 0),
416 vtable_index);
417 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
418 }
419 break;
420 }
421 return pool->data[index];
422 }
423
424 // This function is used to lazily locate superclasses and
425 // superinterfaces. This must be called with the class lock held.
426 void
427 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
428 {
429 jclass ret = *classref;
430
431 // If superclass looks like a constant pool entry, resolve it now.
432 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
433 {
434 if (klass->state < JV_STATE_LINKED)
435 {
436 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
437 ret = _Jv_FindClass (name, klass->loader);
438 if (! ret)
439 {
440 throw new java::lang::NoClassDefFoundError (name->toString());
441 }
442 }
443 else
444 ret = klass->constants.data[(uaddr) classref].clazz;
445 *classref = ret;
446 }
447 }
448
449 // Find a method declared in the cls that is referenced from klass and
450 // perform access checks.
451 _Jv_Method *
452 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
453 _Jv_Utf8Const *method_name,
454 _Jv_Utf8Const *method_signature)
455 {
456 using namespace java::lang::reflect;
457
458 for (int i = 0; i < cls->method_count; i++)
459 {
460 _Jv_Method *method = &cls->methods[i];
461 if ( (!_Jv_equalUtf8Consts (method->name,
462 method_name))
463 || (!_Jv_equalUtf8Consts (method->signature,
464 method_signature)))
465 continue;
466
467 if (_Jv_CheckAccess (klass, cls, method->accflags))
468 return method;
469 else
470 {
471 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
472 sb->append(klass->getName());
473 sb->append(JvNewStringLatin1(": "));
474 sb->append(cls->getName());
475 sb->append(JvNewStringLatin1("."));
476 sb->append(_Jv_NewStringUTF(method_name->chars()));
477 sb->append(_Jv_NewStringUTF(method_signature->chars()));
478 throw new java::lang::IllegalAccessError (sb->toString());
479 }
480 }
481 return 0;
482 }
483
484
485 #define INITIAL_IOFFSETS_LEN 4
486 #define INITIAL_IFACES_LEN 4
487
488 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
489
490 // Generate tables for constant-time assignment testing and interface
491 // method lookup. This implements the technique described by Per Bothner
492 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
493 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
494 void
495 _Jv_Linker::prepare_constant_time_tables (jclass klass)
496 {
497 if (klass->isPrimitive () || klass->isInterface ())
498 return;
499
500 // Short-circuit in case we've been called already.
501 if ((klass->idt != NULL) || klass->depth != 0)
502 return;
503
504 // Calculate the class depth and ancestor table. The depth of a class
505 // is how many "extends" it is removed from Object. Thus the depth of
506 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
507 // is 2. Depth is defined for all regular and array classes, but not
508 // interfaces or primitive types.
509
510 jclass klass0 = klass;
511 jboolean has_interfaces = 0;
512 while (klass0 != &java::lang::Object::class$)
513 {
514 has_interfaces += klass0->interface_count;
515 klass0 = klass0->superclass;
516 klass->depth++;
517 }
518
519 // We do class member testing in constant time by using a small table
520 // of all the ancestor classes within each class. The first element is
521 // a pointer to the current class, and the rest are pointers to the
522 // classes ancestors, ordered from the current class down by decreasing
523 // depth. We do not include java.lang.Object in the table of ancestors,
524 // since it is redundant.
525
526 // FIXME: _Jv_AllocBytes
527 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth
528 * sizeof (jclass));
529 klass0 = klass;
530 for (int index = 0; index < klass->depth; index++)
531 {
532 klass->ancestors[index] = klass0;
533 klass0 = klass0->superclass;
534 }
535
536 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
537 return;
538
539 // Optimization: If class implements no interfaces, use a common
540 // predefined interface table.
541 if (!has_interfaces)
542 {
543 klass->idt = &null_idt;
544 return;
545 }
546
547 // FIXME: _Jv_AllocBytes
548 klass->idt =
549 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
550
551 _Jv_ifaces ifaces;
552 ifaces.count = 0;
553 ifaces.len = INITIAL_IFACES_LEN;
554 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
555
556 int itable_size = get_interfaces (klass, &ifaces);
557
558 if (ifaces.count > 0)
559 {
560 klass->idt->cls.itable =
561 // FIXME: _Jv_AllocBytes
562 (void **) _Jv_Malloc (itable_size * sizeof (void *));
563 klass->idt->cls.itable_length = itable_size;
564
565 jshort *itable_offsets =
566 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
567
568 generate_itable (klass, &ifaces, itable_offsets);
569
570 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
571 ifaces.count);
572
573 for (int i = 0; i < ifaces.count; i++)
574 {
575 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
576 itable_offsets[i];
577 }
578
579 klass->idt->cls.iindex = cls_iindex;
580
581 _Jv_Free (ifaces.list);
582 _Jv_Free (itable_offsets);
583 }
584 else
585 {
586 klass->idt->cls.iindex = SHRT_MAX;
587 }
588 }
589
590 // Return index of item in list, or -1 if item is not present.
591 inline jshort
592 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
593 {
594 for (int i=0; i < list_len; i++)
595 {
596 if (list[i] == item)
597 return i;
598 }
599 return -1;
600 }
601
602 // Find all unique interfaces directly or indirectly implemented by klass.
603 // Returns the size of the interface dispatch table (itable) for klass, which
604 // is the number of unique interfaces plus the total number of methods that
605 // those interfaces declare. May extend ifaces if required.
606 jshort
607 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
608 {
609 jshort result = 0;
610
611 for (int i = 0; i < klass->interface_count; i++)
612 {
613 jclass iface = klass->interfaces[i];
614
615 /* Make sure interface is linked. */
616 wait_for_state(iface, JV_STATE_LINKED);
617
618 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
619 {
620 if (ifaces->count + 1 >= ifaces->len)
621 {
622 /* Resize ifaces list */
623 ifaces->len = ifaces->len * 2;
624 ifaces->list
625 = (jclass *) _Jv_Realloc (ifaces->list,
626 ifaces->len * sizeof(jclass));
627 }
628 ifaces->list[ifaces->count] = iface;
629 ifaces->count++;
630
631 result += get_interfaces (klass->interfaces[i], ifaces);
632 }
633 }
634
635 if (klass->isInterface())
636 result += klass->method_count + 1;
637 else if (klass->superclass)
638 result += get_interfaces (klass->superclass, ifaces);
639 return result;
640 }
641
642 // Fill out itable in klass, resolving method declarations in each ifaces.
643 // itable_offsets is filled out with the position of each iface in itable,
644 // such that itable[itable_offsets[n]] == ifaces.list[n].
645 void
646 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
647 jshort *itable_offsets)
648 {
649 void **itable = klass->idt->cls.itable;
650 jshort itable_pos = 0;
651
652 for (int i = 0; i < ifaces->count; i++)
653 {
654 jclass iface = ifaces->list[i];
655 itable_offsets[i] = itable_pos;
656 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
657
658 /* Create interface dispatch table for iface */
659 if (iface->idt == NULL)
660 {
661 // FIXME: _Jv_AllocBytes
662 iface->idt
663 = (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
664
665 // The first element of ioffsets is its length (itself included).
666 // FIXME: _Jv_AllocBytes
667 jshort *ioffsets = (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN
668 * sizeof (jshort));
669 ioffsets[0] = INITIAL_IOFFSETS_LEN;
670 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
671 ioffsets[i] = -1;
672
673 iface->idt->iface.ioffsets = ioffsets;
674 }
675 }
676 }
677
678 // Format method name for use in error messages.
679 jstring
680 _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
681 jclass derived)
682 {
683 using namespace java::lang;
684 StringBuffer *buf = new StringBuffer (klass->name->toString());
685 buf->append (jchar ('.'));
686 buf->append (meth->name->toString());
687 buf->append ((jchar) ' ');
688 buf->append (meth->signature->toString());
689 if (derived)
690 {
691 buf->append(JvNewStringLatin1(" in "));
692 buf->append(derived->name->toString());
693 }
694 return buf->toString();
695 }
696
697 void
698 _Jv_ThrowNoSuchMethodError ()
699 {
700 throw new java::lang::NoSuchMethodError;
701 }
702
703 // Each superinterface of a class (i.e. each interface that the class
704 // directly or indirectly implements) has a corresponding "Partial
705 // Interface Dispatch Table" whose size is (number of methods + 1) words.
706 // The first word is a pointer to the interface (i.e. the java.lang.Class
707 // instance for that interface). The remaining words are pointers to the
708 // actual methods that implement the methods declared in the interface,
709 // in order of declaration.
710 //
711 // Append partial interface dispatch table for "iface" to "itable", at
712 // position itable_pos.
713 // Returns the offset at which the next partial ITable should be appended.
714 jshort
715 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
716 void **itable, jshort pos)
717 {
718 using namespace java::lang::reflect;
719
720 itable[pos++] = (void *) iface;
721 _Jv_Method *meth;
722
723 for (int j=0; j < iface->method_count; j++)
724 {
725 meth = NULL;
726 for (jclass cl = klass; cl; cl = cl->getSuperclass())
727 {
728 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
729 iface->methods[j].signature);
730
731 if (meth)
732 break;
733 }
734
735 if (meth && (meth->name->first() == '<'))
736 {
737 // leave a placeholder in the itable for hidden init methods.
738 itable[pos] = NULL;
739 }
740 else if (meth)
741 {
742 if ((meth->accflags & Modifier::STATIC) != 0)
743 throw new java::lang::IncompatibleClassChangeError
744 (_Jv_GetMethodString (klass, meth));
745 if ((meth->accflags & Modifier::ABSTRACT) != 0)
746 throw new java::lang::AbstractMethodError
747 (_Jv_GetMethodString (klass, meth));
748 if ((meth->accflags & Modifier::PUBLIC) == 0)
749 throw new java::lang::IllegalAccessError
750 (_Jv_GetMethodString (klass, meth));
751
752 itable[pos] = meth->ncode;
753 }
754 else
755 {
756 // The method doesn't exist in klass. Binary compatibility rules
757 // permit this, so we delay the error until runtime using a pointer
758 // to a method which throws an exception.
759 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
760 }
761 pos++;
762 }
763
764 return pos;
765 }
766
767 static _Jv_Mutex_t iindex_mutex;
768 static bool iindex_mutex_initialized = false;
769
770 // We need to find the correct offset in the Class Interface Dispatch
771 // Table for a given interface. Once we have that, invoking an interface
772 // method just requires combining the Method's index in the interface
773 // (known at compile time) to get the correct method. Doing a type test
774 // (cast or instanceof) is the same problem: Once we have a possible Partial
775 // Interface Dispatch Table, we just compare the first element to see if it
776 // matches the desired interface. So how can we find the correct offset?
777 // Our solution is to keep a vector of candiate offsets in each interface
778 // (idt->iface.ioffsets), and in each class we have an index
779 // (idt->cls.iindex) used to select the correct offset from ioffsets.
780 //
781 // Calculate and return iindex for a new class.
782 // ifaces is a vector of num interfaces that the class implements.
783 // offsets[j] is the offset in the interface dispatch table for the
784 // interface corresponding to ifaces[j].
785 // May extend the interface ioffsets if required.
786 jshort
787 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
788 {
789 int i;
790 int j;
791
792 // Acquire a global lock to prevent itable corruption in case of multiple
793 // classes that implement an intersecting set of interfaces being linked
794 // simultaneously. We can assume that the mutex will be initialized
795 // single-threaded.
796 if (! iindex_mutex_initialized)
797 {
798 _Jv_MutexInit (&iindex_mutex);
799 iindex_mutex_initialized = true;
800 }
801
802 _Jv_MutexLock (&iindex_mutex);
803
804 for (i=1;; i++) /* each potential position in ioffsets */
805 {
806 for (j=0;; j++) /* each iface */
807 {
808 if (j >= num)
809 goto found;
810 if (i >= ifaces[j]->idt->iface.ioffsets[0])
811 continue;
812 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
813 /* We can potentially share this position with another class. */
814 if (ioffset >= 0 && ioffset != offsets[j])
815 break; /* Nope. Try next i. */
816 }
817 }
818 found:
819 for (j = 0; j < num; j++)
820 {
821 int len = ifaces[j]->idt->iface.ioffsets[0];
822 if (i >= len)
823 {
824 // Resize ioffsets.
825 int newlen = 2 * len;
826 if (i >= newlen)
827 newlen = i + 3;
828 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
829 // FIXME: _Jv_AllocBytes
830 jshort *new_ioffsets = (jshort *) _Jv_Malloc (newlen
831 * sizeof(jshort));
832 memcpy (&new_ioffsets[1], &old_ioffsets[1],
833 (len - 1) * sizeof (jshort));
834 new_ioffsets[0] = newlen;
835
836 while (len < newlen)
837 new_ioffsets[len++] = -1;
838
839 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
840 }
841 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
842 }
843
844 _Jv_MutexUnlock (&iindex_mutex);
845
846 return i;
847 }
848
849
850 // Functions for indirect dispatch (symbolic virtual binding) support.
851
852 // There are three tables, atable otable and itable. atable is an
853 // array of addresses, and otable is an array of offsets, and these
854 // are used for static and virtual members respectively. itable is an
855 // array of pairs {address, index} where each address is a pointer to
856 // an interface.
857
858 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
859 // symbol is a tuple of {classname, member name, signature}.
860
861 // Set this to true to enable debugging of indirect dispatch tables/linking.
862 static bool debug_link = false;
863
864 // link_symbol_table() scans these two arrays and fills in the
865 // corresponding atable and otable with the addresses of static
866 // members and the offsets of virtual members.
867
868 // The offset (in bytes) for each resolved method or field is placed
869 // at the corresponding position in the virtual method offset table
870 // (klass->otable).
871
872 // The same otable and atable may be shared by many classes.
873
874 // This must be called while holding the class lock.
875
876 void
877 _Jv_Linker::link_symbol_table (jclass klass)
878 {
879 int index = 0;
880 _Jv_MethodSymbol sym;
881 if (klass->otable == NULL
882 || klass->otable->state != 0)
883 goto atable;
884
885 klass->otable->state = 1;
886
887 if (debug_link)
888 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
889 for (index = 0;
890 (sym = klass->otable_syms[index]).class_name != NULL;
891 ++index)
892 {
893 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
894 _Jv_Method *meth = NULL;
895
896 _Jv_Utf8Const *signature = sym.signature;
897
898 {
899 static char *bounce = (char *)_Jv_ThrowNoSuchMethodError;
900 ptrdiff_t offset = (char *)(klass->vtable) - bounce;
901 klass->otable->offsets[index] = offset;
902 }
903
904 if (target_class == NULL)
905 throw new java::lang::NoClassDefFoundError
906 (_Jv_NewStringUTF (sym.class_name->chars()));
907
908 // We're looking for a field or a method, and we can tell
909 // which is needed by looking at the signature.
910 if (signature->first() == '(' && signature->len() >= 2)
911 {
912 // Looks like someone is trying to invoke an interface method
913 if (target_class->isInterface())
914 {
915 using namespace java::lang;
916 StringBuffer *sb = new StringBuffer();
917 sb->append(JvNewStringLatin1("found interface "));
918 sb->append(target_class->getName());
919 sb->append(JvNewStringLatin1(" when searching for a class"));
920 throw new VerifyError(sb->toString());
921 }
922
923 // If the target class does not have a vtable_method_count yet,
924 // then we can't tell the offsets for its methods, so we must lay
925 // it out now.
926 wait_for_state(target_class, JV_STATE_PREPARED);
927
928 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
929 sym.signature);
930
931 if (meth != NULL)
932 {
933 int offset = _Jv_VTable::idx_to_offset (meth->index);
934 if (offset == -1)
935 JvFail ("Bad method index");
936 JvAssert (meth->index < target_class->vtable_method_count);
937 klass->otable->offsets[index] = offset;
938 }
939 if (debug_link)
940 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
941 (int)index,
942 (int)klass->otable->offsets[index],
943 (const char*)target_class->name->chars(),
944 target_class,
945 (const char*)sym.name->chars(),
946 (const char*)signature->chars());
947 continue;
948 }
949
950 // Try fields.
951 {
952 wait_for_state(target_class, JV_STATE_PREPARED);
953 _Jv_Field *the_field = find_field (klass, target_class,
954 sym.name, sym.signature);
955 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
956 throw new java::lang::IncompatibleClassChangeError;
957 else
958 klass->otable->offsets[index] = the_field->u.boffset;
959 }
960 }
961
962 atable:
963 if (klass->atable == NULL || klass->atable->state != 0)
964 goto itable;
965
966 klass->atable->state = 1;
967
968 for (index = 0;
969 (sym = klass->atable_syms[index]).class_name != NULL;
970 ++index)
971 {
972 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
973 _Jv_Method *meth = NULL;
974 _Jv_Utf8Const *signature = sym.signature;
975
976 // ??? Setting this pointer to null will at least get us a
977 // NullPointerException
978 klass->atable->addresses[index] = NULL;
979
980 if (target_class == NULL)
981 throw new java::lang::NoClassDefFoundError
982 (_Jv_NewStringUTF (sym.class_name->chars()));
983
984 // We're looking for a static field or a static method, and we
985 // can tell which is needed by looking at the signature.
986 if (signature->first() == '(' && signature->len() >= 2)
987 {
988 // If the target class does not have a vtable_method_count yet,
989 // then we can't tell the offsets for its methods, so we must lay
990 // it out now.
991 wait_for_state (target_class, JV_STATE_PREPARED);
992
993 // Interface methods cannot have bodies.
994 if (target_class->isInterface())
995 {
996 using namespace java::lang;
997 StringBuffer *sb = new StringBuffer();
998 sb->append(JvNewStringLatin1("class "));
999 sb->append(target_class->getName());
1000 sb->append(JvNewStringLatin1(" is an interface: "
1001 "class expected"));
1002 throw new VerifyError(sb->toString());
1003 }
1004
1005 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1006 sym.signature);
1007
1008 if (meth != NULL)
1009 {
1010 if (meth->ncode) // Maybe abstract?
1011 {
1012 klass->atable->addresses[index] = meth->ncode;
1013 if (debug_link)
1014 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1015 index,
1016 &klass->atable->addresses[index],
1017 (const char*)target_class->name->chars(),
1018 klass,
1019 (const char*)sym.name->chars(),
1020 (const char*)signature->chars());
1021 }
1022 }
1023 else
1024 klass->atable->addresses[index]
1025 = (void *)_Jv_ThrowNoSuchMethodError;
1026
1027 continue;
1028 }
1029
1030 // Try fields.
1031 {
1032 wait_for_state(target_class, JV_STATE_PREPARED);
1033 _Jv_Field *the_field = find_field (klass, target_class,
1034 sym.name, sym.signature);
1035 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1036 klass->atable->addresses[index] = the_field->u.addr;
1037 else
1038 throw new java::lang::IncompatibleClassChangeError;
1039 }
1040 }
1041
1042 itable:
1043 if (klass->itable == NULL
1044 || klass->itable->state != 0)
1045 return;
1046
1047 klass->itable->state = 1;
1048
1049 for (index = 0;
1050 (sym = klass->itable_syms[index]).class_name != NULL;
1051 ++index)
1052 {
1053 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1054 _Jv_Utf8Const *signature = sym.signature;
1055
1056 jclass cls;
1057 int i;
1058
1059 wait_for_state(target_class, JV_STATE_LOADED);
1060 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1061 sym.name, sym.signature);
1062
1063 if (found)
1064 {
1065 klass->itable->addresses[index * 2] = cls;
1066 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1067 if (debug_link)
1068 {
1069 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1070 index,
1071 klass->itable->addresses[index * 2],
1072 (const char*)cls->name->chars(),
1073 cls,
1074 (const char*)sym.name->chars(),
1075 (const char*)signature->chars());
1076 fprintf (stderr, " [%d] = offset %d\n",
1077 index + 1,
1078 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1079 }
1080
1081 }
1082 else
1083 throw new java::lang::IncompatibleClassChangeError;
1084 }
1085
1086 }
1087
1088 // For each catch_record in the list of caught classes, fill in the
1089 // address field.
1090 void
1091 _Jv_Linker::link_exception_table (jclass self)
1092 {
1093 struct _Jv_CatchClass *catch_record = self->catch_classes;
1094 if (!catch_record || catch_record->classname)
1095 return;
1096 catch_record++;
1097 while (catch_record->classname)
1098 {
1099 try
1100 {
1101 jclass target_class
1102 = _Jv_FindClass (catch_record->classname,
1103 self->getClassLoaderInternal ());
1104 *catch_record->address = target_class;
1105 }
1106 catch (::java::lang::Throwable *t)
1107 {
1108 // FIXME: We need to do something better here.
1109 *catch_record->address = 0;
1110 }
1111 catch_record++;
1112 }
1113 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1114 }
1115
1116 // This is put in empty vtable slots.
1117 static void
1118 _Jv_abstractMethodError (void)
1119 {
1120 throw new java::lang::AbstractMethodError();
1121 }
1122
1123 // Set itable method indexes for members of interface IFACE.
1124 void
1125 _Jv_Linker::layout_interface_methods (jclass iface)
1126 {
1127 if (! iface->isInterface())
1128 return;
1129
1130 // itable indexes start at 1.
1131 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1132 // itable so they are also assigned an index here.
1133 for (int i = 0; i < iface->method_count; i++)
1134 iface->methods[i].index = i + 1;
1135 }
1136
1137 // Prepare virtual method declarations in KLASS, and any superclasses
1138 // as required, by determining their vtable index, setting
1139 // method->index, and finally setting the class's vtable_method_count.
1140 // Must be called with the lock for KLASS held.
1141 void
1142 _Jv_Linker::layout_vtable_methods (jclass klass)
1143 {
1144 if (klass->vtable != NULL || klass->isInterface()
1145 || klass->vtable_method_count != -1)
1146 return;
1147
1148 jclass superclass = klass->getSuperclass();
1149
1150 if (superclass != NULL && superclass->vtable_method_count == -1)
1151 {
1152 JvSynchronize sync (superclass);
1153 layout_vtable_methods (superclass);
1154 }
1155
1156 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1157
1158 for (int i = 0; i < klass->method_count; ++i)
1159 {
1160 _Jv_Method *meth = &klass->methods[i];
1161 _Jv_Method *super_meth = NULL;
1162
1163 if (! _Jv_isVirtualMethod (meth))
1164 continue;
1165
1166 if (superclass != NULL)
1167 {
1168 jclass declarer;
1169 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1170 meth->signature, &declarer);
1171 // See if this method actually overrides the other method
1172 // we've found.
1173 if (super_meth)
1174 {
1175 if (! _Jv_isVirtualMethod (super_meth)
1176 || ! _Jv_CheckAccess (klass, declarer,
1177 super_meth->accflags))
1178 super_meth = NULL;
1179 else if ((super_meth->accflags
1180 & java::lang::reflect::Modifier::FINAL) != 0)
1181 {
1182 using namespace java::lang;
1183 StringBuffer *sb = new StringBuffer();
1184 sb->append(JvNewStringLatin1("method "));
1185 sb->append(_Jv_GetMethodString(klass, meth));
1186 sb->append(JvNewStringLatin1(" overrides final method "));
1187 sb->append(_Jv_GetMethodString(declarer, super_meth));
1188 throw new VerifyError(sb->toString());
1189 }
1190 }
1191 }
1192
1193 if (super_meth)
1194 meth->index = super_meth->index;
1195 else
1196 meth->index = index++;
1197 }
1198
1199 klass->vtable_method_count = index;
1200 }
1201
1202 // Set entries in VTABLE for virtual methods declared in KLASS.
1203 void
1204 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1205 {
1206 for (int i = klass->method_count - 1; i >= 0; i--)
1207 {
1208 using namespace java::lang::reflect;
1209
1210 _Jv_Method *meth = &klass->methods[i];
1211 if (meth->index == (_Jv_ushort) -1)
1212 continue;
1213 if ((meth->accflags & Modifier::ABSTRACT))
1214 vtable->set_method(meth->index, (void *) &_Jv_abstractMethodError);
1215 else
1216 vtable->set_method(meth->index, meth->ncode);
1217 }
1218 }
1219
1220 // Allocate and lay out the virtual method table for KLASS. This will
1221 // also cause vtables to be generated for any non-abstract
1222 // superclasses, and virtual method layout to occur for any abstract
1223 // superclasses. Must be called with monitor lock for KLASS held.
1224 void
1225 _Jv_Linker::make_vtable (jclass klass)
1226 {
1227 using namespace java::lang::reflect;
1228
1229 // If the vtable exists, or for interface classes, do nothing. All
1230 // other classes, including abstract classes, need a vtable.
1231 if (klass->vtable != NULL || klass->isInterface())
1232 return;
1233
1234 // Ensure all the `ncode' entries are set.
1235 klass->engine->create_ncode(klass);
1236
1237 // Class must be laid out before we can create a vtable.
1238 if (klass->vtable_method_count == -1)
1239 layout_vtable_methods (klass);
1240
1241 // Allocate the new vtable.
1242 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1243 klass->vtable = vtable;
1244
1245 // Copy the vtable of the closest superclass.
1246 jclass superclass = klass->superclass;
1247 {
1248 JvSynchronize sync (superclass);
1249 make_vtable (superclass);
1250 }
1251 for (int i = 0; i < superclass->vtable_method_count; ++i)
1252 vtable->set_method (i, superclass->vtable->get_method (i));
1253
1254 // Set the class pointer and GC descriptor.
1255 vtable->clas = klass;
1256 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1257
1258 // For each virtual declared in klass, set new vtable entry or
1259 // override an old one.
1260 set_vtable_entries (klass, vtable);
1261
1262 // It is an error to have an abstract method in a concrete class.
1263 if (! (klass->accflags & Modifier::ABSTRACT))
1264 {
1265 for (int i = 0; i < klass->vtable_method_count; ++i)
1266 if (vtable->get_method(i) == (void *) &_Jv_abstractMethodError)
1267 {
1268 using namespace java::lang;
1269 jclass orig = klass;
1270 while (klass != NULL)
1271 {
1272 for (int j = 0; j < klass->method_count; ++j)
1273 {
1274 if (klass->methods[j].index == i)
1275 throw new AbstractMethodError(_Jv_GetMethodString(klass,
1276 &klass->methods[j],
1277 orig));
1278 }
1279 klass = klass->getSuperclass ();
1280 }
1281 // Couldn't find the name, which is weird.
1282 // But we still must throw the error.
1283 throw new AbstractMethodError ();
1284 }
1285 }
1286 }
1287
1288 // Lay out the class, allocating space for static fields and computing
1289 // offsets of instance fields. The class lock must be held by the
1290 // caller.
1291 void
1292 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1293 {
1294 if (klass->size_in_bytes != -1)
1295 return;
1296
1297 // Compute the alignment for this type by searching through the
1298 // superclasses and finding the maximum required alignment. We
1299 // could consider caching this in the Class.
1300 int max_align = __alignof__ (java::lang::Object);
1301 jclass super = klass->getSuperclass();
1302 while (super != NULL)
1303 {
1304 // Ensure that our super has its super installed before
1305 // recursing.
1306 wait_for_state(super, JV_STATE_LOADING);
1307 ensure_fields_laid_out(super);
1308 int num = JvNumInstanceFields (super);
1309 _Jv_Field *field = JvGetFirstInstanceField (super);
1310 while (num > 0)
1311 {
1312 int field_align = get_alignment_from_class (field->type);
1313 if (field_align > max_align)
1314 max_align = field_align;
1315 ++field;
1316 --num;
1317 }
1318 super = super->getSuperclass();
1319 }
1320
1321 int instance_size;
1322 int static_size = 0;
1323
1324 // Although java.lang.Object is never interpreted, an interface can
1325 // have a null superclass. Note that we have to lay out an
1326 // interface because it might have static fields.
1327 if (klass->superclass)
1328 instance_size = klass->superclass->size();
1329 else
1330 instance_size = java::lang::Object::class$.size();
1331
1332 for (int i = 0; i < klass->field_count; i++)
1333 {
1334 int field_size;
1335 int field_align;
1336
1337 _Jv_Field *field = &klass->fields[i];
1338
1339 if (! field->isRef ())
1340 {
1341 // It is safe to resolve the field here, since it's a
1342 // primitive class, which does not cause loading to happen.
1343 resolve_field (field, klass->loader);
1344
1345 field_size = field->type->size ();
1346 field_align = get_alignment_from_class (field->type);
1347 }
1348 else
1349 {
1350 field_size = sizeof (jobject);
1351 field_align = __alignof__ (jobject);
1352 }
1353
1354 field->bsize = field_size;
1355
1356 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1357 {
1358 if (field->u.addr == NULL)
1359 {
1360 // This computes an offset into a region we'll allocate
1361 // shortly, and then add this offset to the start
1362 // address.
1363 static_size = ROUND (static_size, field_align);
1364 field->u.boffset = static_size;
1365 static_size += field_size;
1366 }
1367 }
1368 else
1369 {
1370 instance_size = ROUND (instance_size, field_align);
1371 field->u.boffset = instance_size;
1372 instance_size += field_size;
1373 if (field_align > max_align)
1374 max_align = field_align;
1375 }
1376 }
1377
1378 if (static_size != 0)
1379 klass->engine->allocate_static_fields (klass, static_size);
1380
1381 // Set the instance size for the class. Note that first we round it
1382 // to the alignment required for this object; this keeps us in sync
1383 // with our current ABI.
1384 instance_size = ROUND (instance_size, max_align);
1385 klass->size_in_bytes = instance_size;
1386 }
1387
1388 // This takes the class to state JV_STATE_LINKED. The class lock must
1389 // be held when calling this.
1390 void
1391 _Jv_Linker::ensure_class_linked (jclass klass)
1392 {
1393 if (klass->state >= JV_STATE_LINKED)
1394 return;
1395
1396 int state = klass->state;
1397 try
1398 {
1399 // Short-circuit, so that mutually dependent classes are ok.
1400 klass->state = JV_STATE_LINKED;
1401
1402 _Jv_Constants *pool = &klass->constants;
1403
1404 // Compiled classes require that their class constants be
1405 // resolved here. However, interpreted classes need their
1406 // constants to be resolved lazily. If we resolve an
1407 // interpreted class' constants eagerly, we can end up with
1408 // spurious IllegalAccessErrors when the constant pool contains
1409 // a reference to a class we can't access. This can validly
1410 // occur in an obscure case involving the InnerClasses
1411 // attribute.
1412 #ifdef INTERPRETER
1413 if (! _Jv_IsInterpretedClass (klass))
1414 #endif
1415 {
1416 // Resolve class constants first, since other constant pool
1417 // entries may rely on these.
1418 for (int index = 1; index < pool->size; ++index)
1419 {
1420 if (pool->tags[index] == JV_CONSTANT_Class)
1421 resolve_pool_entry (klass, index);
1422 }
1423 }
1424
1425 #if 0 // Should be redundant now
1426 // If superclass looks like a constant pool entry,
1427 // resolve it now.
1428 if ((uaddr) klass->superclass < (uaddr) pool->size)
1429 klass->superclass = pool->data[(uaddr) klass->superclass].clazz;
1430
1431 // Likewise for interfaces.
1432 for (int i = 0; i < klass->interface_count; i++)
1433 {
1434 if ((uaddr) klass->interfaces[i] < (uaddr) pool->size)
1435 klass->interfaces[i]
1436 = pool->data[(uaddr) klass->interfaces[i]].clazz;
1437 }
1438 #endif
1439
1440 // Resolve the remaining constant pool entries.
1441 for (int index = 1; index < pool->size; ++index)
1442 {
1443 if (pool->tags[index] == JV_CONSTANT_String)
1444 {
1445 jstring str;
1446
1447 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1448 pool->data[index].o = str;
1449 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1450 }
1451 }
1452
1453 if (klass->engine->need_resolve_string_fields())
1454 {
1455 jfieldID f = JvGetFirstStaticField (klass);
1456 for (int n = JvNumStaticFields (klass); n > 0; --n)
1457 {
1458 int mod = f->getModifiers ();
1459 // If we have a static String field with a non-null initial
1460 // value, we know it points to a Utf8Const.
1461 resolve_field(f, klass->loader);
1462 if (f->getClass () == &java::lang::String::class$
1463 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1464 {
1465 jstring *strp = (jstring *) f->u.addr;
1466 if (*strp)
1467 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1468 }
1469 f = f->getNextField ();
1470 }
1471 }
1472
1473 klass->notifyAll ();
1474
1475 _Jv_PushClass (klass);
1476 }
1477 catch (java::lang::Throwable *t)
1478 {
1479 klass->state = state;
1480 throw t;
1481 }
1482 }
1483
1484 // This ensures that symbolic superclass and superinterface references
1485 // are resolved for the indicated class. This must be called with the
1486 // class lock held.
1487 void
1488 _Jv_Linker::ensure_supers_installed (jclass klass)
1489 {
1490 resolve_class_ref (klass, &klass->superclass);
1491 // An interface won't have a superclass.
1492 if (klass->superclass)
1493 wait_for_state (klass->superclass, JV_STATE_LOADING);
1494
1495 for (int i = 0; i < klass->interface_count; ++i)
1496 {
1497 resolve_class_ref (klass, &klass->interfaces[i]);
1498 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1499 }
1500 }
1501
1502 // This adds missing `Miranda methods' to a class.
1503 void
1504 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1505 {
1506 // Note that at this point, all our supers, and the supers of all
1507 // our superclasses and superinterfaces, will have been installed.
1508
1509 for (int i = 0; i < iface_class->interface_count; ++i)
1510 {
1511 jclass interface = iface_class->interfaces[i];
1512
1513 for (int j = 0; j < interface->method_count; ++j)
1514 {
1515 _Jv_Method *meth = &interface->methods[j];
1516 // Don't bother with <clinit>.
1517 if (meth->name->first() == '<')
1518 continue;
1519 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1520 meth->signature);
1521 if (! new_meth)
1522 {
1523 // We assume that such methods are very unlikely, so we
1524 // just reallocate the method array each time one is
1525 // found. This greatly simplifies the searching --
1526 // otherwise we have to make sure that each such method
1527 // found is really unique among all superinterfaces.
1528 int new_count = base->method_count + 1;
1529 _Jv_Method *new_m
1530 = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method)
1531 * new_count);
1532 memcpy (new_m, base->methods,
1533 sizeof (_Jv_Method) * base->method_count);
1534
1535 // Add new method.
1536 new_m[base->method_count] = *meth;
1537 new_m[base->method_count].index = (_Jv_ushort) -1;
1538 new_m[base->method_count].accflags
1539 |= java::lang::reflect::Modifier::INVISIBLE;
1540
1541 base->methods = new_m;
1542 base->method_count = new_count;
1543 }
1544 }
1545
1546 wait_for_state (interface, JV_STATE_LOADED);
1547 add_miranda_methods (base, interface);
1548 }
1549 }
1550
1551 // This ensures that the class' method table is "complete". This must
1552 // be called with the class lock held.
1553 void
1554 _Jv_Linker::ensure_method_table_complete (jclass klass)
1555 {
1556 if (klass->vtable != NULL || klass->isInterface())
1557 return;
1558
1559 // We need our superclass to have its own Miranda methods installed.
1560 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1561
1562 // A class might have so-called "Miranda methods". This is a method
1563 // that is declared in an interface and not re-declared in an
1564 // abstract class. Some compilers don't emit declarations for such
1565 // methods in the class; this will give us problems since we expect
1566 // a declaration for any method requiring a vtable entry. We handle
1567 // this here by searching for such methods and constructing new
1568 // internal declarations for them. Note that we do this
1569 // unconditionally, and not just for abstract classes, to correctly
1570 // account for cases where a class is modified to be concrete and
1571 // still incorrectly inherits an abstract method.
1572 int pre_count = klass->method_count;
1573 add_miranda_methods (klass, klass);
1574
1575 // Let the execution engine know that we've added methods.
1576 if (klass->method_count != pre_count)
1577 klass->engine->post_miranda_hook(klass);
1578 }
1579
1580 // Verify a class. Must be called with class lock held.
1581 void
1582 _Jv_Linker::verify_class (jclass klass)
1583 {
1584 klass->engine->verify(klass);
1585 }
1586
1587 // Check the assertions contained in the type assertion table for KLASS.
1588 // This is the equivilent of bytecode verification for native, BC-ABI code.
1589 void
1590 _Jv_Linker::verify_type_assertions (jclass klass)
1591 {
1592 if (debug_link)
1593 fprintf (stderr, "Evaluating type assertions for %s:\n",
1594 klass->name->chars());
1595
1596 if (klass->assertion_table == NULL)
1597 return;
1598
1599 for (int i = 0;; i++)
1600 {
1601 int assertion_code = klass->assertion_table[i].assertion_code;
1602 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1603 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1604
1605 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1606 return;
1607 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1608 {
1609 if (debug_link)
1610 {
1611 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1612 assertion_code, op1->chars(), op2->chars());
1613 }
1614
1615 // The operands are class signatures. op1 is the source,
1616 // op2 is the target.
1617 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1618 klass->getClassLoaderInternal());
1619 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1620 klass->getClassLoaderInternal());
1621
1622 // If the class doesn't exist, ignore the assertion. An exception
1623 // will be thrown later if an attempt is made to actually
1624 // instantiate the class.
1625 if (cl1 == NULL || cl2 == NULL)
1626 continue;
1627
1628 if (! _Jv_IsAssignableFromSlow (cl2, cl1))
1629 {
1630 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1631 s = s->concat (klass->getName());
1632 s = s->concat (JvNewStringUTF (": "));
1633 s = s->concat (cl1->getName());
1634 s = s->concat (JvNewStringUTF (" is not assignable to "));
1635 s = s->concat (cl2->getName());
1636 throw new java::lang::VerifyError (s);
1637 }
1638 }
1639 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1640 {
1641 // TODO: Implement this.
1642 }
1643 // Unknown assertion codes are ignored, for forwards-compatibility.
1644 }
1645 }
1646
1647 void
1648 _Jv_Linker::print_class_loaded (jclass klass)
1649 {
1650 char *codesource = NULL;
1651 if (klass->protectionDomain != NULL)
1652 {
1653 java::security::CodeSource *cs
1654 = klass->protectionDomain->getCodeSource();
1655 if (cs != NULL)
1656 {
1657 jstring css = cs->toString();
1658 int len = JvGetStringUTFLength(css);
1659 codesource = (char *) _Jv_AllocBytes(len + 1);
1660 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1661 codesource[len] = '\0';
1662 }
1663 }
1664 if (codesource == NULL)
1665 codesource = "<no code source>";
1666
1667 // We use a somewhat bogus test for the ABI here.
1668 char *abi;
1669 #ifdef INTERPRETER
1670 if (_Jv_IsInterpretedClass (klass))
1671 #else
1672 if (false)
1673 #endif
1674 abi = "bytecode";
1675 else if (klass->state == JV_STATE_PRELOADING)
1676 abi = "BC-compiled";
1677 else
1678 abi = "pre-compiled";
1679
1680 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1681 codesource);
1682 }
1683
1684 // FIXME: mention invariants and stuff.
1685 void
1686 _Jv_Linker::wait_for_state (jclass klass, int state)
1687 {
1688 if (klass->state >= state)
1689 return;
1690
1691 JvSynchronize sync (klass);
1692
1693 // This is similar to the strategy for class initialization. If we
1694 // already hold the lock, just leave.
1695 java::lang::Thread *self = java::lang::Thread::currentThread();
1696 while (klass->state <= state
1697 && klass->thread
1698 && klass->thread != self)
1699 klass->wait ();
1700
1701 java::lang::Thread *save = klass->thread;
1702 klass->thread = self;
1703
1704 // Print some debugging info if requested. Interpreted classes are
1705 // handled in defineclass, so we only need to handle the two
1706 // pre-compiled cases here.
1707 if (gcj::verbose_class_flag
1708 && (klass->state == JV_STATE_COMPILED
1709 || klass->state == JV_STATE_PRELOADING)
1710 #ifdef INTERPRETER
1711 && ! _Jv_IsInterpretedClass (klass)
1712 #endif
1713 )
1714 print_class_loaded (klass);
1715
1716 try
1717 {
1718 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
1719 {
1720 ensure_supers_installed (klass);
1721 klass->set_state(JV_STATE_LOADING);
1722 }
1723
1724 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
1725 {
1726 ensure_method_table_complete (klass);
1727 klass->set_state(JV_STATE_LOADED);
1728 }
1729
1730 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
1731 {
1732 ensure_fields_laid_out (klass);
1733 make_vtable (klass);
1734 layout_interface_methods (klass);
1735 prepare_constant_time_tables (klass);
1736 klass->set_state(JV_STATE_PREPARED);
1737 }
1738
1739 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
1740 {
1741 verify_class (klass);
1742
1743 ensure_class_linked (klass);
1744 link_exception_table (klass);
1745 link_symbol_table (klass);
1746 klass->set_state(JV_STATE_LINKED);
1747 }
1748 }
1749 catch (java::lang::Throwable *exc)
1750 {
1751 klass->thread = save;
1752 klass->set_state(JV_STATE_ERROR);
1753 throw exc;
1754 }
1755
1756 klass->thread = save;
1757
1758 if (klass->state == JV_STATE_ERROR)
1759 throw new java::lang::LinkageError;
1760 }