OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libjava/] [link.cc] - Blame information for rev 810

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.