klassVtable.cpp 49.7 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29 30 31 32 33
#include "precompiled.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "gc_implementation/shared/markSweep.inline.hpp"
#include "memory/gcLocker.hpp"
#include "memory/resourceArea.hpp"
#include "memory/universe.inline.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/klassVtable.hpp"
34
#include "oops/method.hpp"
35 36 37 38 39 40
#include "oops/objArrayOop.hpp"
#include "oops/oop.inline.hpp"
#include "prims/jvmtiRedefineClassesTrace.hpp"
#include "runtime/arguments.hpp"
#include "runtime/handles.inline.hpp"
#include "utilities/copy.hpp"
D
duke 已提交
41

42 43 44 45
inline InstanceKlass* klassVtable::ik() const {
  Klass* k = _klass();
  assert(k->oop_is_instance(), "not an InstanceKlass");
  return (InstanceKlass*)k;
D
duke 已提交
46 47 48 49
}


// this function computes the vtable size (including the size needed for miranda
50
// methods) and the number of miranda methods in this class.
D
duke 已提交
51
// Note on Miranda methods: Let's say there is a class C that implements
52 53 54 55
// interface I, and none of C's superclasses implements I.
// Let's say there is an abstract method m in I that neither C
// nor any of its super classes implement (i.e there is no method of any access,
// with the same name and signature as m), then m is a Miranda method which is
D
duke 已提交
56 57
// entered as a public abstract method in C's vtable.  From then on it should
// treated as any other public method in C for method over-ride purposes.
58 59 60 61 62 63
void klassVtable::compute_vtable_size_and_num_mirandas(
    int* vtable_length_ret, int* num_new_mirandas,
    GrowableArray<Method*>* all_mirandas, Klass* super,
    Array<Method*>* methods, AccessFlags class_flags,
    Handle classloader, Symbol* classname, Array<Klass*>* local_interfaces,
    TRAPS) {
D
duke 已提交
64 65 66
  No_Safepoint_Verifier nsv;

  // set up default result values
67
  int vtable_length = 0;
D
duke 已提交
68 69

  // start off with super's vtable length
70
  InstanceKlass* sk = (InstanceKlass*)super;
D
duke 已提交
71 72 73 74 75
  vtable_length = super == NULL ? 0 : sk->vtable_length();

  // go thru each method in the methods table to see if it needs a new entry
  int len = methods->length();
  for (int i = 0; i < len; i++) {
76 77
    assert(methods->at(i)->is_method(), "must be a Method*");
    methodHandle mh(THREAD, methods->at(i));
D
duke 已提交
78

79
    if (needs_new_vtable_entry(mh, super, classloader, classname, class_flags, THREAD)) {
D
duke 已提交
80 81 82 83
      vtable_length += vtableEntry::size(); // we need a new entry
    }
  }

84
  GrowableArray<Method*> new_mirandas(20);
D
duke 已提交
85
  // compute the number of mirandas methods that must be added to the end
86 87 88 89
  get_mirandas(&new_mirandas, all_mirandas, super, methods, local_interfaces);
  *num_new_mirandas = new_mirandas.length();

  vtable_length += *num_new_mirandas * vtableEntry::size();
D
duke 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

  if (Universe::is_bootstrapping() && vtable_length == 0) {
    // array classes don't have their superclass set correctly during
    // bootstrapping
    vtable_length = Universe::base_vtable_size();
  }

  if (super == NULL && !Universe::is_bootstrapping() &&
      vtable_length != Universe::base_vtable_size()) {
    // Someone is attempting to redefine java.lang.Object incorrectly.  The
    // only way this should happen is from
    // SystemDictionary::resolve_from_stream(), which will detect this later
    // and throw a security exception.  So don't assert here to let
    // the exception occur.
    vtable_length = Universe::base_vtable_size();
  }
  assert(super != NULL || vtable_length == Universe::base_vtable_size(),
         "bad vtable size for class Object");
  assert(vtable_length % vtableEntry::size() == 0, "bad vtable length");
  assert(vtable_length >= Universe::base_vtable_size(), "vtable too small");
110 111

  *vtable_length_ret = vtable_length;
D
duke 已提交
112 113
}

114
int klassVtable::index_of(Method* m, int len) const {
115
  assert(m->has_vtable_index(), "do not ask this of non-vtable methods");
D
duke 已提交
116 117 118
  return m->vtable_index();
}

119 120 121
// Copy super class's vtable to the first part (prefix) of this class's vtable,
// and return the number of entries copied.  Expects that 'super' is the Java
// super class (arrays can have "array" super classes that must be skipped).
D
duke 已提交
122 123 124 125 126
int klassVtable::initialize_from_super(KlassHandle super) {
  if (super.is_null()) {
    return 0;
  } else {
    // copy methods from superKlass
127
    // can't inherit from array class, so must be InstanceKlass
D
duke 已提交
128
    assert(super->oop_is_instance(), "must be instance klass");
129
    InstanceKlass* sk = (InstanceKlass*)super();
D
duke 已提交
130 131 132 133 134 135 136 137
    klassVtable* superVtable = sk->vtable();
    assert(superVtable->length() <= _length, "vtable too short");
#ifdef ASSERT
    superVtable->verify(tty, true);
#endif
    superVtable->copy_vtable_to(table());
#ifndef PRODUCT
    if (PrintVtables && Verbose) {
138
      ResourceMark rm;
D
duke 已提交
139 140 141 142 143 144 145
      tty->print_cr("copy vtable from %s to %s size %d", sk->internal_name(), klass()->internal_name(), _length);
    }
#endif
    return superVtable->length();
  }
}

146 147
//
// Revised lookup semantics   introduced 1.3 (Kestrel beta)
D
duke 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
void klassVtable::initialize_vtable(bool checkconstraints, TRAPS) {

  // Note:  Arrays can have intermediate array supers.  Use java_super to skip them.
  KlassHandle super (THREAD, klass()->java_super());
  int nofNewEntries = 0;

  if (PrintVtables && !klass()->oop_is_array()) {
    ResourceMark rm(THREAD);
    tty->print_cr("Initializing: %s", _klass->name()->as_C_string());
  }

#ifdef ASSERT
  oop* end_of_obj = (oop*)_klass() + _klass()->size();
  oop* end_of_vtable = (oop*)&table()[_length];
  assert(end_of_vtable <= end_of_obj, "vtable extends beyond end");
#endif

  if (Universe::is_bootstrapping()) {
    // just clear everything
    for (int i = 0; i < _length; i++) table()[i].clear();
    return;
  }

  int super_vtable_len = initialize_from_super(super);
  if (klass()->oop_is_array()) {
    assert(super_vtable_len == _length, "arrays shouldn't introduce new methods");
  } else {
175
    assert(_klass->oop_is_instance(), "must be InstanceKlass");
D
duke 已提交
176

177 178
    Array<Method*>* methods = ik()->methods();
    int len = methods->length();
D
duke 已提交
179 180
    int initialized = super_vtable_len;

181 182
    // Check each of this class's methods against super;
    // if override, replace in copy of super vtable, otherwise append to end
D
duke 已提交
183
    for (int i = 0; i < len; i++) {
184
      // update_inherited_vtable can stop for gc - ensure using handles
D
duke 已提交
185
      HandleMark hm(THREAD);
186 187
      assert(methods->at(i)->is_method(), "must be a Method*");
      methodHandle mh(THREAD, methods->at(i));
D
duke 已提交
188

189
      bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, checkconstraints, CHECK);
D
duke 已提交
190 191 192 193 194 195 196 197

      if (needs_new_entry) {
        put_method_at(mh(), initialized);
        mh()->set_vtable_index(initialized); // set primary vtable index
        initialized++;
      }
    }

198 199
    // add miranda methods to end of vtable.
    initialized = fill_in_mirandas(initialized);
D
duke 已提交
200

201
    // In class hierarchies where the accessibility is not increasing (i.e., going from private ->
202
    // package_private -> public/protected), the vtable might actually be smaller than our initial
D
duke 已提交
203 204 205 206 207 208 209 210 211
    // calculation.
    assert(initialized <= _length, "vtable initialization failed");
    for(;initialized < _length; initialized++) {
      put_method_at(NULL, initialized);
    }
    NOT_PRODUCT(verify(tty, true));
  }
}

212 213 214 215
// Called for cases where a method does not override its superclass' vtable entry
// For bytecodes not produced by javac together it is possible that a method does not override
// the superclass's method, but might indirectly override a super-super class's vtable entry
// If none found, return a null superk, else return the superk of the method this does override
216
InstanceKlass* klassVtable::find_transitive_override(InstanceKlass* initialsuper, methodHandle target_method,
217
                            int vtable_index, Handle target_loader, Symbol* target_classname, Thread * THREAD) {
218
  InstanceKlass* superk = initialsuper;
219
  while (superk != NULL && superk->super() != NULL) {
220
    InstanceKlass* supersuperklass = InstanceKlass::cast(superk->super());
221 222
    klassVtable* ssVtable = supersuperklass->vtable();
    if (vtable_index < ssVtable->length()) {
223
      Method* super_method = ssVtable->method_at(vtable_index);
224
#ifndef PRODUCT
225 226 227
      Symbol* name= target_method()->name();
      Symbol* signature = target_method()->signature();
      assert(super_method->name() == name && super_method->signature() == signature, "vtable entry name/sig mismatch");
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
#endif
      if (supersuperklass->is_override(super_method, target_loader, target_classname, THREAD)) {
#ifndef PRODUCT
        if (PrintVtables && Verbose) {
          ResourceMark rm(THREAD);
          tty->print("transitive overriding superclass %s with %s::%s index %d, original flags: ",
           supersuperklass->internal_name(),
           _klass->internal_name(), (target_method() != NULL) ?
           target_method()->name()->as_C_string() : "<NULL>", vtable_index);
           super_method->access_flags().print_on(tty);
           tty->print("overriders flags: ");
           target_method->access_flags().print_on(tty);
           tty->cr();
        }
#endif /*PRODUCT*/
        break; // return found superk
      }
    } else  {
      // super class has no vtable entry here, stop transitive search
247
      superk = (InstanceKlass*)NULL;
248 249 250
      break;
    }
    // if no override found yet, continue to search up
251
    superk = InstanceKlass::cast(superk->super());
252
  }
D
duke 已提交
253

254
  return superk;
D
duke 已提交
255 256 257
}

// Update child's copy of super vtable for overrides
258
// OR return true if a new vtable entry is required.
259
// Only called for InstanceKlass's, i.e. not for arrays
D
duke 已提交
260
// If that changed, could not use _klass as handle for klass
261
bool klassVtable::update_inherited_vtable(InstanceKlass* klass, methodHandle target_method, int super_vtable_len,
262
                  bool checkconstraints, TRAPS) {
D
duke 已提交
263 264
  ResourceMark rm;
  bool allocate_new = true;
265
  assert(klass->oop_is_instance(), "must be InstanceKlass");
266
  assert(klass == target_method()->method_holder(), "caller resp.");
D
duke 已提交
267 268 269

  // Initialize the method's vtable index to "nonvirtual".
  // If we allocate a vtable entry, we will update it to a non-negative number.
270
  target_method()->set_vtable_index(Method::nonvirtual_vtable_index);
D
duke 已提交
271 272 273 274 275 276

  // Static and <init> methods are never in
  if (target_method()->is_static() || target_method()->name() ==  vmSymbols::object_initializer_name()) {
    return false;
  }

277
  if (target_method->is_final_method(klass->access_flags())) {
D
duke 已提交
278 279 280 281
    // a final method never needs a new entry; final methods can be statically
    // resolved and they have to be present in the vtable only if they override
    // a super's method, in which case they re-use its entry
    allocate_new = false;
282 283 284 285 286 287
  } else if (klass->is_interface()) {
    allocate_new = false;  // see note below in needs_new_vtable_entry
    // An interface never allocates new vtable slots, only inherits old ones.
    // This method will either be assigned its own itable index later,
    // or be assigned an inherited vtable index in the loop below.
    target_method()->set_vtable_index(Method::pending_itable_index);
D
duke 已提交
288 289 290 291 292 293 294
  }

  // we need a new entry if there is no superclass
  if (klass->super() == NULL) {
    return allocate_new;
  }

295
  // private methods in classes always have a new entry in the vtable
296 297
  // specification interpretation since classic has
  // private methods not overriding
298
  // JDK8 adds private methods in interfaces which require invokespecial
D
duke 已提交
299 300 301 302 303 304
  if (target_method()->is_private()) {
    return allocate_new;
  }

  // search through the vtable and update overridden entries
  // Since check_signature_loaders acquires SystemDictionary_lock
305 306
  // which can block for gc, once we are in this loop, use handles
  // For classfiles built with >= jdk7, we now look for transitive overrides
D
duke 已提交
307

308 309
  Symbol* name = target_method()->name();
  Symbol* signature = target_method()->signature();
310
  Handle target_loader(THREAD, _klass()->class_loader());
311
  Symbol*  target_classname = _klass->name();
D
duke 已提交
312
  for(int i = 0; i < super_vtable_len; i++) {
313
    Method* super_method = method_at(i);
D
duke 已提交
314
    // Check if method name matches
315
    if (super_method->name() == name && super_method->signature() == signature) {
D
duke 已提交
316

317
      // get super_klass for method_holder for the found method
318
      InstanceKlass* super_klass =  super_method->method_holder();
D
duke 已提交
319

320 321 322
      if ((super_klass->is_override(super_method, target_loader, target_classname, THREAD)) ||
      ((klass->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION)
        && ((super_klass = find_transitive_override(super_klass, target_method, i, target_loader,
323
             target_classname, THREAD)) != (InstanceKlass*)NULL))) {
324 325
        // overriding, so no new entry
        allocate_new = false;
D
duke 已提交
326 327 328 329 330 331 332 333 334 335

        if (checkconstraints) {
        // Override vtable entry if passes loader constraint check
        // if loader constraint checking requested
        // No need to visit his super, since he and his super
        // have already made any needed loader constraints.
        // Since loader constraints are transitive, it is enough
        // to link to the first super, and we get all the others.
          Handle super_loader(THREAD, super_klass->class_loader());

336
          if (target_loader() != super_loader()) {
D
duke 已提交
337
            ResourceMark rm(THREAD);
338
            Symbol* failed_type_symbol =
339
              SystemDictionary::check_signature_loaders(signature, target_loader,
D
duke 已提交
340 341
                                                        super_loader, true,
                                                        CHECK_(false));
342
            if (failed_type_symbol != NULL) {
D
duke 已提交
343 344 345 346 347 348
              const char* msg = "loader constraint violation: when resolving "
                "overridden method \"%s\" the class loader (instance"
                " of %s) of the current class, %s, and its superclass loader "
                "(instance of %s), have different Class objects for the type "
                "%s used in the signature";
              char* sig = target_method()->name_and_sig_as_C_string();
349
              const char* loader1 = SystemDictionary::loader_name(target_loader());
D
duke 已提交
350 351
              char* current = _klass->name()->as_C_string();
              const char* loader2 = SystemDictionary::loader_name(super_loader());
352
              char* failed_type_name = failed_type_symbol->as_C_string();
D
duke 已提交
353 354 355 356 357 358 359 360
              size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
                strlen(current) + strlen(loader2) + strlen(failed_type_name);
              char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
              jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
                           failed_type_name);
              THROW_MSG_(vmSymbols::java_lang_LinkageError(), buf, false);
            }
          }
361
       }
D
duke 已提交
362

363 364
        put_method_at(target_method(), i);
        target_method()->set_vtable_index(i);
D
duke 已提交
365
#ifndef PRODUCT
366 367 368 369 370 371 372 373 374
        if (PrintVtables && Verbose) {
          tty->print("overriding with %s::%s index %d, original flags: ",
           _klass->internal_name(), (target_method() != NULL) ?
           target_method()->name()->as_C_string() : "<NULL>", i);
           super_method->access_flags().print_on(tty);
           tty->print("overriders flags: ");
           target_method->access_flags().print_on(tty);
           tty->cr();
        }
D
duke 已提交
375
#endif /*PRODUCT*/
376 377 378
      } else {
        // allocate_new = true; default. We might override one entry,
        // but not override another. Once we override one, not need new
D
duke 已提交
379
#ifndef PRODUCT
380 381 382 383 384 385 386 387
        if (PrintVtables && Verbose) {
          tty->print("NOT overriding with %s::%s index %d, original flags: ",
           _klass->internal_name(), (target_method() != NULL) ?
           target_method()->name()->as_C_string() : "<NULL>", i);
           super_method->access_flags().print_on(tty);
           tty->print("overriders flags: ");
           target_method->access_flags().print_on(tty);
           tty->cr();
D
duke 已提交
388
        }
389
#endif /*PRODUCT*/
D
duke 已提交
390 391 392 393 394 395
      }
    }
  }
  return allocate_new;
}

396
void klassVtable::put_method_at(Method* m, int index) {
D
duke 已提交
397 398
#ifndef PRODUCT
  if (PrintVtables && Verbose) {
399
    ResourceMark rm;
D
duke 已提交
400 401 402 403 404 405 406 407 408 409 410 411
    tty->print_cr("adding %s::%s at index %d", _klass->internal_name(),
      (m != NULL) ? m->name()->as_C_string() : "<NULL>", index);
  }
#endif
  table()[index].set(m);
}

// Find out if a method "m" with superclass "super", loader "classloader" and
// name "classname" needs a new vtable entry.  Let P be a class package defined
// by "classloader" and "classname".
// NOTE: The logic used here is very similar to the one used for computing
// the vtables indices for a method. We cannot directly use that function because,
412
// we allocate the InstanceKlass at load time, and that requires that the
413 414 415 416
// superclass has been loaded.
// However, the vtable entries are filled in at link time, and therefore
// the superclass' vtable may not yet have been filled in.
bool klassVtable::needs_new_vtable_entry(methodHandle target_method,
417
                                         Klass* super,
418
                                         Handle classloader,
419
                                         Symbol* classname,
420 421
                                         AccessFlags class_flags,
                                         TRAPS) {
422 423 424 425 426 427
  if (class_flags.is_interface()) {
    // Interfaces do not use vtables, so there is no point to assigning
    // a vtable index to any of their methods.  If we refrain from doing this,
    // we can use Method::_vtable_index to hold the itable index
    return false;
  }
428

429
  if (target_method->is_final_method(class_flags) ||
D
duke 已提交
430 431 432
      // a final method never needs a new entry; final methods can be statically
      // resolved and they have to be present in the vtable only if they override
      // a super's method, in which case they re-use its entry
433
      (target_method()->is_static()) ||
D
duke 已提交
434
      // static methods don't need to be in vtable
435
      (target_method()->name() ==  vmSymbols::object_initializer_name())
D
duke 已提交
436 437 438 439 440 441 442 443 444 445
      // <init> is never called dynamically-bound
      ) {
    return false;
  }

  // we need a new entry if there is no superclass
  if (super == NULL) {
    return true;
  }

446
  // private methods in classes always have a new entry in the vtable
447 448
  // specification interpretation since classic has
  // private methods not overriding
449
  // JDK8 adds private methods in interfaces which require invokespecial
450
  if (target_method()->is_private()) {
D
duke 已提交
451 452 453 454 455
    return true;
  }

  // search through the super class hierarchy to see if we need
  // a new entry
456
  ResourceMark rm;
457 458
  Symbol* name = target_method()->name();
  Symbol* signature = target_method()->signature();
459 460 461 462
  Klass* k = super;
  Method* super_method = NULL;
  InstanceKlass *holder = NULL;
  Method* recheck_method =  NULL;
D
duke 已提交
463 464
  while (k != NULL) {
    // lookup through the hierarchy for a method with matching name and sign.
465
    super_method = InstanceKlass::cast(k)->lookup_method(name, signature);
466
    if (super_method == NULL) {
D
duke 已提交
467 468 469
      break; // we still have to search for a matching miranda method
    }
    // get the class holding the matching method
470
    // make sure you use that class for is_override
471
    InstanceKlass* superk = super_method->method_holder();
472 473 474 475 476 477 478 479 480
    // we want only instance method matches
    // pretend private methods are not in the super vtable
    // since we do override around them: e.g. a.m pub/b.m private/c.m pub,
    // ignore private, c.m pub does override a.m pub
    // For classes that were not javac'd together, we also do transitive overriding around
    // methods that have less accessibility
    if ((!super_method->is_static()) &&
       (!super_method->is_private())) {
      if (superk->is_override(super_method, classloader, classname, THREAD)) {
D
duke 已提交
481
        return false;
482
      // else keep looking for transitive overrides
D
duke 已提交
483 484 485
      }
    }

486 487
    // Start with lookup result and continue to search up
    k = superk->super(); // haven't found an override match yet; continue to look
D
duke 已提交
488 489 490 491
  }

  // if the target method is public or protected it may have a matching
  // miranda method in the super, whose entry it should re-use.
492 493
  // Actually, to handle cases that javac would not generate, we need
  // this check for all access permissions.
494
  InstanceKlass *sk = InstanceKlass::cast(super);
495 496 497
  if (sk->has_miranda_methods()) {
    if (sk->lookup_method_in_all_interfaces(name, signature) != NULL) {
      return false;  // found a matching miranda; we do not need a new entry
D
duke 已提交
498 499 500 501 502 503 504 505
    }
  }
  return true; // found no match; we need a new entry
}

// Support for miranda methods

// get the vtable index of a miranda method with matching "name" and "signature"
506
int klassVtable::index_of_miranda(Symbol* name, Symbol* signature) {
D
duke 已提交
507 508
  // search from the bottom, might be faster
  for (int i = (length() - 1); i >= 0; i--) {
509
    Method* m = table()[i].method();
D
duke 已提交
510 511 512 513 514
    if (is_miranda_entry_at(i) &&
        m->name() == name && m->signature() == signature) {
      return i;
    }
  }
515
  return Method::invalid_vtable_index;
D
duke 已提交
516 517
}

518 519
// check if an entry at an index is miranda
// requires that method m at entry be declared ("held") by an interface.
D
duke 已提交
520
bool klassVtable::is_miranda_entry_at(int i) {
521 522 523
  Method* m = method_at(i);
  Klass* method_holder = m->method_holder();
  InstanceKlass *mhk = InstanceKlass::cast(method_holder);
D
duke 已提交
524

525
  // miranda methods are public abstract instance interface methods in a class's vtable
D
duke 已提交
526
  if (mhk->is_interface()) {
527
    assert(m->is_public(), "should be public");
D
duke 已提交
528 529 530 531 532 533 534
    assert(ik()->implements_interface(method_holder) , "this class should implement the interface");
    assert(is_miranda(m, ik()->methods(), ik()->super()), "should be a miranda_method");
    return true;
  }
  return false;
}

535 536 537
// check if a method is a miranda method, given a class's methods table and its super
// "miranda" means not static, not defined by this class, and not defined
// in super unless it is private and therefore inaccessible to this class.
D
duke 已提交
538
// the caller must make sure that the method belongs to an interface implemented by the class
539 540
// Miranda methods only include public interface instance methods
// Not private methods, not static methods, not default = concrete abstract
541
bool klassVtable::is_miranda(Method* m, Array<Method*>* class_methods, Klass* super) {
542 543 544
  if (m->is_static()) {
    return false;
  }
545 546
  Symbol* name = m->name();
  Symbol* signature = m->signature();
547
  if (InstanceKlass::find_method(class_methods, name, signature) == NULL) {
548
    // did not find it in the method table of the current class
D
duke 已提交
549 550 551
    if (super == NULL) {
      // super doesn't exist
      return true;
552 553
    }

554
    Method* mo = InstanceKlass::cast(super)->lookup_method(name, signature);
555 556 557
    if (mo == NULL || mo->access_flags().is_private() ) {
      // super class hierarchy does not implement it or protection is different
      return true;
D
duke 已提交
558 559
    }
  }
560

D
duke 已提交
561 562 563
  return false;
}

564 565 566 567 568 569 570 571
// Scans current_interface_methods for miranda methods that do not
// already appear in new_mirandas and are also not defined-and-non-private
// in super (superclass).  These mirandas are added to all_mirandas if it is
// not null; in addition, those that are not duplicates of miranda methods
// inherited by super from its interfaces are added to new_mirandas.
// Thus, new_mirandas will be the set of mirandas that this class introduces,
// all_mirandas will be the set of all mirandas applicable to this class
// including all defined in superclasses.
572 573 574 575
void klassVtable::add_new_mirandas_to_lists(
    GrowableArray<Method*>* new_mirandas, GrowableArray<Method*>* all_mirandas,
    Array<Method*>* current_interface_methods, Array<Method*>* class_methods,
    Klass* super) {
D
duke 已提交
576 577 578
  // iterate thru the current interface's method to see if it a miranda
  int num_methods = current_interface_methods->length();
  for (int i = 0; i < num_methods; i++) {
579
    Method* im = current_interface_methods->at(i);
D
duke 已提交
580
    bool is_duplicate = false;
581
    int num_of_current_mirandas = new_mirandas->length();
D
duke 已提交
582 583
    // check for duplicate mirandas in different interfaces we implement
    for (int j = 0; j < num_of_current_mirandas; j++) {
584
      Method* miranda = new_mirandas->at(j);
D
duke 已提交
585 586 587 588 589 590 591 592 593
      if ((im->name() == miranda->name()) &&
          (im->signature() == miranda->signature())) {
        is_duplicate = true;
        break;
      }
    }

    if (!is_duplicate) { // we don't want duplicate miranda entries in the vtable
      if (is_miranda(im, class_methods, super)) { // is it a miranda at all?
594
        InstanceKlass *sk = InstanceKlass::cast(super);
D
duke 已提交
595 596
        // check if it is a duplicate of a super's miranda
        if (sk->lookup_method_in_all_interfaces(im->name(), im->signature()) == NULL) {
597 598 599 600
          new_mirandas->append(im);
        }
        if (all_mirandas != NULL) {
          all_mirandas->append(im);
D
duke 已提交
601 602 603 604 605 606
        }
      }
    }
  }
}

607 608
void klassVtable::get_mirandas(GrowableArray<Method*>* new_mirandas,
                               GrowableArray<Method*>* all_mirandas,
609 610
                               Klass* super, Array<Method*>* class_methods,
                               Array<Klass*>* local_interfaces) {
611
  assert((new_mirandas->length() == 0) , "current mirandas must be 0");
D
duke 已提交
612 613 614 615

  // iterate thru the local interfaces looking for a miranda
  int num_local_ifs = local_interfaces->length();
  for (int i = 0; i < num_local_ifs; i++) {
616
    InstanceKlass *ik = InstanceKlass::cast(local_interfaces->at(i));
617 618
    add_new_mirandas_to_lists(new_mirandas, all_mirandas,
                              ik->methods(), class_methods, super);
D
duke 已提交
619
    // iterate thru each local's super interfaces
620
    Array<Klass*>* super_ifs = ik->transitive_interfaces();
D
duke 已提交
621 622
    int num_super_ifs = super_ifs->length();
    for (int j = 0; j < num_super_ifs; j++) {
623
      InstanceKlass *sik = InstanceKlass::cast(super_ifs->at(j));
624 625
      add_new_mirandas_to_lists(new_mirandas, all_mirandas,
                                sik->methods(), class_methods, super);
D
duke 已提交
626 627 628 629
    }
  }
}

630 631 632 633
// Discover miranda methods ("miranda" = "interface abstract, no binding"),
// and append them into the vtable starting at index initialized,
// return the new value of initialized.
int klassVtable::fill_in_mirandas(int initialized) {
634 635 636 637
  GrowableArray<Method*> mirandas(20);
  get_mirandas(&mirandas, NULL, ik()->super(), ik()->methods(),
               ik()->local_interfaces());
  for (int i = 0; i < mirandas.length(); i++) {
638 639
    put_method_at(mirandas.at(i), initialized);
    ++initialized;
D
duke 已提交
640
  }
641
  return initialized;
D
duke 已提交
642 643
}

644 645
// Copy this class's vtable to the vtable beginning at start.
// Used to copy superclass vtable to prefix of subclass's vtable.
D
duke 已提交
646 647 648 649
void klassVtable::copy_vtable_to(vtableEntry* start) {
  Copy::disjoint_words((HeapWord*)table(), (HeapWord*)start, _length * vtableEntry::size());
}

650
#if INCLUDE_JVMTI
651
void klassVtable::adjust_method_entries(Method** old_methods, Method** new_methods,
D
duke 已提交
652 653 654
                                        int methods_length, bool * trace_name_printed) {
  // search the vtable for uses of either obsolete or EMCP methods
  for (int j = 0; j < methods_length; j++) {
655 656
    Method* old_method = old_methods[j];
    Method* new_method = new_methods[j];
D
duke 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670

    // In the vast majority of cases we could get the vtable index
    // by using:  old_method->vtable_index()
    // However, there are rare cases, eg. sun.awt.X11.XDecoratedPeer.getX()
    // in sun.awt.X11.XFramePeer where methods occur more than once in the
    // vtable, so, alas, we must do an exhaustive search.
    for (int index = 0; index < length(); index++) {
      if (unchecked_method_at(index) == old_method) {
        put_method_at(new_method, index);

        if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
          if (!(*trace_name_printed)) {
            // RC_TRACE_MESG macro has an embedded ResourceMark
            RC_TRACE_MESG(("adjust: name=%s",
671
                           old_method->method_holder()->external_name()));
D
duke 已提交
672 673 674 675 676 677 678
            *trace_name_printed = true;
          }
          // RC_TRACE macro has an embedded ResourceMark
          RC_TRACE(0x00100000, ("vtable method update: %s(%s)",
                                new_method->name()->as_C_string(),
                                new_method->signature()->as_C_string()));
        }
679
        // cannot 'break' here; see for-loop comment above.
D
duke 已提交
680 681 682 683 684
      }
    }
  }
}

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
// a vtable should never contain old or obsolete methods
bool klassVtable::check_no_old_or_obsolete_entries() {
  for (int i = 0; i < length(); i++) {
    Method* m = unchecked_method_at(i);
    if (m != NULL &&
        (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
      return false;
    }
  }
  return true;
}

void klassVtable::dump_vtable() {
  tty->print_cr("vtable dump --");
  for (int i = 0; i < length(); i++) {
    Method* m = unchecked_method_at(i);
    if (m != NULL) {
      tty->print("      (%5d)  ", i);
      m->access_flags().print_on(tty);
      tty->print(" --  ");
      m->print_name(tty);
      tty->cr();
    }
  }
}
#endif // INCLUDE_JVMTI

712 713 714 715 716 717 718 719 720
// CDS/RedefineClasses support - clear vtables so they can be reinitialized
void klassVtable::clear_vtable() {
  for (int i = 0; i < _length; i++) table()[i].clear();
}

bool klassVtable::is_initialized() {
  return _length == 0 || table()[0].method() != NULL;
}

D
duke 已提交
721 722 723 724
//-----------------------------------------------------------------------------------------
// Itable code

// Initialize a itableMethodEntry
725
void itableMethodEntry::initialize(Method* m) {
D
duke 已提交
726 727 728 729 730 731 732 733 734 735 736 737
  if (m == NULL) return;

  _method = m;
}

klassItable::klassItable(instanceKlassHandle klass) {
  _klass = klass;

  if (klass->itable_length() > 0) {
    itableOffsetEntry* offset_entry = (itableOffsetEntry*)klass->start_of_itable();
    if (offset_entry  != NULL && offset_entry->interface_klass() != NULL) { // Check that itable is initialized
      // First offset entry points to the first method_entry
738
      intptr_t* method_entry  = (intptr_t *)(((address)klass()) + offset_entry->offset());
D
duke 已提交
739 740
      intptr_t* end         = klass->end_of_itable();

741
      _table_offset      = (intptr_t*)offset_entry - (intptr_t*)klass();
D
duke 已提交
742 743 744 745 746 747 748
      _size_offset_table = (method_entry - ((intptr_t*)offset_entry)) / itableOffsetEntry::size();
      _size_method_table = (end - method_entry)                  / itableMethodEntry::size();
      assert(_table_offset >= 0 && _size_offset_table >= 0 && _size_method_table >= 0, "wrong computation");
      return;
    }
  }

749
  // The length of the itable was either zero, or it has not yet been initialized.
D
duke 已提交
750 751 752 753 754 755 756 757 758
  _table_offset      = 0;
  _size_offset_table = 0;
  _size_method_table = 0;
}

static int initialize_count = 0;

// Initialization
void klassItable::initialize_itable(bool checkconstraints, TRAPS) {
759 760 761 762 763 764
  if (_klass->is_interface()) {
    // This needs to go after vtable indexes are assigned but
    // before implementors need to know the number of itable indexes.
    assign_itable_indexes_for_interface(_klass());
  }

765 766 767 768 769 770 771 772 773
  // Cannot be setup doing bootstrapping, interfaces don't have
  // itables, and klass with only ones entry have empty itables
  if (Universe::is_bootstrapping() ||
      _klass->is_interface() ||
      _klass->itable_length() == itableOffsetEntry::size()) return;

  // There's alway an extra itable entry so we can null-terminate it.
  guarantee(size_offset_table() >= 1, "too small");
  int num_interfaces = size_offset_table() - 1;
D
duke 已提交
774
  if (num_interfaces > 0) {
775 776
    if (TraceItables) tty->print_cr("%3d: Initializing itables for %s", ++initialize_count,
                                    _klass->name()->as_C_string());
D
duke 已提交
777 778


779
    // Iterate through all interfaces
D
duke 已提交
780 781 782
    int i;
    for(i = 0; i < num_interfaces; i++) {
      itableOffsetEntry* ioe = offset_entry(i);
783
      HandleMark hm(THREAD);
D
duke 已提交
784 785 786 787 788 789
      KlassHandle interf_h (THREAD, ioe->interface_klass());
      assert(interf_h() != NULL && ioe->offset() != 0, "bad offset entry in itable");
      initialize_itable_for_interface(ioe->offset(), interf_h, checkconstraints, CHECK);
    }

  }
790 791 792
  // Check that the last entry is empty
  itableOffsetEntry* ioe = offset_entry(size_offset_table() - 1);
  guarantee(ioe->interface_klass() == NULL && ioe->offset() == 0, "terminator entry missing");
D
duke 已提交
793 794 795
}


796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
inline bool interface_method_needs_itable_index(Method* m) {
  if (m->is_static())           return false;   // e.g., Stream.empty
  if (m->is_initializer())      return false;   // <init> or <clinit>
  // If an interface redeclares a method from java.lang.Object,
  // it should already have a vtable index, don't touch it.
  // e.g., CharSequence.toString (from initialize_vtable)
  // if (m->has_vtable_index())  return false; // NO!
  return true;
}

int klassItable::assign_itable_indexes_for_interface(Klass* klass) {
  // an interface does not have an itable, but its methods need to be numbered
  if (TraceItables) tty->print_cr("%3d: Initializing itable for interface %s", ++initialize_count,
                                  klass->name()->as_C_string());
  Array<Method*>* methods = InstanceKlass::cast(klass)->methods();
  int nof_methods = methods->length();
  int ime_num = 0;
  for (int i = 0; i < nof_methods; i++) {
    Method* m = methods->at(i);
    if (interface_method_needs_itable_index(m)) {
      assert(!m->is_final_method(), "no final interface methods");
      // If m is already assigned a vtable index, do not disturb it.
      if (!m->has_vtable_index()) {
        assert(m->vtable_index() == Method::pending_itable_index, "set by initialize_vtable");
        m->set_itable_index(ime_num);
        // Progress to next itable entry
        ime_num++;
      }
    }
  }
  assert(ime_num == method_count_for_interface(klass), "proper sizing");
  return ime_num;
}

int klassItable::method_count_for_interface(Klass* interf) {
  assert(interf->oop_is_instance(), "must be");
  assert(interf->is_interface(), "must be");
  Array<Method*>* methods = InstanceKlass::cast(interf)->methods();
  int nof_methods = methods->length();
  while (nof_methods > 0) {
    Method* m = methods->at(nof_methods-1);
    if (m->has_itable_index()) {
      int length = m->itable_index() + 1;
#ifdef ASSERT
      while (nof_methods = 0) {
        m = methods->at(--nof_methods);
        assert(!m->has_itable_index() || m->itable_index() < length, "");
      }
#endif //ASSERT
      return length;  // return the rightmost itable index, plus one
    }
    nof_methods -= 1;
  }
  // no methods have itable indexes
  return 0;
}


D
duke 已提交
854
void klassItable::initialize_itable_for_interface(int method_table_offset, KlassHandle interf_h, bool checkconstraints, TRAPS) {
855 856
  Array<Method*>* methods = InstanceKlass::cast(interf_h())->methods();
  int nof_methods = methods->length();
D
duke 已提交
857
  HandleMark hm;
858
  assert(nof_methods > 0, "at least one method must exist for interface to be in vtable");
859
  Handle interface_loader (THREAD, InstanceKlass::cast(interf_h())->class_loader());
D
duke 已提交
860

861 862
  int ime_count = method_count_for_interface(interf_h());
  for (int i = 0; i < nof_methods; i++) {
863
    Method* m = methods->at(i);
864 865 866
    methodHandle target;
    if (m->has_itable_index()) {
      LinkResolver::lookup_instance_method_in_klasses(target, _klass, m->name(), m->signature(), CHECK);
D
duke 已提交
867 868 869 870 871 872 873
    }
    if (target == NULL || !target->is_public() || target->is_abstract()) {
      // Entry do not resolve. Leave it empty
    } else {
      // Entry did resolve, check loader constraints before initializing
      // if checkconstraints requested
      if (checkconstraints) {
874
        Handle method_holder_loader (THREAD, target->method_holder()->class_loader());
D
duke 已提交
875 876
        if (method_holder_loader() != interface_loader()) {
          ResourceMark rm(THREAD);
877
          Symbol* failed_type_symbol =
878
            SystemDictionary::check_signature_loaders(m->signature(),
D
duke 已提交
879 880 881
                                                      method_holder_loader,
                                                      interface_loader,
                                                      true, CHECK);
882
          if (failed_type_symbol != NULL) {
D
duke 已提交
883 884 885 886 887 888
            const char* msg = "loader constraint violation in interface "
              "itable initialization: when resolving method \"%s\" the class"
              " loader (instance of %s) of the current class, %s, "
              "and the class loader (instance of %s) for interface "
              "%s have different Class objects for the type %s "
              "used in the signature";
889
            char* sig = target()->name_and_sig_as_C_string();
D
duke 已提交
890
            const char* loader1 = SystemDictionary::loader_name(method_holder_loader());
891
            char* current = _klass->name()->as_C_string();
D
duke 已提交
892
            const char* loader2 = SystemDictionary::loader_name(interface_loader());
893
            char* iface = InstanceKlass::cast(interf_h())->name()->as_C_string();
894
            char* failed_type_name = failed_type_symbol->as_C_string();
D
duke 已提交
895 896 897 898 899 900 901 902 903 904 905 906
            size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
              strlen(current) + strlen(loader2) + strlen(iface) +
              strlen(failed_type_name);
            char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
            jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
                         iface, failed_type_name);
            THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
          }
        }
      }

      // ime may have moved during GC so recalculate address
907 908 909
      int ime_num = m->itable_index();
      assert(ime_num < ime_count, "oob");
      itableOffsetEntry::method_entry(_klass(), method_table_offset)[ime_num].initialize(target());
D
duke 已提交
910 911 912 913
    }
  }
}

914 915
// Update entry for specific Method*
void klassItable::initialize_with_method(Method* m) {
D
duke 已提交
916 917 918 919 920 921 922 923 924
  itableMethodEntry* ime = method_entry(0);
  for(int i = 0; i < _size_method_table; i++) {
    if (ime->method() == m) {
      ime->initialize(m);
    }
    ime++;
  }
}

925
#if INCLUDE_JVMTI
926
void klassItable::adjust_method_entries(Method** old_methods, Method** new_methods,
D
duke 已提交
927 928 929
                                        int methods_length, bool * trace_name_printed) {
  // search the itable for uses of either obsolete or EMCP methods
  for (int j = 0; j < methods_length; j++) {
930 931
    Method* old_method = old_methods[j];
    Method* new_method = new_methods[j];
D
duke 已提交
932 933
    itableMethodEntry* ime = method_entry(0);

934 935 936 937
    // The itable can describe more than one interface and the same
    // method signature can be specified by more than one interface.
    // This means we have to do an exhaustive search to find all the
    // old_method references.
D
duke 已提交
938 939 940 941 942 943 944 945
    for (int i = 0; i < _size_method_table; i++) {
      if (ime->method() == old_method) {
        ime->initialize(new_method);

        if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
          if (!(*trace_name_printed)) {
            // RC_TRACE_MESG macro has an embedded ResourceMark
            RC_TRACE_MESG(("adjust: name=%s",
946
              old_method->method_holder()->external_name()));
D
duke 已提交
947 948 949 950 951 952 953
            *trace_name_printed = true;
          }
          // RC_TRACE macro has an embedded ResourceMark
          RC_TRACE(0x00200000, ("itable method update: %s(%s)",
            new_method->name()->as_C_string(),
            new_method->signature()->as_C_string()));
        }
954
        // cannot 'break' here; see for-loop comment above.
D
duke 已提交
955 956 957 958 959 960
      }
      ime++;
    }
  }
}

961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
// an itable should never contain old or obsolete methods
bool klassItable::check_no_old_or_obsolete_entries() {
  itableMethodEntry* ime = method_entry(0);
  for (int i = 0; i < _size_method_table; i++) {
    Method* m = ime->method();
    if (m != NULL &&
        (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
      return false;
    }
    ime++;
  }
  return true;
}

void klassItable::dump_itable() {
  itableMethodEntry* ime = method_entry(0);
  tty->print_cr("itable dump --");
  for (int i = 0; i < _size_method_table; i++) {
    Method* m = ime->method();
    if (m != NULL) {
      tty->print("      (%5d)  ", i);
      m->access_flags().print_on(tty);
      tty->print(" --  ");
      m->print_name(tty);
      tty->cr();
    }
    ime++;
  }
}
#endif // INCLUDE_JVMTI

D
duke 已提交
992 993 994 995

// Setup
class InterfaceVisiterClosure : public StackObj {
 public:
996
  virtual void doit(Klass* intf, int method_count) = 0;
D
duke 已提交
997 998
};

999
// Visit all interfaces with at least one itable method
1000
void visit_all_interfaces(Array<Klass*>* transitive_intf, InterfaceVisiterClosure *blk) {
D
duke 已提交
1001 1002
  // Handle array argument
  for(int i = 0; i < transitive_intf->length(); i++) {
1003
    Klass* intf = transitive_intf->at(i);
H
hseigel 已提交
1004
    assert(intf->is_interface(), "sanity check");
D
duke 已提交
1005

1006 1007 1008 1009 1010 1011 1012 1013 1014
    // Find no. of itable methods
    int method_count = 0;
    // method_count = klassItable::method_count_for_interface(intf);
    Array<Method*>* methods = InstanceKlass::cast(intf)->methods();
    if (methods->length() > 0) {
      for (int i = methods->length(); --i >= 0; ) {
        if (interface_method_needs_itable_index(methods->at(i))) {
          method_count++;
        }
D
duke 已提交
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
      }
    }

    // Only count interfaces with at least one method
    if (method_count > 0) {
      blk->doit(intf, method_count);
    }
  }
}

class CountInterfacesClosure : public InterfaceVisiterClosure {
 private:
  int _nof_methods;
  int _nof_interfaces;
 public:
   CountInterfacesClosure() { _nof_methods = 0; _nof_interfaces = 0; }

   int nof_methods() const    { return _nof_methods; }
   int nof_interfaces() const { return _nof_interfaces; }

1035
   void doit(Klass* intf, int method_count) { _nof_methods += method_count; _nof_interfaces++; }
D
duke 已提交
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
};

class SetupItableClosure : public InterfaceVisiterClosure  {
 private:
  itableOffsetEntry* _offset_entry;
  itableMethodEntry* _method_entry;
  address            _klass_begin;
 public:
  SetupItableClosure(address klass_begin, itableOffsetEntry* offset_entry, itableMethodEntry* method_entry) {
    _klass_begin  = klass_begin;
    _offset_entry = offset_entry;
    _method_entry = method_entry;
  }

  itableMethodEntry* method_entry() const { return _method_entry; }

1052
  void doit(Klass* intf, int method_count) {
D
duke 已提交
1053 1054 1055 1056 1057 1058 1059
    int offset = ((address)_method_entry) - _klass_begin;
    _offset_entry->initialize(intf, offset);
    _offset_entry++;
    _method_entry += method_count;
  }
};

1060
int klassItable::compute_itable_size(Array<Klass*>* transitive_interfaces) {
D
duke 已提交
1061 1062
  // Count no of interfaces and total number of interface methods
  CountInterfacesClosure cic;
1063
  visit_all_interfaces(transitive_interfaces, &cic);
D
duke 已提交
1064

1065 1066
  // There's alway an extra itable entry so we can null-terminate it.
  int itable_size = calc_itable_size(cic.nof_interfaces() + 1, cic.nof_methods());
D
duke 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085

  // Statistics
  update_stats(itable_size * HeapWordSize);

  return itable_size;
}


// Fill out offset table and interface klasses into the itable space
void klassItable::setup_itable_offset_table(instanceKlassHandle klass) {
  if (klass->itable_length() == 0) return;
  assert(!klass->is_interface(), "Should have zero length itable");

  // Count no of interfaces and total number of interface methods
  CountInterfacesClosure cic;
  visit_all_interfaces(klass->transitive_interfaces(), &cic);
  int nof_methods    = cic.nof_methods();
  int nof_interfaces = cic.nof_interfaces();

1086 1087
  // Add one extra entry so we can null-terminate the table
  nof_interfaces++;
D
duke 已提交
1088

1089
  assert(compute_itable_size(klass->transitive_interfaces()) ==
D
duke 已提交
1090 1091 1092 1093 1094 1095 1096
         calc_itable_size(nof_interfaces, nof_methods),
         "mismatch calculation of itable size");

  // Fill-out offset table
  itableOffsetEntry* ioe = (itableOffsetEntry*)klass->start_of_itable();
  itableMethodEntry* ime = (itableMethodEntry*)(ioe + nof_interfaces);
  intptr_t* end               = klass->end_of_itable();
1097
  assert((oop*)(ime + nof_methods) <= (oop*)klass->start_of_nonstatic_oop_maps(), "wrong offset calculation (1)");
1098
  assert((oop*)(end) == (oop*)(ime + nof_methods),                      "wrong offset calculation (2)");
D
duke 已提交
1099 1100

  // Visit all interfaces and initialize itable offset table
1101
  SetupItableClosure sic((address)klass(), ioe, ime);
D
duke 已提交
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
  visit_all_interfaces(klass->transitive_interfaces(), &sic);

#ifdef ASSERT
  ime  = sic.method_entry();
  oop* v = (oop*) klass->end_of_itable();
  assert( (oop*)(ime) == v, "wrong offset calculation (2)");
#endif
}


1112
// inverse to itable_index
1113 1114
Method* klassItable::method_for_itable_index(Klass* intf, int itable_index) {
  assert(InstanceKlass::cast(intf)->is_interface(), "sanity check");
1115
  assert(intf->verify_itable_index(itable_index), "");
1116
  Array<Method*>* methods = InstanceKlass::cast(intf)->methods();
1117

1118
  if (itable_index < 0 || itable_index >= method_count_for_interface(intf))
1119 1120
    return NULL;                // help caller defend against bad indexes

1121
  int index = itable_index;
1122
  Method* m = methods->at(index);
1123 1124 1125 1126 1127 1128 1129 1130 1131
  int index2 = -1;
  while (!m->has_itable_index() ||
         (index2 = m->itable_index()) != itable_index) {
    assert(index2 < itable_index, "monotonic");
    if (++index == methods->length())
      return NULL;
    m = methods->at(index);
  }
  assert(m->itable_index() == itable_index, "correct inverse");
1132 1133 1134 1135

  return m;
}

D
duke 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
void klassVtable::verify(outputStream* st, bool forced) {
  // make sure table is initialized
  if (!Universe::is_fully_initialized()) return;
#ifndef PRODUCT
  // avoid redundant verifies
  if (!forced && _verify_count == Universe::verify_count()) return;
  _verify_count = Universe::verify_count();
#endif
  oop* end_of_obj = (oop*)_klass() + _klass()->size();
  oop* end_of_vtable = (oop *)&table()[_length];
  if (end_of_vtable > end_of_obj) {
1147 1148
    fatal(err_msg("klass %s: klass object too short (vtable extends beyond "
                  "end)", _klass->internal_name()));
D
duke 已提交
1149 1150 1151 1152
  }

  for (int i = 0; i < _length; i++) table()[i].verify(this, st);
  // verify consistency with superKlass vtable
1153
  Klass* super = _klass->super();
D
duke 已提交
1154
  if (super != NULL) {
1155
    InstanceKlass* sk = InstanceKlass::cast(super);
D
duke 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
    klassVtable* vt = sk->vtable();
    for (int i = 0; i < vt->length(); i++) {
      verify_against(st, vt, i);
    }
  }
}

void klassVtable::verify_against(outputStream* st, klassVtable* vt, int index) {
  vtableEntry* vte = &vt->table()[index];
  if (vte->method()->name()      != table()[index].method()->name() ||
      vte->method()->signature() != table()[index].method()->signature()) {
    fatal("mismatched name/signature of vtable entries");
  }
}

#ifndef PRODUCT
void klassVtable::print() {
  ResourceMark rm;
  tty->print("klassVtable for klass %s (length %d):\n", _klass->internal_name(), length());
  for (int i = 0; i < length(); i++) {
    table()[i].print();
    tty->cr();
  }
}
#endif

void vtableEntry::verify(klassVtable* vt, outputStream* st) {
  NOT_PRODUCT(FlagSetting fs(IgnoreLockingAssertions, true));
  assert(method() != NULL, "must have set method");
  method()->verify();
  // we sub_type, because it could be a miranda method
  if (!vt->klass()->is_subtype_of(method()->method_holder())) {
#ifndef PRODUCT
    print();
#endif
1191
    fatal(err_msg("vtableEntry " PTR_FORMAT ": method is from subclass", this));
D
duke 已提交
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
  }
}

#ifndef PRODUCT

void vtableEntry::print() {
  ResourceMark rm;
  tty->print("vtableEntry %s: ", method()->name()->as_C_string());
  if (Verbose) {
    tty->print("m %#lx ", (address)method());
  }
}

class VtableStats : AllStatic {
 public:
  static int no_klasses;                // # classes with vtables
  static int no_array_klasses;          // # array classes
  static int no_instance_klasses;       // # instanceKlasses
  static int sum_of_vtable_len;         // total # of vtable entries
  static int sum_of_array_vtable_len;   // total # of vtable entries in array klasses only
  static int fixed;                     // total fixed overhead in bytes
  static int filler;                    // overhead caused by filler bytes
  static int entries;                   // total bytes consumed by vtable entries
  static int array_entries;             // total bytes consumed by array vtable entries

1217 1218
  static void do_class(Klass* k) {
    Klass* kl = k;
D
duke 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    klassVtable* vt = kl->vtable();
    if (vt == NULL) return;
    no_klasses++;
    if (kl->oop_is_instance()) {
      no_instance_klasses++;
      kl->array_klasses_do(do_class);
    }
    if (kl->oop_is_array()) {
      no_array_klasses++;
      sum_of_array_vtable_len += vt->length();
    }
    sum_of_vtable_len += vt->length();
  }

  static void compute() {
    SystemDictionary::classes_do(do_class);
    fixed  = no_klasses * oopSize;      // vtable length
    // filler size is a conservative approximation
1237
    filler = oopSize * (no_klasses - no_instance_klasses) * (sizeof(InstanceKlass) - sizeof(ArrayKlass) - 1);
D
duke 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
    entries = sizeof(vtableEntry) * sum_of_vtable_len;
    array_entries = sizeof(vtableEntry) * sum_of_array_vtable_len;
  }
};

int VtableStats::no_klasses = 0;
int VtableStats::no_array_klasses = 0;
int VtableStats::no_instance_klasses = 0;
int VtableStats::sum_of_vtable_len = 0;
int VtableStats::sum_of_array_vtable_len = 0;
int VtableStats::fixed = 0;
int VtableStats::filler = 0;
int VtableStats::entries = 0;
int VtableStats::array_entries = 0;

void klassVtable::print_statistics() {
  ResourceMark rm;
  HandleMark hm;
  VtableStats::compute();
  tty->print_cr("vtable statistics:");
  tty->print_cr("%6d classes (%d instance, %d array)", VtableStats::no_klasses, VtableStats::no_instance_klasses, VtableStats::no_array_klasses);
  int total = VtableStats::fixed + VtableStats::filler + VtableStats::entries;
  tty->print_cr("%6d bytes fixed overhead (refs + vtable object header)", VtableStats::fixed);
  tty->print_cr("%6d bytes filler overhead", VtableStats::filler);
  tty->print_cr("%6d bytes for vtable entries (%d for arrays)", VtableStats::entries, VtableStats::array_entries);
  tty->print_cr("%6d bytes total", total);
}

int  klassItable::_total_classes;   // Total no. of classes with itables
long klassItable::_total_size;      // Total no. of bytes used for itables

void klassItable::print_statistics() {
 tty->print_cr("itable statistics:");
 tty->print_cr("%6d classes with itables", _total_classes);
 tty->print_cr("%6d K uses for itables (average by class: %d bytes)", _total_size / K, _total_size / _total_classes);
}

#endif // PRODUCT