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