instanceKlass.cpp 132.9 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 34 35 36
#include "precompiled.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/verifier.hpp"
#include "classfile/vmSymbols.hpp"
#include "compiler/compileBroker.hpp"
#include "gc_implementation/shared/markSweep.inline.hpp"
#include "gc_interface/collectedHeap.inline.hpp"
#include "interpreter/oopMapCache.hpp"
#include "interpreter/rewriter.hpp"
#include "jvmtifiles/jvmti.h"
#include "memory/genOopClosures.inline.hpp"
37
#include "memory/heapInspection.hpp"
38
#include "memory/metadataFactory.hpp"
39
#include "memory/oopFactory.hpp"
40
#include "oops/fieldStreams.hpp"
41
#include "oops/instanceClassLoaderKlass.hpp"
42
#include "oops/instanceKlass.hpp"
43
#include "oops/instanceMirrorKlass.hpp"
44
#include "oops/instanceOop.hpp"
45 46
#include "oops/klass.inline.hpp"
#include "oops/method.hpp"
47
#include "oops/oop.inline.hpp"
48
#include "oops/symbol.hpp"
49 50
#include "prims/jvmtiExport.hpp"
#include "prims/jvmtiRedefineClassesTrace.hpp"
51
#include "prims/jvmtiRedefineClasses.hpp"
52
#include "prims/methodComparator.hpp"
53 54 55 56
#include "runtime/fieldDescriptor.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
57
#include "runtime/thread.inline.hpp"
58
#include "services/classLoadingService.hpp"
59 60
#include "services/threadService.hpp"
#include "utilities/dtrace.hpp"
61 62
#include "utilities/macros.hpp"
#if INCLUDE_ALL_GCS
63
#include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
64 65 66 67 68
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
#include "gc_implementation/g1/g1OopClosures.inline.hpp"
#include "gc_implementation/g1/g1RemSet.inline.hpp"
#include "gc_implementation/g1/heapRegionSeq.inline.hpp"
#include "gc_implementation/parNew/parOopClosures.inline.hpp"
69
#include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
70 71 72
#include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
#include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
#include "oops/oop.pcgc.inline.hpp"
73
#endif // INCLUDE_ALL_GCS
74 75 76
#ifdef COMPILER1
#include "c1/c1_Compiler.hpp"
#endif
D
duke 已提交
77

78 79
#ifdef DTRACE_ENABLED

D
dcubed 已提交
80 81
#ifndef USDT2

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
  char*, intptr_t, oop, intptr_t);
HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
  char*, intptr_t, oop, intptr_t, int);
HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
  char*, intptr_t, oop, intptr_t, int);
HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
  char*, intptr_t, oop, intptr_t, int);
HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
  char*, intptr_t, oop, intptr_t, int);
HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
  char*, intptr_t, oop, intptr_t, int);
HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
  char*, intptr_t, oop, intptr_t, int);
HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
  char*, intptr_t, oop, intptr_t, int);

#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
  {                                                              \
    char* data = NULL;                                           \
    int len = 0;                                                 \
103
    Symbol* name = (clss)->name();                               \
104 105 106 107 108 109 110 111 112 113 114 115
    if (name != NULL) {                                          \
      data = (char*)name->bytes();                               \
      len = name->utf8_length();                                 \
    }                                                            \
    HS_DTRACE_PROBE4(hotspot, class__initialization__##type,     \
      data, len, (clss)->class_loader(), thread_type);           \
  }

#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
  {                                                              \
    char* data = NULL;                                           \
    int len = 0;                                                 \
116
    Symbol* name = (clss)->name();                               \
117 118 119 120 121 122 123
    if (name != NULL) {                                          \
      data = (char*)name->bytes();                               \
      len = name->utf8_length();                                 \
    }                                                            \
    HS_DTRACE_PROBE5(hotspot, class__initialization__##type,     \
      data, len, (clss)->class_loader(), thread_type, wait);     \
  }
D
dcubed 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
#else /* USDT2 */

#define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
#define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
#define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
#define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
#define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
#define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
#define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
#define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
  {                                                              \
    char* data = NULL;                                           \
    int len = 0;                                                 \
    Symbol* name = (clss)->name();                               \
    if (name != NULL) {                                          \
      data = (char*)name->bytes();                               \
      len = name->utf8_length();                                 \
    }                                                            \
    HOTSPOT_CLASS_INITIALIZATION_##type(                         \
      data, len, (clss)->class_loader(), thread_type);           \
  }

#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
  {                                                              \
    char* data = NULL;                                           \
    int len = 0;                                                 \
    Symbol* name = (clss)->name();                               \
    if (name != NULL) {                                          \
      data = (char*)name->bytes();                               \
      len = name->utf8_length();                                 \
    }                                                            \
    HOTSPOT_CLASS_INITIALIZATION_##type(                         \
      data, len, (clss)->class_loader(), thread_type, wait);     \
  }
#endif /* USDT2 */
160 161 162 163 164 165 166 167

#else //  ndef DTRACE_ENABLED

#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)

#endif //  ndef DTRACE_ENABLED

168 169
volatile int InstanceKlass::_total_instanceKlass_count = 0;

170 171
InstanceKlass* InstanceKlass::allocate_instance_klass(
                                              ClassLoaderData* loader_data,
C
coleenp 已提交
172 173 174 175 176 177 178
                                              int vtable_len,
                                              int itable_len,
                                              int static_field_size,
                                              int nonstatic_oop_map_size,
                                              ReferenceType rt,
                                              AccessFlags access_flags,
                                              Symbol* name,
179
                                              Klass* super_klass,
C
coleenp 已提交
180 181
                                              bool is_anonymous,
                                              TRAPS) {
182 183

  int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
C
coleenp 已提交
184
                                 access_flags.is_interface(), is_anonymous);
185 186 187 188 189

  // Allocation
  InstanceKlass* ik;
  if (rt == REF_NONE) {
    if (name == vmSymbols::java_lang_Class()) {
190
      ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
191
        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
C
coleenp 已提交
192
        access_flags, is_anonymous);
193 194 195 196
    } else if (name == vmSymbols::java_lang_ClassLoader() ||
          (SystemDictionary::ClassLoader_klass_loaded() &&
          super_klass != NULL &&
          super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
197
      ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
198
        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
C
coleenp 已提交
199
        access_flags, is_anonymous);
200 201 202 203
    } else {
      // normal class
      ik = new (loader_data, size, THREAD) InstanceKlass(
        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
C
coleenp 已提交
204
        access_flags, is_anonymous);
205 206 207
    }
  } else {
    // reference klass
208
    ik = new (loader_data, size, THREAD) InstanceRefKlass(
209
        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
C
coleenp 已提交
210
        access_flags, is_anonymous);
211 212
  }

213 214 215 216 217 218 219 220 221 222
  // Check for pending exception before adding to the loader data and incrementing
  // class count.  Can get OOM here.
  if (HAS_PENDING_EXCEPTION) {
    return NULL;
  }

  // Add all classes to our internal class loader list here,
  // including classes in the bootstrap (NULL) class loader.
  loader_data->add_class(ik);

223
  Atomic::inc(&_total_instanceKlass_count);
224 225 226
  return ik;
}

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

// copy method ordering from resource area to Metaspace
void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
  if (m != NULL) {
    // allocate a new array and copy contents (memcpy?)
    _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
    for (int i = 0; i < m->length(); i++) {
      _method_ordering->at_put(i, m->at(i));
    }
  } else {
    _method_ordering = Universe::the_empty_int_array();
  }
}


242 243 244 245 246 247 248 249 250
InstanceKlass::InstanceKlass(int vtable_len,
                             int itable_len,
                             int static_field_size,
                             int nonstatic_oop_map_size,
                             ReferenceType rt,
                             AccessFlags access_flags,
                             bool is_anonymous) {
  No_Safepoint_Verifier no_safepoint; // until k becomes parsable

251 252
  int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
                                   access_flags.is_interface(), is_anonymous);
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  set_vtable_length(vtable_len);
  set_itable_length(itable_len);
  set_static_field_size(static_field_size);
  set_nonstatic_oop_map_size(nonstatic_oop_map_size);
  set_access_flags(access_flags);
  _misc_flags = 0;  // initialize to zero
  set_is_anonymous(is_anonymous);
  assert(size() == iksize, "wrong size for object");

  set_array_klasses(NULL);
  set_methods(NULL);
  set_method_ordering(NULL);
  set_local_interfaces(NULL);
  set_transitive_interfaces(NULL);
  init_implementor();
  set_fields(NULL, 0);
  set_constants(NULL);
  set_class_loader_data(NULL);
272
  set_source_file_name_index(0);
273 274 275 276 277 278 279 280 281 282 283 284 285 286
  set_source_debug_extension(NULL, 0);
  set_array_name(NULL);
  set_inner_classes(NULL);
  set_static_oop_field_count(0);
  set_nonstatic_field_size(0);
  set_is_marked_dependent(false);
  set_init_state(InstanceKlass::allocated);
  set_init_thread(NULL);
  set_reference_type(rt);
  set_oop_map_cache(NULL);
  set_jni_ids(NULL);
  set_osr_nmethods_head(NULL);
  set_breakpoints(NULL);
  init_previous_versions();
287
  set_generic_signature_index(0);
288 289 290 291 292 293 294
  release_set_methods_jmethod_ids(NULL);
  release_set_methods_cached_itable_indices(NULL);
  set_annotations(NULL);
  set_jvmti_cached_class_field_map(NULL);
  set_initial_method_idnum(0);
  _dependencies = NULL;
  set_jvmti_cached_class_field_map(NULL);
295
  set_cached_class_file(NULL);
296 297 298 299
  set_initial_method_idnum(0);
  set_minor_version(0);
  set_major_version(0);
  NOT_PRODUCT(_verify_count = 0;)
300 301 302

  // initialize the non-header words to zero
  intptr_t* p = (intptr_t*)this;
303
  for (int index = InstanceKlass::header_size(); index < iksize; index++) {
304 305 306 307 308
    p[index] = NULL_WORD;
  }

  // Set temporary value until parseClassFile updates it with the real instance
  // size.
309
  set_layout_helper(Klass::instance_layout_helper(0, true));
310 311 312
}


313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
                                       Array<Method*>* methods) {
  if (methods != NULL && methods != Universe::the_empty_method_array()) {
    for (int i = 0; i < methods->length(); i++) {
      Method* method = methods->at(i);
      if (method == NULL) continue;  // maybe null if error processing
      // Only want to delete methods that are not executing for RedefineClasses.
      // The previous version will point to them so they're not totally dangling
      assert (!method->on_stack(), "shouldn't be called with methods on stack");
      MetadataFactory::free_metadata(loader_data, method);
    }
    MetadataFactory::free_array<Method*>(loader_data, methods);
  }
}

void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
                                          Klass* super_klass,
                                          Array<Klass*>* local_interfaces,
                                          Array<Klass*>* transitive_interfaces) {
  // Only deallocate transitive interfaces if not empty, same as super class
  // or same as local interfaces.  See code in parseClassFile.
  Array<Klass*>* ti = transitive_interfaces;
  if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
    // check that the interfaces don't come from super class
    Array<Klass*>* sti = (super_klass == NULL) ? NULL :
                    InstanceKlass::cast(super_klass)->transitive_interfaces();
    if (ti != sti) {
      MetadataFactory::free_array<Klass*>(loader_data, ti);
    }
  }

  // local interfaces can be empty
  if (local_interfaces != Universe::the_empty_klass_array()) {
    MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
  }
}

350 351 352 353 354
// This function deallocates the metadata and C heap pointers that the
// InstanceKlass points to.
void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {

  // Orphan the mirror first, CMS thinks it's still live.
355 356 357
  if (java_mirror() != NULL) {
    java_lang_Class::set_klass(java_mirror(), NULL);
  }
358 359 360 361 362 363 364 365 366 367 368 369 370 371

  // Need to take this class off the class loader data list.
  loader_data->remove_class(this);

  // The array_klass for this class is created later, after error handling.
  // For class redefinition, we keep the original class so this scratch class
  // doesn't have an array class.  Either way, assert that there is nothing
  // to deallocate.
  assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");

  // Release C heap allocated data that this might point to, which includes
  // reference counting symbol names.
  release_C_heap_structures();

372
  deallocate_methods(loader_data, methods());
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
  set_methods(NULL);

  if (method_ordering() != Universe::the_empty_int_array()) {
    MetadataFactory::free_array<int>(loader_data, method_ordering());
  }
  set_method_ordering(NULL);

  // This array is in Klass, but remove it with the InstanceKlass since
  // this place would be the only caller and it can share memory with transitive
  // interfaces.
  if (secondary_supers() != Universe::the_empty_klass_array() &&
      secondary_supers() != transitive_interfaces()) {
    MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
  }
  set_secondary_supers(NULL);

389
  deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
390 391 392 393 394 395 396 397
  set_transitive_interfaces(NULL);
  set_local_interfaces(NULL);

  MetadataFactory::free_array<jushort>(loader_data, fields());
  set_fields(NULL, 0);

  // If a method from a redefined class is using this constant pool, don't
  // delete it, yet.  The new class's previous version will point to this.
398 399 400 401 402
  if (constants() != NULL) {
    assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
    MetadataFactory::free_metadata(loader_data, constants());
    set_constants(NULL);
  }
403 404 405 406 407 408

  if (inner_classes() != Universe::the_empty_short_array()) {
    MetadataFactory::free_array<jushort>(loader_data, inner_classes());
  }
  set_inner_classes(NULL);

409 410
  // We should deallocate the Annotations instance
  MetadataFactory::free_metadata(loader_data, annotations());
411 412 413 414
  set_annotations(NULL);
}

bool InstanceKlass::should_be_initialized() const {
D
duke 已提交
415 416 417
  return !is_initialized();
}

418 419
klassVtable* InstanceKlass::vtable() const {
  return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
D
duke 已提交
420 421
}

422 423
klassItable* InstanceKlass::itable() const {
  return new klassItable(instanceKlassHandle(this));
D
duke 已提交
424 425
}

426
void InstanceKlass::eager_initialize(Thread *thread) {
D
duke 已提交
427 428 429 430 431 432 433
  if (!EagerInitialization) return;

  if (this->is_not_initialized()) {
    // abort if the the class has a class initializer
    if (this->class_initializer() != NULL) return;

    // abort if it is java.lang.Object (initialization is handled in genesis)
434
    Klass* super = this->super();
D
duke 已提交
435 436 437
    if (super == NULL) return;

    // abort if the super class should be initialized
438
    if (!InstanceKlass::cast(super)->is_initialized()) return;
D
duke 已提交
439 440

    // call body to expose the this pointer
441
    instanceKlassHandle this_oop(thread, this);
D
duke 已提交
442 443 444 445
    eager_initialize_impl(this_oop);
  }
}

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
// JVMTI spec thinks there are signers and protection domain in the
// instanceKlass.  These accessors pretend these fields are there.
// The hprof specification also thinks these fields are in InstanceKlass.
oop InstanceKlass::protection_domain() const {
  // return the protection_domain from the mirror
  return java_lang_Class::protection_domain(java_mirror());
}

// To remove these from requires an incompatible change and CCC request.
objArrayOop InstanceKlass::signers() const {
  // return the signers from the mirror
  return java_lang_Class::signers(java_mirror());
}

volatile oop InstanceKlass::init_lock() const {
  // return the init lock from the mirror
  return java_lang_Class::init_lock(java_mirror());
}
D
duke 已提交
464

465
void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
D
duke 已提交
466
  EXCEPTION_MARK;
467
  volatile oop init_lock = this_oop->init_lock();
468
  ObjectLocker ol(init_lock, THREAD);
D
duke 已提交
469 470 471 472

  // abort if someone beat us to the initialization
  if (!this_oop->is_not_initialized()) return;  // note: not equivalent to is_initialized()

473
  ClassState old_state = this_oop->init_state();
D
duke 已提交
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
  link_class_impl(this_oop, true, THREAD);
  if (HAS_PENDING_EXCEPTION) {
    CLEAR_PENDING_EXCEPTION;
    // Abort if linking the class throws an exception.

    // Use a test to avoid redundantly resetting the state if there's
    // no change.  Set_init_state() asserts that state changes make
    // progress, whereas here we might just be spinning in place.
    if( old_state != this_oop->_init_state )
      this_oop->set_init_state (old_state);
  } else {
    // linking successfull, mark class as initialized
    this_oop->set_init_state (fully_initialized);
    // trace
    if (TraceClassInitialization) {
      ResourceMark rm(THREAD);
      tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
    }
  }
}


// See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
// process. The step comments refers to the procedure described in that section.
// Note: implementation moved to static method to expose the this pointer.
499
void InstanceKlass::initialize(TRAPS) {
D
duke 已提交
500 501
  if (this->should_be_initialized()) {
    HandleMark hm(THREAD);
502
    instanceKlassHandle this_oop(THREAD, this);
D
duke 已提交
503 504 505 506 507 508 509 510 511 512
    initialize_impl(this_oop, CHECK);
    // Note: at this point the class may be initialized
    //       OR it may be in the state of being initialized
    //       in case of recursive initialization!
  } else {
    assert(is_initialized(), "sanity check");
  }
}


513
bool InstanceKlass::verify_code(
D
duke 已提交
514 515 516 517
    instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
  // 1) Verify the bytecodes
  Verifier::Mode mode =
    throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
518
  return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
D
duke 已提交
519 520 521 522 523 524
}


// Used exclusively by the shared spaces dump mechanism to prevent
// classes mapped into the shared regions in new VMs from appearing linked.

525
void InstanceKlass::unlink_class() {
D
duke 已提交
526 527 528 529
  assert(is_linked(), "must be linked");
  _init_state = loaded;
}

530
void InstanceKlass::link_class(TRAPS) {
D
duke 已提交
531 532
  assert(is_loaded(), "must be loaded");
  if (!is_linked()) {
533 534
    HandleMark hm(THREAD);
    instanceKlassHandle this_oop(THREAD, this);
D
duke 已提交
535 536 537 538 539 540
    link_class_impl(this_oop, true, CHECK);
  }
}

// Called to verify that a class can link during initialization, without
// throwing a VerifyError.
541
bool InstanceKlass::link_class_or_fail(TRAPS) {
D
duke 已提交
542 543
  assert(is_loaded(), "must be loaded");
  if (!is_linked()) {
544 545
    HandleMark hm(THREAD);
    instanceKlassHandle this_oop(THREAD, this);
D
duke 已提交
546 547 548 549 550
    link_class_impl(this_oop, false, CHECK_false);
  }
  return is_linked();
}

551
bool InstanceKlass::link_class_impl(
D
duke 已提交
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
  // check for error state
  if (this_oop->is_in_error_state()) {
    ResourceMark rm(THREAD);
    THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
               this_oop->external_name(), false);
  }
  // return if already verified
  if (this_oop->is_linked()) {
    return true;
  }

  // Timing
  // timer handles recursion
  assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
  JavaThread* jt = (JavaThread*)THREAD;

  // link super class before linking this class
  instanceKlassHandle super(THREAD, this_oop->super());
  if (super.not_null()) {
    if (super->is_interface()) {  // check if super class is an interface
      ResourceMark rm(THREAD);
      Exceptions::fthrow(
        THREAD_AND_LOCATION,
576
        vmSymbols::java_lang_IncompatibleClassChangeError(),
D
duke 已提交
577 578 579 580 581 582 583 584 585 586 587
        "class %s has interface %s as super class",
        this_oop->external_name(),
        super->external_name()
      );
      return false;
    }

    link_class_impl(super, throw_verifyerror, CHECK_false);
  }

  // link all interfaces implemented by this class before linking this class
588
  Array<Klass*>* interfaces = this_oop->local_interfaces();
D
duke 已提交
589 590 591
  int num_interfaces = interfaces->length();
  for (int index = 0; index < num_interfaces; index++) {
    HandleMark hm(THREAD);
592
    instanceKlassHandle ih(THREAD, interfaces->at(index));
D
duke 已提交
593 594 595 596 597 598 599 600
    link_class_impl(ih, throw_verifyerror, CHECK_false);
  }

  // in case the class is linked in the process of linking its superclasses
  if (this_oop->is_linked()) {
    return true;
  }

601 602 603 604 605 606 607 608 609
  // trace only the link time for this klass that includes
  // the verification time
  PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
                             ClassLoader::perf_class_link_selftime(),
                             ClassLoader::perf_classes_linked(),
                             jt->get_thread_stat()->perf_recursion_counts_addr(),
                             jt->get_thread_stat()->perf_timers_addr(),
                             PerfClassTraceTime::CLASS_LINK);

D
duke 已提交
610 611
  // verification & rewriting
  {
612
    volatile oop init_lock = this_oop->init_lock();
613
    ObjectLocker ol(init_lock, THREAD);
D
duke 已提交
614 615 616
    // rewritten will have been set if loader constraint error found
    // on an earlier link attempt
    // don't verify or rewrite if already rewritten
617

D
duke 已提交
618 619 620 621 622
    if (!this_oop->is_linked()) {
      if (!this_oop->is_rewritten()) {
        {
          // Timer includes any side effects of class verification (resolution,
          // etc), but not recursive entry into verify_code().
623 624 625 626 627 628
          PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
                                   ClassLoader::perf_class_verify_selftime(),
                                   ClassLoader::perf_classes_verified(),
                                   jt->get_thread_stat()->perf_recursion_counts_addr(),
                                   jt->get_thread_stat()->perf_timers_addr(),
                                   PerfClassTraceTime::CLASS_VERIFY);
D
duke 已提交
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
          bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
          if (!verify_ok) {
            return false;
          }
        }

        // Just in case a side-effect of verify linked this class already
        // (which can sometimes happen since the verifier loads classes
        // using custom class loaders, which are free to initialize things)
        if (this_oop->is_linked()) {
          return true;
        }

        // also sets rewritten
        this_oop->rewrite_class(CHECK_false);
      }

646
      // relocate jsrs and link methods after they are all rewritten
647
      this_oop->link_methods(CHECK_false);
648

D
duke 已提交
649 650
      // Initialize the vtable and interface table after
      // methods have been rewritten since rewrite may
651
      // fabricate new Method*s.
D
duke 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
      // also does loader constraint checking
      if (!this_oop()->is_shared()) {
        ResourceMark rm(THREAD);
        this_oop->vtable()->initialize_vtable(true, CHECK_false);
        this_oop->itable()->initialize_itable(true, CHECK_false);
      }
#ifdef ASSERT
      else {
        ResourceMark rm(THREAD);
        this_oop->vtable()->verify(tty, true);
        // In case itable verification is ever added.
        // this_oop->itable()->verify(tty, true);
      }
#endif
      this_oop->set_init_state(linked);
      if (JvmtiExport::should_post_class_prepare()) {
        Thread *thread = THREAD;
        assert(thread->is_Java_thread(), "thread->is_Java_thread()");
        JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
      }
    }
  }
  return true;
}


// Rewrite the byte codes of all of the methods of a class.
// The rewriter must be called exactly once. Rewriting must happen after
// verification but before the first method of the class is executed.
681
void InstanceKlass::rewrite_class(TRAPS) {
D
duke 已提交
682
  assert(is_loaded(), "must be loaded");
683
  instanceKlassHandle this_oop(THREAD, this);
D
duke 已提交
684 685 686 687
  if (this_oop->is_rewritten()) {
    assert(this_oop()->is_shared(), "rewriting an unshared class?");
    return;
  }
688
  Rewriter::rewrite(this_oop, CHECK);
D
duke 已提交
689 690 691
  this_oop->set_rewritten();
}

692 693 694
// Now relocate and link method entry points after class is rewritten.
// This is outside is_rewritten flag. In case of an exception, it can be
// executed more than once.
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
void InstanceKlass::link_methods(TRAPS) {
  int len = methods()->length();
  for (int i = len-1; i >= 0; i--) {
    methodHandle m(THREAD, methods()->at(i));

    // Set up method entry points for compiler and interpreter    .
    m->link_method(m, CHECK);

    // This is for JVMTI and unrelated to relocator but the last thing we do
#ifdef ASSERT
    if (StressMethodComparator) {
      ResourceMark rm(THREAD);
      static int nmc = 0;
      for (int j = i; j >= 0 && j >= i-4; j--) {
        if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
        bool z = MethodComparator::methods_EMCP(m(),
                   methods()->at(j));
        if (j == i && !z) {
          tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
          assert(z, "method must compare equal to itself");
        }
      }
    }
#endif //ASSERT
  }
720 721
}

D
duke 已提交
722

723
void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
D
duke 已提交
724 725 726 727
  // Make sure klass is linked (verified) before initialization
  // A class could already be verified, since it has been reflected upon.
  this_oop->link_class(CHECK);

728
  DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
729 730 731

  bool wait = false;

D
duke 已提交
732 733
  // refer to the JVM book page 47 for description of steps
  // Step 1
734 735
  {
    volatile oop init_lock = this_oop->init_lock();
736
    ObjectLocker ol(init_lock, THREAD);
D
duke 已提交
737 738 739 740 741 742 743 744

    Thread *self = THREAD; // it's passed the current thread

    // Step 2
    // If we were to use wait() instead of waitInterruptibly() then
    // we might end up throwing IE from link/symbol resolution sites
    // that aren't expected to throw.  This would wreak havoc.  See 6320309.
    while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
745
        wait = true;
D
duke 已提交
746 747 748 749
      ol.waitUninterruptibly(CHECK);
    }

    // Step 3
750
    if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
751
      DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
752
      return;
753
    }
D
duke 已提交
754 755

    // Step 4
756
    if (this_oop->is_initialized()) {
757
      DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
758
      return;
759
    }
D
duke 已提交
760 761 762

    // Step 5
    if (this_oop->is_in_error_state()) {
763
      DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
764 765 766 767
      ResourceMark rm(THREAD);
      const char* desc = "Could not initialize class ";
      const char* className = this_oop->external_name();
      size_t msglen = strlen(desc) + strlen(className) + 1;
768
      char* message = NEW_RESOURCE_ARRAY(char, msglen);
D
duke 已提交
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
      if (NULL == message) {
        // Out of memory: can't create detailed error message
        THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
      } else {
        jio_snprintf(message, msglen, "%s%s", desc, className);
        THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
      }
    }

    // Step 6
    this_oop->set_init_state(being_initialized);
    this_oop->set_init_thread(self);
  }

  // Step 7
784
  Klass* super_klass = this_oop->super();
H
hseigel 已提交
785 786
  if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
    super_klass->initialize(THREAD);
D
duke 已提交
787 788 789 790 791 792 793 794 795

    if (HAS_PENDING_EXCEPTION) {
      Handle e(THREAD, PENDING_EXCEPTION);
      CLEAR_PENDING_EXCEPTION;
      {
        EXCEPTION_MARK;
        this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
        CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
      }
796
      DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
797 798 799 800
      THROW_OOP(e());
    }
  }

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
  if (this_oop->has_default_methods()) {
    // Step 7.5: initialize any interfaces which have default methods
    for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
      Klass* iface = this_oop->local_interfaces()->at(i);
      InstanceKlass* ik = InstanceKlass::cast(iface);
      if (ik->has_default_methods() && ik->should_be_initialized()) {
        ik->initialize(THREAD);

        if (HAS_PENDING_EXCEPTION) {
          Handle e(THREAD, PENDING_EXCEPTION);
          CLEAR_PENDING_EXCEPTION;
          {
            EXCEPTION_MARK;
            // Locks object, set state, and notify all waiting threads
            this_oop->set_initialization_state_and_notify(
                initialization_error, THREAD);

            // ignore any exception thrown, superclass initialization error is
            // thrown below
            CLEAR_PENDING_EXCEPTION;
          }
          DTRACE_CLASSINIT_PROBE_WAIT(
              super__failed, InstanceKlass::cast(this_oop()), -1, wait);
          THROW_OOP(e());
        }
      }
    }
  }

D
duke 已提交
830 831 832 833
  // Step 8
  {
    assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
    JavaThread* jt = (JavaThread*)THREAD;
834
    DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
835 836
    // Timer includes any side effects of class initialization (resolution,
    // etc), but not recursive entry into call_class_initializer().
837 838 839 840 841 842
    PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
                             ClassLoader::perf_class_init_selftime(),
                             ClassLoader::perf_classes_inited(),
                             jt->get_thread_stat()->perf_recursion_counts_addr(),
                             jt->get_thread_stat()->perf_timers_addr(),
                             PerfClassTraceTime::CLASS_CLINIT);
D
duke 已提交
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    this_oop->call_class_initializer(THREAD);
  }

  // Step 9
  if (!HAS_PENDING_EXCEPTION) {
    this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
    { ResourceMark rm(THREAD);
      debug_only(this_oop->vtable()->verify(tty, true);)
    }
  }
  else {
    // Step 10 and 11
    Handle e(THREAD, PENDING_EXCEPTION);
    CLEAR_PENDING_EXCEPTION;
    {
      EXCEPTION_MARK;
      this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
      CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
    }
862
    DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
863
    if (e->is_a(SystemDictionary::Error_klass())) {
D
duke 已提交
864 865 866
      THROW_OOP(e());
    } else {
      JavaCallArguments args(e);
867 868
      THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
                vmSymbols::throwable_void_signature(),
D
duke 已提交
869 870 871
                &args);
    }
  }
872
  DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
873 874 875 876
}


// Note: implementation moved to static method to expose the this pointer.
877 878
void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
  instanceKlassHandle kh(THREAD, this);
D
duke 已提交
879 880 881
  set_initialization_state_and_notify_impl(kh, state, CHECK);
}

882 883
void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
  volatile oop init_lock = this_oop->init_lock();
884
  ObjectLocker ol(init_lock, THREAD);
D
duke 已提交
885 886 887 888
  this_oop->set_init_state(state);
  ol.notify_all(CHECK);
}

889 890
// The embedded _implementor field can only record one implementor.
// When there are more than one implementors, the _implementor field
891
// is set to the interface Klass* itself. Following are the possible
892 893
// values for the _implementor field:
//   NULL                  - no implementor
894
//   implementor Klass*    - one implementor
895 896 897
//   self                  - more than one implementor
//
// The _implementor field only exists for interfaces.
898
void InstanceKlass::add_implementor(Klass* k) {
D
duke 已提交
899
  assert(Compile_lock->owned_by_self(), "");
900
  assert(is_interface(), "not interface");
D
duke 已提交
901 902
  // Filter out my subinterfaces.
  // (Note: Interfaces are never on the subklass list.)
903
  if (InstanceKlass::cast(k)->is_interface()) return;
D
duke 已提交
904 905 906 907

  // Filter out subclasses whose supers already implement me.
  // (Note: CHA must walk subclasses of direct implementors
  // in order to locate indirect implementors.)
908 909
  Klass* sk = InstanceKlass::cast(k)->super();
  if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
D
duke 已提交
910 911 912 913 914
    // We only need to check one immediate superclass, since the
    // implements_interface query looks at transitive_interfaces.
    // Any supers of the super have the same (or fewer) transitive_interfaces.
    return;

915
  Klass* ik = implementor();
916 917
  if (ik == NULL) {
    set_implementor(k);
918
  } else if (ik != this) {
919 920
    // There is already an implementor. Use itself as an indicator of
    // more than one implementors.
921
    set_implementor(this);
D
duke 已提交
922 923 924 925
  }

  // The implementor also implements the transitive_interfaces
  for (int index = 0; index < local_interfaces()->length(); index++) {
926
    InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
D
duke 已提交
927 928 929
  }
}

930
void InstanceKlass::init_implementor() {
931 932 933
  if (is_interface()) {
    set_implementor(NULL);
  }
D
duke 已提交
934 935 936
}


937
void InstanceKlass::process_interfaces(Thread *thread) {
D
duke 已提交
938
  // link this class into the implementors list of every interface it implements
939
  Klass* this_as_klass_oop = this;
D
duke 已提交
940
  for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
941 942
    assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
    InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
D
duke 已提交
943
    assert(interf->is_interface(), "expected interface");
944
    interf->add_implementor(this_as_klass_oop);
D
duke 已提交
945 946 947
  }
}

948
bool InstanceKlass::can_be_primary_super_slow() const {
D
duke 已提交
949 950 951 952 953 954
  if (is_interface())
    return false;
  else
    return Klass::can_be_primary_super_slow();
}

955
GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
D
duke 已提交
956
  // The secondaries are the implemented interfaces.
957 958
  InstanceKlass* ik = InstanceKlass::cast(this);
  Array<Klass*>* interfaces = ik->transitive_interfaces();
D
duke 已提交
959 960
  int num_secondaries = num_extra_slots + interfaces->length();
  if (num_secondaries == 0) {
961 962 963
    // Must share this for correct bootstrapping!
    set_secondary_supers(Universe::the_empty_klass_array());
    return NULL;
D
duke 已提交
964
  } else if (num_extra_slots == 0) {
965 966 967 968
    // The secondary super list is exactly the same as the transitive interfaces.
    // Redefine classes has to be careful not to delete this!
    set_secondary_supers(interfaces);
    return NULL;
D
duke 已提交
969
  } else {
970 971 972
    // Copy transitive interfaces to a temporary growable array to be constructed
    // into the secondary super list with extra slots.
    GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
D
duke 已提交
973
    for (int i = 0; i < interfaces->length(); i++) {
974
      secondaries->push(interfaces->at(i));
D
duke 已提交
975 976 977 978 979
    }
    return secondaries;
  }
}

980
bool InstanceKlass::compute_is_subtype_of(Klass* k) {
H
hseigel 已提交
981
  if (k->is_interface()) {
D
duke 已提交
982 983 984 985 986 987
    return implements_interface(k);
  } else {
    return Klass::compute_is_subtype_of(k);
  }
}

988 989
bool InstanceKlass::implements_interface(Klass* k) const {
  if (this == k) return true;
H
hseigel 已提交
990
  assert(k->is_interface(), "should be an interface class");
D
duke 已提交
991
  for (int i = 0; i < transitive_interfaces()->length(); i++) {
992
    if (transitive_interfaces()->at(i) == k) {
D
duke 已提交
993 994 995 996 997 998
      return true;
    }
  }
  return false;
}

999
objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
D
duke 已提交
1000 1001
  if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
  if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
1002
    report_java_out_of_memory("Requested array size exceeds VM limit");
1003
    JvmtiExport::post_array_size_exhausted();
D
duke 已提交
1004 1005 1006
    THROW_OOP_0(Universe::out_of_memory_error_array_size());
  }
  int size = objArrayOopDesc::object_size(length);
1007
  Klass* ak = array_klass(n, CHECK_NULL);
D
duke 已提交
1008 1009 1010 1011 1012 1013
  KlassHandle h_ak (THREAD, ak);
  objArrayOop o =
    (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
  return o;
}

1014
instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
D
duke 已提交
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
  if (TraceFinalizerRegistration) {
    tty->print("Registered ");
    i->print_value_on(tty);
    tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
  }
  instanceHandle h_i(THREAD, i);
  // Pass the handle as argument, JavaCalls::call expects oop as jobjects
  JavaValue result(T_VOID);
  JavaCallArguments args(h_i);
  methodHandle mh (THREAD, Universe::finalizer_register_method());
  JavaCalls::call(&result, mh, &args, CHECK_NULL);
  return h_i();
}

1029
instanceOop InstanceKlass::allocate_instance(TRAPS) {
D
duke 已提交
1030 1031 1032
  bool has_finalizer_flag = has_finalizer(); // Query before possible GC
  int size = size_helper();  // Query before forming handle.

1033
  KlassHandle h_k(THREAD, this);
D
duke 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043

  instanceOop i;

  i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
  if (has_finalizer_flag && !RegisterFinalizersAtInit) {
    i = register_finalizer(i, CHECK_NULL);
  }
  return i;
}

1044
void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
D
duke 已提交
1045 1046 1047 1048 1049
  if (is_interface() || is_abstract()) {
    ResourceMark rm(THREAD);
    THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
              : vmSymbols::java_lang_InstantiationException(), external_name());
  }
1050
  if (this == SystemDictionary::Class_klass()) {
D
duke 已提交
1051 1052 1053 1054 1055 1056
    ResourceMark rm(THREAD);
    THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
              : vmSymbols::java_lang_IllegalAccessException(), external_name());
  }
}

1057 1058
Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
  instanceKlassHandle this_oop(THREAD, this);
D
duke 已提交
1059 1060 1061
  return array_klass_impl(this_oop, or_null, n, THREAD);
}

1062
Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
D
duke 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
  if (this_oop->array_klasses() == NULL) {
    if (or_null) return NULL;

    ResourceMark rm;
    JavaThread *jt = (JavaThread *)THREAD;
    {
      // Atomic creation of array_klasses
      MutexLocker mc(Compile_lock, THREAD);   // for vtables
      MutexLocker ma(MultiArray_lock, THREAD);

      // Check if update has already taken place
      if (this_oop->array_klasses() == NULL) {
1075
        Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
D
duke 已提交
1076 1077 1078 1079 1080
        this_oop->set_array_klasses(k);
      }
    }
  }
  // _this will always be set at this point
1081
  ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
D
duke 已提交
1082 1083 1084 1085 1086 1087
  if (or_null) {
    return oak->array_klass_or_null(n);
  }
  return oak->array_klass(n, CHECK_NULL);
}

1088
Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
D
duke 已提交
1089 1090 1091
  return array_klass_impl(or_null, 1, THREAD);
}

1092 1093
void InstanceKlass::call_class_initializer(TRAPS) {
  instanceKlassHandle ik (THREAD, this);
D
duke 已提交
1094 1095 1096 1097 1098
  call_class_initializer_impl(ik, THREAD);
}

static int call_class_initializer_impl_counter = 0;   // for debugging

1099 1100
Method* InstanceKlass::class_initializer() {
  Method* clinit = find_method(
1101 1102 1103 1104 1105
      vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
  if (clinit != NULL && clinit->has_valid_initializer_flags()) {
    return clinit;
  }
  return NULL;
D
duke 已提交
1106 1107
}

1108
void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
1109 1110 1111 1112 1113 1114 1115
  if (ReplayCompiles &&
      (ReplaySuppressInitializers == 1 ||
       ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
    // Hide the existence of the initializer for the purpose of replaying the compile
    return;
  }

D
duke 已提交
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
  methodHandle h_method(THREAD, this_oop->class_initializer());
  assert(!this_oop->is_initialized(), "we cannot initialize twice");
  if (TraceClassInitialization) {
    tty->print("%d Initializing ", call_class_initializer_impl_counter++);
    this_oop->name()->print_value();
    tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
  }
  if (h_method() != NULL) {
    JavaCallArguments args; // No arguments
    JavaValue result(T_VOID);
    JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
  }
}


1131
void InstanceKlass::mask_for(methodHandle method, int bci,
D
duke 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
  InterpreterOopMap* entry_for) {
  // Dirty read, then double-check under a lock.
  if (_oop_map_cache == NULL) {
    // Otherwise, allocate a new one.
    MutexLocker x(OopMapCacheAlloc_lock);
    // First time use. Allocate a cache in C heap
    if (_oop_map_cache == NULL) {
      _oop_map_cache = new OopMapCache();
    }
  }
  // _oop_map_cache is constant after init; lookup below does is own locking.
  _oop_map_cache->lookup(method, bci, entry_for);
}


1147 1148
bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1149 1150
    Symbol* f_name = fs.name();
    Symbol* f_sig  = fs.signature();
D
duke 已提交
1151
    if (f_name == name && f_sig == sig) {
1152
      fd->initialize(const_cast<InstanceKlass*>(this), fs.index());
D
duke 已提交
1153 1154 1155 1156 1157 1158 1159
      return true;
    }
  }
  return false;
}


1160
Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
D
duke 已提交
1161 1162
  const int n = local_interfaces()->length();
  for (int i = 0; i < n; i++) {
1163
    Klass* intf1 = local_interfaces()->at(i);
H
hseigel 已提交
1164
    assert(intf1->is_interface(), "just checking type");
D
duke 已提交
1165
    // search for field in current interface
1166
    if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
D
duke 已提交
1167 1168 1169 1170
      assert(fd->is_static(), "interface field must be static");
      return intf1;
    }
    // search for field in direct superinterfaces
1171
    Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
D
duke 已提交
1172 1173 1174 1175 1176 1177 1178
    if (intf2 != NULL) return intf2;
  }
  // otherwise field lookup fails
  return NULL;
}


1179
Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
D
duke 已提交
1180 1181 1182
  // search order according to newest JVM spec (5.4.3.2, p.167).
  // 1) search for field in current klass
  if (find_local_field(name, sig, fd)) {
1183
    return const_cast<InstanceKlass*>(this);
D
duke 已提交
1184 1185
  }
  // 2) search for field recursively in direct superinterfaces
1186
  { Klass* intf = find_interface_field(name, sig, fd);
D
duke 已提交
1187 1188 1189
    if (intf != NULL) return intf;
  }
  // 3) apply field lookup recursively if superclass exists
1190 1191
  { Klass* supr = super();
    if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
D
duke 已提交
1192 1193 1194 1195 1196 1197
  }
  // 4) otherwise field lookup fails
  return NULL;
}


1198
Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
D
duke 已提交
1199 1200 1201
  // search order according to newest JVM spec (5.4.3.2, p.167).
  // 1) search for field in current klass
  if (find_local_field(name, sig, fd)) {
1202
    if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
D
duke 已提交
1203 1204 1205
  }
  // 2) search for field recursively in direct superinterfaces
  if (is_static) {
1206
    Klass* intf = find_interface_field(name, sig, fd);
D
duke 已提交
1207 1208 1209
    if (intf != NULL) return intf;
  }
  // 3) apply field lookup recursively if superclass exists
1210 1211
  { Klass* supr = super();
    if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
D
duke 已提交
1212 1213 1214 1215 1216 1217
  }
  // 4) otherwise field lookup fails
  return NULL;
}


1218 1219
bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1220
    if (fs.offset() == offset) {
1221
      fd->initialize(const_cast<InstanceKlass*>(this), fs.index());
D
duke 已提交
1222 1223 1224 1225 1226 1227 1228
      if (fd->is_static() == is_static) return true;
    }
  }
  return false;
}


1229 1230
bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  Klass* klass = const_cast<InstanceKlass*>(this);
D
duke 已提交
1231
  while (klass != NULL) {
1232
    if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
D
duke 已提交
1233 1234
      return true;
    }
H
hseigel 已提交
1235
    klass = klass->super();
D
duke 已提交
1236 1237 1238 1239 1240
  }
  return false;
}


1241
void InstanceKlass::methods_do(void f(Method* method)) {
D
duke 已提交
1242 1243
  int len = methods()->length();
  for (int index = 0; index < len; index++) {
1244
    Method* m = methods()->at(index);
D
duke 已提交
1245 1246 1247 1248 1249
    assert(m->is_method(), "must be method");
    f(m);
  }
}

1250

1251
void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1252 1253 1254
  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
    if (fs.access_flags().is_static()) {
      fieldDescriptor fd;
1255
      fd.initialize(this, fs.index());
1256 1257
      cl->do_field(&fd);
    }
D
duke 已提交
1258 1259 1260 1261
  }
}


1262 1263
void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, TRAPS), TRAPS) {
  instanceKlassHandle h_this(THREAD, this);
D
duke 已提交
1264 1265 1266 1267
  do_local_static_fields_impl(h_this, f, CHECK);
}


1268
void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_oop, void f(fieldDescriptor* fd, TRAPS), TRAPS) {
1269 1270 1271 1272 1273 1274
  for (JavaFieldStream fs(this_oop()); !fs.done(); fs.next()) {
    if (fs.access_flags().is_static()) {
      fieldDescriptor fd;
      fd.initialize(this_oop(), fs.index());
      f(&fd, CHECK);
    }
D
duke 已提交
1275 1276 1277 1278
  }
}


1279 1280 1281 1282
static int compare_fields_by_offset(int* a, int* b) {
  return a[0] - b[0];
}

1283 1284
void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
  InstanceKlass* super = superklass();
D
duke 已提交
1285 1286 1287
  if (super != NULL) {
    super->do_nonstatic_fields(cl);
  }
1288
  fieldDescriptor fd;
1289
  int length = java_fields_count();
1290
  // In DebugInfo nonstatic fields are sorted by offset.
Z
zgu 已提交
1291
  int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1292
  int j = 0;
1293
  for (int i = 0; i < length; i += 1) {
1294
    fd.initialize(this, i);
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
    if (!fd.is_static()) {
      fields_sorted[j + 0] = fd.offset();
      fields_sorted[j + 1] = i;
      j += 2;
    }
  }
  if (j > 0) {
    length = j;
    // _sort_Fn is defined in growableArray.hpp.
    qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
    for (int i = 0; i < length; i += 2) {
1306
      fd.initialize(this, fields_sorted[i + 1]);
1307 1308 1309
      assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
      cl->do_field(&fd);
    }
D
duke 已提交
1310
  }
Z
zgu 已提交
1311
  FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
D
duke 已提交
1312 1313 1314
}


1315 1316
void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
  if (array_klasses() != NULL)
1317
    ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
1318 1319 1320
}

void InstanceKlass::array_klasses_do(void f(Klass* k)) {
D
duke 已提交
1321
  if (array_klasses() != NULL)
1322
    ArrayKlass::cast(array_klasses())->array_klasses_do(f);
D
duke 已提交
1323 1324 1325
}

#ifdef ASSERT
1326
static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
D
duke 已提交
1327 1328
  int len = methods->length();
  for (int index = 0; index < len; index++) {
1329
    Method* m = methods->at(index);
D
duke 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338
    assert(m->is_method(), "must be method");
    if (m->signature() == signature && m->name() == name) {
       return index;
    }
  }
  return -1;
}
#endif

1339
static int binary_search(Array<Method*>* methods, Symbol* name) {
D
duke 已提交
1340 1341 1342 1343 1344 1345
  int len = methods->length();
  // methods are sorted, so do binary search
  int l = 0;
  int h = len - 1;
  while (l <= h) {
    int mid = (l + h) >> 1;
1346
    Method* m = methods->at(mid);
D
duke 已提交
1347 1348 1349
    assert(m->is_method(), "must be method");
    int res = m->name()->fast_compare(name);
    if (res == 0) {
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
      return mid;
    } else if (res < 0) {
      l = mid + 1;
    } else {
      h = mid - 1;
    }
  }
  return -1;
}

Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
  return InstanceKlass::find_method(methods(), name, signature);
}

Method* InstanceKlass::find_method(
    Array<Method*>* methods, Symbol* name, Symbol* signature) {
  int hit = binary_search(methods, name);
  if (hit != -1) {
    Method* m = methods->at(hit);
    // Do linear search to find matching signature.  First, quick check
    // for common case
    if (m->signature() == signature) return m;
    // search downwards through overloaded methods
    int i;
    for (i = hit - 1; i >= 0; --i) {
1375
        Method* m = methods->at(i);
D
duke 已提交
1376 1377 1378
        assert(m->is_method(), "must be method");
        if (m->name() != name) break;
        if (m->signature() == signature) return m;
1379 1380 1381
    }
    // search upwards
    for (i = hit + 1; i < methods->length(); ++i) {
1382
        Method* m = methods->at(i);
D
duke 已提交
1383 1384 1385 1386
        assert(m->is_method(), "must be method");
        if (m->name() != name) break;
        if (m->signature() == signature) return m;
    }
1387
    // not found
D
duke 已提交
1388
#ifdef ASSERT
1389 1390
    int index = linear_search(methods, name, signature);
    assert(index == -1, err_msg("binary search should have found entry %d", index));
D
duke 已提交
1391
#endif
1392
  }
D
duke 已提交
1393 1394 1395
  return NULL;
}

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
  return find_method_by_name(methods(), name, end);
}

int InstanceKlass::find_method_by_name(
    Array<Method*>* methods, Symbol* name, int* end_ptr) {
  assert(end_ptr != NULL, "just checking");
  int start = binary_search(methods, name);
  int end = start + 1;
  if (start != -1) {
    while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
    while (end < methods->length() && (methods->at(end))->name() == name) ++end;
    *end_ptr = end;
    return start;
  }
  return -1;
}

1414 1415
Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature) const {
  Klass* klass = const_cast<InstanceKlass*>(this);
D
duke 已提交
1416
  while (klass != NULL) {
1417
    Method* method = InstanceKlass::cast(klass)->find_method(name, signature);
D
duke 已提交
1418
    if (method != NULL) return method;
1419
    klass = InstanceKlass::cast(klass)->super();
D
duke 已提交
1420 1421 1422 1423 1424
  }
  return NULL;
}

// lookup a method in all the interfaces that this class implements
1425
Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1426
                                                         Symbol* signature) const {
1427
  Array<Klass*>* all_ifs = transitive_interfaces();
D
duke 已提交
1428
  int num_ifs = all_ifs->length();
1429
  InstanceKlass *ik = NULL;
D
duke 已提交
1430
  for (int i = 0; i < num_ifs; i++) {
1431 1432
    ik = InstanceKlass::cast(all_ifs->at(i));
    Method* m = ik->lookup_method(name, signature);
D
duke 已提交
1433 1434 1435 1436 1437 1438 1439 1440
    if (m != NULL) {
      return m;
    }
  }
  return NULL;
}

/* jni_id_for_impl for jfieldIds only */
1441
JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
D
duke 已提交
1442 1443 1444 1445 1446
  MutexLocker ml(JfieldIdCreation_lock);
  // Retry lookup after we got the lock
  JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
  if (probe == NULL) {
    // Slow case, allocate new static field identifier
1447
    probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
D
duke 已提交
1448 1449 1450 1451 1452 1453 1454
    this_oop->set_jni_ids(probe);
  }
  return probe;
}


/* jni_id_for for jfieldIds only */
1455
JNIid* InstanceKlass::jni_id_for(int offset) {
D
duke 已提交
1456 1457
  JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
  if (probe == NULL) {
1458
    probe = jni_id_for_impl(this, offset);
D
duke 已提交
1459 1460 1461 1462
  }
  return probe;
}

1463 1464
u2 InstanceKlass::enclosing_method_data(int offset) {
  Array<jushort>* inner_class_list = inner_classes();
1465 1466 1467 1468 1469 1470 1471 1472 1473
  if (inner_class_list == NULL) {
    return 0;
  }
  int length = inner_class_list->length();
  if (length % inner_class_next_offset == 0) {
    return 0;
  } else {
    int index = length - enclosing_method_attribute_size;
    assert(offset < enclosing_method_attribute_size, "invalid offset");
1474
    return inner_class_list->at(index + offset);
1475 1476 1477
  }
}

1478
void InstanceKlass::set_enclosing_method_indices(u2 class_index,
1479
                                                 u2 method_index) {
1480
  Array<jushort>* inner_class_list = inner_classes();
1481 1482 1483 1484
  assert (inner_class_list != NULL, "_inner_classes list is not set up");
  int length = inner_class_list->length();
  if (length % inner_class_next_offset == enclosing_method_attribute_size) {
    int index = length - enclosing_method_attribute_size;
1485
    inner_class_list->at_put(
1486
      index + enclosing_method_class_index_offset, class_index);
1487
    inner_class_list->at_put(
1488 1489 1490
      index + enclosing_method_method_index_offset, method_index);
  }
}
D
duke 已提交
1491 1492

// Lookup or create a jmethodID.
1493 1494 1495 1496
// This code is called by the VMThread and JavaThreads so the
// locking has to be done very carefully to avoid deadlocks
// and/or other cache consistency problems.
//
1497
jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
D
duke 已提交
1498 1499 1500 1501 1502
  size_t idnum = (size_t)method_h->method_idnum();
  jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  size_t length = 0;
  jmethodID id = NULL;

1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
  // We use a double-check locking idiom here because this cache is
  // performance sensitive. In the normal system, this cache only
  // transitions from NULL to non-NULL which is safe because we use
  // release_set_methods_jmethod_ids() to advertise the new cache.
  // A partially constructed cache should never be seen by a racing
  // thread. We also use release_store_ptr() to save a new jmethodID
  // in the cache so a partially constructed jmethodID should never be
  // seen either. Cache reads of existing jmethodIDs proceed without a
  // lock, but cache writes of a new jmethodID requires uniqueness and
  // creation of the cache itself requires no leaks so a lock is
  // generally acquired in those two cases.
  //
  // If the RedefineClasses() API has been used, then this cache can
  // grow and we'll have transitions from non-NULL to bigger non-NULL.
  // Cache creation requires no leaks and we require safety between all
  // cache accesses and freeing of the old cache so a lock is generally
  // acquired when the RedefineClasses() API has been used.

  if (jmeths != NULL) {
    // the cache already exists
    if (!ik_h->idnum_can_increment()) {
      // the cache can't grow so we can just get the current values
      get_jmethod_id_length_value(jmeths, idnum, &length, &id);
    } else {
      // cache can grow so we have to be more careful
      if (Threads::number_of_threads() == 0 ||
          SafepointSynchronize::is_at_safepoint()) {
        // we're single threaded or at a safepoint - no locking needed
        get_jmethod_id_length_value(jmeths, idnum, &length, &id);
      } else {
        MutexLocker ml(JmethodIdCreation_lock);
        get_jmethod_id_length_value(jmeths, idnum, &length, &id);
      }
    }
  }
  // implied else:
  // we need to allocate a cache so default length and id values are good

  if (jmeths == NULL ||   // no cache yet
      length <= idnum ||  // cache is too short
      id == NULL) {       // cache doesn't contain entry
D
duke 已提交
1544

1545 1546 1547 1548 1549 1550 1551 1552 1553
    // This function can be called by the VMThread so we have to do all
    // things that might block on a safepoint before grabbing the lock.
    // Otherwise, we can deadlock with the VMThread or have a cache
    // consistency issue. These vars keep track of what we might have
    // to free after the lock is dropped.
    jmethodID  to_dealloc_id     = NULL;
    jmethodID* to_dealloc_jmeths = NULL;

    // may not allocate new_jmeths or use it if we allocate it
D
duke 已提交
1554 1555
    jmethodID* new_jmeths = NULL;
    if (length <= idnum) {
1556
      // allocate a new cache that might be used
D
duke 已提交
1557
      size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
Z
zgu 已提交
1558
      new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
D
duke 已提交
1559
      memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1560 1561
      // cache size is stored in element[0], other elements offset by one
      new_jmeths[0] = (jmethodID)size;
D
duke 已提交
1562 1563
    }

1564
    // allocate a new jmethodID that might be used
D
duke 已提交
1565 1566 1567
    jmethodID new_id = NULL;
    if (method_h->is_old() && !method_h->is_obsolete()) {
      // The method passed in is old (but not obsolete), we need to use the current version
1568
      Method* current_method = ik_h->method_with_idnum((int)idnum);
D
duke 已提交
1569
      assert(current_method != NULL, "old and but not obsolete, so should exist");
1570
      new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
D
duke 已提交
1571 1572 1573
    } else {
      // It is the current version of the method or an obsolete method,
      // use the version passed in
1574
      new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
D
duke 已提交
1575 1576
    }

1577 1578 1579 1580 1581
    if (Threads::number_of_threads() == 0 ||
        SafepointSynchronize::is_at_safepoint()) {
      // we're single threaded or at a safepoint - no locking needed
      id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
                                          &to_dealloc_id, &to_dealloc_jmeths);
1582
    } else {
D
duke 已提交
1583
      MutexLocker ml(JmethodIdCreation_lock);
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
      id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
                                          &to_dealloc_id, &to_dealloc_jmeths);
    }

    // The lock has been dropped so we can free resources.
    // Free up either the old cache or the new cache if we allocated one.
    if (to_dealloc_jmeths != NULL) {
      FreeHeap(to_dealloc_jmeths);
    }
    // free up the new ID since it wasn't needed
    if (to_dealloc_id != NULL) {
1595
      Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
1596 1597 1598 1599
    }
  }
  return id;
}
D
duke 已提交
1600 1601


1602 1603 1604 1605 1606
// Common code to fetch the jmethodID from the cache or update the
// cache with the new jmethodID. This function should never do anything
// that causes the caller to go to a safepoint or we can deadlock with
// the VMThread or have cache consistency issues.
//
1607
jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
            instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
            jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
            jmethodID** to_dealloc_jmeths_p) {
  assert(new_id != NULL, "sanity check");
  assert(to_dealloc_id_p != NULL, "sanity check");
  assert(to_dealloc_jmeths_p != NULL, "sanity check");
  assert(Threads::number_of_threads() == 0 ||
         SafepointSynchronize::is_at_safepoint() ||
         JmethodIdCreation_lock->owned_by_self(), "sanity check");

  // reacquire the cache - we are locked, single threaded or at a safepoint
1619
  jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1620 1621
  jmethodID  id     = NULL;
  size_t     length = 0;
1622

1623 1624
  if (jmeths == NULL ||                         // no cache yet
      (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
1625
    if (jmeths != NULL) {
1626
      // copy any existing entries from the old cache
1627 1628
      for (size_t index = 0; index < length; index++) {
        new_jmeths[index+1] = jmeths[index+1];
D
duke 已提交
1629
      }
1630
      *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
D
duke 已提交
1631
    }
1632 1633
    ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
  } else {
1634
    // fetch jmethodID (if any) from the existing cache
1635
    id = jmeths[idnum+1];
1636
    *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
1637 1638
  }
  if (id == NULL) {
1639 1640 1641 1642
    // No matching jmethodID in the existing cache or we have a new
    // cache or we just grew the cache. This cache write is done here
    // by the first thread to win the foot race because a jmethodID
    // needs to be unique once it is generally available.
1643
    id = new_id;
1644 1645 1646 1647 1648

    // The jmethodID cache can be read while unlocked so we have to
    // make sure the new jmethodID is complete before installing it
    // in the cache.
    OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
1649
  } else {
1650
    *to_dealloc_id_p = new_id; // save new id for later delete
1651
  }
1652 1653
  return id;
}
D
duke 已提交
1654

1655 1656 1657 1658

// Common code to get the jmethodID cache length and the jmethodID
// value at index idnum if there is one.
//
1659
void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
       size_t idnum, size_t *length_p, jmethodID* id_p) {
  assert(cache != NULL, "sanity check");
  assert(length_p != NULL, "sanity check");
  assert(id_p != NULL, "sanity check");

  // cache size is stored in element[0], other elements offset by one
  *length_p = (size_t)cache[0];
  if (*length_p <= idnum) {  // cache is too short
    *id_p = NULL;
  } else {
    *id_p = cache[idnum+1];  // fetch jmethodID (if any)
D
duke 已提交
1671 1672 1673 1674 1675
  }
}


// Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
1676
jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
D
duke 已提交
1677 1678 1679 1680
  size_t idnum = (size_t)method->method_idnum();
  jmethodID* jmeths = methods_jmethod_ids_acquire();
  size_t length;                                // length assigned as debugging crumb
  jmethodID id = NULL;
1681
  if (jmeths != NULL &&                         // If there is a cache
D
duke 已提交
1682 1683 1684 1685 1686 1687 1688 1689
      (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
    id = jmeths[idnum+1];                       // Look up the id (may be NULL)
  }
  return id;
}


// Cache an itable index
1690
void InstanceKlass::set_cached_itable_index(size_t idnum, int index) {
D
duke 已提交
1691
  int* indices = methods_cached_itable_indices_acquire();
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
  int* to_dealloc_indices = NULL;

  // We use a double-check locking idiom here because this cache is
  // performance sensitive. In the normal system, this cache only
  // transitions from NULL to non-NULL which is safe because we use
  // release_set_methods_cached_itable_indices() to advertise the
  // new cache. A partially constructed cache should never be seen
  // by a racing thread. Cache reads and writes proceed without a
  // lock, but creation of the cache itself requires no leaks so a
  // lock is generally acquired in that case.
  //
  // If the RedefineClasses() API has been used, then this cache can
  // grow and we'll have transitions from non-NULL to bigger non-NULL.
  // Cache creation requires no leaks and we require safety between all
  // cache accesses and freeing of the old cache so a lock is generally
  // acquired when the RedefineClasses() API has been used.

  if (indices == NULL || idnum_can_increment()) {
    // we need a cache or the cache can grow
D
duke 已提交
1711
    MutexLocker ml(JNICachedItableIndex_lock);
1712
    // reacquire the cache to see if another thread already did the work
D
duke 已提交
1713 1714
    indices = methods_cached_itable_indices_acquire();
    size_t length = 0;
1715
    // cache size is stored in element[0], other elements offset by one
D
duke 已提交
1716 1717
    if (indices == NULL || (length = (size_t)indices[0]) <= idnum) {
      size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
Z
zgu 已提交
1718
      int* new_indices = NEW_C_HEAP_ARRAY(int, size+1, mtClass);
1719 1720
      new_indices[0] = (int)size;
      // copy any existing entries
D
duke 已提交
1721 1722 1723 1724 1725 1726 1727 1728 1729
      size_t i;
      for (i = 0; i < length; i++) {
        new_indices[i+1] = indices[i+1];
      }
      // Set all the rest to -1
      for (i = length; i < size; i++) {
        new_indices[i+1] = -1;
      }
      if (indices != NULL) {
1730 1731 1732
        // We have an old cache to delete so save it for after we
        // drop the lock.
        to_dealloc_indices = indices;
D
duke 已提交
1733 1734 1735
      }
      release_set_methods_cached_itable_indices(indices = new_indices);
    }
1736 1737 1738 1739 1740

    if (idnum_can_increment()) {
      // this cache can grow so we have to write to it safely
      indices[idnum+1] = index;
    }
D
duke 已提交
1741 1742 1743
  } else {
    CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
  }
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755

  if (!idnum_can_increment()) {
    // The cache cannot grow and this JNI itable index value does not
    // have to be unique like a jmethodID. If there is a race to set it,
    // it doesn't matter.
    indices[idnum+1] = index;
  }

  if (to_dealloc_indices != NULL) {
    // we allocated a new cache so free the old one
    FreeHeap(to_dealloc_indices);
  }
D
duke 已提交
1756 1757 1758 1759
}


// Retrieve a cached itable index
1760
int InstanceKlass::cached_itable_index(size_t idnum) {
D
duke 已提交
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
  int* indices = methods_cached_itable_indices_acquire();
  if (indices != NULL && ((size_t)indices[0]) > idnum) {
     // indices exist and are long enough, retrieve possible cached
    return indices[idnum+1];
  }
  return -1;
}


//
// Walk the list of dependent nmethods searching for nmethods which
1772
// are dependent on the changes that were passed in and mark them for
D
duke 已提交
1773 1774
// deoptimization.  Returns the number of nmethods found.
//
1775
int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
D
duke 已提交
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
  assert_locked_or_safepoint(CodeCache_lock);
  int found = 0;
  nmethodBucket* b = _dependencies;
  while (b != NULL) {
    nmethod* nm = b->get_nmethod();
    // since dependencies aren't removed until an nmethod becomes a zombie,
    // the dependency list may contain nmethods which aren't alive.
    if (nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
      if (TraceDependencies) {
        ResourceMark rm;
        tty->print_cr("Marked for deoptimization");
        tty->print_cr("  context = %s", this->external_name());
        changes.print();
        nm->print();
        nm->print_dependencies();
      }
      nm->mark_for_deoptimization();
      found++;
    }
    b = b->next();
  }
  return found;
}


//
// Add an nmethodBucket to the list of dependencies for this nmethod.
// It's possible that an nmethod has multiple dependencies on this klass
// so a count is kept for each bucket to guarantee that creation and
// deletion of dependencies is consistent.
//
1807
void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
D
duke 已提交
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
  assert_locked_or_safepoint(CodeCache_lock);
  nmethodBucket* b = _dependencies;
  nmethodBucket* last = NULL;
  while (b != NULL) {
    if (nm == b->get_nmethod()) {
      b->increment();
      return;
    }
    b = b->next();
  }
  _dependencies = new nmethodBucket(nm, _dependencies);
}


//
// Decrement count of the nmethod in the dependency list and remove
// the bucket competely when the count goes to 0.  This method must
// find a corresponding bucket otherwise there's a bug in the
// recording of dependecies.
//
1828
void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
D
duke 已提交
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
  assert_locked_or_safepoint(CodeCache_lock);
  nmethodBucket* b = _dependencies;
  nmethodBucket* last = NULL;
  while (b != NULL) {
    if (nm == b->get_nmethod()) {
      if (b->decrement() == 0) {
        if (last == NULL) {
          _dependencies = b->next();
        } else {
          last->set_next(b->next());
        }
        delete b;
      }
      return;
    }
    last = b;
    b = b->next();
  }
#ifdef ASSERT
  tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
  nm->print();
#endif // ASSERT
  ShouldNotReachHere();
}


#ifndef PRODUCT
1856
void InstanceKlass::print_dependent_nmethods(bool verbose) {
D
duke 已提交
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
  nmethodBucket* b = _dependencies;
  int idx = 0;
  while (b != NULL) {
    nmethod* nm = b->get_nmethod();
    tty->print("[%d] count=%d { ", idx++, b->count());
    if (!verbose) {
      nm->print_on(tty, "nmethod");
      tty->print_cr(" } ");
    } else {
      nm->print();
      nm->print_dependencies();
      tty->print_cr("--- } ");
    }
    b = b->next();
  }
}


1875
bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
D
duke 已提交
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
  nmethodBucket* b = _dependencies;
  while (b != NULL) {
    if (nm == b->get_nmethod()) {
      return true;
    }
    b = b->next();
  }
  return false;
}
#endif //PRODUCT


1888 1889
// Garbage collection

1890 1891 1892 1893 1894 1895
#ifdef ASSERT
template <class T> void assert_is_in(T *p) {
  T heap_oop = oopDesc::load_heap_oop(p);
  if (!oopDesc::is_null(heap_oop)) {
    oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
    assert(Universe::heap()->is_in(o), "should be in heap");
D
duke 已提交
1896 1897
  }
}
1898 1899 1900 1901
template <class T> void assert_is_in_closed_subset(T *p) {
  T heap_oop = oopDesc::load_heap_oop(p);
  if (!oopDesc::is_null(heap_oop)) {
    oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1902 1903
    assert(Universe::heap()->is_in_closed_subset(o),
           err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
  }
}
template <class T> void assert_is_in_reserved(T *p) {
  T heap_oop = oopDesc::load_heap_oop(p);
  if (!oopDesc::is_null(heap_oop)) {
    oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
    assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
  }
}
template <class T> void assert_nothing(T *p) {}

#else
template <class T> void assert_is_in(T *p) {}
template <class T> void assert_is_in_closed_subset(T *p) {}
template <class T> void assert_is_in_reserved(T *p) {}
template <class T> void assert_nothing(T *p) {}
#endif // ASSERT

//
// Macros that iterate over areas of oops which are specialized on type of
// oop pointer either narrow or wide, depending on UseCompressedOops
//
// Parameters are:
//   T         - type of oop to point to (either oop or narrowOop)
//   start_p   - starting pointer for region to iterate over
//   count     - number of oops or narrowOops to iterate over
//   do_oop    - action to perform on each oop (it's arbitrary C code which
//               makes it more efficient to put in a macro rather than making
//               it a template function)
//   assert_fn - assert function which is template function because performance
//               doesn't matter when enabled.
#define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
  T, start_p, count, do_oop,                \
  assert_fn)                                \
{                                           \
  T* p         = (T*)(start_p);             \
  T* const end = p + (count);               \
  while (p < end) {                         \
    (assert_fn)(p);                         \
    do_oop;                                 \
    ++p;                                    \
  }                                         \
}

#define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
  T, start_p, count, do_oop,                \
  assert_fn)                                \
{                                           \
  T* const start = (T*)(start_p);           \
  T*       p     = start + (count);         \
  while (start < p) {                       \
    --p;                                    \
    (assert_fn)(p);                         \
    do_oop;                                 \
  }                                         \
}

#define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
  T, start_p, count, low, high,             \
  do_oop, assert_fn)                        \
{                                           \
  T* const l = (T*)(low);                   \
  T* const h = (T*)(high);                  \
  assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
         mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
         "bounded region must be properly aligned"); \
  T* p       = (T*)(start_p);               \
  T* end     = p + (count);                 \
  if (p < l) p = l;                         \
  if (end > h) end = h;                     \
  while (p < end) {                         \
    (assert_fn)(p);                         \
    do_oop;                                 \
    ++p;                                    \
  }                                         \
}


// The following macros call specialized macros, passing either oop or
// narrowOop as the specialization type.  These test the UseCompressedOops
// flag.
#define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
{                                                                        \
  /* Compute oopmap block range. The common case                         \
     is nonstatic_oop_map_size == 1. */                                  \
  OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
1990
  OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
1991 1992 1993
  if (UseCompressedOops) {                                               \
    while (map < end_map) {                                              \
      InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
1994
        obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
1995 1996 1997 1998 1999 2000
        do_oop, assert_fn)                                               \
      ++map;                                                             \
    }                                                                    \
  } else {                                                               \
    while (map < end_map) {                                              \
      InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
2001
        obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2002 2003 2004 2005 2006 2007 2008 2009 2010
        do_oop, assert_fn)                                               \
      ++map;                                                             \
    }                                                                    \
  }                                                                      \
}

#define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
{                                                                        \
  OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
2011
  OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
2012 2013 2014 2015
  if (UseCompressedOops) {                                               \
    while (start_map < map) {                                            \
      --map;                                                             \
      InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
2016
        obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2017 2018 2019 2020 2021 2022
        do_oop, assert_fn)                                               \
    }                                                                    \
  } else {                                                               \
    while (start_map < map) {                                            \
      --map;                                                             \
      InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
2023
        obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
        do_oop, assert_fn)                                               \
    }                                                                    \
  }                                                                      \
}

#define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
                                              assert_fn)                 \
{                                                                        \
  /* Compute oopmap block range. The common case is                      \
     nonstatic_oop_map_size == 1, so we accept the                       \
     usually non-existent extra overhead of examining                    \
     all the maps. */                                                    \
  OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
2037
  OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
2038 2039 2040
  if (UseCompressedOops) {                                               \
    while (map < end_map) {                                              \
      InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
2041
        obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2042 2043 2044 2045 2046 2047 2048
        low, high,                                                       \
        do_oop, assert_fn)                                               \
      ++map;                                                             \
    }                                                                    \
  } else {                                                               \
    while (map < end_map) {                                              \
      InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
2049
        obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2050 2051 2052 2053 2054 2055 2056
        low, high,                                                       \
        do_oop, assert_fn)                                               \
      ++map;                                                             \
    }                                                                    \
  }                                                                      \
}

2057
void InstanceKlass::oop_follow_contents(oop obj) {
2058
  assert(obj != NULL, "can't follow the content of NULL object");
2059
  MarkSweep::follow_klass(obj->klass());
2060 2061 2062 2063
  InstanceKlass_OOP_MAP_ITERATE( \
    obj, \
    MarkSweep::mark_and_push(p), \
    assert_is_in_closed_subset)
D
duke 已提交
2064 2065
}

2066
#if INCLUDE_ALL_GCS
2067
void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
D
duke 已提交
2068
                                        oop obj) {
2069
  assert(obj != NULL, "can't follow the content of NULL object");
2070 2071 2072
  PSParallelCompact::follow_klass(cm, obj->klass());
  // Only mark the header and let the scan of the meta-data mark
  // everything else.
2073 2074 2075 2076
  InstanceKlass_OOP_MAP_ITERATE( \
    obj, \
    PSParallelCompact::mark_and_push(cm, p), \
    assert_is_in)
D
duke 已提交
2077
}
2078
#endif // INCLUDE_ALL_GCS
D
duke 已提交
2079

2080
// closure's do_metadata() method dictates whether the given closure should be
D
duke 已提交
2081 2082
// applied to the klass ptr in the object header.

2083 2084 2085 2086 2087 2088
#define if_do_metadata_checked(closure, nv_suffix)                    \
  /* Make sure the non-virtual and the virtual versions match. */     \
  assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
      "Inconsistency in do_metadata");                                \
  if (closure->do_metadata##nv_suffix())

2089 2090
#define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
                                                                             \
2091
int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
2092 2093
  SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  /* header */                                                          \
2094 2095
  if_do_metadata_checked(closure, nv_suffix) {                          \
    closure->do_klass##nv_suffix(obj->klass());                         \
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
  }                                                                     \
  InstanceKlass_OOP_MAP_ITERATE(                                        \
    obj,                                                                \
    SpecializationStats::                                               \
      record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
    (closure)->do_oop##nv_suffix(p),                                    \
    assert_is_in_closed_subset)                                         \
  return size_helper();                                                 \
}

2106
#if INCLUDE_ALL_GCS
2107 2108
#define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
                                                                                \
2109
int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
2110 2111 2112
                                              OopClosureType* closure) {        \
  SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
  /* header */                                                                  \
2113 2114
  if_do_metadata_checked(closure, nv_suffix) {                                  \
    closure->do_klass##nv_suffix(obj->klass());                                 \
2115 2116 2117 2118 2119 2120 2121 2122 2123
  }                                                                             \
  /* instance variables */                                                      \
  InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
    obj,                                                                        \
    SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
    (closure)->do_oop##nv_suffix(p),                                            \
    assert_is_in_closed_subset)                                                 \
   return size_helper();                                                        \
}
2124
#endif // INCLUDE_ALL_GCS
2125

2126 2127
#define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
                                                                        \
2128
int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
2129 2130 2131
                                                  OopClosureType* closure, \
                                                  MemRegion mr) {          \
  SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2132 2133 2134 2135
  if_do_metadata_checked(closure, nv_suffix) {                           \
    if (mr.contains(obj)) {                                              \
      closure->do_klass##nv_suffix(obj->klass());                        \
    }                                                                    \
2136 2137 2138 2139 2140 2141
  }                                                                      \
  InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
    obj, mr.start(), mr.end(),                                           \
    (closure)->do_oop##nv_suffix(p),                                     \
    assert_is_in_closed_subset)                                          \
  return size_helper();                                                  \
D
duke 已提交
2142 2143 2144
}

ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2145
ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
D
duke 已提交
2146
ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2147
ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2148
#if INCLUDE_ALL_GCS
2149 2150
ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2151
#endif // INCLUDE_ALL_GCS
D
duke 已提交
2152

2153
int InstanceKlass::oop_adjust_pointers(oop obj) {
D
duke 已提交
2154
  int size = size_helper();
2155 2156 2157 2158
  InstanceKlass_OOP_MAP_ITERATE( \
    obj, \
    MarkSweep::adjust_pointer(p), \
    assert_is_in)
2159
  MarkSweep::adjust_klass(obj->klass());
D
duke 已提交
2160 2161 2162
  return size;
}

2163
#if INCLUDE_ALL_GCS
2164
void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
2165 2166 2167 2168 2169 2170
  InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
    obj, \
    if (PSScavenge::should_scavenge(p)) { \
      pm->claim_or_forward_depth(p); \
    }, \
    assert_nothing )
D
duke 已提交
2171 2172
}

2173 2174
int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
  int size = size_helper();
2175 2176 2177
  InstanceKlass_OOP_MAP_ITERATE( \
    obj, \
    PSParallelCompact::adjust_pointer(p), \
2178 2179 2180
    assert_is_in)
  obj->update_header(cm);
  return size;
D
duke 已提交
2181 2182
}

2183
#endif // INCLUDE_ALL_GCS
D
duke 已提交
2184

2185 2186
void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
  assert(is_loader_alive(is_alive), "this klass should be live");
2187 2188
  if (is_interface()) {
    if (ClassUnloading) {
2189
      Klass* impl = implementor();
2190
      if (impl != NULL) {
2191
        if (!impl->is_loader_alive(is_alive)) {
2192
          // remove this guy
2193 2194 2195 2196 2197
          Klass** klass = adr_implementor();
          assert(klass != NULL, "null klass");
          if (klass != NULL) {
            *klass = NULL;
          }
2198
        }
D
duke 已提交
2199 2200 2201
      }
    }
  }
2202
}
2203

2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
  for (int m = 0; m < methods()->length(); m++) {
    MethodData* mdo = methods()->at(m)->method_data();
    if (mdo != NULL) {
      for (ProfileData* data = mdo->first_data();
           mdo->is_valid(data);
           data = mdo->next_data(data)) {
        data->clean_weak_klass_links(is_alive);
      }
    }
  }
D
duke 已提交
2215 2216
}

2217 2218 2219 2220 2221 2222 2223

static void remove_unshareable_in_class(Klass* k) {
  // remove klass's unshareable info
  k->remove_unshareable_info();
}

void InstanceKlass::remove_unshareable_info() {
D
duke 已提交
2224
  Klass::remove_unshareable_info();
2225 2226 2227 2228
  // Unlink the class
  if (is_linked()) {
    unlink_class();
  }
D
duke 已提交
2229
  init_implementor();
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254

  constants()->remove_unshareable_info();

  for (int i = 0; i < methods()->length(); i++) {
    Method* m = methods()->at(i);
    m->remove_unshareable_info();
  }

  // do array classes also.
  array_klasses_do(remove_unshareable_in_class);
}

void restore_unshareable_in_class(Klass* k, TRAPS) {
  k->restore_unshareable_info(CHECK);
}

void InstanceKlass::restore_unshareable_info(TRAPS) {
  Klass::restore_unshareable_info(CHECK);
  instanceKlassHandle ik(THREAD, this);

  Array<Method*>* methods = ik->methods();
  int num_methods = methods->length();
  for (int index2 = 0; index2 < num_methods; ++index2) {
    methodHandle m(THREAD, methods->at(index2));
    m()->link_method(m, CHECK);
2255 2256
    // restore method's vtable by calling a virtual function
    m->restore_vtable();
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
  }
  if (JvmtiExport::has_redefined_a_class()) {
    // Reinitialize vtable because RedefineClasses may have changed some
    // entries in this vtable for super classes so the CDS vtable might
    // point to old or obsolete entries.  RedefineClasses doesn't fix up
    // vtables in the shared system dictionary, only the main one.
    // It also redefines the itable too so fix that too.
    ResourceMark rm(THREAD);
    ik->vtable()->initialize_vtable(false, CHECK);
    ik->itable()->initialize_itable(false, CHECK);
  }

  // restore constant pool resolved references
  ik->constants()->restore_unshareable_info(CHECK);

  ik->array_klasses_do(restore_unshareable_in_class, CHECK);
D
duke 已提交
2273 2274
}

2275
static void clear_all_breakpoints(Method* m) {
D
duke 已提交
2276 2277 2278
  m->clear_all_breakpoints();
}

2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295

void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
  // notify the debugger
  if (JvmtiExport::should_post_class_unload()) {
    JvmtiExport::post_class_unload(ik);
  }

  // notify ClassLoadingService of class unload
  ClassLoadingService::notify_class_unloaded(ik);
}

void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
  // Clean up C heap
  ik->release_C_heap_structures();
  ik->constants()->release_C_heap_structures();
}

2296
void InstanceKlass::release_C_heap_structures() {
2297 2298 2299 2300 2301

  // Can't release the constant pool here because the constant pool can be
  // deallocated separately from the InstanceKlass for default methods and
  // redefine classes.

D
duke 已提交
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
  // Deallocate oop map cache
  if (_oop_map_cache != NULL) {
    delete _oop_map_cache;
    _oop_map_cache = NULL;
  }

  // Deallocate JNI identifiers for jfieldIDs
  JNIid::deallocate(jni_ids());
  set_jni_ids(NULL);

  jmethodID* jmeths = methods_jmethod_ids_acquire();
  if (jmeths != (jmethodID*)NULL) {
    release_set_methods_jmethod_ids(NULL);
    FreeHeap(jmeths);
  }

2318 2319 2320 2321 2322 2323 2324 2325 2326
  // Deallocate MemberNameTable
  {
    Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
    MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
    MemberNameTable* mnt = member_names();
    if (mnt != NULL) {
      delete mnt;
      set_member_names(NULL);
    }
2327 2328
  }

D
duke 已提交
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
  int* indices = methods_cached_itable_indices_acquire();
  if (indices != (int*)NULL) {
    release_set_methods_cached_itable_indices(NULL);
    FreeHeap(indices);
  }

  // release dependencies
  nmethodBucket* b = _dependencies;
  _dependencies = NULL;
  while (b != NULL) {
    nmethodBucket* next = b->next();
    delete b;
    b = next;
  }

  // Deallocate breakpoint records
  if (breakpoints() != 0x0) {
    methods_do(clear_all_breakpoints);
    assert(breakpoints() == 0x0, "should have cleared breakpoints");
  }

  // deallocate information about previous versions
  if (_previous_versions != NULL) {
    for (int i = _previous_versions->length() - 1; i >= 0; i--) {
      PreviousVersionNode * pv_node = _previous_versions->at(i);
      delete pv_node;
    }
    delete _previous_versions;
    _previous_versions = NULL;
  }

  // deallocate the cached class file
2361 2362 2363
  if (_cached_class_file != NULL) {
    os::free(_cached_class_file, mtClass);
    _cached_class_file = NULL;
D
duke 已提交
2364
  }
2365 2366 2367 2368 2369 2370

  // Decrement symbol reference counts associated with the unloaded class.
  if (_name != NULL) _name->decrement_refcount();
  // unreference array name derived from this class name (arrays of an unloaded
  // class can't be referenced anymore).
  if (_array_name != NULL)  _array_name->decrement_refcount();
2371
  if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
2372 2373 2374

  assert(_total_instanceKlass_count >= 1, "Sanity check");
  Atomic::dec(&_total_instanceKlass_count);
2375 2376
}

2377
void InstanceKlass::set_source_debug_extension(char* array, int length) {
2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
  if (array == NULL) {
    _source_debug_extension = NULL;
  } else {
    // Adding one to the attribute length in order to store a null terminator
    // character could cause an overflow because the attribute length is
    // already coded with an u4 in the classfile, but in practice, it's
    // unlikely to happen.
    assert((length+1) > length, "Overflow checking");
    char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
    for (int i = 0; i < length; i++) {
      sde[i] = array[i];
    }
    sde[length] = '\0';
    _source_debug_extension = sde;
  }
D
duke 已提交
2393 2394
}

2395
address InstanceKlass::static_field_addr(int offset) {
2396
  return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + (intptr_t)java_mirror());
2397 2398 2399
}


2400
const char* InstanceKlass::signature_name() const {
D
duke 已提交
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
  const char* src = (const char*) (name()->as_C_string());
  const int src_length = (int)strlen(src);
  char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
  int src_index = 0;
  int dest_index = 0;
  dest[dest_index++] = 'L';
  while (src_index < src_length) {
    dest[dest_index++] = src[src_index++];
  }
  dest[dest_index++] = ';';
  dest[dest_index] = '\0';
  return dest;
}

// different verisons of is_same_class_package
2416 2417 2418
bool InstanceKlass::is_same_class_package(Klass* class2) {
  Klass* class1 = this;
  oop classloader1 = InstanceKlass::cast(class1)->class_loader();
H
hseigel 已提交
2419
  Symbol* classname1 = class1->name();
D
duke 已提交
2420

H
hseigel 已提交
2421
  if (class2->oop_is_objArray()) {
2422
    class2 = ObjArrayKlass::cast(class2)->bottom_klass();
D
duke 已提交
2423 2424
  }
  oop classloader2;
H
hseigel 已提交
2425
  if (class2->oop_is_instance()) {
2426
    classloader2 = InstanceKlass::cast(class2)->class_loader();
D
duke 已提交
2427
  } else {
H
hseigel 已提交
2428
    assert(class2->oop_is_typeArray(), "should be type array");
D
duke 已提交
2429 2430
    classloader2 = NULL;
  }
H
hseigel 已提交
2431
  Symbol* classname2 = class2->name();
D
duke 已提交
2432

2433
  return InstanceKlass::is_same_class_package(classloader1, classname1,
D
duke 已提交
2434 2435 2436
                                              classloader2, classname2);
}

2437 2438 2439
bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
  Klass* class1 = this;
  oop classloader1 = InstanceKlass::cast(class1)->class_loader();
H
hseigel 已提交
2440
  Symbol* classname1 = class1->name();
D
duke 已提交
2441

2442
  return InstanceKlass::is_same_class_package(classloader1, classname1,
D
duke 已提交
2443 2444 2445 2446 2447
                                              classloader2, classname2);
}

// return true if two classes are in the same package, classloader
// and classname information is enough to determine a class's package
2448
bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
2449
                                          oop class_loader2, Symbol* class_name2) {
D
duke 已提交
2450 2451
  if (class_loader1 != class_loader2) {
    return false;
2452 2453
  } else if (class_name1 == class_name2) {
    return true;                // skip painful bytewise comparison
D
duke 已提交
2454 2455 2456
  } else {
    ResourceMark rm;

2457
    // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
D
duke 已提交
2458 2459
    // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
    // Otherwise, we just compare jbyte values between the strings.
2460 2461
    const jbyte *name1 = class_name1->base();
    const jbyte *name2 = class_name2->base();
D
duke 已提交
2462

2463 2464
    const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
    const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
D
duke 已提交
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499

    if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
      // One of the two doesn't have a package.  Only return true
      // if the other one also doesn't have a package.
      return last_slash1 == last_slash2;
    } else {
      // Skip over '['s
      if (*name1 == '[') {
        do {
          name1++;
        } while (*name1 == '[');
        if (*name1 != 'L') {
          // Something is terribly wrong.  Shouldn't be here.
          return false;
        }
      }
      if (*name2 == '[') {
        do {
          name2++;
        } while (*name2 == '[');
        if (*name2 != 'L') {
          // Something is terribly wrong.  Shouldn't be here.
          return false;
        }
      }

      // Check that package part is identical
      int length1 = last_slash1 - name1;
      int length2 = last_slash2 - name2;

      return UTF8::equal(name1, length1, name2, length2);
    }
  }
}

2500 2501 2502
// Returns true iff super_method can be overridden by a method in targetclassname
// See JSL 3rd edition 8.4.6.1
// Assumes name-signature match
2503 2504 2505
// "this" is InstanceKlass of super_method which must exist
// note that the InstanceKlass of the method in the targetclassname has not always been created yet
bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
   // Private methods can not be overridden
   if (super_method->is_private()) {
     return false;
   }
   // If super method is accessible, then override
   if ((super_method->is_protected()) ||
       (super_method->is_public())) {
     return true;
   }
   // Package-private methods are not inherited outside of package
   assert(super_method->is_package_private(), "must be package private");
2517
   return(is_same_class_package(targetclassloader(), targetclassname));
2518
}
D
duke 已提交
2519

2520
/* defined for now in jvm.cpp, for historical reasons *--
2521
Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
2522
                                                     Symbol*& simple_name_result, TRAPS) {
2523 2524 2525 2526 2527
  ...
}
*/

// tell if two classes have the same enclosing class (at package level)
2528 2529 2530
bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
                                                Klass* class2_oop, TRAPS) {
  if (class2_oop == class1())                       return true;
H
hseigel 已提交
2531
  if (!class2_oop->oop_is_instance())  return false;
2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
  instanceKlassHandle class2(THREAD, class2_oop);

  // must be in same package before we try anything else
  if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
    return false;

  // As long as there is an outer1.getEnclosingClass,
  // shift the search outward.
  instanceKlassHandle outer1 = class1;
  for (;;) {
    // As we walk along, look for equalities between outer1 and class2.
    // Eventually, the walks will terminate as outer1 stops
    // at the top-level class around the original class.
2545
    bool ignore_inner_is_member;
2546
    Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
2547
                                                    CHECK_false);
2548 2549 2550 2551 2552 2553 2554 2555
    if (next == NULL)  break;
    if (next == class2())  return true;
    outer1 = instanceKlassHandle(THREAD, next);
  }

  // Now do the same for class2.
  instanceKlassHandle outer2 = class2;
  for (;;) {
2556
    bool ignore_inner_is_member;
2557
    Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2558
                                                    CHECK_false);
2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
    if (next == NULL)  break;
    // Might as well check the new outer against all available values.
    if (next == class1())  return true;
    if (next == outer1())  return true;
    outer2 = instanceKlassHandle(THREAD, next);
  }

  // If by this point we have not found an equality between the
  // two classes, we know they are in separate package members.
  return false;
}

D
duke 已提交
2571

2572
jint InstanceKlass::compute_modifier_flags(TRAPS) const {
D
duke 已提交
2573 2574 2575
  jint access = access_flags().as_int();

  // But check if it happens to be member class.
2576
  instanceKlassHandle ik(THREAD, this);
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
  InnerClassesIterator iter(ik);
  for (; !iter.done(); iter.next()) {
    int ioff = iter.inner_class_info_index();
    // Inner class attribute can be zero, skip it.
    // Strange but true:  JVM spec. allows null inner class refs.
    if (ioff == 0) continue;

    // only look at classes that are already loaded
    // since we are looking for the flags for our self.
    Symbol* inner_name = ik->constants()->klass_name_at(ioff);
    if ((ik->name() == inner_name)) {
      // This is really a member class.
      access = iter.inner_access_flags();
      break;
D
duke 已提交
2591 2592 2593 2594 2595 2596
    }
  }
  // Remember to strip ACC_SUPER bit
  return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
}

2597
jint InstanceKlass::jvmti_class_status() const {
D
duke 已提交
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613
  jint result = 0;

  if (is_linked()) {
    result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
  }

  if (is_initialized()) {
    assert(is_linked(), "Class status is not consistent");
    result |= JVMTI_CLASS_STATUS_INITIALIZED;
  }
  if (is_in_error_state()) {
    result |= JVMTI_CLASS_STATUS_ERROR;
  }
  return result;
}

2614
Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
D
duke 已提交
2615 2616 2617 2618 2619 2620
  itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
  int method_table_offset_in_words = ioe->offset()/wordSize;
  int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
                       / itableOffsetEntry::size();

  for (int cnt = 0 ; ; cnt ++, ioe ++) {
T
twisti 已提交
2621
    // If the interface isn't implemented by the receiver class,
D
duke 已提交
2622 2623
    // the VM should throw IncompatibleClassChangeError.
    if (cnt >= nof_interfaces) {
2624
      THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
D
duke 已提交
2625 2626
    }

2627
    Klass* ik = ioe->interface_klass();
D
duke 已提交
2628 2629 2630
    if (ik == holder) break;
  }

2631 2632
  itableMethodEntry* ime = ioe->first_method_entry(this);
  Method* m = ime[index].method();
D
duke 已提交
2633
  if (m == NULL) {
2634
    THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
D
duke 已提交
2635 2636 2637 2638 2639
  }
  return m;
}

// On-stack replacement stuff
2640
void InstanceKlass::add_osr_nmethod(nmethod* n) {
D
duke 已提交
2641 2642 2643 2644 2645
  // only one compilation can be active
  NEEDS_CLEANUP
  // This is a short non-blocking critical region, so the no safepoint check is ok.
  OsrList_lock->lock_without_safepoint_check();
  assert(n->is_osr_method(), "wrong kind of nmethod");
2646
  n->set_osr_link(osr_nmethods_head());
D
duke 已提交
2647
  set_osr_nmethods_head(n);
I
iveresov 已提交
2648 2649
  // Raise the highest osr level if necessary
  if (TieredCompilation) {
2650
    Method* m = n->method();
I
iveresov 已提交
2651 2652
    m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
  }
D
duke 已提交
2653 2654
  // Remember to unlock again
  OsrList_lock->unlock();
I
iveresov 已提交
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664

  // Get rid of the osr methods for the same bci that have lower levels.
  if (TieredCompilation) {
    for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
      nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
      if (inv != NULL && inv->is_in_use()) {
        inv->make_not_entrant();
      }
    }
  }
D
duke 已提交
2665 2666 2667
}


2668
void InstanceKlass::remove_osr_nmethod(nmethod* n) {
D
duke 已提交
2669 2670 2671 2672 2673
  // This is a short non-blocking critical region, so the no safepoint check is ok.
  OsrList_lock->lock_without_safepoint_check();
  assert(n->is_osr_method(), "wrong kind of nmethod");
  nmethod* last = NULL;
  nmethod* cur  = osr_nmethods_head();
I
iveresov 已提交
2674
  int max_level = CompLevel_none;  // Find the max comp level excluding n
2675
  Method* m = n->method();
D
duke 已提交
2676 2677
  // Search for match
  while(cur != NULL && cur != n) {
I
iveresov 已提交
2678 2679 2680 2681
    if (TieredCompilation) {
      // Find max level before n
      max_level = MAX2(max_level, cur->comp_level());
    }
D
duke 已提交
2682
    last = cur;
2683
    cur = cur->osr_link();
D
duke 已提交
2684
  }
I
iveresov 已提交
2685
  nmethod* next = NULL;
D
duke 已提交
2686
  if (cur == n) {
I
iveresov 已提交
2687
    next = cur->osr_link();
D
duke 已提交
2688 2689
    if (last == NULL) {
      // Remove first element
I
iveresov 已提交
2690
      set_osr_nmethods_head(next);
D
duke 已提交
2691
    } else {
I
iveresov 已提交
2692
      last->set_osr_link(next);
D
duke 已提交
2693 2694
    }
  }
2695
  n->set_osr_link(NULL);
I
iveresov 已提交
2696 2697 2698 2699 2700 2701 2702 2703 2704
  if (TieredCompilation) {
    cur = next;
    while (cur != NULL) {
      // Find max level after n
      max_level = MAX2(max_level, cur->comp_level());
      cur = cur->osr_link();
    }
    m->set_highest_osr_comp_level(max_level);
  }
D
duke 已提交
2705 2706 2707 2708
  // Remember to unlock again
  OsrList_lock->unlock();
}

2709
nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
D
duke 已提交
2710 2711 2712
  // This is a short non-blocking critical region, so the no safepoint check is ok.
  OsrList_lock->lock_without_safepoint_check();
  nmethod* osr = osr_nmethods_head();
I
iveresov 已提交
2713
  nmethod* best = NULL;
D
duke 已提交
2714 2715
  while (osr != NULL) {
    assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
I
iveresov 已提交
2716 2717 2718 2719 2720 2721
    // There can be a time when a c1 osr method exists but we are waiting
    // for a c2 version. When c2 completes its osr nmethod we will trash
    // the c1 version and only be able to find the c2 version. However
    // while we overflow in the c1 code at back branches we don't want to
    // try and switch to the same code as we are already running

D
duke 已提交
2722 2723
    if (osr->method() == m &&
        (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
I
iveresov 已提交
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
      if (match_level) {
        if (osr->comp_level() == comp_level) {
          // Found a match - return it.
          OsrList_lock->unlock();
          return osr;
        }
      } else {
        if (best == NULL || (osr->comp_level() > best->comp_level())) {
          if (osr->comp_level() == CompLevel_highest_tier) {
            // Found the best possible - return it.
            OsrList_lock->unlock();
            return osr;
          }
          best = osr;
        }
      }
D
duke 已提交
2740
    }
2741
    osr = osr->osr_link();
D
duke 已提交
2742 2743
  }
  OsrList_lock->unlock();
I
iveresov 已提交
2744 2745 2746
  if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
    return best;
  }
D
duke 已提交
2747 2748 2749
  return NULL;
}

2750
void InstanceKlass::add_member_name(int index, Handle mem_name) {
2751 2752
  jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
  MutexLocker ml(MemberNameTable_lock);
2753
  assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
2754 2755 2756
  DEBUG_ONLY(No_Safepoint_Verifier nsv);

  if (_member_names == NULL) {
2757
    _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
2758
  }
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771
  _member_names->add_member_name(index, mem_name_wref);
}

oop InstanceKlass::get_member_name(int index) {
  MutexLocker ml(MemberNameTable_lock);
  assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
  DEBUG_ONLY(No_Safepoint_Verifier nsv);

  if (_member_names == NULL) {
    return NULL;
  }
  oop mem_name =_member_names->get_member_name(index);
  return mem_name;
2772 2773
}

D
duke 已提交
2774 2775 2776
// -----------------------------------------------------------------------------------------------------
// Printing

2777 2778
#ifndef PRODUCT

2779 2780
#define BULLET  " - "

2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
static const char* state_names[] = {
  "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
};

void InstanceKlass::print_on(outputStream* st) const {
  assert(is_klass(), "must be klass");
  Klass::print_on(st);

  st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
  st->print(BULLET"klass size:        %d", size());                               st->cr();
  st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
  st->print(BULLET"state:             "); st->print_cr(state_names[_init_state]);
  st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
  st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
  st->print(BULLET"sub:               ");
  Klass* sub = subklass();
  int n;
  for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
    if (n < MaxSubklassPrintSize) {
      sub->print_value_on(st);
      st->print("   ");
    }
  }
  if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
  st->cr();

  if (is_interface()) {
    st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
    if (nof_implementors() == 1) {
      st->print_cr(BULLET"implementor:    ");
      st->print("   ");
      implementor()->print_value_on(st);
      st->cr();
    }
  }

  st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
  st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
  if (Verbose) {
    Array<Method*>* method_array = methods();
    for(int i = 0; i < method_array->length(); i++) {
      st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
    }
  }
  st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);       st->cr();
  st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
  st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
  st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
  if (class_loader_data() != NULL) {
    st->print(BULLET"class loader data:  ");
    class_loader_data()->print_value_on(st);
    st->cr();
  }
  st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
  if (source_file_name() != NULL) {
    st->print(BULLET"source file:       ");
    source_file_name()->print_value_on(st);
    st->cr();
  }
  if (source_debug_extension() != NULL) {
    st->print(BULLET"source debug extension:       ");
    st->print("%s", source_debug_extension());
    st->cr();
  }
C
coleenp 已提交
2845 2846 2847 2848
  st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
  st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
  st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
  st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903
  {
    ResourceMark rm;
    // PreviousVersionInfo objects returned via PreviousVersionWalker
    // contain a GrowableArray of handles. We have to clean up the
    // GrowableArray _after_ the PreviousVersionWalker destructor
    // has destroyed the handles.
    {
      bool have_pv = false;
      PreviousVersionWalker pvw((InstanceKlass*)this);
      for (PreviousVersionInfo * pv_info = pvw.next_previous_version();
           pv_info != NULL; pv_info = pvw.next_previous_version()) {
        if (!have_pv)
          st->print(BULLET"previous version:  ");
        have_pv = true;
        pv_info->prev_constant_pool_handle()()->print_value_on(st);
      }
      if (have_pv)  st->cr();
    } // pvw is cleaned up
  } // rm is cleaned up

  if (generic_signature() != NULL) {
    st->print(BULLET"generic signature: ");
    generic_signature()->print_value_on(st);
    st->cr();
  }
  st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
  st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
  st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
  st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
  st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
  FieldPrinter print_static_field(st);
  ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
  st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
  FieldPrinter print_nonstatic_field(st);
  ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);

  st->print(BULLET"non-static oop maps: ");
  OopMapBlock* map     = start_of_nonstatic_oop_maps();
  OopMapBlock* end_map = map + nonstatic_oop_map_count();
  while (map < end_map) {
    st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
    map++;
  }
  st->cr();
}

#endif //PRODUCT

void InstanceKlass::print_value_on(outputStream* st) const {
  assert(is_klass(), "must be klass");
  name()->print_value_on(st);
}

#ifndef PRODUCT

D
duke 已提交
2904
void FieldPrinter::do_field(fieldDescriptor* fd) {
2905
  _st->print(BULLET);
2906
   if (_obj == NULL) {
D
duke 已提交
2907 2908 2909 2910 2911 2912 2913 2914 2915
     fd->print_on(_st);
     _st->cr();
   } else {
     fd->print_on_for(_st, _obj);
     _st->cr();
   }
}


2916
void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
D
duke 已提交
2917 2918
  Klass::oop_print_on(obj, st);

2919
  if (this == SystemDictionary::String_klass()) {
D
duke 已提交
2920 2921 2922 2923 2924 2925 2926
    typeArrayOop value  = java_lang_String::value(obj);
    juint        offset = java_lang_String::offset(obj);
    juint        length = java_lang_String::length(obj);
    if (value != NULL &&
        value->is_typeArray() &&
        offset          <= (juint) value->length() &&
        offset + length <= (juint) value->length()) {
2927
      st->print(BULLET"string: ");
D
duke 已提交
2928 2929 2930 2931 2932 2933 2934
      Handle h_obj(obj);
      java_lang_String::print(h_obj, st);
      st->cr();
      if (!WizardMode)  return;  // that is enough
    }
  }

2935
  st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
2936 2937
  FieldPrinter print_field(st, obj);
  do_nonstatic_fields(&print_field);
D
duke 已提交
2938

2939
  if (this == SystemDictionary::Class_klass()) {
2940 2941 2942
    st->print(BULLET"signature: ");
    java_lang_Class::print_signature(obj, st);
    st->cr();
2943
    Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
2944
    st->print(BULLET"fake entry for mirror: ");
2945
    mirrored_klass->print_value_on_maybe_null(st);
D
duke 已提交
2946
    st->cr();
2947
    Klass* array_klass = java_lang_Class::array_klass(obj);
2948
    st->print(BULLET"fake entry for array: ");
2949
    array_klass->print_value_on_maybe_null(st);
D
duke 已提交
2950
    st->cr();
2951 2952
    st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
    st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
2953 2954 2955
    Klass* real_klass = java_lang_Class::as_Klass(obj);
    if (real_klass != NULL && real_klass->oop_is_instance()) {
      InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
2956
    }
2957
  } else if (this == SystemDictionary::MethodType_klass()) {
2958
    st->print(BULLET"signature: ");
2959
    java_lang_invoke_MethodType::print_signature(obj, st);
2960
    st->cr();
D
duke 已提交
2961 2962 2963
  }
}

2964 2965
#endif //PRODUCT

2966
void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
D
duke 已提交
2967 2968 2969
  st->print("a ");
  name()->print_value_on(st);
  obj->print_address_on(st);
2970
  if (this == SystemDictionary::String_klass()
2971 2972 2973 2974 2975 2976 2977 2978
      && java_lang_String::value(obj) != NULL) {
    ResourceMark rm;
    int len = java_lang_String::length(obj);
    int plen = (len < 24 ? len : 12);
    char* str = java_lang_String::as_utf8_string(obj, 0, plen);
    st->print(" = \"%s\"", str);
    if (len > plen)
      st->print("...[%d]", len);
2979 2980
  } else if (this == SystemDictionary::Class_klass()) {
    Klass* k = java_lang_Class::as_Klass(obj);
2981 2982 2983 2984 2985 2986 2987
    st->print(" = ");
    if (k != NULL) {
      k->print_value_on(st);
    } else {
      const char* tname = type2name(java_lang_Class::primitive_type(obj));
      st->print("%s", tname ? tname : "type?");
    }
2988
  } else if (this == SystemDictionary::MethodType_klass()) {
2989
    st->print(" = ");
2990
    java_lang_invoke_MethodType::print_signature(obj, st);
2991 2992 2993
  } else if (java_lang_boxing_object::is_instance(obj)) {
    st->print(" = ");
    java_lang_boxing_object::print(obj, st);
2994
  } else if (this == SystemDictionary::LambdaForm_klass()) {
2995 2996 2997 2998 2999
    oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
    if (vmentry != NULL) {
      st->print(" => ");
      vmentry->print_value_on(st);
    }
3000 3001
  } else if (this == SystemDictionary::MemberName_klass()) {
    Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3002 3003 3004 3005 3006 3007 3008 3009
    if (vmtarget != NULL) {
      st->print(" = ");
      vmtarget->print_value_on(st);
    } else {
      java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
      st->print(".");
      java_lang_invoke_MemberName::name(obj)->print_value_on(st);
    }
3010
  }
D
duke 已提交
3011 3012
}

3013
const char* InstanceKlass::internal_name() const {
D
duke 已提交
3014 3015 3016
  return external_name();
}

3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061
#if INCLUDE_SERVICES
// Size Statistics
void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
  Klass::collect_statistics(sz);

  sz->_inst_size  = HeapWordSize * size_helper();
  sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
  sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
  sz->_nonstatic_oopmap_bytes = HeapWordSize *
        ((is_interface() || is_anonymous()) ?
         align_object_offset(nonstatic_oop_map_size()) :
         nonstatic_oop_map_size());

  int n = 0;
  n += (sz->_methods_array_bytes         = sz->count_array(methods()));
  n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
  n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
  n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
  n += (sz->_fields_bytes                = sz->count_array(fields()));
  n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
  sz->_ro_bytes += n;

  const ConstantPool* cp = constants();
  if (cp) {
    cp->collect_statistics(sz);
  }

  const Annotations* anno = annotations();
  if (anno) {
    anno->collect_statistics(sz);
  }

  const Array<Method*>* methods_array = methods();
  if (methods()) {
    for (int i = 0; i < methods_array->length(); i++) {
      Method* method = methods_array->at(i);
      if (method) {
        sz->_method_count ++;
        method->collect_statistics(sz);
      }
    }
  }
}
#endif // INCLUDE_SERVICES

D
duke 已提交
3062 3063 3064
// Verification

class VerifyFieldClosure: public OopClosure {
3065 3066 3067 3068 3069
 protected:
  template <class T> void do_oop_work(T* p) {
    oop obj = oopDesc::load_decode_heap_oop(p);
    if (!obj->is_oop_or_null()) {
      tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
D
duke 已提交
3070 3071 3072 3073
      Universe::print();
      guarantee(false, "boom");
    }
  }
3074 3075 3076
 public:
  virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
  virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
D
duke 已提交
3077 3078
};

3079
void InstanceKlass::verify_on(outputStream* st, bool check_dictionary) {
3080
#ifndef PRODUCT
3081
  // Avoid redundant verifies, this really should be in product.
3082 3083 3084
  if (_verify_count == Universe::verify_count()) return;
  _verify_count = Universe::verify_count();
#endif
3085 3086 3087 3088 3089 3090 3091

  // Verify Klass
  Klass::verify_on(st, check_dictionary);

  // Verify that klass is present in SystemDictionary if not already
  // verifying the SystemDictionary.
  if (is_loaded() && !is_anonymous() && check_dictionary) {
3092 3093 3094 3095 3096 3097
    Symbol* h_name = name();
    SystemDictionary::verify_obj_klass_present(h_name, class_loader_data());
  }

  // Verify vtables
  if (is_linked()) {
3098
    ResourceMark rm;
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125
    // $$$ This used to be done only for m/s collections.  Doing it
    // always seemed a valid generalization.  (DLD -- 6/00)
    vtable()->verify(st);
  }

  // Verify first subklass
  if (subklass_oop() != NULL) {
    guarantee(subklass_oop()->is_klass(), "should be klass");
  }

  // Verify siblings
  Klass* super = this->super();
  Klass* sib = next_sibling();
  if (sib != NULL) {
    if (sib == this) {
      fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
    }

    guarantee(sib->is_klass(), "should be klass");
    guarantee(sib->super() == super, "siblings should have same superklass");
  }

  // Verify implementor fields
  Klass* im = implementor();
  if (im != NULL) {
    guarantee(is_interface(), "only interfaces should have implementor set");
    guarantee(im->is_klass(), "should be klass");
H
hseigel 已提交
3126
    guarantee(!im->is_interface() || im == this,
3127 3128 3129 3130 3131 3132 3133 3134
      "implementors cannot be interfaces");
  }

  // Verify local interfaces
  if (local_interfaces()) {
    Array<Klass*>* local_interfaces = this->local_interfaces();
    for (int j = 0; j < local_interfaces->length(); j++) {
      Klass* e = local_interfaces->at(j);
H
hseigel 已提交
3135
      guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3136 3137 3138 3139 3140 3141 3142 3143
    }
  }

  // Verify transitive interfaces
  if (transitive_interfaces() != NULL) {
    Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
    for (int j = 0; j < transitive_interfaces->length(); j++) {
      Klass* e = transitive_interfaces->at(j);
H
hseigel 已提交
3144
      guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
    }
  }

  // Verify methods
  if (methods() != NULL) {
    Array<Method*>* methods = this->methods();
    for (int j = 0; j < methods->length(); j++) {
      guarantee(methods->at(j)->is_method(), "non-method in methods array");
    }
    for (int j = 0; j < methods->length() - 1; j++) {
      Method* m1 = methods->at(j);
      Method* m2 = methods->at(j + 1);
      guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
    }
  }

  // Verify method ordering
  if (method_ordering() != NULL) {
    Array<int>* method_ordering = this->method_ordering();
    int length = method_ordering->length();
    if (JvmtiExport::can_maintain_original_method_order() ||
3166
        ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
      guarantee(length == methods()->length(), "invalid method ordering length");
      jlong sum = 0;
      for (int j = 0; j < length; j++) {
        int original_index = method_ordering->at(j);
        guarantee(original_index >= 0, "invalid method ordering index");
        guarantee(original_index < length, "invalid method ordering index");
        sum += original_index;
      }
      // Verify sum of indices 0,1,...,length-1
      guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
    } else {
      guarantee(length == 0, "invalid method ordering length");
    }
  }

  // Verify JNI static field identifiers
  if (jni_ids() != NULL) {
    jni_ids()->verify(this);
  }

  // Verify other fields
  if (array_klasses() != NULL) {
    guarantee(array_klasses()->is_klass(), "should be klass");
  }
  if (constants() != NULL) {
    guarantee(constants()->is_constantPool(), "should be constant pool");
  }
3194 3195 3196
  const Klass* host = host_klass();
  if (host != NULL) {
    guarantee(host->is_klass(), "should be klass");
3197 3198 3199 3200
  }
}

void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
D
duke 已提交
3201 3202
  Klass::oop_verify_on(obj, st);
  VerifyFieldClosure blk;
3203
  obj->oop_iterate_no_header(&blk);
D
duke 已提交
3204 3205
}

3206

3207 3208 3209 3210
// JNIid class for jfieldIDs only
// Note to reviewers:
// These JNI functions are just moved over to column 1 and not changed
// in the compressed oops workspace.
3211
JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3212 3213 3214 3215 3216
  _holder = holder;
  _offset = offset;
  _next = next;
  debug_only(_is_static_field_id = false;)
}
D
duke 已提交
3217 3218


3219 3220 3221 3222 3223 3224 3225 3226
JNIid* JNIid::find(int offset) {
  JNIid* current = this;
  while (current != NULL) {
    if (current->offset() == offset) return current;
    current = current->next();
  }
  return NULL;
}
D
duke 已提交
3227 3228

void JNIid::deallocate(JNIid* current) {
3229 3230 3231 3232 3233 3234 3235
  while (current != NULL) {
    JNIid* next = current->next();
    delete current;
    current = next;
  }
}

D
duke 已提交
3236

3237
void JNIid::verify(Klass* holder) {
3238
  int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3239
  int end_field_offset;
3240
  end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
D
duke 已提交
3241

3242 3243 3244
  JNIid* current = this;
  while (current != NULL) {
    guarantee(current->holder() == holder, "Invalid klass in JNIid");
D
duke 已提交
3245
#ifdef ASSERT
3246 3247 3248 3249 3250 3251
    int o = current->offset();
    if (current->is_static_field_id()) {
      guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
    }
#endif
    current = current->next();
D
duke 已提交
3252
  }
3253 3254 3255 3256
}


#ifdef ASSERT
3257 3258
void InstanceKlass::set_init_state(ClassState state) {
  bool good_state = is_shared() ? (_init_state <= state)
3259 3260
                                               : (_init_state < state);
  assert(good_state || state == allocated, "illegal state transition");
3261
  _init_state = (u1)state;
3262
}
D
duke 已提交
3263 3264 3265 3266 3267
#endif


// RedefineClasses() support for previous versions:

3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359
// Purge previous versions
static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
  if (ik->previous_versions() != NULL) {
    // This klass has previous versions so see what we can cleanup
    // while it is safe to do so.

    int deleted_count = 0;    // leave debugging breadcrumbs
    int live_count = 0;
    ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
                       ClassLoaderData::the_null_class_loader_data() :
                       ik->class_loader_data();

    // RC_TRACE macro has an embedded ResourceMark
    RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
      ik->external_name(), ik->previous_versions()->length()));

    for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
      // check the previous versions array
      PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
      ConstantPool* cp_ref = pv_node->prev_constant_pool();
      assert(cp_ref != NULL, "cp ref was unexpectedly cleared");

      ConstantPool* pvcp = cp_ref;
      if (!pvcp->on_stack()) {
        // If the constant pool isn't on stack, none of the methods
        // are executing.  Delete all the methods, the constant pool and
        // and this previous version node.
        GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
        if (method_refs != NULL) {
          for (int j = method_refs->length() - 1; j >= 0; j--) {
            Method* method = method_refs->at(j);
            assert(method != NULL, "method ref was unexpectedly cleared");
            method_refs->remove_at(j);
            // method will be freed with associated class.
          }
        }
        // Remove the constant pool
        delete pv_node;
        // Since we are traversing the array backwards, we don't have to
        // do anything special with the index.
        ik->previous_versions()->remove_at(i);
        deleted_count++;
        continue;
      } else {
        RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
        assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
        guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
        live_count++;
      }

      // At least one method is live in this previous version, clean out
      // the others or mark them as obsolete.
      GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
      if (method_refs != NULL) {
        RC_TRACE(0x00000200, ("purge: previous methods length=%d",
          method_refs->length()));
        for (int j = method_refs->length() - 1; j >= 0; j--) {
          Method* method = method_refs->at(j);
          assert(method != NULL, "method ref was unexpectedly cleared");

          // Remove the emcp method if it's not executing
          // If it's been made obsolete by a redefinition of a non-emcp
          // method, mark it as obsolete but leave it to clean up later.
          if (!method->on_stack()) {
            method_refs->remove_at(j);
          } else if (emcp_method_count == 0) {
            method->set_is_obsolete();
          } else {
            // RC_TRACE macro has an embedded ResourceMark
            RC_TRACE(0x00000200,
              ("purge: %s(%s): prev method @%d in version @%d is alive",
              method->name()->as_C_string(),
              method->signature()->as_C_string(), j, i));
          }
        }
      }
    }
    assert(ik->previous_versions()->length() == live_count, "sanity check");
    RC_TRACE(0x00000200,
      ("purge: previous version stats: live=%d, deleted=%d", live_count,
      deleted_count));
  }
}

// External interface for use during class unloading.
void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
  // Call with >0 emcp methods since they are not currently being redefined.
  purge_previous_versions_internal(ik, 1);
}


// Potentially add an information node that contains pointers to the
D
duke 已提交
3360
// interesting parts of the previous version of the_class.
3361
// This is also where we clean out any unused references.
3362 3363 3364 3365
// Note that while we delete nodes from the _previous_versions
// array, we never delete the array itself until the klass is
// unloaded. The has_been_redefined() query depends on that fact.
//
3366
void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
3367
       BitMap* emcp_methods, int emcp_method_count) {
D
duke 已提交
3368
  assert(Thread::current()->is_VM_thread(),
3369
         "only VMThread can add previous versions");
D
duke 已提交
3370 3371 3372 3373 3374

  if (_previous_versions == NULL) {
    // This is the first previous version so make some space.
    // Start with 2 elements under the assumption that the class
    // won't be redefined much.
Z
zgu 已提交
3375
    _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
D
duke 已提交
3376 3377 3378
                            GrowableArray<PreviousVersionNode *>(2, true);
  }

3379 3380
  ConstantPool* cp_ref = ikh->constants();

D
duke 已提交
3381
  // RC_TRACE macro has an embedded ResourceMark
3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
  RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
                        "on_stack=%d",
    ikh->external_name(), _previous_versions->length(), emcp_method_count,
    cp_ref->on_stack()));

  // If the constant pool for this previous version of the class
  // is not marked as being on the stack, then none of the methods
  // in this previous version of the class are on the stack so
  // we don't need to create a new PreviousVersionNode. However,
  // we still need to examine older previous versions below.
  Array<Method*>* old_methods = ikh->methods();

  if (cp_ref->on_stack()) {
D
duke 已提交
3395 3396
  PreviousVersionNode * pv_node = NULL;
  if (emcp_method_count == 0) {
3397 3398
      // non-shared ConstantPool gets a reference
      pv_node = new PreviousVersionNode(cp_ref, !cp_ref->is_shared(), NULL);
D
duke 已提交
3399
    RC_TRACE(0x00000400,
3400
        ("add: all methods are obsolete; flushing any EMCP refs"));
D
duke 已提交
3401 3402
  } else {
    int local_count = 0;
3403 3404
      GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
        GrowableArray<Method*>(emcp_method_count, true);
D
duke 已提交
3405 3406
    for (int i = 0; i < old_methods->length(); i++) {
      if (emcp_methods->at(i)) {
3407 3408 3409 3410 3411
          // this old method is EMCP. Save it only if it's on the stack
          Method* old_method = old_methods->at(i);
          if (old_method->on_stack()) {
            method_refs->append(old_method);
          }
D
duke 已提交
3412 3413 3414 3415 3416 3417
        if (++local_count >= emcp_method_count) {
          // no more EMCP methods so bail out now
          break;
        }
      }
    }
3418 3419 3420 3421
      // non-shared ConstantPool gets a reference
      pv_node = new PreviousVersionNode(cp_ref, !cp_ref->is_shared(), method_refs);
    }
    // append new previous version.
D
duke 已提交
3422
  _previous_versions->append(pv_node);
3423
  }
D
duke 已提交
3424

3425 3426
  // Since the caller is the VMThread and we are at a safepoint, this
  // is a good time to clear out unused references.
D
duke 已提交
3427 3428 3429 3430

  RC_TRACE(0x00000400, ("add: previous version length=%d",
    _previous_versions->length()));

3431 3432
  // Purge previous versions not executing on the stack
  purge_previous_versions_internal(this, emcp_method_count);
D
duke 已提交
3433 3434 3435 3436

  int obsolete_method_count = old_methods->length() - emcp_method_count;

  if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3437 3438
      _previous_versions->length() > 0) {
    // We have a mix of obsolete and EMCP methods so we have to
D
duke 已提交
3439 3440 3441 3442 3443
    // clear out any matching EMCP method entries the hard way.
    int local_count = 0;
    for (int i = 0; i < old_methods->length(); i++) {
      if (!emcp_methods->at(i)) {
        // only obsolete methods are interesting
3444
        Method* old_method = old_methods->at(i);
3445 3446
        Symbol* m_name = old_method->name();
        Symbol* m_signature = old_method->signature();
D
duke 已提交
3447

3448 3449 3450 3451
        // we might not have added the last entry
        for (int j = _previous_versions->length() - 1; j >= 0; j--) {
          // check the previous versions array for non executing obsolete methods
          PreviousVersionNode * pv_node = _previous_versions->at(j);
D
duke 已提交
3452

3453
          GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
D
duke 已提交
3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
          if (method_refs == NULL) {
            // We have run into a PreviousVersion generation where
            // all methods were made obsolete during that generation's
            // RedefineClasses() operation. At the time of that
            // operation, all EMCP methods were flushed so we don't
            // have to go back any further.
            //
            // A NULL method_refs is different than an empty method_refs.
            // We cannot infer any optimizations about older generations
            // from an empty method_refs for the current generation.
            break;
          }

          for (int k = method_refs->length() - 1; k >= 0; k--) {
3468
            Method* method = method_refs->at(k);
D
duke 已提交
3469

3470 3471
            if (!method->is_obsolete() &&
                method->name() == m_name &&
D
duke 已提交
3472 3473 3474
                method->signature() == m_signature) {
              // The current RedefineClasses() call has made all EMCP
              // versions of this method obsolete so mark it as obsolete
3475
              // and remove the reference.
D
duke 已提交
3476 3477 3478 3479 3480
              RC_TRACE(0x00000400,
                ("add: %s(%s): flush obsolete method @%d in version @%d",
                m_name->as_C_string(), m_signature->as_C_string(), k, j));

              method->set_is_obsolete();
3481 3482
              // Leave obsolete methods on the previous version list to
              // clean up later.
D
duke 已提交
3483 3484 3485 3486 3487 3488 3489
              break;
            }
          }

          // The previous loop may not find a matching EMCP method, but
          // that doesn't mean that we can optimize and not go any
          // further back in the PreviousVersion generations. The EMCP
3490
          // method for this generation could have already been deleted,
D
duke 已提交
3491
          // but there still may be an older EMCP method that has not
3492
          // been deleted.
D
duke 已提交
3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504
        }

        if (++local_count >= obsolete_method_count) {
          // no more obsolete methods so bail out now
          break;
        }
      }
    }
  }
} // end add_previous_version()


3505 3506 3507
// Determine if InstanceKlass has a previous version.
bool InstanceKlass::has_previous_version() const {
  return (_previous_versions != NULL && _previous_versions->length() > 0);
D
duke 已提交
3508 3509
} // end has_previous_version()

3510 3511 3512

Method* InstanceKlass::method_with_idnum(int idnum) {
  Method* m = NULL;
D
duke 已提交
3513
  if (idnum < methods()->length()) {
3514
    m = methods()->at(idnum);
D
duke 已提交
3515 3516 3517
  }
  if (m == NULL || m->method_idnum() != idnum) {
    for (int index = 0; index < methods()->length(); ++index) {
3518
      m = methods()->at(index);
D
duke 已提交
3519 3520 3521 3522 3523 3524 3525 3526
      if (m->method_idnum() == idnum) {
        return m;
      }
    }
  }
  return m;
}

3527 3528 3529 3530 3531 3532 3533 3534
jint InstanceKlass::get_cached_class_file_len() {
  return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
}

unsigned char * InstanceKlass::get_cached_class_file_bytes() {
  return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
}

D
duke 已提交
3535 3536

// Construct a PreviousVersionNode entry for the array hung off
3537 3538 3539
// the InstanceKlass.
PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
  bool prev_cp_is_weak, GrowableArray<Method*>* prev_EMCP_methods) {
D
duke 已提交
3540 3541

  _prev_constant_pool = prev_constant_pool;
3542
  _prev_cp_is_weak = prev_cp_is_weak;
D
duke 已提交
3543 3544 3545 3546 3547 3548 3549
  _prev_EMCP_methods = prev_EMCP_methods;
}


// Destroy a PreviousVersionNode
PreviousVersionNode::~PreviousVersionNode() {
  if (_prev_constant_pool != NULL) {
3550
    _prev_constant_pool = NULL;
D
duke 已提交
3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
  }

  if (_prev_EMCP_methods != NULL) {
    delete _prev_EMCP_methods;
  }
}


// Construct a PreviousVersionInfo entry
PreviousVersionInfo::PreviousVersionInfo(PreviousVersionNode *pv_node) {
  _prev_constant_pool_handle = constantPoolHandle();  // NULL handle
  _prev_EMCP_method_handles = NULL;

3564 3565
  ConstantPool* cp = pv_node->prev_constant_pool();
  assert(cp != NULL, "constant pool ref was unexpectedly cleared");
D
duke 已提交
3566
  if (cp == NULL) {
3567
    return;  // robustness
D
duke 已提交
3568 3569
  }

3570
  // make the ConstantPool* safe to return
D
duke 已提交
3571 3572
  _prev_constant_pool_handle = constantPoolHandle(cp);

3573
  GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
D
duke 已提交
3574
  if (method_refs == NULL) {
3575
    // the InstanceKlass did not have any EMCP methods
D
duke 已提交
3576 3577 3578 3579 3580 3581 3582
    return;
  }

  _prev_EMCP_method_handles = new GrowableArray<methodHandle>(10);

  int n_methods = method_refs->length();
  for (int i = 0; i < n_methods; i++) {
3583 3584
    Method* method = method_refs->at(i);
    assert (method != NULL, "method has been cleared");
D
duke 已提交
3585
    if (method == NULL) {
3586
      continue;  // robustness
D
duke 已提交
3587
    }
3588
    // make the Method* safe to return
D
duke 已提交
3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601
    _prev_EMCP_method_handles->append(methodHandle(method));
  }
}


// Destroy a PreviousVersionInfo
PreviousVersionInfo::~PreviousVersionInfo() {
  // Since _prev_EMCP_method_handles is not C-heap allocated, we
  // don't have to delete it.
}


// Construct a helper for walking the previous versions array
3602
PreviousVersionWalker::PreviousVersionWalker(InstanceKlass *ik) {
D
duke 已提交
3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639
  _previous_versions = ik->previous_versions();
  _current_index = 0;
  // _hm needs no initialization
  _current_p = NULL;
}


// Destroy a PreviousVersionWalker
PreviousVersionWalker::~PreviousVersionWalker() {
  // Delete the current info just in case the caller didn't walk to
  // the end of the previous versions list. No harm if _current_p is
  // already NULL.
  delete _current_p;

  // When _hm is destroyed, all the Handles returned in
  // PreviousVersionInfo objects will be destroyed.
  // Also, after this destructor is finished it will be
  // safe to delete the GrowableArray allocated in the
  // PreviousVersionInfo objects.
}


// Return the interesting information for the next previous version
// of the klass. Returns NULL if there are no more previous versions.
PreviousVersionInfo* PreviousVersionWalker::next_previous_version() {
  if (_previous_versions == NULL) {
    // no previous versions so nothing to return
    return NULL;
  }

  delete _current_p;  // cleanup the previous info for the caller
  _current_p = NULL;  // reset to NULL so we don't delete same object twice

  int length = _previous_versions->length();

  while (_current_index < length) {
    PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
Z
zgu 已提交
3640
    PreviousVersionInfo * pv_info = new (ResourceObj::C_HEAP, mtClass)
D
duke 已提交
3641 3642 3643
                                          PreviousVersionInfo(pv_node);

    constantPoolHandle cp_h = pv_info->prev_constant_pool_handle();
3644
    assert (!cp_h.is_null(), "null cp found in previous version");
D
duke 已提交
3645

3646
    // The caller will need to delete pv_info when they are done with it.
D
duke 已提交
3647 3648 3649 3650
    _current_p = pv_info;
    return pv_info;
  }

3651
  // all of the underlying nodes' info has been deleted
D
duke 已提交
3652 3653
  return NULL;
} // end next_previous_version()