instanceKlass.cpp 144.6 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2019, 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
#include "precompiled.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/systemDictionary.hpp"
I
iklam 已提交
28
#include "classfile/systemDictionaryShared.hpp"
29 30 31 32 33 34 35 36 37
#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"
38
#include "memory/heapInspection.hpp"
39
#include "memory/iterator.inline.hpp"
40
#include "memory/metadataFactory.hpp"
41
#include "memory/oopFactory.hpp"
42
#include "oops/fieldStreams.hpp"
43
#include "oops/instanceClassLoaderKlass.hpp"
44
#include "oops/instanceKlass.hpp"
45
#include "oops/instanceMirrorKlass.hpp"
46
#include "oops/instanceOop.hpp"
47 48
#include "oops/klass.inline.hpp"
#include "oops/method.hpp"
49
#include "oops/oop.inline.hpp"
50
#include "oops/symbol.hpp"
51 52
#include "prims/jvmtiExport.hpp"
#include "prims/jvmtiRedefineClassesTrace.hpp"
53
#include "prims/jvmtiRedefineClasses.hpp"
54
#include "prims/jvmtiThreadState.hpp"
55
#include "prims/methodComparator.hpp"
56 57 58 59
#include "runtime/fieldDescriptor.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
60
#include "runtime/orderAccess.inline.hpp"
61
#include "runtime/thread.inline.hpp"
62
#include "services/classLoadingService.hpp"
63 64
#include "services/threadService.hpp"
#include "utilities/dtrace.hpp"
65 66
#include "utilities/macros.hpp"
#if INCLUDE_ALL_GCS
67
#include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
68 69 70
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
#include "gc_implementation/g1/g1OopClosures.inline.hpp"
#include "gc_implementation/g1/g1RemSet.inline.hpp"
71
#include "gc_implementation/g1/heapRegionManager.inline.hpp"
72
#include "gc_implementation/parNew/parOopClosures.inline.hpp"
73
#include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
74 75 76
#include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
#include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
#include "oops/oop.pcgc.inline.hpp"
77
#endif // INCLUDE_ALL_GCS
78 79 80
#ifdef COMPILER1
#include "c1/c1_Compiler.hpp"
#endif
81 82 83 84
#if INCLUDE_JFR
#include "jfr/jfrEvents.hpp"
#endif

D
duke 已提交
85

86 87
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

88 89
#ifdef DTRACE_ENABLED

D
dcubed 已提交
90 91
#ifndef USDT2

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
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;                                                 \
113
    Symbol* name = (clss)->name();                               \
114 115 116 117 118
    if (name != NULL) {                                          \
      data = (char*)name->bytes();                               \
      len = name->utf8_length();                                 \
    }                                                            \
    HS_DTRACE_PROBE4(hotspot, class__initialization__##type,     \
119
      data, len, (void *)(clss)->class_loader(), thread_type);           \
120 121 122 123 124 125
  }

#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
  {                                                              \
    char* data = NULL;                                           \
    int len = 0;                                                 \
126
    Symbol* name = (clss)->name();                               \
127 128 129 130 131
    if (name != NULL) {                                          \
      data = (char*)name->bytes();                               \
      len = name->utf8_length();                                 \
    }                                                            \
    HS_DTRACE_PROBE5(hotspot, class__initialization__##type,     \
132
      data, len, (void *)(clss)->class_loader(), thread_type, wait);     \
133
  }
D
dcubed 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
#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(                         \
154
      data, len, (void *)(clss)->class_loader(), thread_type); \
D
dcubed 已提交
155 156 157 158 159 160 161 162 163 164 165 166
  }

#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(                         \
167
      data, len, (void *)(clss)->class_loader(), thread_type, wait); \
D
dcubed 已提交
168 169
  }
#endif /* USDT2 */
170 171 172 173 174 175 176 177

#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

178 179
volatile int InstanceKlass::_total_instanceKlass_count = 0;

180 181
InstanceKlass* InstanceKlass::allocate_instance_klass(
                                              ClassLoaderData* loader_data,
C
coleenp 已提交
182 183 184 185 186 187 188
                                              int vtable_len,
                                              int itable_len,
                                              int static_field_size,
                                              int nonstatic_oop_map_size,
                                              ReferenceType rt,
                                              AccessFlags access_flags,
                                              Symbol* name,
189
                                              Klass* super_klass,
C
coleenp 已提交
190 191
                                              bool is_anonymous,
                                              TRAPS) {
192 193

  int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
C
coleenp 已提交
194
                                 access_flags.is_interface(), is_anonymous);
195 196 197 198 199

  // Allocation
  InstanceKlass* ik;
  if (rt == REF_NONE) {
    if (name == vmSymbols::java_lang_Class()) {
200
      ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
201
        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
C
coleenp 已提交
202
        access_flags, is_anonymous);
203 204 205 206
    } else if (name == vmSymbols::java_lang_ClassLoader() ||
          (SystemDictionary::ClassLoader_klass_loaded() &&
          super_klass != NULL &&
          super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
207
      ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
208
        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
C
coleenp 已提交
209
        access_flags, is_anonymous);
210 211 212 213
    } else {
      // normal class
      ik = new (loader_data, size, THREAD) InstanceKlass(
        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
C
coleenp 已提交
214
        access_flags, is_anonymous);
215 216 217
    }
  } else {
    // reference klass
218
    ik = new (loader_data, size, THREAD) InstanceRefKlass(
219
        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
C
coleenp 已提交
220
        access_flags, is_anonymous);
221 222
  }

223 224 225 226 227 228 229 230 231 232
  // 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);

233
  Atomic::inc(&_total_instanceKlass_count);
234 235 236
  return ik;
}

237 238 239 240 241 242 243 244 245 246 247 248 249 250

// 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();
  }
}

251 252 253 254 255 256 257
// create a new array of vtable_indices for default methods
Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
  Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
  assert(default_vtable_indices() == NULL, "only create once");
  set_default_vtable_indices(vtable_indices);
  return vtable_indices;
}
258

259 260 261 262 263 264 265 266 267
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

268 269
  int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
                                   access_flags.is_interface(), is_anonymous);
270

271 272 273 274 275 276 277 278 279 280 281 282
  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);
283 284
  set_default_methods(NULL);
  set_default_vtable_indices(NULL);
285 286 287 288 289 290
  set_local_interfaces(NULL);
  set_transitive_interfaces(NULL);
  init_implementor();
  set_fields(NULL, 0);
  set_constants(NULL);
  set_class_loader_data(NULL);
291
  set_source_file_name_index(0);
292 293 294 295 296 297
  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);
298
  set_has_unloaded_dependent(false);
299 300 301 302 303 304 305 306
  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();
307
  set_generic_signature_index(0);
308 309 310 311 312 313
  release_set_methods_jmethod_ids(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);
314
  set_cached_class_file(NULL);
315 316 317 318
  set_initial_method_idnum(0);
  set_minor_version(0);
  set_major_version(0);
  NOT_PRODUCT(_verify_count = 0;)
319 320 321

  // initialize the non-header words to zero
  intptr_t* p = (intptr_t*)this;
322
  for (int index = InstanceKlass::header_size(); index < iksize; index++) {
323 324 325 326 327
    p[index] = NULL_WORD;
  }

  // Set temporary value until parseClassFile updates it with the real instance
  // size.
328
  set_layout_helper(Klass::instance_layout_helper(0, true));
329 330 331
}


332 333
void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
                                       Array<Method*>* methods) {
334 335
  if (methods != NULL && methods != Universe::the_empty_method_array() &&
      !methods->is_shared()) {
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    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();
359
    if (ti != sti && ti != NULL && !ti->is_shared()) {
360 361 362 363 364
      MetadataFactory::free_array<Klass*>(loader_data, ti);
    }
  }

  // local interfaces can be empty
365 366
  if (local_interfaces != Universe::the_empty_klass_array() &&
      local_interfaces != NULL && !local_interfaces->is_shared()) {
367 368 369 370
    MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
  }
}

371 372 373 374 375
// 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.
376 377 378
  if (java_mirror() != NULL) {
    java_lang_Class::set_klass(java_mirror(), NULL);
  }
379 380 381 382 383 384 385 386 387 388 389 390 391 392

  // 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();

393
  deallocate_methods(loader_data, methods());
394 395
  set_methods(NULL);

396 397 398
  if (method_ordering() != NULL &&
      method_ordering() != Universe::the_empty_int_array() &&
      !method_ordering()->is_shared()) {
399 400 401 402
    MetadataFactory::free_array<int>(loader_data, method_ordering());
  }
  set_method_ordering(NULL);

403 404
  // default methods can be empty
  if (default_methods() != NULL &&
405 406
      default_methods() != Universe::the_empty_method_array() &&
      !default_methods()->is_shared()) {
407 408 409 410 411 412
    MetadataFactory::free_array<Method*>(loader_data, default_methods());
  }
  // Do NOT deallocate the default methods, they are owned by superinterfaces.
  set_default_methods(NULL);

  // default methods vtable indices can be empty
413 414
  if (default_vtable_indices() != NULL &&
      !default_vtable_indices()->is_shared()) {
415 416 417 418 419
    MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
  }
  set_default_vtable_indices(NULL);


420 421 422
  // 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.
423 424 425 426
  if (secondary_supers() != NULL &&
      secondary_supers() != Universe::the_empty_klass_array() &&
      secondary_supers() != transitive_interfaces() &&
      !secondary_supers()->is_shared()) {
427 428 429 430
    MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
  }
  set_secondary_supers(NULL);

431
  deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
432 433 434
  set_transitive_interfaces(NULL);
  set_local_interfaces(NULL);

435 436 437
  if (fields() != NULL && !fields()->is_shared()) {
    MetadataFactory::free_array<jushort>(loader_data, fields());
  }
438 439 440 441
  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.
442 443
  if (constants() != NULL) {
    assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
444 445 446
    if (!constants()->is_shared()) {
      MetadataFactory::free_metadata(loader_data, constants());
    }
447 448 449
    // Delete any cached resolution errors for the constant pool
    SystemDictionary::delete_resolution_error(constants());

450 451
    set_constants(NULL);
  }
452

453 454 455
  if (inner_classes() != NULL &&
      inner_classes() != Universe::the_empty_short_array() &&
      !inner_classes()->is_shared()) {
456 457 458 459
    MetadataFactory::free_array<jushort>(loader_data, inner_classes());
  }
  set_inner_classes(NULL);

460 461 462 463
  // We should deallocate the Annotations instance if it's not in shared spaces.
  if (annotations() != NULL && !annotations()->is_shared()) {
    MetadataFactory::free_metadata(loader_data, annotations());
  }
464 465 466 467
  set_annotations(NULL);
}

bool InstanceKlass::should_be_initialized() const {
D
duke 已提交
468 469 470
  return !is_initialized();
}

471 472
klassVtable* InstanceKlass::vtable() const {
  return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
D
duke 已提交
473 474
}

475 476
klassItable* InstanceKlass::itable() const {
  return new klassItable(instanceKlassHandle(this));
D
duke 已提交
477 478
}

479
void InstanceKlass::eager_initialize(Thread *thread) {
D
duke 已提交
480 481 482 483 484 485 486
  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)
487
    Klass* super = this->super();
D
duke 已提交
488 489 490
    if (super == NULL) return;

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

    // call body to expose the this pointer
494
    instanceKlassHandle this_oop(thread, this);
D
duke 已提交
495 496 497 498
    eager_initialize_impl(this_oop);
  }
}

499 500 501 502 503 504 505 506 507 508 509 510 511 512
// 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());
}

513
oop InstanceKlass::init_lock() const {
514
  // return the init lock from the mirror
515
  oop lock = java_lang_Class::init_lock(java_mirror());
516 517
  // Prevent reordering with any access of initialization state
  OrderAccess::loadload();
518 519 520 521 522 523 524 525 526 527 528 529 530 531
  assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
         "only fully initialized state can have a null lock");
  return lock;
}

// Set the initialization lock to null so the object can be GC'ed.  Any racing
// threads to get this lock will see a null lock and will not lock.
// That's okay because they all check for initialized state after getting
// the lock and return.
void InstanceKlass::fence_and_clear_init_lock() {
  // make sure previous stores are all done, notably the init_state.
  OrderAccess::storestore();
  java_lang_Class::set_init_lock(java_mirror(), NULL);
  assert(!is_not_initialized(), "class must be initialized now");
532
}
D
duke 已提交
533

534
void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
D
duke 已提交
535
  EXCEPTION_MARK;
536
  oop init_lock = this_oop->init_lock();
537
  ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
D
duke 已提交
538 539 540 541

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

542
  ClassState old_state = this_oop->init_state();
D
duke 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555
  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);
556
    this_oop->fence_and_clear_init_lock();
D
duke 已提交
557 558 559 560 561 562 563 564 565 566 567 568
    // 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.
569
void InstanceKlass::initialize(TRAPS) {
D
duke 已提交
570 571
  if (this->should_be_initialized()) {
    HandleMark hm(THREAD);
572
    instanceKlassHandle this_oop(THREAD, this);
D
duke 已提交
573 574 575 576 577 578 579 580 581 582
    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");
  }
}


583
bool InstanceKlass::verify_code(
D
duke 已提交
584 585 586 587
    instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
  // 1) Verify the bytecodes
  Verifier::Mode mode =
    throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
588
  return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), THREAD);
D
duke 已提交
589 590 591 592 593 594
}


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

595
void InstanceKlass::unlink_class() {
D
duke 已提交
596 597 598 599
  assert(is_linked(), "must be linked");
  _init_state = loaded;
}

600
void InstanceKlass::link_class(TRAPS) {
D
duke 已提交
601 602
  assert(is_loaded(), "must be loaded");
  if (!is_linked()) {
603 604
    HandleMark hm(THREAD);
    instanceKlassHandle this_oop(THREAD, this);
D
duke 已提交
605 606 607 608 609 610
    link_class_impl(this_oop, true, CHECK);
  }
}

// Called to verify that a class can link during initialization, without
// throwing a VerifyError.
611
bool InstanceKlass::link_class_or_fail(TRAPS) {
D
duke 已提交
612 613
  assert(is_loaded(), "must be loaded");
  if (!is_linked()) {
614 615
    HandleMark hm(THREAD);
    instanceKlassHandle this_oop(THREAD, this);
D
duke 已提交
616 617 618 619 620
    link_class_impl(this_oop, false, CHECK_false);
  }
  return is_linked();
}

621
bool InstanceKlass::link_class_impl(
D
duke 已提交
622
    instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
623 624 625 626 627
  // check for error state.
  // This is checking for the wrong state.  If the state is initialization_error,
  // then this class *was* linked.  The CDS code does a try_link_class and uses
  // initialization_error to mark classes to not include in the archive during
  // DumpSharedSpaces.  This should be removed when the CDS bug is fixed.
D
duke 已提交
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
  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,
650
        vmSymbols::java_lang_IncompatibleClassChangeError(),
D
duke 已提交
651 652 653 654 655 656 657 658 659 660 661
        "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
662
  Array<Klass*>* interfaces = this_oop->local_interfaces();
D
duke 已提交
663 664 665
  int num_interfaces = interfaces->length();
  for (int index = 0; index < num_interfaces; index++) {
    HandleMark hm(THREAD);
666
    instanceKlassHandle ih(THREAD, interfaces->at(index));
D
duke 已提交
667 668 669 670 671 672 673 674
    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;
  }

675 676 677 678 679 680 681 682 683
  // 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 已提交
684 685
  // verification & rewriting
  {
686
    oop init_lock = this_oop->init_lock();
687
    ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
D
duke 已提交
688 689 690
    // rewritten will have been set if loader constraint error found
    // on an earlier link attempt
    // don't verify or rewrite if already rewritten
691

D
duke 已提交
692 693 694 695 696
    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().
697 698 699 700 701 702
          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 已提交
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
          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);
I
iklam 已提交
718 719 720 721 722 723 724 725 726 727
      } else if (this_oop()->is_shared()) {
        ResourceMark rm(THREAD);
        char* message_buffer; // res-allocated by check_verification_dependencies
        Handle loader = this_oop()->class_loader();
        Handle pd     = this_oop()->protection_domain();
        bool verified = SystemDictionaryShared::check_verification_dependencies(this_oop(),
                        loader, pd, &message_buffer, THREAD);
        if (!verified) {
          THROW_MSG_(vmSymbols::java_lang_VerifyError(), message_buffer, false);
        }
D
duke 已提交
728 729
      }

730
      // relocate jsrs and link methods after they are all rewritten
731
      this_oop->link_methods(CHECK_false);
732

D
duke 已提交
733 734
      // Initialize the vtable and interface table after
      // methods have been rewritten since rewrite may
735
      // fabricate new Method*s.
D
duke 已提交
736
      // also does loader constraint checking
J
jiangli 已提交
737 738 739 740 741 742
      //
      // Initialize_vtable and initialize_itable need to be rerun for
      // a shared class if the class is not loaded by the NULL classloader.
      ClassLoaderData * loader_data = this_oop->class_loader_data();
      if (!(this_oop()->is_shared() &&
            loader_data->is_the_null_class_loader_data())) {
D
duke 已提交
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
        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.
770
void InstanceKlass::rewrite_class(TRAPS) {
D
duke 已提交
771
  assert(is_loaded(), "must be loaded");
772
  instanceKlassHandle this_oop(THREAD, this);
D
duke 已提交
773 774 775 776
  if (this_oop->is_rewritten()) {
    assert(this_oop()->is_shared(), "rewriting an unshared class?");
    return;
  }
777
  Rewriter::rewrite(this_oop, CHECK);
D
duke 已提交
778 779 780
  this_oop->set_rewritten();
}

781 782 783
// 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.
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
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
  }
809 810
}

811
// Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_k, TRAPS) {
  assert (this_k->has_default_methods(), "caller should have checked this");
  for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {
    Klass* iface = this_k->local_interfaces()->at(i);
    InstanceKlass* ik = InstanceKlass::cast(iface);

    // Initialization is depth first search ie. we start with top of the inheritance tree
    // has_default_methods drives searching superinterfaces since it
    // means has_default_methods in its superinterface hierarchy
    if (ik->has_default_methods()) {
      ik->initialize_super_interfaces(ik, CHECK);
    }

    // Only initialize() interfaces that "declare" concrete methods.
    if (ik->should_be_initialized() && ik->declares_default_methods()) {
      ik->initialize(CHECK);
828 829 830
    }
  }
}
D
duke 已提交
831

832
void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
D
duke 已提交
833 834 835 836
  // 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);

837
  DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
838 839 840

  bool wait = false;

D
duke 已提交
841 842
  // refer to the JVM book page 47 for description of steps
  // Step 1
843
  {
844
    oop init_lock = this_oop->init_lock();
845
    ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
D
duke 已提交
846 847 848 849 850 851 852 853

    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)) {
854
        wait = true;
D
duke 已提交
855 856 857 858
      ol.waitUninterruptibly(CHECK);
    }

    // Step 3
859
    if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
860
      DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
861
      return;
862
    }
D
duke 已提交
863 864

    // Step 4
865
    if (this_oop->is_initialized()) {
866
      DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
867
      return;
868
    }
D
duke 已提交
869 870 871

    // Step 5
    if (this_oop->is_in_error_state()) {
872
      DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
873 874 875 876
      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;
877
      char* message = NEW_RESOURCE_ARRAY(char, msglen);
D
duke 已提交
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
      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
893 894 895 896 897 898 899 900 901 902 903 904 905 906
  // Next, if C is a class rather than an interface, initialize its super class and super
  // interfaces.
  if (!this_oop->is_interface()) {
    Klass* super_klass = this_oop->super();
    if (super_klass != NULL && super_klass->should_be_initialized()) {
      super_klass->initialize(THREAD);
    }
    // If C implements any interfaces that declares a non-abstract, non-static method,
    // the initialization of C triggers initialization of its super interfaces.
    // Only need to recurse if has_default_methods which includes declaring and
    // inheriting default methods
    if (!HAS_PENDING_EXCEPTION && this_oop->has_default_methods()) {
      this_oop->initialize_super_interfaces(this_oop, THREAD);
    }
D
duke 已提交
907

908
    // If any exceptions, complete abruptly, throwing the same exception as above.
D
duke 已提交
909 910 911 912 913
    if (HAS_PENDING_EXCEPTION) {
      Handle e(THREAD, PENDING_EXCEPTION);
      CLEAR_PENDING_EXCEPTION;
      {
        EXCEPTION_MARK;
914 915 916
        // Locks object, set state, and notify all waiting threads
        this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
        CLEAR_PENDING_EXCEPTION;
D
duke 已提交
917
      }
918
      DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
919 920 921 922 923 924 925 926
      THROW_OOP(e());
    }
  }

  // Step 8
  {
    assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
    JavaThread* jt = (JavaThread*)THREAD;
927
    DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
928 929
    // Timer includes any side effects of class initialization (resolution,
    // etc), but not recursive entry into call_class_initializer().
930 931 932 933 934 935
    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 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948 949
    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;
950 951 952
    // JVMTI has already reported the pending exception
    // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
    JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
D
duke 已提交
953 954 955 956
    {
      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
957 958 959
      // JVMTI has already reported the pending exception
      // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
      JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
D
duke 已提交
960
    }
961
    DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
962
    if (e->is_a(SystemDictionary::Error_klass())) {
D
duke 已提交
963 964 965
      THROW_OOP(e());
    } else {
      JavaCallArguments args(e);
966 967
      THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
                vmSymbols::throwable_void_signature(),
D
duke 已提交
968 969 970
                &args);
    }
  }
971
  DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
D
duke 已提交
972 973 974 975
}


// Note: implementation moved to static method to expose the this pointer.
976 977
void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
  instanceKlassHandle kh(THREAD, this);
D
duke 已提交
978 979 980
  set_initialization_state_and_notify_impl(kh, state, CHECK);
}

981
void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
982
  oop init_lock = this_oop->init_lock();
983 984 985 986 987 988 989 990 991
  if (init_lock != NULL) {
    ObjectLocker ol(init_lock, THREAD);
    this_oop->set_init_state(state);
    this_oop->fence_and_clear_init_lock();
    ol.notify_all(CHECK);
  } else {
    assert(init_lock != NULL, "The initialization state should never be set twice");
    this_oop->set_init_state(state);
  }
D
duke 已提交
992 993
}

994 995
// The embedded _implementor field can only record one implementor.
// When there are more than one implementors, the _implementor field
996
// is set to the interface Klass* itself. Following are the possible
997 998
// values for the _implementor field:
//   NULL                  - no implementor
999
//   implementor Klass*    - one implementor
1000 1001 1002
//   self                  - more than one implementor
//
// The _implementor field only exists for interfaces.
1003
void InstanceKlass::add_implementor(Klass* k) {
D
duke 已提交
1004
  assert(Compile_lock->owned_by_self(), "");
1005
  assert(is_interface(), "not interface");
D
duke 已提交
1006 1007
  // Filter out my subinterfaces.
  // (Note: Interfaces are never on the subklass list.)
1008
  if (InstanceKlass::cast(k)->is_interface()) return;
D
duke 已提交
1009 1010 1011 1012

  // Filter out subclasses whose supers already implement me.
  // (Note: CHA must walk subclasses of direct implementors
  // in order to locate indirect implementors.)
1013 1014
  Klass* sk = InstanceKlass::cast(k)->super();
  if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
D
duke 已提交
1015 1016 1017 1018 1019
    // 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;

1020
  Klass* ik = implementor();
1021 1022
  if (ik == NULL) {
    set_implementor(k);
1023
  } else if (ik != this) {
1024 1025
    // There is already an implementor. Use itself as an indicator of
    // more than one implementors.
1026
    set_implementor(this);
D
duke 已提交
1027 1028 1029 1030
  }

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

1035
void InstanceKlass::init_implementor() {
1036 1037 1038
  if (is_interface()) {
    set_implementor(NULL);
  }
D
duke 已提交
1039 1040 1041
}


1042
void InstanceKlass::process_interfaces(Thread *thread) {
D
duke 已提交
1043
  // link this class into the implementors list of every interface it implements
1044
  Klass* this_as_klass_oop = this;
D
duke 已提交
1045
  for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
1046 1047
    assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
    InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
D
duke 已提交
1048
    assert(interf->is_interface(), "expected interface");
1049
    interf->add_implementor(this_as_klass_oop);
D
duke 已提交
1050 1051 1052
  }
}

1053
bool InstanceKlass::can_be_primary_super_slow() const {
D
duke 已提交
1054 1055 1056 1057 1058 1059
  if (is_interface())
    return false;
  else
    return Klass::can_be_primary_super_slow();
}

1060
GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
D
duke 已提交
1061
  // The secondaries are the implemented interfaces.
1062 1063
  InstanceKlass* ik = InstanceKlass::cast(this);
  Array<Klass*>* interfaces = ik->transitive_interfaces();
D
duke 已提交
1064 1065
  int num_secondaries = num_extra_slots + interfaces->length();
  if (num_secondaries == 0) {
1066 1067 1068
    // Must share this for correct bootstrapping!
    set_secondary_supers(Universe::the_empty_klass_array());
    return NULL;
D
duke 已提交
1069
  } else if (num_extra_slots == 0) {
1070 1071 1072 1073
    // 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 已提交
1074
  } else {
1075 1076 1077
    // 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 已提交
1078
    for (int i = 0; i < interfaces->length(); i++) {
1079
      secondaries->push(interfaces->at(i));
D
duke 已提交
1080 1081 1082 1083 1084
    }
    return secondaries;
  }
}

1085
bool InstanceKlass::compute_is_subtype_of(Klass* k) {
H
hseigel 已提交
1086
  if (k->is_interface()) {
D
duke 已提交
1087 1088 1089 1090 1091 1092
    return implements_interface(k);
  } else {
    return Klass::compute_is_subtype_of(k);
  }
}

1093 1094
bool InstanceKlass::implements_interface(Klass* k) const {
  if (this == k) return true;
H
hseigel 已提交
1095
  assert(k->is_interface(), "should be an interface class");
D
duke 已提交
1096
  for (int i = 0; i < transitive_interfaces()->length(); i++) {
1097
    if (transitive_interfaces()->at(i) == k) {
D
duke 已提交
1098 1099 1100 1101 1102 1103
      return true;
    }
  }
  return false;
}

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
  // Verify direct super interface
  if (this == k) return true;
  assert(k->is_interface(), "should be an interface class");
  for (int i = 0; i < local_interfaces()->length(); i++) {
    if (local_interfaces()->at(i) == k) {
      return true;
    }
  }
  return false;
}

1116
objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
D
duke 已提交
1117 1118
  if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
  if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
1119
    report_java_out_of_memory("Requested array size exceeds VM limit");
1120
    JvmtiExport::post_array_size_exhausted();
D
duke 已提交
1121 1122 1123
    THROW_OOP_0(Universe::out_of_memory_error_array_size());
  }
  int size = objArrayOopDesc::object_size(length);
1124
  Klass* ak = array_klass(n, CHECK_NULL);
D
duke 已提交
1125 1126 1127 1128 1129 1130
  KlassHandle h_ak (THREAD, ak);
  objArrayOop o =
    (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
  return o;
}

1131
instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
D
duke 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
  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();
}

1146
instanceOop InstanceKlass::allocate_instance(TRAPS) {
D
duke 已提交
1147 1148 1149
  bool has_finalizer_flag = has_finalizer(); // Query before possible GC
  int size = size_helper();  // Query before forming handle.

1150
  KlassHandle h_k(THREAD, this);
D
duke 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

  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;
}

1161
void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
D
duke 已提交
1162 1163 1164 1165 1166
  if (is_interface() || is_abstract()) {
    ResourceMark rm(THREAD);
    THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
              : vmSymbols::java_lang_InstantiationException(), external_name());
  }
1167
  if (this == SystemDictionary::Class_klass()) {
D
duke 已提交
1168 1169 1170 1171 1172 1173
    ResourceMark rm(THREAD);
    THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
              : vmSymbols::java_lang_IllegalAccessException(), external_name());
  }
}

1174 1175
Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
  instanceKlassHandle this_oop(THREAD, this);
D
duke 已提交
1176 1177 1178
  return array_klass_impl(this_oop, or_null, n, THREAD);
}

1179
Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
D
duke 已提交
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
  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) {
1192
        Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
D
duke 已提交
1193 1194 1195 1196 1197
        this_oop->set_array_klasses(k);
      }
    }
  }
  // _this will always be set at this point
1198
  ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
D
duke 已提交
1199 1200 1201
  if (or_null) {
    return oak->array_klass_or_null(n);
  }
1202
  return oak->array_klass(n, THREAD);
D
duke 已提交
1203 1204
}

1205
Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
D
duke 已提交
1206 1207 1208
  return array_klass_impl(or_null, 1, THREAD);
}

1209 1210
void InstanceKlass::call_class_initializer(TRAPS) {
  instanceKlassHandle ik (THREAD, this);
D
duke 已提交
1211 1212 1213 1214 1215
  call_class_initializer_impl(ik, THREAD);
}

static int call_class_initializer_impl_counter = 0;   // for debugging

1216 1217
Method* InstanceKlass::class_initializer() {
  Method* clinit = find_method(
1218 1219 1220 1221 1222
      vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
  if (clinit != NULL && clinit->has_valid_initializer_flags()) {
    return clinit;
  }
  return NULL;
D
duke 已提交
1223 1224
}

1225
void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
1226 1227 1228 1229 1230 1231 1232
  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 已提交
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
  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)
  }
}


1248
void InstanceKlass::mask_for(methodHandle method, int bci,
D
duke 已提交
1249 1250 1251 1252 1253 1254 1255
  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) {
1256 1257 1258 1259 1260
      // Release stores from OopMapCache constructor before assignment
      // to _oop_map_cache. C++ compilers on ppc do not emit the
      // required memory barrier only because of the volatile
      // qualifier of _oop_map_cache.
      OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());
D
duke 已提交
1261 1262 1263 1264 1265 1266 1267
    }
  }
  // _oop_map_cache is constant after init; lookup below does is own locking.
  _oop_map_cache->lookup(method, bci, entry_for);
}


1268 1269
bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1270 1271
    Symbol* f_name = fs.name();
    Symbol* f_sig  = fs.signature();
D
duke 已提交
1272
    if (f_name == name && f_sig == sig) {
1273
      fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
D
duke 已提交
1274 1275 1276 1277 1278 1279 1280
      return true;
    }
  }
  return false;
}


1281
Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
D
duke 已提交
1282 1283
  const int n = local_interfaces()->length();
  for (int i = 0; i < n; i++) {
1284
    Klass* intf1 = local_interfaces()->at(i);
H
hseigel 已提交
1285
    assert(intf1->is_interface(), "just checking type");
D
duke 已提交
1286
    // search for field in current interface
1287
    if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
D
duke 已提交
1288 1289 1290 1291
      assert(fd->is_static(), "interface field must be static");
      return intf1;
    }
    // search for field in direct superinterfaces
1292
    Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
D
duke 已提交
1293 1294 1295 1296 1297 1298 1299
    if (intf2 != NULL) return intf2;
  }
  // otherwise field lookup fails
  return NULL;
}


1300
Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
D
duke 已提交
1301 1302 1303
  // 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)) {
1304
    return const_cast<InstanceKlass*>(this);
D
duke 已提交
1305 1306
  }
  // 2) search for field recursively in direct superinterfaces
1307
  { Klass* intf = find_interface_field(name, sig, fd);
D
duke 已提交
1308 1309 1310
    if (intf != NULL) return intf;
  }
  // 3) apply field lookup recursively if superclass exists
1311 1312
  { Klass* supr = super();
    if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
D
duke 已提交
1313 1314 1315 1316 1317 1318
  }
  // 4) otherwise field lookup fails
  return NULL;
}


1319
Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
D
duke 已提交
1320 1321 1322
  // 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)) {
1323
    if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
D
duke 已提交
1324 1325 1326
  }
  // 2) search for field recursively in direct superinterfaces
  if (is_static) {
1327
    Klass* intf = find_interface_field(name, sig, fd);
D
duke 已提交
1328 1329 1330
    if (intf != NULL) return intf;
  }
  // 3) apply field lookup recursively if superclass exists
1331 1332
  { Klass* supr = super();
    if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
D
duke 已提交
1333 1334 1335 1336 1337 1338
  }
  // 4) otherwise field lookup fails
  return NULL;
}


1339 1340
bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1341
    if (fs.offset() == offset) {
1342
      fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
D
duke 已提交
1343 1344 1345 1346 1347 1348 1349
      if (fd->is_static() == is_static) return true;
    }
  }
  return false;
}


1350 1351
bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
  Klass* klass = const_cast<InstanceKlass*>(this);
D
duke 已提交
1352
  while (klass != NULL) {
1353
    if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
D
duke 已提交
1354 1355
      return true;
    }
H
hseigel 已提交
1356
    klass = klass->super();
D
duke 已提交
1357 1358 1359 1360 1361
  }
  return false;
}


1362
void InstanceKlass::methods_do(void f(Method* method)) {
D
duke 已提交
1363 1364
  int len = methods()->length();
  for (int index = 0; index < len; index++) {
1365
    Method* m = methods()->at(index);
D
duke 已提交
1366 1367 1368 1369 1370
    assert(m->is_method(), "must be method");
    f(m);
  }
}

1371

1372
void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1373 1374
  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
    if (fs.access_flags().is_static()) {
1375
      fieldDescriptor& fd = fs.field_descriptor();
1376 1377
      cl->do_field(&fd);
    }
D
duke 已提交
1378 1379 1380 1381
  }
}


1382
void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1383
  instanceKlassHandle h_this(THREAD, this);
1384
  do_local_static_fields_impl(h_this, f, mirror, CHECK);
D
duke 已提交
1385 1386 1387
}


1388 1389 1390
void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,
                             void f(fieldDescriptor* fd, Handle mirror, TRAPS), Handle mirror, TRAPS) {
  for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {
1391
    if (fs.access_flags().is_static()) {
1392
      fieldDescriptor& fd = fs.field_descriptor();
1393
      f(&fd, mirror, CHECK);
1394
    }
D
duke 已提交
1395 1396 1397 1398
  }
}


1399 1400 1401 1402
static int compare_fields_by_offset(int* a, int* b) {
  return a[0] - b[0];
}

1403 1404
void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
  InstanceKlass* super = superklass();
D
duke 已提交
1405 1406 1407
  if (super != NULL) {
    super->do_nonstatic_fields(cl);
  }
1408
  fieldDescriptor fd;
1409
  int length = java_fields_count();
1410
  // In DebugInfo nonstatic fields are sorted by offset.
Z
zgu 已提交
1411
  int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1412
  int j = 0;
1413
  for (int i = 0; i < length; i += 1) {
1414
    fd.reinitialize(this, i);
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
    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) {
1426
      fd.reinitialize(this, fields_sorted[i + 1]);
1427 1428 1429
      assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
      cl->do_field(&fd);
    }
D
duke 已提交
1430
  }
Z
zgu 已提交
1431
  FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
D
duke 已提交
1432 1433 1434
}


1435 1436
void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
  if (array_klasses() != NULL)
1437
    ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
1438 1439 1440
}

void InstanceKlass::array_klasses_do(void f(Klass* k)) {
D
duke 已提交
1441
  if (array_klasses() != NULL)
1442
    ArrayKlass::cast(array_klasses())->array_klasses_do(f);
D
duke 已提交
1443 1444 1445
}

#ifdef ASSERT
1446
static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
D
duke 已提交
1447 1448
  int len = methods->length();
  for (int index = 0; index < len; index++) {
1449
    Method* m = methods->at(index);
D
duke 已提交
1450 1451 1452 1453 1454 1455 1456 1457 1458
    assert(m->is_method(), "must be method");
    if (m->signature() == signature && m->name() == name) {
       return index;
    }
  }
  return -1;
}
#endif

1459
static int binary_search(Array<Method*>* methods, Symbol* name) {
D
duke 已提交
1460 1461 1462 1463 1464 1465
  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;
1466
    Method* m = methods->at(mid);
D
duke 已提交
1467 1468 1469
    assert(m->is_method(), "must be method");
    int res = m->name()->fast_compare(name);
    if (res == 0) {
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
      return mid;
    } else if (res < 0) {
      l = mid + 1;
    } else {
      h = mid - 1;
    }
  }
  return -1;
}

1480
// find_method looks up the name/signature in the local methods array
1481
Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
1482
  return find_method_impl(name, signature, find_overpass, find_static, find_private);
1483 1484
}

1485 1486 1487 1488 1489
Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature,
                                        OverpassLookupMode overpass_mode,
                                        StaticLookupMode static_mode,
                                        PrivateLookupMode private_mode) const {
  return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);
1490 1491
}

1492 1493 1494 1495
// find_instance_method looks up the name/signature in the local methods array
// and skips over static methods
Method* InstanceKlass::find_instance_method(
    Array<Method*>* methods, Symbol* name, Symbol* signature) {
1496 1497 1498
  Method* meth = InstanceKlass::find_method_impl(methods, name, signature,
                                                 find_overpass, skip_static, find_private);
  assert(((meth == NULL) || !meth->is_static()), "find_instance_method should have skipped statics");
1499 1500 1501
  return meth;
}

1502 1503 1504 1505 1506 1507
// find_instance_method looks up the name/signature in the local methods array
// and skips over static methods
Method* InstanceKlass::find_instance_method(Symbol* name, Symbol* signature) {
    return InstanceKlass::find_instance_method(methods(), name, signature);
}

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
// Find looks up the name/signature in the local methods array
// and filters on the overpass, static and private flags
// This returns the first one found
// note that the local methods array can have up to one overpass, one static
// and one instance (private or not) with the same name/signature
Method* InstanceKlass::find_local_method(Symbol* name, Symbol* signature,
                                        OverpassLookupMode overpass_mode,
                                        StaticLookupMode static_mode,
                                        PrivateLookupMode private_mode) const {
  return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);
}

// Find looks up the name/signature in the local methods array
// and filters on the overpass, static and private flags
// This returns the first one found
// note that the local methods array can have up to one overpass, one static
// and one instance (private or not) with the same name/signature
Method* InstanceKlass::find_local_method(Array<Method*>* methods,
                                        Symbol* name, Symbol* signature,
                                        OverpassLookupMode overpass_mode,
                                        StaticLookupMode static_mode,
                                        PrivateLookupMode private_mode) {
  return InstanceKlass::find_method_impl(methods, name, signature, overpass_mode, static_mode, private_mode);
}


1534
// find_method looks up the name/signature in the local methods array
1535 1536
Method* InstanceKlass::find_method(
    Array<Method*>* methods, Symbol* name, Symbol* signature) {
1537
  return InstanceKlass::find_method_impl(methods, name, signature, find_overpass, find_static, find_private);
1538 1539 1540
}

Method* InstanceKlass::find_method_impl(
1541 1542 1543 1544
    Array<Method*>* methods, Symbol* name, Symbol* signature,
    OverpassLookupMode overpass_mode, StaticLookupMode static_mode,
    PrivateLookupMode private_mode) {
  int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
1545 1546 1547
  return hit >= 0 ? methods->at(hit): NULL;
}

1548 1549
bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static, bool skipping_private) {
    return  ((m->signature() == signature) &&
1550
            (!skipping_overpass || !m->is_overpass()) &&
1551 1552
            (!skipping_static || !m->is_static()) &&
            (!skipping_private || !m->is_private()));
1553 1554
}

1555 1556 1557
// Used directly for default_methods to find the index into the
// default_vtable_indices, and indirectly by find_method
// find_method_index looks in the local methods array to return the index
1558 1559 1560 1561
// of the matching name/signature. If, overpass methods are being ignored,
// the search continues to find a potential non-overpass match.  This capability
// is important during method resolution to prefer a static method, for example,
// over an overpass method.
1562 1563 1564 1565 1566
// There is the possibility in any _method's array to have the same name/signature
// for a static method, an overpass method and a local instance method
// To correctly catch a given method, the search criteria may need
// to explicitly skip the other two. For local instance methods, it
// is often necessary to skip private methods
1567
int InstanceKlass::find_method_index(
1568 1569 1570 1571 1572 1573
    Array<Method*>* methods, Symbol* name, Symbol* signature,
    OverpassLookupMode overpass_mode, StaticLookupMode static_mode,
    PrivateLookupMode private_mode) {
  bool skipping_overpass = (overpass_mode == skip_overpass);
  bool skipping_static = (static_mode == skip_static);
  bool skipping_private = (private_mode == skip_private);
1574 1575 1576
  int hit = binary_search(methods, name);
  if (hit != -1) {
    Method* m = methods->at(hit);
1577

1578
    // Do linear search to find matching signature.  First, quick check
1579
    // for common case, ignoring overpasses if requested.
1580
    if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return hit;
1581

1582 1583 1584
    // search downwards through overloaded methods
    int i;
    for (i = hit - 1; i >= 0; --i) {
1585
        Method* m = methods->at(i);
D
duke 已提交
1586 1587
        assert(m->is_method(), "must be method");
        if (m->name() != name) break;
1588
        if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;
1589 1590 1591
    }
    // search upwards
    for (i = hit + 1; i < methods->length(); ++i) {
1592
        Method* m = methods->at(i);
D
duke 已提交
1593 1594
        assert(m->is_method(), "must be method");
        if (m->name() != name) break;
1595
        if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;
D
duke 已提交
1596
    }
1597
    // not found
D
duke 已提交
1598
#ifdef ASSERT
1599
    int index = (skipping_overpass || skipping_static || skipping_private) ? -1 : linear_search(methods, name, signature);
1600
    assert(index == -1, err_msg("binary search should have found entry %d", index));
D
duke 已提交
1601
#endif
1602
  }
1603
  return -1;
D
duke 已提交
1604
}
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
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;
}

1623 1624
// uncached_lookup_method searches both the local class methods array and all
// superclasses methods arrays, skipping any overpass methods in superclasses.
1625 1626
Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const {
  OverpassLookupMode overpass_local_mode = overpass_mode;
1627
  Klass* klass = const_cast<InstanceKlass*>(this);
D
duke 已提交
1628
  while (klass != NULL) {
1629
    Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, overpass_local_mode, find_static, find_private);
1630
    if (method != NULL) {
1631 1632
      return method;
    }
1633
    klass = InstanceKlass::cast(klass)->super();
1634
    overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
D
duke 已提交
1635 1636 1637 1638
  }
  return NULL;
}

1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
#ifdef ASSERT
// search through class hierarchy and return true if this class or
// one of the superclasses was redefined
bool InstanceKlass::has_redefined_this_or_super() const {
  const InstanceKlass* klass = this;
  while (klass != NULL) {
    if (klass->has_been_redefined()) {
      return true;
    }
    klass = InstanceKlass::cast(klass->super());
  }
  return false;
}
#endif

1654 1655 1656 1657
// lookup a method in the default methods list then in all transitive interfaces
// Do NOT return private or static methods
Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
                                                         Symbol* signature) const {
1658
  Method* m = NULL;
1659 1660 1661 1662 1663
  if (default_methods() != NULL) {
    m = find_method(default_methods(), name, signature);
  }
  // Look up interfaces
  if (m == NULL) {
1664
    m = lookup_method_in_all_interfaces(name, signature, find_defaults);
1665 1666 1667 1668
  }
  return m;
}

D
duke 已提交
1669
// lookup a method in all the interfaces that this class implements
1670 1671
// Do NOT return private or static methods, new in JDK8 which are not externally visible
// They should only be found in the initial InterfaceMethodRef
1672
Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1673
                                                       Symbol* signature,
1674
                                                       DefaultsLookupMode defaults_mode) const {
1675
  Array<Klass*>* all_ifs = transitive_interfaces();
D
duke 已提交
1676
  int num_ifs = all_ifs->length();
1677
  InstanceKlass *ik = NULL;
D
duke 已提交
1678
  for (int i = 0; i < num_ifs; i++) {
1679 1680
    ik = InstanceKlass::cast(all_ifs->at(i));
    Method* m = ik->lookup_method(name, signature);
1681
    if (m != NULL && m->is_public() && !m->is_static() &&
1682
        ((defaults_mode != skip_defaults) || !m->is_default_method())) {
D
duke 已提交
1683 1684 1685 1686 1687 1688 1689
      return m;
    }
  }
  return NULL;
}

/* jni_id_for_impl for jfieldIds only */
1690
JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
D
duke 已提交
1691 1692 1693 1694 1695
  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
1696
    probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
D
duke 已提交
1697 1698 1699 1700 1701 1702 1703
    this_oop->set_jni_ids(probe);
  }
  return probe;
}


/* jni_id_for for jfieldIds only */
1704
JNIid* InstanceKlass::jni_id_for(int offset) {
D
duke 已提交
1705 1706
  JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
  if (probe == NULL) {
1707
    probe = jni_id_for_impl(this, offset);
D
duke 已提交
1708 1709 1710 1711
  }
  return probe;
}

1712 1713
u2 InstanceKlass::enclosing_method_data(int offset) {
  Array<jushort>* inner_class_list = inner_classes();
1714 1715 1716 1717 1718 1719 1720 1721 1722
  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");
1723
    return inner_class_list->at(index + offset);
1724 1725 1726
  }
}

1727
void InstanceKlass::set_enclosing_method_indices(u2 class_index,
1728
                                                 u2 method_index) {
1729
  Array<jushort>* inner_class_list = inner_classes();
1730 1731 1732 1733
  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;
1734
    inner_class_list->at_put(
1735
      index + enclosing_method_class_index_offset, class_index);
1736
    inner_class_list->at_put(
1737 1738 1739
      index + enclosing_method_method_index_offset, method_index);
  }
}
D
duke 已提交
1740 1741

// Lookup or create a jmethodID.
1742 1743 1744 1745
// 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.
//
1746
jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
D
duke 已提交
1747 1748 1749 1750 1751
  size_t idnum = (size_t)method_h->method_idnum();
  jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
  size_t length = 0;
  jmethodID id = NULL;

1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
  // 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 已提交
1793

1794 1795 1796 1797 1798 1799 1800 1801 1802
    // 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 已提交
1803 1804
    jmethodID* new_jmeths = NULL;
    if (length <= idnum) {
1805
      // allocate a new cache that might be used
D
duke 已提交
1806
      size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
Z
zgu 已提交
1807
      new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
D
duke 已提交
1808
      memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1809 1810
      // cache size is stored in element[0], other elements offset by one
      new_jmeths[0] = (jmethodID)size;
D
duke 已提交
1811 1812
    }

1813
    // allocate a new jmethodID that might be used
D
duke 已提交
1814 1815 1816
    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
1817
      Method* current_method = ik_h->method_with_idnum((int)idnum);
D
duke 已提交
1818
      assert(current_method != NULL, "old and but not obsolete, so should exist");
1819
      new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
D
duke 已提交
1820 1821 1822
    } else {
      // It is the current version of the method or an obsolete method,
      // use the version passed in
1823
      new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
D
duke 已提交
1824 1825
    }

1826 1827 1828 1829 1830
    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);
1831
    } else {
D
duke 已提交
1832
      MutexLocker ml(JmethodIdCreation_lock);
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
      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) {
1844
      Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
1845 1846 1847 1848
    }
  }
  return id;
}
D
duke 已提交
1849 1850


1851 1852 1853 1854 1855
// 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.
//
1856
jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
            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
1868
  jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1869 1870
  jmethodID  id     = NULL;
  size_t     length = 0;
1871

1872 1873
  if (jmeths == NULL ||                         // no cache yet
      (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
1874
    if (jmeths != NULL) {
1875
      // copy any existing entries from the old cache
1876 1877
      for (size_t index = 0; index < length; index++) {
        new_jmeths[index+1] = jmeths[index+1];
D
duke 已提交
1878
      }
1879
      *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
D
duke 已提交
1880
    }
1881 1882
    ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
  } else {
1883
    // fetch jmethodID (if any) from the existing cache
1884
    id = jmeths[idnum+1];
1885
    *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
1886 1887
  }
  if (id == NULL) {
1888 1889 1890 1891
    // 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.
1892
    id = new_id;
1893 1894 1895 1896 1897

    // 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);
1898
  } else {
1899
    *to_dealloc_id_p = new_id; // save new id for later delete
1900
  }
1901 1902
  return id;
}
D
duke 已提交
1903

1904 1905 1906 1907

// Common code to get the jmethodID cache length and the jmethodID
// value at index idnum if there is one.
//
1908
void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
       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 已提交
1920 1921 1922 1923 1924
  }
}


// Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
1925
jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
D
duke 已提交
1926 1927 1928 1929
  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;
1930
  if (jmeths != NULL &&                         // If there is a cache
D
duke 已提交
1931 1932 1933 1934 1935 1936
      (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;
}

1937 1938 1939
int nmethodBucket::decrement() {
  return Atomic::add(-1, (volatile int *)&_count);
}
D
duke 已提交
1940 1941 1942

//
// Walk the list of dependent nmethods searching for nmethods which
1943
// are dependent on the changes that were passed in and mark them for
D
duke 已提交
1944 1945
// deoptimization.  Returns the number of nmethods found.
//
1946
int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
D
duke 已提交
1947 1948 1949 1950 1951 1952 1953
  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.
1954
    if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
D
duke 已提交
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
      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;
}

1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
void InstanceKlass::clean_dependent_nmethods() {
  assert_locked_or_safepoint(CodeCache_lock);

  if (has_unloaded_dependent()) {
    nmethodBucket* b = _dependencies;
    nmethodBucket* last = NULL;
    while (b != NULL) {
      assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));

      nmethodBucket* next = b->next();

      if (b->count() == 0) {
        if (last == NULL) {
          _dependencies = next;
        } else {
          last->set_next(next);
        }
        delete b;
        // last stays the same.
      } else {
        last = b;
      }

      b = next;
    }
    set_has_unloaded_dependent(false);
  }
#ifdef ASSERT
  else {
    // Verification
    for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {
      assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
      assert(b->count() != 0, "empty buckets need to be cleaned");
    }
  }
#endif
}
D
duke 已提交
2008 2009 2010 2011 2012 2013 2014

//
// 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.
//
2015
void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
D
duke 已提交
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
  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.
//
2036
void InstanceKlass::remove_dependent_nmethod(nmethod* nm, bool delete_immediately) {
D
duke 已提交
2037 2038 2039 2040 2041
  assert_locked_or_safepoint(CodeCache_lock);
  nmethodBucket* b = _dependencies;
  nmethodBucket* last = NULL;
  while (b != NULL) {
    if (nm == b->get_nmethod()) {
2042 2043 2044
      int val = b->decrement();
      guarantee(val >= 0, err_msg("Underflow: %d", val));
      if (val == 0) {
2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
        if (delete_immediately) {
          if (last == NULL) {
            _dependencies = b->next();
          } else {
            last->set_next(b->next());
          }
          delete b;
        } else {
          // The deletion of this entry is deferred until a later, potentially parallel GC phase.
          set_has_unloaded_dependent(true);
        }
D
duke 已提交
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
      }
      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
2071
void InstanceKlass::print_dependent_nmethods(bool verbose) {
D
duke 已提交
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
  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();
  }
}


2090
bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
D
duke 已提交
2091 2092 2093
  nmethodBucket* b = _dependencies;
  while (b != NULL) {
    if (nm == b->get_nmethod()) {
2094 2095
#ifdef ASSERT
      int count = b->count();
2096
      assert(count >= 0, err_msg("count shouldn't be negative: %d", count));
2097
#endif
D
duke 已提交
2098 2099 2100 2101 2102 2103 2104 2105 2106
      return true;
    }
    b = b->next();
  }
  return false;
}
#endif //PRODUCT


2107 2108
// Garbage collection

2109 2110 2111 2112 2113 2114
#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 已提交
2115 2116
  }
}
2117 2118 2119 2120
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);
2121 2122
    assert(Universe::heap()->is_in_closed_subset(o),
           err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
  }
}
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();            \
2209
  OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
2210 2211 2212
  if (UseCompressedOops) {                                               \
    while (map < end_map) {                                              \
      InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
2213
        obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2214 2215 2216 2217 2218 2219
        do_oop, assert_fn)                                               \
      ++map;                                                             \
    }                                                                    \
  } else {                                                               \
    while (map < end_map) {                                              \
      InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
2220
        obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2221 2222 2223 2224 2225 2226 2227 2228 2229
        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();          \
2230
  OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
2231 2232 2233 2234
  if (UseCompressedOops) {                                               \
    while (start_map < map) {                                            \
      --map;                                                             \
      InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
2235
        obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2236 2237 2238 2239 2240 2241
        do_oop, assert_fn)                                               \
    }                                                                    \
  } else {                                                               \
    while (start_map < map) {                                            \
      --map;                                                             \
      InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
2242
        obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
        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();            \
2256
  OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
2257 2258 2259
  if (UseCompressedOops) {                                               \
    while (map < end_map) {                                              \
      InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
2260
        obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2261 2262 2263 2264 2265 2266 2267
        low, high,                                                       \
        do_oop, assert_fn)                                               \
      ++map;                                                             \
    }                                                                    \
  } else {                                                               \
    while (map < end_map) {                                              \
      InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
2268
        obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2269 2270 2271 2272 2273 2274 2275
        low, high,                                                       \
        do_oop, assert_fn)                                               \
      ++map;                                                             \
    }                                                                    \
  }                                                                      \
}

2276
void InstanceKlass::oop_follow_contents(oop obj) {
2277
  assert(obj != NULL, "can't follow the content of NULL object");
2278
  MarkSweep::follow_klass(obj->klass());
2279 2280 2281 2282
  InstanceKlass_OOP_MAP_ITERATE( \
    obj, \
    MarkSweep::mark_and_push(p), \
    assert_is_in_closed_subset)
D
duke 已提交
2283 2284
}

2285
#if INCLUDE_ALL_GCS
2286
void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
D
duke 已提交
2287
                                        oop obj) {
2288
  assert(obj != NULL, "can't follow the content of NULL object");
2289 2290 2291
  PSParallelCompact::follow_klass(cm, obj->klass());
  // Only mark the header and let the scan of the meta-data mark
  // everything else.
2292 2293 2294 2295
  InstanceKlass_OOP_MAP_ITERATE( \
    obj, \
    PSParallelCompact::mark_and_push(cm, p), \
    assert_is_in)
D
duke 已提交
2296
}
2297
#endif // INCLUDE_ALL_GCS
D
duke 已提交
2298

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

2302 2303
#define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
                                                                             \
2304
int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
2305 2306
  SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
  /* header */                                                          \
2307 2308
  if_do_metadata_checked(closure, nv_suffix) {                          \
    closure->do_klass##nv_suffix(obj->klass());                         \
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
  }                                                                     \
  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();                                                 \
}

2319
#if INCLUDE_ALL_GCS
2320 2321
#define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
                                                                                \
2322
int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
2323 2324
                                              OopClosureType* closure) {        \
  SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
2325 2326 2327
                                                                                \
  assert_should_ignore_metadata(closure, nv_suffix);                            \
                                                                                \
2328 2329 2330 2331 2332 2333 2334 2335
  /* 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();                                                        \
}
2336
#endif // INCLUDE_ALL_GCS
2337

2338 2339
#define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
                                                                        \
2340
int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
2341 2342 2343
                                                  OopClosureType* closure, \
                                                  MemRegion mr) {          \
  SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2344 2345 2346 2347
  if_do_metadata_checked(closure, nv_suffix) {                           \
    if (mr.contains(obj)) {                                              \
      closure->do_klass##nv_suffix(obj->klass());                        \
    }                                                                    \
2348 2349 2350 2351 2352 2353
  }                                                                      \
  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 已提交
2354 2355 2356
}

ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2357
ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
D
duke 已提交
2358
ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2359
ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2360
#if INCLUDE_ALL_GCS
2361 2362
ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2363
#endif // INCLUDE_ALL_GCS
D
duke 已提交
2364

2365
int InstanceKlass::oop_adjust_pointers(oop obj) {
D
duke 已提交
2366
  int size = size_helper();
2367 2368 2369 2370
  InstanceKlass_OOP_MAP_ITERATE( \
    obj, \
    MarkSweep::adjust_pointer(p), \
    assert_is_in)
D
duke 已提交
2371 2372 2373
  return size;
}

2374
#if INCLUDE_ALL_GCS
2375
void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
2376 2377 2378 2379 2380 2381
  InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
    obj, \
    if (PSScavenge::should_scavenge(p)) { \
      pm->claim_or_forward_depth(p); \
    }, \
    assert_nothing )
D
duke 已提交
2382 2383
}

2384 2385
int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
  int size = size_helper();
2386 2387 2388
  InstanceKlass_OOP_MAP_ITERATE( \
    obj, \
    PSParallelCompact::adjust_pointer(p), \
2389 2390
    assert_is_in)
  return size;
D
duke 已提交
2391 2392
}

2393
#endif // INCLUDE_ALL_GCS
D
duke 已提交
2394

2395 2396 2397 2398 2399 2400 2401
void InstanceKlass::clean_weak_instanceklass_links(BoolObjectClosure* is_alive) {
  clean_implementors_list(is_alive);
  clean_method_data(is_alive);

  clean_dependent_nmethods();
}

2402
void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
2403
  assert(class_loader_data()->is_alive(is_alive), "this klass should be live");
2404 2405
  if (is_interface()) {
    if (ClassUnloading) {
2406
      Klass* impl = implementor();
2407
      if (impl != NULL) {
2408
        if (!impl->is_loader_alive(is_alive)) {
2409
          // remove this guy
2410 2411 2412 2413 2414
          Klass** klass = adr_implementor();
          assert(klass != NULL, "null klass");
          if (klass != NULL) {
            *klass = NULL;
          }
2415
        }
D
duke 已提交
2416 2417 2418
      }
    }
  }
2419
}
2420

2421 2422 2423 2424
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) {
2425
      mdo->clean_method_data(is_alive);
2426 2427
    }
  }
D
duke 已提交
2428 2429
}

2430 2431 2432 2433 2434 2435 2436

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

void InstanceKlass::remove_unshareable_info() {
D
duke 已提交
2437
  Klass::remove_unshareable_info();
2438 2439 2440 2441
  // Unlink the class
  if (is_linked()) {
    unlink_class();
  }
D
duke 已提交
2442
  init_implementor();
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454

  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);
}

2455 2456 2457 2458
static void restore_unshareable_in_class(Klass* k, TRAPS) {
  // Array classes have null protection domain.
  // --> see ArrayKlass::complete_create_array_klass()
  k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2459 2460
}

2461 2462
void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
  Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2463 2464 2465 2466 2467 2468
  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));
2469
    m->restore_unshareable_info(CHECK);
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
  }
  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 已提交
2486 2487
}

2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519
// returns true IFF is_in_error_state() has been changed as a result of this call.
bool InstanceKlass::check_sharing_error_state() {
  assert(DumpSharedSpaces, "should only be called during dumping");
  bool old_state = is_in_error_state();

  if (!is_in_error_state()) {
    bool bad = false;
    for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
      if (sup->is_in_error_state()) {
        bad = true;
        break;
      }
    }
    if (!bad) {
      Array<Klass*>* interfaces = transitive_interfaces();
      for (int i = 0; i < interfaces->length(); i++) {
        Klass* iface = interfaces->at(i);
        if (InstanceKlass::cast(iface)->is_in_error_state()) {
          bad = true;
          break;
        }
      }
    }

    if (bad) {
      set_in_error_state();
    }
  }

  return (old_state != is_in_error_state());
}

2520
static void clear_all_breakpoints(Method* m) {
D
duke 已提交
2521 2522 2523
  m->clear_all_breakpoints();
}

2524 2525 2526 2527 2528 2529 2530 2531 2532

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);
2533 2534 2535 2536 2537 2538 2539 2540

#if INCLUDE_JFR
  assert(ik != NULL, "invariant");
  EventClassUnload event;
  event.set_unloadedClass(ik);
  event.set_definingClassLoader(ik->class_loader_data());
  event.commit();
#endif
2541 2542 2543 2544 2545 2546 2547 2548
}

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

2549
void InstanceKlass::release_C_heap_structures() {
2550 2551 2552 2553 2554

  // 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 已提交
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
  // 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);
  }

2571 2572 2573 2574 2575 2576 2577 2578 2579
  // 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);
    }
2580 2581
  }

D
duke 已提交
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
  // 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 the cached class file
2598 2599 2600
  if (_cached_class_file != NULL) {
    os::free(_cached_class_file, mtClass);
    _cached_class_file = NULL;
D
duke 已提交
2601
  }
2602 2603 2604 2605 2606 2607

  // 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();
2608
  if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
2609 2610 2611

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

2614
void InstanceKlass::set_source_debug_extension(char* array, int length) {
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629
  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 已提交
2630 2631
}

2632
address InstanceKlass::static_field_addr(int offset) {
2633
  return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
2634 2635 2636
}


2637
const char* InstanceKlass::signature_name() const {
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
  int hash_len = 0;
  char hash_buf[40];

  // If this is an anonymous class, append a hash to make the name unique
  if (is_anonymous()) {
    assert(EnableInvokeDynamic, "EnableInvokeDynamic was not set.");
    intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
    sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
    hash_len = (int)strlen(hash_buf);
  }

  // Get the internal name as a c string
D
duke 已提交
2650 2651
  const char* src = (const char*) (name()->as_C_string());
  const int src_length = (int)strlen(src);
2652 2653 2654 2655

  char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);

  // Add L as type indicator
D
duke 已提交
2656 2657
  int dest_index = 0;
  dest[dest_index++] = 'L';
2658 2659 2660

  // Add the actual class name
  for (int src_index = 0; src_index < src_length; ) {
D
duke 已提交
2661 2662
    dest[dest_index++] = src[src_index++];
  }
2663 2664 2665 2666 2667 2668 2669

  // If we have a hash, append it
  for (int hash_index = 0; hash_index < hash_len; ) {
    dest[dest_index++] = hash_buf[hash_index++];
  }

  // Add the semicolon and the NULL
D
duke 已提交
2670 2671 2672 2673 2674 2675
  dest[dest_index++] = ';';
  dest[dest_index] = '\0';
  return dest;
}

// different verisons of is_same_class_package
2676 2677 2678
bool InstanceKlass::is_same_class_package(Klass* class2) {
  Klass* class1 = this;
  oop classloader1 = InstanceKlass::cast(class1)->class_loader();
H
hseigel 已提交
2679
  Symbol* classname1 = class1->name();
D
duke 已提交
2680

H
hseigel 已提交
2681
  if (class2->oop_is_objArray()) {
2682
    class2 = ObjArrayKlass::cast(class2)->bottom_klass();
D
duke 已提交
2683 2684
  }
  oop classloader2;
H
hseigel 已提交
2685
  if (class2->oop_is_instance()) {
2686
    classloader2 = InstanceKlass::cast(class2)->class_loader();
D
duke 已提交
2687
  } else {
H
hseigel 已提交
2688
    assert(class2->oop_is_typeArray(), "should be type array");
D
duke 已提交
2689 2690
    classloader2 = NULL;
  }
H
hseigel 已提交
2691
  Symbol* classname2 = class2->name();
D
duke 已提交
2692

2693
  return InstanceKlass::is_same_class_package(classloader1, classname1,
D
duke 已提交
2694 2695 2696
                                              classloader2, classname2);
}

2697 2698 2699
bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
  Klass* class1 = this;
  oop classloader1 = InstanceKlass::cast(class1)->class_loader();
H
hseigel 已提交
2700
  Symbol* classname1 = class1->name();
D
duke 已提交
2701

2702
  return InstanceKlass::is_same_class_package(classloader1, classname1,
D
duke 已提交
2703 2704 2705 2706 2707
                                              classloader2, classname2);
}

// return true if two classes are in the same package, classloader
// and classname information is enough to determine a class's package
2708
bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
2709
                                          oop class_loader2, Symbol* class_name2) {
D
duke 已提交
2710 2711
  if (class_loader1 != class_loader2) {
    return false;
2712 2713
  } else if (class_name1 == class_name2) {
    return true;                // skip painful bytewise comparison
D
duke 已提交
2714 2715 2716
  } else {
    ResourceMark rm;

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

2723 2724
    const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
    const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
D
duke 已提交
2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759

    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);
    }
  }
}

2760 2761 2762
// 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
2763 2764 2765
// "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) {
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776
   // 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");
2777
   return(is_same_class_package(targetclassloader(), targetclassname));
2778
}
D
duke 已提交
2779

2780
/* defined for now in jvm.cpp, for historical reasons *--
2781
Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
2782
                                                     Symbol*& simple_name_result, TRAPS) {
2783 2784 2785 2786 2787
  ...
}
*/

// tell if two classes have the same enclosing class (at package level)
2788 2789 2790
bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
                                                Klass* class2_oop, TRAPS) {
  if (class2_oop == class1())                       return true;
H
hseigel 已提交
2791
  if (!class2_oop->oop_is_instance())  return false;
2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804
  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.
2805
    bool ignore_inner_is_member;
2806
    Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
2807
                                                    CHECK_false);
2808 2809 2810 2811 2812 2813 2814 2815
    if (next == NULL)  break;
    if (next == class2())  return true;
    outer1 = instanceKlassHandle(THREAD, next);
  }

  // Now do the same for class2.
  instanceKlassHandle outer2 = class2;
  for (;;) {
2816
    bool ignore_inner_is_member;
2817
    Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2818
                                                    CHECK_false);
2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830
    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 已提交
2831

2832
jint InstanceKlass::compute_modifier_flags(TRAPS) const {
D
duke 已提交
2833 2834 2835
  jint access = access_flags().as_int();

  // But check if it happens to be member class.
2836
  instanceKlassHandle ik(THREAD, this);
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
  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 已提交
2851 2852 2853 2854 2855 2856
    }
  }
  // Remember to strip ACC_SUPER bit
  return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
}

2857
jint InstanceKlass::jvmti_class_status() const {
D
duke 已提交
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
  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;
}

2874
Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
D
duke 已提交
2875 2876 2877 2878 2879 2880
  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 已提交
2881
    // If the interface isn't implemented by the receiver class,
D
duke 已提交
2882 2883
    // the VM should throw IncompatibleClassChangeError.
    if (cnt >= nof_interfaces) {
2884
      THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
D
duke 已提交
2885 2886
    }

2887
    Klass* ik = ioe->interface_klass();
D
duke 已提交
2888 2889 2890
    if (ik == holder) break;
  }

2891 2892
  itableMethodEntry* ime = ioe->first_method_entry(this);
  Method* m = ime[index].method();
D
duke 已提交
2893
  if (m == NULL) {
2894
    THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
D
duke 已提交
2895 2896 2897 2898
  }
  return m;
}

2899 2900 2901 2902 2903 2904

#if INCLUDE_JVMTI
// update default_methods for redefineclasses for methods that are
// not yet in the vtable due to concurrent subclass define and superinterface
// redefinition
// Note: those in the vtable, should have been updated via adjust_method_entries
2905
void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) {
2906 2907
  // search the default_methods for uses of either obsolete or EMCP methods
  if (default_methods() != NULL) {
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
    for (int index = 0; index < default_methods()->length(); index ++) {
      Method* old_method = default_methods()->at(index);
      if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
        continue; // skip uninteresting entries
      }
      assert(!old_method->is_deleted(), "default methods may not be deleted");

      Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());

      assert(new_method != NULL, "method_with_idnum() should not be NULL");
      assert(old_method != new_method, "sanity check");

      default_methods()->at_put(index, new_method);
      if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
        if (!(*trace_name_printed)) {
          // RC_TRACE_MESG macro has an embedded ResourceMark
          RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
                         external_name(),
                         old_method->method_holder()->external_name()));
          *trace_name_printed = true;
2928
        }
2929 2930 2931
        RC_TRACE(0x00100000, ("default method update: %s(%s) ",
                              new_method->name()->as_C_string(),
                              new_method->signature()->as_C_string()));
2932 2933 2934 2935 2936 2937
      }
    }
  }
}
#endif // INCLUDE_JVMTI

D
duke 已提交
2938
// On-stack replacement stuff
2939
void InstanceKlass::add_osr_nmethod(nmethod* n) {
2940 2941 2942 2943 2944 2945 2946
#ifndef PRODUCT
  if (TieredCompilation) {
      nmethod * prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);
      assert(prev == NULL || !prev->is_in_use(),
      "redundunt OSR recompilation detected. memory leak in CodeCache!");
  }
#endif
D
duke 已提交
2947 2948 2949 2950 2951
  // 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");
2952
  n->set_osr_link(osr_nmethods_head());
D
duke 已提交
2953
  set_osr_nmethods_head(n);
I
iveresov 已提交
2954 2955
  // Raise the highest osr level if necessary
  if (TieredCompilation) {
2956
    Method* m = n->method();
I
iveresov 已提交
2957 2958
    m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
  }
D
duke 已提交
2959 2960
  // Remember to unlock again
  OsrList_lock->unlock();
I
iveresov 已提交
2961 2962 2963 2964 2965 2966 2967 2968 2969 2970

  // 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 已提交
2971 2972 2973
}


2974
void InstanceKlass::remove_osr_nmethod(nmethod* n) {
D
duke 已提交
2975 2976 2977 2978 2979
  // 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 已提交
2980
  int max_level = CompLevel_none;  // Find the max comp level excluding n
2981
  Method* m = n->method();
D
duke 已提交
2982 2983
  // Search for match
  while(cur != NULL && cur != n) {
2984
    if (TieredCompilation && m == cur->method()) {
I
iveresov 已提交
2985 2986 2987
      // Find max level before n
      max_level = MAX2(max_level, cur->comp_level());
    }
D
duke 已提交
2988
    last = cur;
2989
    cur = cur->osr_link();
D
duke 已提交
2990
  }
I
iveresov 已提交
2991
  nmethod* next = NULL;
D
duke 已提交
2992
  if (cur == n) {
I
iveresov 已提交
2993
    next = cur->osr_link();
D
duke 已提交
2994 2995
    if (last == NULL) {
      // Remove first element
I
iveresov 已提交
2996
      set_osr_nmethods_head(next);
D
duke 已提交
2997
    } else {
I
iveresov 已提交
2998
      last->set_osr_link(next);
D
duke 已提交
2999 3000
    }
  }
3001
  n->set_osr_link(NULL);
I
iveresov 已提交
3002 3003 3004 3005
  if (TieredCompilation) {
    cur = next;
    while (cur != NULL) {
      // Find max level after n
3006 3007 3008
      if (m == cur->method()) {
        max_level = MAX2(max_level, cur->comp_level());
      }
I
iveresov 已提交
3009 3010 3011 3012
      cur = cur->osr_link();
    }
    m->set_highest_osr_comp_level(max_level);
  }
D
duke 已提交
3013 3014 3015 3016
  // Remember to unlock again
  OsrList_lock->unlock();
}

3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032
int InstanceKlass::mark_osr_nmethods(const Method* m) {
  // This is a short non-blocking critical region, so the no safepoint check is ok.
  MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
  nmethod* osr = osr_nmethods_head();
  int found = 0;
  while (osr != NULL) {
    assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
    if (osr->method() == m) {
      osr->mark_for_deoptimization();
      found++;
    }
    osr = osr->osr_link();
  }
  return found;
}

3033
nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
D
duke 已提交
3034 3035 3036
  // 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 已提交
3037
  nmethod* best = NULL;
D
duke 已提交
3038 3039
  while (osr != NULL) {
    assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
I
iveresov 已提交
3040 3041 3042 3043 3044 3045
    // 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 已提交
3046 3047
    if (osr->method() == m &&
        (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
I
iveresov 已提交
3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
      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 已提交
3064
    }
3065
    osr = osr->osr_link();
D
duke 已提交
3066 3067
  }
  OsrList_lock->unlock();
3068 3069 3070

  assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");
  if (best != NULL && best->comp_level() >= comp_level) {
I
iveresov 已提交
3071 3072
    return best;
  }
D
duke 已提交
3073 3074 3075
  return NULL;
}

3076
oop InstanceKlass::add_member_name(Handle mem_name, bool intern) {
3077 3078 3079 3080
  jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
  MutexLocker ml(MemberNameTable_lock);
  DEBUG_ONLY(No_Safepoint_Verifier nsv);

3081 3082 3083 3084 3085
  // Check if method has been redefined while taking out MemberNameTable_lock, if so
  // return false.  We cannot cache obsolete methods. They will crash when the function
  // is called!
  Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name());
  if (method->is_obsolete()) {
3086
    return NULL;
3087 3088 3089
  } else if (method->is_old()) {
    // Replace method with redefined version
    java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum()));
3090
  }
3091 3092

  if (_member_names == NULL) {
3093
    _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
3094
  }
3095 3096 3097 3098 3099
  if (intern) {
    return _member_names->find_or_add_member_name(mem_name_wref);
  } else {
    return _member_names->add_member_name(mem_name_wref);
  }
3100 3101
}

D
duke 已提交
3102 3103 3104
// -----------------------------------------------------------------------------------------------------
// Printing

3105 3106
#ifndef PRODUCT

3107 3108
#define BULLET  " - "

3109 3110 3111 3112
static const char* state_names[] = {
  "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
};

3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124
static void print_vtable(intptr_t* start, int len, outputStream* st) {
  for (int i = 0; i < len; i++) {
    intptr_t e = start[i];
    st->print("%d : " INTPTR_FORMAT, i, e);
    if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
      st->print(" ");
      ((Metadata*)e)->print_value_on(st);
    }
    st->cr();
  }
}

3125 3126 3127 3128 3129 3130 3131
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();
3132
  st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
  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();
3159
  if (Verbose || WizardMode) {
3160
    Array<Method*>* method_array = methods();
3161
    for (int i = 0; i < method_array->length(); i++) {
3162 3163 3164
      st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
    }
  }
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
  st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
  st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
  if (Verbose && default_methods() != NULL) {
    Array<Method*>* method_array = default_methods();
    for (int i = 0; i < method_array->length(); i++) {
      st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
    }
  }
  if (default_vtable_indices() != NULL) {
    st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
  }
3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
  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 已提交
3195 3196 3197 3198
  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();
3199
  {
3200
    bool have_pv = false;
3201 3202 3203 3204
    // previous versions are linked together through the InstanceKlass
    for (InstanceKlass* pv_node = _previous_versions;
         pv_node != NULL;
         pv_node = pv_node->previous_versions()) {
3205 3206 3207
      if (!have_pv)
        st->print(BULLET"previous version:  ");
      have_pv = true;
3208
      pv_node->constants()->print_value_on(st);
3209 3210
    }
    if (have_pv) st->cr();
3211
  }
3212 3213 3214 3215 3216 3217 3218 3219 3220

  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();
3221
  if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3222
  st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
3223
  if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244
  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");
3245
  if (Verbose || WizardMode)  access_flags().print_on(st);
3246 3247 3248 3249 3250
  name()->print_value_on(st);
}

#ifndef PRODUCT

D
duke 已提交
3251
void FieldPrinter::do_field(fieldDescriptor* fd) {
3252
  _st->print(BULLET);
3253
   if (_obj == NULL) {
D
duke 已提交
3254 3255 3256 3257 3258 3259 3260 3261 3262
     fd->print_on(_st);
     _st->cr();
   } else {
     fd->print_on_for(_st, _obj);
     _st->cr();
   }
}


3263
void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
D
duke 已提交
3264 3265
  Klass::oop_print_on(obj, st);

3266
  if (this == SystemDictionary::String_klass()) {
D
duke 已提交
3267 3268 3269 3270 3271 3272 3273
    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()) {
3274
      st->print(BULLET"string: ");
3275
      java_lang_String::print(obj, st);
D
duke 已提交
3276 3277 3278 3279 3280
      st->cr();
      if (!WizardMode)  return;  // that is enough
    }
  }

3281
  st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3282 3283
  FieldPrinter print_field(st, obj);
  do_nonstatic_fields(&print_field);
D
duke 已提交
3284

3285
  if (this == SystemDictionary::Class_klass()) {
3286 3287 3288
    st->print(BULLET"signature: ");
    java_lang_Class::print_signature(obj, st);
    st->cr();
3289
    Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3290
    st->print(BULLET"fake entry for mirror: ");
3291
    mirrored_klass->print_value_on_maybe_null(st);
D
duke 已提交
3292
    st->cr();
3293
    Klass* array_klass = java_lang_Class::array_klass(obj);
3294
    st->print(BULLET"fake entry for array: ");
3295
    array_klass->print_value_on_maybe_null(st);
D
duke 已提交
3296
    st->cr();
3297 3298
    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));
3299 3300 3301
    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);
3302
    }
3303
  } else if (this == SystemDictionary::MethodType_klass()) {
3304
    st->print(BULLET"signature: ");
3305
    java_lang_invoke_MethodType::print_signature(obj, st);
3306
    st->cr();
D
duke 已提交
3307 3308 3309
  }
}

3310 3311
#endif //PRODUCT

3312
void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
D
duke 已提交
3313 3314 3315
  st->print("a ");
  name()->print_value_on(st);
  obj->print_address_on(st);
3316
  if (this == SystemDictionary::String_klass()
3317 3318 3319 3320 3321 3322 3323 3324
      && 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);
3325 3326
  } else if (this == SystemDictionary::Class_klass()) {
    Klass* k = java_lang_Class::as_Klass(obj);
3327 3328 3329 3330 3331 3332 3333
    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?");
    }
3334
  } else if (this == SystemDictionary::MethodType_klass()) {
3335
    st->print(" = ");
3336
    java_lang_invoke_MethodType::print_signature(obj, st);
3337 3338 3339
  } else if (java_lang_boxing_object::is_instance(obj)) {
    st->print(" = ");
    java_lang_boxing_object::print(obj, st);
3340
  } else if (this == SystemDictionary::LambdaForm_klass()) {
3341 3342 3343 3344 3345
    oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
    if (vmentry != NULL) {
      st->print(" => ");
      vmentry->print_value_on(st);
    }
3346 3347
  } else if (this == SystemDictionary::MemberName_klass()) {
    Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3348 3349 3350 3351 3352 3353 3354 3355
    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);
    }
3356
  }
D
duke 已提交
3357 3358
}

3359
const char* InstanceKlass::internal_name() const {
D
duke 已提交
3360 3361 3362
  return external_name();
}

3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407
#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 已提交
3408 3409 3410
// Verification

class VerifyFieldClosure: public OopClosure {
3411 3412 3413 3414 3415
 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 已提交
3416 3417 3418 3419
      Universe::print();
      guarantee(false, "boom");
    }
  }
3420 3421 3422
 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 已提交
3423 3424
};

3425
void InstanceKlass::verify_on(outputStream* st) {
3426
#ifndef PRODUCT
3427
  // Avoid redundant verifies, this really should be in product.
3428 3429 3430
  if (_verify_count == Universe::verify_count()) return;
  _verify_count = Universe::verify_count();
#endif
3431 3432

  // Verify Klass
3433
  Klass::verify_on(st);
3434

3435 3436 3437
  // Verify that klass is present in ClassLoaderData
  guarantee(class_loader_data()->contains_klass(this),
            "this class isn't found in class loader data");
3438 3439 3440

  // Verify vtables
  if (is_linked()) {
3441
    ResourceMark rm;
3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
    // $$$ 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 已提交
3469
    guarantee(!im->is_interface() || im == this,
3470 3471 3472 3473 3474 3475 3476 3477
      "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 已提交
3478
      guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3479 3480 3481 3482 3483 3484 3485 3486
    }
  }

  // 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 已提交
3487
      guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508
    }
  }

  // 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() ||
3509
        ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524
      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");
    }
  }

3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537
  // Verify default methods
  if (default_methods() != NULL) {
    Array<Method*>* methods = this->default_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");
    }
  }

3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549
  // 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");
  }
3550 3551 3552
  const Klass* host = host_klass();
  if (host != NULL) {
    guarantee(host->is_klass(), "should be klass");
3553 3554 3555 3556
  }
}

void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
D
duke 已提交
3557 3558
  Klass::oop_verify_on(obj, st);
  VerifyFieldClosure blk;
3559
  obj->oop_iterate_no_header(&blk);
D
duke 已提交
3560 3561
}

3562

3563 3564 3565 3566
// 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.
3567
JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3568 3569 3570 3571 3572
  _holder = holder;
  _offset = offset;
  _next = next;
  debug_only(_is_static_field_id = false;)
}
D
duke 已提交
3573 3574


3575 3576 3577 3578 3579 3580 3581 3582
JNIid* JNIid::find(int offset) {
  JNIid* current = this;
  while (current != NULL) {
    if (current->offset() == offset) return current;
    current = current->next();
  }
  return NULL;
}
D
duke 已提交
3583 3584

void JNIid::deallocate(JNIid* current) {
3585 3586 3587 3588 3589 3590 3591
  while (current != NULL) {
    JNIid* next = current->next();
    delete current;
    current = next;
  }
}

D
duke 已提交
3592

3593
void JNIid::verify(Klass* holder) {
3594
  int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3595
  int end_field_offset;
3596
  end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
D
duke 已提交
3597

3598 3599 3600
  JNIid* current = this;
  while (current != NULL) {
    guarantee(current->holder() == holder, "Invalid klass in JNIid");
D
duke 已提交
3601
#ifdef ASSERT
3602 3603 3604 3605 3606 3607
    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 已提交
3608
  }
3609 3610 3611 3612
}


#ifdef ASSERT
3613 3614
void InstanceKlass::set_init_state(ClassState state) {
  bool good_state = is_shared() ? (_init_state <= state)
3615 3616
                                               : (_init_state < state);
  assert(good_state || state == allocated, "illegal state transition");
3617
  _init_state = (u1)state;
3618
}
D
duke 已提交
3619 3620 3621 3622 3623
#endif


// RedefineClasses() support for previous versions:

3624
// Purge previous versions
3625
void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
3626 3627 3628 3629 3630 3631
  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;
3632 3633
    ClassLoaderData* loader_data = ik->class_loader_data();
    assert(loader_data != NULL, "should never be null");
3634 3635

    // RC_TRACE macro has an embedded ResourceMark
3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647
    RC_TRACE(0x00000200, ("purge: %s: previous versions", ik->external_name()));

    // previous versions are linked together through the InstanceKlass
    InstanceKlass* pv_node = ik->previous_versions();
    InstanceKlass* last = ik;
    int version = 0;

    // check the previous versions list
    for (; pv_node != NULL; ) {

      ConstantPool* pvcp = pv_node->constants();
      assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3648 3649 3650 3651


      if (!pvcp->on_stack()) {
        // If the constant pool isn't on stack, none of the methods
3652 3653 3654 3655 3656
        // are executing.  Unlink this previous_version.
        // The previous version InstanceKlass is on the ClassLoaderData deallocate list
        // so will be deallocated during the next phase of class unloading.
        pv_node = pv_node->previous_versions();
        last->link_previous_versions(pv_node);
3657
        deleted_count++;
3658
        version++;
3659 3660
        continue;
      } else {
3661 3662
        RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is alive",
                              pv_node));
3663 3664 3665 3666 3667
        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++;
      }

3668 3669 3670 3671 3672
      // At least one method is live in this previous version so clean its MethodData.
      // Reset dead EMCP methods not to get breakpoints.
      // All methods are deallocated when all of the methods for this class are no
      // longer running.
      Array<Method*>* method_refs = pv_node->methods();
3673 3674 3675
      if (method_refs != NULL) {
        RC_TRACE(0x00000200, ("purge: previous methods length=%d",
          method_refs->length()));
3676
        for (int j = 0; j < method_refs->length(); j++) {
3677 3678 3679
          Method* method = method_refs->at(j);

          if (!method->on_stack()) {
3680 3681 3682 3683
            // no breakpoints for non-running methods
            if (method->is_running_emcp()) {
              method->set_running_emcp(false);
            }
3684
          } else {
3685 3686
            assert (method->is_obsolete() || method->is_running_emcp(),
                    "emcp method cannot run after emcp bit is cleared");
3687 3688 3689 3690
            // 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(),
3691
              method->signature()->as_C_string(), j, version));
3692
            if (method->method_data() != NULL) {
3693 3694
              // Clean out any weak method links for running methods
              // (also should include not EMCP methods)
3695 3696
              method->method_data()->clean_weak_method_links();
            }
3697 3698 3699
          }
        }
      }
3700 3701 3702 3703
      // next previous version
      last = pv_node;
      pv_node = pv_node->previous_versions();
      version++;
3704 3705 3706 3707 3708
    }
    RC_TRACE(0x00000200,
      ("purge: previous version stats: live=%d, deleted=%d", live_count,
      deleted_count));
  }
3709

3710 3711
  // Clean MethodData of this class's methods so they don't refer to
  // old methods that are no longer running.
3712 3713 3714 3715 3716 3717 3718
  Array<Method*>* methods = ik->methods();
  int num_methods = methods->length();
  for (int index2 = 0; index2 < num_methods; ++index2) {
    if (methods->at(index2)->method_data() != NULL) {
      methods->at(index2)->method_data()->clean_weak_method_links();
    }
  }
3719 3720
}

3721 3722
void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
                                                int emcp_method_count) {
D
duke 已提交
3723 3724 3725
  int obsolete_method_count = old_methods->length() - emcp_method_count;

  if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3726
      _previous_versions != NULL) {
3727
    // We have a mix of obsolete and EMCP methods so we have to
D
duke 已提交
3728 3729 3730
    // clear out any matching EMCP method entries the hard way.
    int local_count = 0;
    for (int i = 0; i < old_methods->length(); i++) {
3731 3732
      Method* old_method = old_methods->at(i);
      if (old_method->is_obsolete()) {
D
duke 已提交
3733
        // only obsolete methods are interesting
3734 3735
        Symbol* m_name = old_method->name();
        Symbol* m_signature = old_method->signature();
D
duke 已提交
3736

3737 3738 3739 3740 3741
        // previous versions are linked together through the InstanceKlass
        int j = 0;
        for (InstanceKlass* prev_version = _previous_versions;
             prev_version != NULL;
             prev_version = prev_version->previous_versions(), j++) {
D
duke 已提交
3742

3743 3744
          Array<Method*>* method_refs = prev_version->methods();
          for (int k = 0; k < method_refs->length(); k++) {
3745
            Method* method = method_refs->at(k);
D
duke 已提交
3746

3747 3748
            if (!method->is_obsolete() &&
                method->name() == m_name &&
D
duke 已提交
3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763
                method->signature() == m_signature) {
              // The current RedefineClasses() call has made all EMCP
              // versions of this method obsolete so mark it as obsolete
              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();
              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
3764
          // method for this generation could have already been made obsolete,
D
duke 已提交
3765
          // but there still may be an older EMCP method that has not
3766
          // been made obsolete.
D
duke 已提交
3767 3768 3769 3770 3771 3772 3773 3774 3775
        }

        if (++local_count >= obsolete_method_count) {
          // no more obsolete methods so bail out now
          break;
        }
      }
    }
  }
3776 3777 3778 3779 3780 3781 3782 3783 3784
}

// Save the scratch_class as the previous version if any of the methods are running.
// The previous_versions are used to set breakpoints in EMCP methods and they are
// also used to clean MethodData links to redefined methods that are no longer running.
void InstanceKlass::add_previous_version(instanceKlassHandle scratch_class,
                                         int emcp_method_count) {
  assert(Thread::current()->is_VM_thread(),
         "only VMThread can add previous versions");
D
duke 已提交
3785

3786 3787 3788
  // RC_TRACE macro has an embedded ResourceMark
  RC_TRACE(0x00000400, ("adding previous version ref for %s, EMCP_cnt=%d",
    scratch_class->external_name(), emcp_method_count));
D
duke 已提交
3789

3790 3791
  // Clean out old previous versions
  purge_previous_versions(this);
D
duke 已提交
3792

3793 3794 3795 3796
  // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
  // a previous redefinition may be made obsolete by this redefinition.
  Array<Method*>* old_methods = scratch_class->methods();
  mark_newly_obsolete_methods(old_methods, emcp_method_count);
3797

3798 3799 3800 3801 3802 3803 3804 3805
  // 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 add this as a previous version.
  ConstantPool* cp_ref = scratch_class->constants();
  if (!cp_ref->on_stack()) {
    RC_TRACE(0x00000400, ("add: scratch class not added; no methods are running"));
    return;
3806
  }
3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827

  if (emcp_method_count != 0) {
    // At least one method is still running, check for EMCP methods
    for (int i = 0; i < old_methods->length(); i++) {
      Method* old_method = old_methods->at(i);
      if (!old_method->is_obsolete() && old_method->on_stack()) {
        // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
        // we can add breakpoints for it.

        // We set the method->on_stack bit during safepoints for class redefinition and
        // class unloading and use this bit to set the is_running_emcp bit.
        // After the safepoint, the on_stack bit is cleared and the running emcp
        // method may exit.   If so, we would set a breakpoint in a method that
        // is never reached, but this won't be noticeable to the programmer.
        old_method->set_running_emcp(true);
        RC_TRACE(0x00000400, ("add: EMCP method %s is on_stack " INTPTR_FORMAT,
                              old_method->name_and_sig_as_C_string(), old_method));
      } else if (!old_method->is_obsolete()) {
        RC_TRACE(0x00000400, ("add: EMCP method %s is NOT on_stack " INTPTR_FORMAT,
                              old_method->name_and_sig_as_C_string(), old_method));
      }
3828 3829 3830
    }
  }

3831 3832 3833 3834 3835 3836
  // Add previous version if any methods are still running.
  RC_TRACE(0x00000400, ("add: scratch class added; one of its methods is on_stack"));
  assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
  scratch_class->link_previous_versions(previous_versions());
  link_previous_versions(scratch_class());
} // end add_previous_version()
3837

3838 3839
Method* InstanceKlass::method_with_idnum(int idnum) {
  Method* m = NULL;
D
duke 已提交
3840
  if (idnum < methods()->length()) {
3841
    m = methods()->at(idnum);
D
duke 已提交
3842 3843 3844
  }
  if (m == NULL || m->method_idnum() != idnum) {
    for (int index = 0; index < methods()->length(); ++index) {
3845
      m = methods()->at(index);
D
duke 已提交
3846 3847 3848 3849
      if (m->method_idnum() == idnum) {
        return m;
      }
    }
3850 3851
    // None found, return null for the caller to handle.
    return NULL;
D
duke 已提交
3852 3853 3854 3855
  }
  return m;
}

3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886

Method* InstanceKlass::method_with_orig_idnum(int idnum) {
  if (idnum >= methods()->length()) {
    return NULL;
  }
  Method* m = methods()->at(idnum);
  if (m != NULL && m->orig_method_idnum() == idnum) {
    return m;
  }
  // Obsolete method idnum does not match the original idnum
  for (int index = 0; index < methods()->length(); ++index) {
    m = methods()->at(index);
    if (m->orig_method_idnum() == idnum) {
      return m;
    }
  }
  // None found, return null for the caller to handle.
  return NULL;
}


Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
  InstanceKlass* holder = get_klass_version(version);
  if (holder == NULL) {
    return NULL; // The version of klass is gone, no method is found
  }
  Method* method = holder->method_with_orig_idnum(idnum);
  return method;
}


3887 3888 3889 3890 3891 3892 3893
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);
}