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