1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "aot/aotLoader.hpp"
  28 #include "classfile/classFileParser.hpp"
  29 #include "classfile/classFileStream.hpp"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/classLoaderData.inline.hpp"
  32 #include "classfile/javaClasses.hpp"
  33 #include "classfile/moduleEntry.hpp"
  34 #include "classfile/systemDictionary.hpp"
  35 #include "classfile/systemDictionaryShared.hpp"
  36 #include "classfile/verifier.hpp"
  37 #include "classfile/vmSymbols.hpp"
  38 #include "code/dependencyContext.hpp"
  39 #include "compiler/compileBroker.hpp"
  40 #include "gc/shared/collectedHeap.inline.hpp"
  41 #include "interpreter/oopMapCache.hpp"
  42 #include "interpreter/rewriter.hpp"
  43 #include "jvmtifiles/jvmti.h"
  44 #include "logging/log.hpp"
  45 #include "logging/logMessage.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/heapInspection.hpp"
  49 #include "memory/iterator.inline.hpp"
  50 #include "memory/metadataFactory.hpp"
  51 #include "memory/metaspaceClosure.hpp"
  52 #include "memory/metaspaceShared.hpp"
  53 #include "memory/oopFactory.hpp"
  54 #include "memory/resourceArea.hpp"
  55 #include "oops/fieldStreams.hpp"
  56 #include "oops/instanceClassLoaderKlass.hpp"
  57 #include "oops/instanceKlass.inline.hpp"
  58 #include "oops/instanceMirrorKlass.hpp"
  59 #include "oops/instanceOop.hpp"
  60 #include "oops/klass.inline.hpp"
  61 #include "oops/method.hpp"
  62 #include "oops/oop.inline.hpp"
  63 #include "oops/symbol.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiRedefineClasses.hpp"
  66 #include "prims/jvmtiThreadState.hpp"
  67 #include "prims/methodComparator.hpp"
  68 #include "runtime/atomic.hpp"
  69 #include "runtime/fieldDescriptor.inline.hpp"
  70 #include "runtime/handles.inline.hpp"
  71 #include "runtime/javaCalls.hpp"
  72 #include "runtime/mutexLocker.hpp"
  73 #include "runtime/orderAccess.hpp"
  74 #include "runtime/thread.inline.hpp"
  75 #include "services/classLoadingService.hpp"
  76 #include "services/threadService.hpp"
  77 #include "utilities/dtrace.hpp"
  78 #include "utilities/macros.hpp"
  79 #include "utilities/stringUtils.hpp"
  80 #ifdef COMPILER1
  81 #include "c1/c1_Compiler.hpp"
  82 #endif
  83 #if INCLUDE_JFR
  84 #include "utilities/ticks.hpp"
  85 #include "jfr/jfr.hpp"
  86 #include "jfr/jfrEvents.hpp"
  87 Ticks InstanceKlass::_class_unload_time;
  88 #endif
  89 
  90 
  91 #ifdef DTRACE_ENABLED
  92 
  93 
  94 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
  95 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
  96 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
  97 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
  98 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
  99 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
 100 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
 101 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
 102 #define DTRACE_CLASSINIT_PROBE(type, thread_type)                \
 103   {                                                              \
 104     char* data = NULL;                                           \
 105     int len = 0;                                                 \
 106     Symbol* clss_name = name();                                  \
 107     if (clss_name != NULL) {                                     \
 108       data = (char*)clss_name->bytes();                          \
 109       len = clss_name->utf8_length();                            \
 110     }                                                            \
 111     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 112       data, len, (void*)class_loader(), thread_type);            \
 113   }
 114 
 115 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)     \
 116   {                                                              \
 117     char* data = NULL;                                           \
 118     int len = 0;                                                 \
 119     Symbol* clss_name = name();                                  \
 120     if (clss_name != NULL) {                                     \
 121       data = (char*)clss_name->bytes();                          \
 122       len = clss_name->utf8_length();                            \
 123     }                                                            \
 124     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 125       data, len, (void*)class_loader(), thread_type, wait);      \
 126   }
 127 
 128 #else //  ndef DTRACE_ENABLED
 129 
 130 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
 131 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
 132 
 133 #endif //  ndef DTRACE_ENABLED
 134 
 135 static inline bool is_class_loader(const Symbol* class_name,
 136                                    const ClassFileParser& parser) {
 137   assert(class_name != NULL, "invariant");
 138 
 139   if (class_name == vmSymbols::java_lang_ClassLoader()) {
 140     return true;
 141   }
 142 
 143   if (SystemDictionary::ClassLoader_klass_loaded()) {
 144     const Klass* const super_klass = parser.super_klass();
 145     if (super_klass != NULL) {
 146       if (super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass())) {
 147         return true;
 148       }
 149     }
 150   }
 151   return false;
 152 }
 153 
 154 // called to verify that k is a member of this nest
 155 bool InstanceKlass::has_nest_member(InstanceKlass* k, TRAPS) const {
 156   if (_nest_members == NULL || _nest_members == Universe::the_empty_short_array()) {
 157     if (log_is_enabled(Trace, class, nestmates)) {
 158       ResourceMark rm(THREAD);
 159       log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
 160                                   k->external_name(), this->external_name());
 161     }
 162     return false;
 163   }
 164 
 165   if (log_is_enabled(Trace, class, nestmates)) {
 166     ResourceMark rm(THREAD);
 167     log_trace(class, nestmates)("Checking nest membership of %s in %s",
 168                                 k->external_name(), this->external_name());
 169   }
 170 
 171   // Check names first and if they match then check actual klass. This avoids
 172   // resolving anything unnecessarily.
 173   for (int i = 0; i < _nest_members->length(); i++) {
 174     int cp_index = _nest_members->at(i);
 175     Symbol* name = _constants->klass_name_at(cp_index);
 176     if (name == k->name()) {
 177       log_trace(class, nestmates)("- Found it at nest_members[%d] => cp[%d]", i, cp_index);
 178 
 179       // names match so check actual klass - this may trigger class loading if
 180       // it doesn't match (but that should be impossible)
 181       Klass* k2 = _constants->klass_at(cp_index, CHECK_false);
 182       if (k2 == k) {
 183         log_trace(class, nestmates)("- class is listed as a nest member");
 184         return true;
 185       } else {
 186         // same name but different klass!
 187         log_trace(class, nestmates)(" - klass comparison failed!");
 188         // can't have different classes for the same name, so we're done
 189         return false;
 190       }
 191     }
 192   }
 193   log_trace(class, nestmates)("- class is NOT a nest member!");
 194   return false;
 195 }
 196 
 197 // Return nest-host class, resolving, validating and saving it if needed.
 198 // In cases where this is called from a thread that can not do classloading
 199 // (such as a native JIT thread) then we simply return NULL, which in turn
 200 // causes the access check to return false. Such code will retry the access
 201 // from a more suitable environment later.
 202 InstanceKlass* InstanceKlass::nest_host(Symbol* validationException, TRAPS) {
 203   InstanceKlass* nest_host_k = _nest_host;
 204   if (nest_host_k == NULL) {
 205     // need to resolve and save our nest-host class. This could be attempted
 206     // concurrently but as the result is idempotent and we don't use the class
 207     // then we do not need any synchronization beyond what is implicitly used
 208     // during class loading.
 209     if (_nest_host_index != 0) { // we have a real nest_host
 210       // Before trying to resolve check if we're in a suitable context
 211       if (!THREAD->can_call_java() && !_constants->tag_at(_nest_host_index).is_klass()) {
 212         if (log_is_enabled(Trace, class, nestmates)) {
 213           ResourceMark rm(THREAD);
 214           log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread",
 215                                       this->external_name());
 216         }
 217         return NULL;
 218       }
 219 
 220       if (log_is_enabled(Trace, class, nestmates)) {
 221         ResourceMark rm(THREAD);
 222         log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s",
 223                                     this->external_name(),
 224                                     _constants->klass_name_at(_nest_host_index)->as_C_string());
 225       }
 226 
 227       Klass* k = _constants->klass_at(_nest_host_index, THREAD);
 228       if (HAS_PENDING_EXCEPTION) {
 229         Handle exc_h = Handle(THREAD, PENDING_EXCEPTION);
 230         if (exc_h->is_a(SystemDictionary::NoClassDefFoundError_klass())) {
 231           // throw a new CDNFE with the original as its cause, and a clear msg
 232           ResourceMark rm(THREAD);
 233           char buf[200];
 234           CLEAR_PENDING_EXCEPTION;
 235           jio_snprintf(buf, sizeof(buf),
 236                        "Unable to load nest-host class (%s) of %s",
 237                        _constants->klass_name_at(_nest_host_index)->as_C_string(),
 238                        this->external_name());
 239           log_trace(class, nestmates)("%s - NoClassDefFoundError", buf);
 240           THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), buf, exc_h);
 241         }
 242         // All other exceptions pass through (OOME, StackOverflowError, LinkageErrors etc).
 243         return NULL;
 244       }
 245 
 246       // A valid nest-host is an instance class in the current package that lists this
 247       // class as a nest member. If any of these conditions are not met we post the
 248       // requested exception type (if any) and return NULL
 249 
 250       const char* error = NULL;
 251 
 252       // JVMS 5.4.4 indicates package check comes first
 253       if (is_same_class_package(k)) {
 254 
 255         // Now check actual membership. We can't be a member if our "host" is
 256         // not an instance class.
 257         if (k->is_instance_klass()) {
 258           nest_host_k = InstanceKlass::cast(k);
 259 
 260           bool is_member = nest_host_k->has_nest_member(this, CHECK_NULL);
 261           if (is_member) {
 262             // save resolved nest-host value
 263             _nest_host = nest_host_k;
 264 
 265             if (log_is_enabled(Trace, class, nestmates)) {
 266               ResourceMark rm(THREAD);
 267               log_trace(class, nestmates)("Resolved nest-host of %s to %s",
 268                                           this->external_name(), k->external_name());
 269             }
 270             return nest_host_k;
 271           }
 272         }
 273         error = "current type is not listed as a nest member";
 274       } else {
 275         error = "types are in different packages";
 276       }
 277 
 278       if (log_is_enabled(Trace, class, nestmates)) {
 279         ResourceMark rm(THREAD);
 280         log_trace(class, nestmates)("Type %s is not a nest member of resolved type %s: %s",
 281                                     this->external_name(),
 282                                     k->external_name(),
 283                                     error);
 284       }
 285 
 286       if (validationException != NULL) {
 287         ResourceMark rm(THREAD);
 288         Exceptions::fthrow(THREAD_AND_LOCATION,
 289                            validationException,
 290                            "Type %s is not a nest member of %s: %s",
 291                            this->external_name(),
 292                            k->external_name(),
 293                            error
 294                            );
 295       }
 296       return NULL;
 297     } else {
 298       if (log_is_enabled(Trace, class, nestmates)) {
 299         ResourceMark rm(THREAD);
 300         log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self",
 301                                     this->external_name());
 302       }
 303       // save resolved nest-host value
 304       return (_nest_host = this);
 305     }
 306   }
 307   return nest_host_k;
 308 }
 309 
 310 // check if 'this' and k are nestmates (same nest_host), or k is our nest_host,
 311 // or we are k's nest_host - all of which is covered by comparing the two
 312 // resolved_nest_hosts
 313 bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) {
 314 
 315   assert(this != k, "this should be handled by higher-level code");
 316 
 317   // Per JVMS 5.4.4 we first resolve and validate the current class, then
 318   // the target class k. Resolution exceptions will be passed on by upper
 319   // layers. IncompatibleClassChangeErrors from membership validation failures
 320   // will also be passed through.
 321 
 322   Symbol* icce = vmSymbols::java_lang_IncompatibleClassChangeError();
 323   InstanceKlass* cur_host = nest_host(icce, CHECK_false);
 324   if (cur_host == NULL) {
 325     return false;
 326   }
 327 
 328   Klass* k_nest_host = k->nest_host(icce, CHECK_false);
 329   if (k_nest_host == NULL) {
 330     return false;
 331   }
 332 
 333   bool access = (cur_host == k_nest_host);
 334 
 335   if (log_is_enabled(Trace, class, nestmates)) {
 336     ResourceMark rm(THREAD);
 337     log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
 338                                 this->external_name(),
 339                                 access ? "" : "NOT ",
 340                                 k->external_name());
 341   }
 342 
 343   return access;
 344 }
 345 
 346 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
 347   const int size = InstanceKlass::size(parser.vtable_size(),
 348                                        parser.itable_size(),
 349                                        nonstatic_oop_map_size(parser.total_oop_map_count()),
 350                                        parser.is_interface(),
 351                                        parser.is_unsafe_anonymous(),
 352                                        should_store_fingerprint(parser.is_unsafe_anonymous()));
 353 
 354   const Symbol* const class_name = parser.class_name();
 355   assert(class_name != NULL, "invariant");
 356   ClassLoaderData* loader_data = parser.loader_data();
 357   assert(loader_data != NULL, "invariant");
 358 
 359   InstanceKlass* ik;
 360 
 361   // Allocation
 362   if (REF_NONE == parser.reference_type()) {
 363     if (class_name == vmSymbols::java_lang_Class()) {
 364       // mirror
 365       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
 366     }
 367     else if (is_class_loader(class_name, parser)) {
 368       // class loader
 369       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
 370     } else {
 371       // normal
 372       ik = new (loader_data, size, THREAD) InstanceKlass(parser, InstanceKlass::_misc_kind_other);
 373     }
 374   } else {
 375     // reference
 376     ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
 377   }
 378 
 379   // Check for pending exception before adding to the loader data and incrementing
 380   // class count.  Can get OOM here.
 381   if (HAS_PENDING_EXCEPTION) {
 382     return NULL;
 383   }
 384 
 385   return ik;
 386 }
 387 
 388 
 389 // copy method ordering from resource area to Metaspace
 390 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
 391   if (m != NULL) {
 392     // allocate a new array and copy contents (memcpy?)
 393     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 394     for (int i = 0; i < m->length(); i++) {
 395       _method_ordering->at_put(i, m->at(i));
 396     }
 397   } else {
 398     _method_ordering = Universe::the_empty_int_array();
 399   }
 400 }
 401 
 402 // create a new array of vtable_indices for default methods
 403 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 404   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 405   assert(default_vtable_indices() == NULL, "only create once");
 406   set_default_vtable_indices(vtable_indices);
 407   return vtable_indices;
 408 }
 409 
 410 InstanceKlass::InstanceKlass(const ClassFileParser& parser, unsigned kind, KlassID id) :
 411   Klass(id),
 412   _nest_members(NULL),
 413   _nest_host_index(0),
 414   _nest_host(NULL),
 415   _static_field_size(parser.static_field_size()),
 416   _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
 417   _itable_len(parser.itable_size()),
 418   _reference_type(parser.reference_type()) {
 419     set_vtable_length(parser.vtable_size());
 420     set_kind(kind);
 421     set_access_flags(parser.access_flags());
 422     set_is_unsafe_anonymous(parser.is_unsafe_anonymous());
 423     set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
 424                                                     false));
 425 
 426     assert(NULL == _methods, "underlying memory not zeroed?");
 427     assert(is_instance_klass(), "is layout incorrect?");
 428     assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
 429 }
 430 
 431 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 432                                        Array<Method*>* methods) {
 433   if (methods != NULL && methods != Universe::the_empty_method_array() &&
 434       !methods->is_shared()) {
 435     for (int i = 0; i < methods->length(); i++) {
 436       Method* method = methods->at(i);
 437       if (method == NULL) continue;  // maybe null if error processing
 438       // Only want to delete methods that are not executing for RedefineClasses.
 439       // The previous version will point to them so they're not totally dangling
 440       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 441       MetadataFactory::free_metadata(loader_data, method);
 442     }
 443     MetadataFactory::free_array<Method*>(loader_data, methods);
 444   }
 445 }
 446 
 447 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 448                                           const Klass* super_klass,
 449                                           Array<InstanceKlass*>* local_interfaces,
 450                                           Array<InstanceKlass*>* transitive_interfaces) {
 451   // Only deallocate transitive interfaces if not empty, same as super class
 452   // or same as local interfaces.  See code in parseClassFile.
 453   Array<InstanceKlass*>* ti = transitive_interfaces;
 454   if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) {
 455     // check that the interfaces don't come from super class
 456     Array<InstanceKlass*>* sti = (super_klass == NULL) ? NULL :
 457                     InstanceKlass::cast(super_klass)->transitive_interfaces();
 458     if (ti != sti && ti != NULL && !ti->is_shared()) {
 459       MetadataFactory::free_array<InstanceKlass*>(loader_data, ti);
 460     }
 461   }
 462 
 463   // local interfaces can be empty
 464   if (local_interfaces != Universe::the_empty_instance_klass_array() &&
 465       local_interfaces != NULL && !local_interfaces->is_shared()) {
 466     MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);
 467   }
 468 }
 469 
 470 // This function deallocates the metadata and C heap pointers that the
 471 // InstanceKlass points to.
 472 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
 473 
 474   // Orphan the mirror first, CMS thinks it's still live.
 475   if (java_mirror() != NULL) {
 476     java_lang_Class::set_klass(java_mirror(), NULL);
 477   }
 478 
 479   // Also remove mirror from handles
 480   loader_data->remove_handle(_java_mirror);
 481 
 482   // Need to take this class off the class loader data list.
 483   loader_data->remove_class(this);
 484 
 485   // The array_klass for this class is created later, after error handling.
 486   // For class redefinition, we keep the original class so this scratch class
 487   // doesn't have an array class.  Either way, assert that there is nothing
 488   // to deallocate.
 489   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
 490 
 491   // Release C heap allocated data that this might point to, which includes
 492   // reference counting symbol names.
 493   release_C_heap_structures();
 494 
 495   deallocate_methods(loader_data, methods());
 496   set_methods(NULL);
 497 
 498   if (method_ordering() != NULL &&
 499       method_ordering() != Universe::the_empty_int_array() &&
 500       !method_ordering()->is_shared()) {
 501     MetadataFactory::free_array<int>(loader_data, method_ordering());
 502   }
 503   set_method_ordering(NULL);
 504 
 505   // default methods can be empty
 506   if (default_methods() != NULL &&
 507       default_methods() != Universe::the_empty_method_array() &&
 508       !default_methods()->is_shared()) {
 509     MetadataFactory::free_array<Method*>(loader_data, default_methods());
 510   }
 511   // Do NOT deallocate the default methods, they are owned by superinterfaces.
 512   set_default_methods(NULL);
 513 
 514   // default methods vtable indices can be empty
 515   if (default_vtable_indices() != NULL &&
 516       !default_vtable_indices()->is_shared()) {
 517     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
 518   }
 519   set_default_vtable_indices(NULL);
 520 
 521 
 522   // This array is in Klass, but remove it with the InstanceKlass since
 523   // this place would be the only caller and it can share memory with transitive
 524   // interfaces.
 525   if (secondary_supers() != NULL &&
 526       secondary_supers() != Universe::the_empty_klass_array() &&
 527       // see comments in compute_secondary_supers about the following cast
 528       (address)(secondary_supers()) != (address)(transitive_interfaces()) &&
 529       !secondary_supers()->is_shared()) {
 530     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
 531   }
 532   set_secondary_supers(NULL);
 533 
 534   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
 535   set_transitive_interfaces(NULL);
 536   set_local_interfaces(NULL);
 537 
 538   if (fields() != NULL && !fields()->is_shared()) {
 539     MetadataFactory::free_array<jushort>(loader_data, fields());
 540   }
 541   set_fields(NULL, 0);
 542 
 543   // If a method from a redefined class is using this constant pool, don't
 544   // delete it, yet.  The new class's previous version will point to this.
 545   if (constants() != NULL) {
 546     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
 547     if (!constants()->is_shared()) {
 548       MetadataFactory::free_metadata(loader_data, constants());
 549     }
 550     // Delete any cached resolution errors for the constant pool
 551     SystemDictionary::delete_resolution_error(constants());
 552 
 553     set_constants(NULL);
 554   }
 555 
 556   if (inner_classes() != NULL &&
 557       inner_classes() != Universe::the_empty_short_array() &&
 558       !inner_classes()->is_shared()) {
 559     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
 560   }
 561   set_inner_classes(NULL);
 562 
 563   if (nest_members() != NULL &&
 564       nest_members() != Universe::the_empty_short_array() &&
 565       !nest_members()->is_shared()) {
 566     MetadataFactory::free_array<jushort>(loader_data, nest_members());
 567   }
 568   set_nest_members(NULL);
 569 
 570   // We should deallocate the Annotations instance if it's not in shared spaces.
 571   if (annotations() != NULL && !annotations()->is_shared()) {
 572     MetadataFactory::free_metadata(loader_data, annotations());
 573   }
 574   set_annotations(NULL);
 575 }
 576 
 577 bool InstanceKlass::should_be_initialized() const {
 578   return !is_initialized();
 579 }
 580 
 581 klassItable InstanceKlass::itable() const {
 582   return klassItable(const_cast<InstanceKlass*>(this));
 583 }
 584 
 585 void InstanceKlass::eager_initialize(Thread *thread) {
 586   if (!EagerInitialization) return;
 587 
 588   if (this->is_not_initialized()) {
 589     // abort if the the class has a class initializer
 590     if (this->class_initializer() != NULL) return;
 591 
 592     // abort if it is java.lang.Object (initialization is handled in genesis)
 593     Klass* super_klass = super();
 594     if (super_klass == NULL) return;
 595 
 596     // abort if the super class should be initialized
 597     if (!InstanceKlass::cast(super_klass)->is_initialized()) return;
 598 
 599     // call body to expose the this pointer
 600     eager_initialize_impl();
 601   }
 602 }
 603 
 604 // JVMTI spec thinks there are signers and protection domain in the
 605 // instanceKlass.  These accessors pretend these fields are there.
 606 // The hprof specification also thinks these fields are in InstanceKlass.
 607 oop InstanceKlass::protection_domain() const {
 608   // return the protection_domain from the mirror
 609   return java_lang_Class::protection_domain(java_mirror());
 610 }
 611 
 612 // To remove these from requires an incompatible change and CCC request.
 613 objArrayOop InstanceKlass::signers() const {
 614   // return the signers from the mirror
 615   return java_lang_Class::signers(java_mirror());
 616 }
 617 
 618 oop InstanceKlass::init_lock() const {
 619   // return the init lock from the mirror
 620   oop lock = java_lang_Class::init_lock(java_mirror());
 621   // Prevent reordering with any access of initialization state
 622   OrderAccess::loadload();
 623   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
 624          "only fully initialized state can have a null lock");
 625   return lock;
 626 }
 627 
 628 // Set the initialization lock to null so the object can be GC'ed.  Any racing
 629 // threads to get this lock will see a null lock and will not lock.
 630 // That's okay because they all check for initialized state after getting
 631 // the lock and return.
 632 void InstanceKlass::fence_and_clear_init_lock() {
 633   // make sure previous stores are all done, notably the init_state.
 634   OrderAccess::storestore();
 635   java_lang_Class::set_init_lock(java_mirror(), NULL);
 636   assert(!is_not_initialized(), "class must be initialized now");
 637 }
 638 
 639 void InstanceKlass::eager_initialize_impl() {
 640   EXCEPTION_MARK;
 641   HandleMark hm(THREAD);
 642   Handle h_init_lock(THREAD, init_lock());
 643   ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
 644 
 645   // abort if someone beat us to the initialization
 646   if (!is_not_initialized()) return;  // note: not equivalent to is_initialized()
 647 
 648   ClassState old_state = init_state();
 649   link_class_impl(true, THREAD);
 650   if (HAS_PENDING_EXCEPTION) {
 651     CLEAR_PENDING_EXCEPTION;
 652     // Abort if linking the class throws an exception.
 653 
 654     // Use a test to avoid redundantly resetting the state if there's
 655     // no change.  Set_init_state() asserts that state changes make
 656     // progress, whereas here we might just be spinning in place.
 657     if (old_state != _init_state)
 658       set_init_state(old_state);
 659   } else {
 660     // linking successfull, mark class as initialized
 661     set_init_state(fully_initialized);
 662     fence_and_clear_init_lock();
 663     // trace
 664     if (log_is_enabled(Info, class, init)) {
 665       ResourceMark rm(THREAD);
 666       log_info(class, init)("[Initialized %s without side effects]", external_name());
 667     }
 668   }
 669 }
 670 
 671 
 672 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 673 // process. The step comments refers to the procedure described in that section.
 674 // Note: implementation moved to static method to expose the this pointer.
 675 void InstanceKlass::initialize(TRAPS) {
 676   if (this->should_be_initialized()) {
 677     initialize_impl(CHECK);
 678     // Note: at this point the class may be initialized
 679     //       OR it may be in the state of being initialized
 680     //       in case of recursive initialization!
 681   } else {
 682     assert(is_initialized(), "sanity check");
 683   }
 684 }
 685 
 686 
 687 bool InstanceKlass::verify_code(bool throw_verifyerror, TRAPS) {
 688   // 1) Verify the bytecodes
 689   Verifier::Mode mode =
 690     throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
 691   return Verifier::verify(this, mode, should_verify_class(), THREAD);
 692 }
 693 
 694 
 695 // Used exclusively by the shared spaces dump mechanism to prevent
 696 // classes mapped into the shared regions in new VMs from appearing linked.
 697 
 698 void InstanceKlass::unlink_class() {
 699   assert(is_linked(), "must be linked");
 700   _init_state = loaded;
 701 }
 702 
 703 void InstanceKlass::link_class(TRAPS) {
 704   assert(is_loaded(), "must be loaded");
 705   if (!is_linked()) {
 706     link_class_impl(true, CHECK);
 707   }
 708 }
 709 
 710 // Called to verify that a class can link during initialization, without
 711 // throwing a VerifyError.
 712 bool InstanceKlass::link_class_or_fail(TRAPS) {
 713   assert(is_loaded(), "must be loaded");
 714   if (!is_linked()) {
 715     link_class_impl(false, CHECK_false);
 716   }
 717   return is_linked();
 718 }
 719 
 720 bool InstanceKlass::link_class_impl(bool throw_verifyerror, TRAPS) {
 721   if (DumpSharedSpaces && is_in_error_state()) {
 722     // This is for CDS dumping phase only -- we use the in_error_state to indicate that
 723     // the class has failed verification. Throwing the NoClassDefFoundError here is just
 724     // a convenient way to stop repeat attempts to verify the same (bad) class.
 725     //
 726     // Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown
 727     // if we are executing Java code. This is not a problem for CDS dumping phase since
 728     // it doesn't execute any Java code.
 729     ResourceMark rm(THREAD);
 730     Exceptions::fthrow(THREAD_AND_LOCATION,
 731                        vmSymbols::java_lang_NoClassDefFoundError(),
 732                        "Class %s, or one of its supertypes, failed class initialization",
 733                        external_name());
 734     return false;
 735   }
 736   // return if already verified
 737   if (is_linked()) {
 738     return true;
 739   }
 740 
 741   // Timing
 742   // timer handles recursion
 743   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
 744   JavaThread* jt = (JavaThread*)THREAD;
 745 
 746   // link super class before linking this class
 747   Klass* super_klass = super();
 748   if (super_klass != NULL) {
 749     if (super_klass->is_interface()) {  // check if super class is an interface
 750       ResourceMark rm(THREAD);
 751       Exceptions::fthrow(
 752         THREAD_AND_LOCATION,
 753         vmSymbols::java_lang_IncompatibleClassChangeError(),
 754         "class %s has interface %s as super class",
 755         external_name(),
 756         super_klass->external_name()
 757       );
 758       return false;
 759     }
 760 
 761     InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
 762     ik_super->link_class_impl(throw_verifyerror, CHECK_false);
 763   }
 764 
 765   // link all interfaces implemented by this class before linking this class
 766   Array<InstanceKlass*>* interfaces = local_interfaces();
 767   int num_interfaces = interfaces->length();
 768   for (int index = 0; index < num_interfaces; index++) {
 769     InstanceKlass* interk = interfaces->at(index);
 770     interk->link_class_impl(throw_verifyerror, CHECK_false);
 771   }
 772 
 773   // in case the class is linked in the process of linking its superclasses
 774   if (is_linked()) {
 775     return true;
 776   }
 777 
 778   // trace only the link time for this klass that includes
 779   // the verification time
 780   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 781                              ClassLoader::perf_class_link_selftime(),
 782                              ClassLoader::perf_classes_linked(),
 783                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 784                              jt->get_thread_stat()->perf_timers_addr(),
 785                              PerfClassTraceTime::CLASS_LINK);
 786 
 787   // verification & rewriting
 788   {
 789     HandleMark hm(THREAD);
 790     Handle h_init_lock(THREAD, init_lock());
 791     ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
 792     // rewritten will have been set if loader constraint error found
 793     // on an earlier link attempt
 794     // don't verify or rewrite if already rewritten
 795     //
 796 
 797     if (!is_linked()) {
 798       if (!is_rewritten()) {
 799         {
 800           bool verify_ok = verify_code(throw_verifyerror, THREAD);
 801           if (!verify_ok) {
 802             return false;
 803           }
 804         }
 805 
 806         // Just in case a side-effect of verify linked this class already
 807         // (which can sometimes happen since the verifier loads classes
 808         // using custom class loaders, which are free to initialize things)
 809         if (is_linked()) {
 810           return true;
 811         }
 812 
 813         // also sets rewritten
 814         rewrite_class(CHECK_false);
 815       } else if (is_shared()) {
 816         SystemDictionaryShared::check_verification_constraints(this, CHECK_false);
 817       }
 818 
 819       // relocate jsrs and link methods after they are all rewritten
 820       link_methods(CHECK_false);
 821 
 822       // Initialize the vtable and interface table after
 823       // methods have been rewritten since rewrite may
 824       // fabricate new Method*s.
 825       // also does loader constraint checking
 826       //
 827       // initialize_vtable and initialize_itable need to be rerun for
 828       // a shared class if the class is not loaded by the NULL classloader.
 829       ClassLoaderData * loader_data = class_loader_data();
 830       if (!(is_shared() &&
 831             loader_data->is_the_null_class_loader_data())) {
 832         vtable().initialize_vtable(true, CHECK_false);
 833         itable().initialize_itable(true, CHECK_false);
 834       }
 835 #ifdef ASSERT
 836       else {
 837         vtable().verify(tty, true);
 838         // In case itable verification is ever added.
 839         // itable().verify(tty, true);
 840       }
 841 #endif
 842       set_init_state(linked);
 843       if (JvmtiExport::should_post_class_prepare()) {
 844         Thread *thread = THREAD;
 845         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 846         JvmtiExport::post_class_prepare((JavaThread *) thread, this);
 847       }
 848     }
 849   }
 850   return true;
 851 }
 852 
 853 // Rewrite the byte codes of all of the methods of a class.
 854 // The rewriter must be called exactly once. Rewriting must happen after
 855 // verification but before the first method of the class is executed.
 856 void InstanceKlass::rewrite_class(TRAPS) {
 857   assert(is_loaded(), "must be loaded");
 858   if (is_rewritten()) {
 859     assert(is_shared(), "rewriting an unshared class?");
 860     return;
 861   }
 862   Rewriter::rewrite(this, CHECK);
 863   set_rewritten();
 864 }
 865 
 866 // Now relocate and link method entry points after class is rewritten.
 867 // This is outside is_rewritten flag. In case of an exception, it can be
 868 // executed more than once.
 869 void InstanceKlass::link_methods(TRAPS) {
 870   int len = methods()->length();
 871   for (int i = len-1; i >= 0; i--) {
 872     methodHandle m(THREAD, methods()->at(i));
 873 
 874     // Set up method entry points for compiler and interpreter    .
 875     m->link_method(m, CHECK);
 876   }
 877 }
 878 
 879 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
 880 void InstanceKlass::initialize_super_interfaces(TRAPS) {
 881   assert (has_nonstatic_concrete_methods(), "caller should have checked this");
 882   for (int i = 0; i < local_interfaces()->length(); ++i) {
 883     InstanceKlass* ik = local_interfaces()->at(i);
 884 
 885     // Initialization is depth first search ie. we start with top of the inheritance tree
 886     // has_nonstatic_concrete_methods drives searching superinterfaces since it
 887     // means has_nonstatic_concrete_methods in its superinterface hierarchy
 888     if (ik->has_nonstatic_concrete_methods()) {
 889       ik->initialize_super_interfaces(CHECK);
 890     }
 891 
 892     // Only initialize() interfaces that "declare" concrete methods.
 893     if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) {
 894       ik->initialize(CHECK);
 895     }
 896   }
 897 }
 898 
 899 void InstanceKlass::initialize_impl(TRAPS) {
 900   HandleMark hm(THREAD);
 901 
 902   // Make sure klass is linked (verified) before initialization
 903   // A class could already be verified, since it has been reflected upon.
 904   link_class(CHECK);
 905 
 906   DTRACE_CLASSINIT_PROBE(required, -1);
 907 
 908   bool wait = false;
 909 
 910   // refer to the JVM book page 47 for description of steps
 911   // Step 1
 912   {
 913     Handle h_init_lock(THREAD, init_lock());
 914     ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
 915 
 916     Thread *self = THREAD; // it's passed the current thread
 917 
 918     // Step 2
 919     // If we were to use wait() instead of waitInterruptibly() then
 920     // we might end up throwing IE from link/symbol resolution sites
 921     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
 922     while(is_being_initialized() && !is_reentrant_initialization(self)) {
 923         wait = true;
 924       ol.waitUninterruptibly(CHECK);
 925     }
 926 
 927     // Step 3
 928     if (is_being_initialized() && is_reentrant_initialization(self)) {
 929       DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait);
 930       return;
 931     }
 932 
 933     // Step 4
 934     if (is_initialized()) {
 935       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait);
 936       return;
 937     }
 938 
 939     // Step 5
 940     if (is_in_error_state()) {
 941       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);
 942       ResourceMark rm(THREAD);
 943       const char* desc = "Could not initialize class ";
 944       const char* className = external_name();
 945       size_t msglen = strlen(desc) + strlen(className) + 1;
 946       char* message = NEW_RESOURCE_ARRAY(char, msglen);
 947       if (NULL == message) {
 948         // Out of memory: can't create detailed error message
 949           THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
 950       } else {
 951         jio_snprintf(message, msglen, "%s%s", desc, className);
 952           THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
 953       }
 954     }
 955 
 956     // Step 6
 957     set_init_state(being_initialized);
 958     set_init_thread(self);
 959   }
 960 
 961   // Step 7
 962   // Next, if C is a class rather than an interface, initialize it's super class and super
 963   // interfaces.
 964   if (!is_interface()) {
 965     Klass* super_klass = super();
 966     if (super_klass != NULL && super_klass->should_be_initialized()) {
 967       super_klass->initialize(THREAD);
 968     }
 969     // If C implements any interface that declares a non-static, concrete method,
 970     // the initialization of C triggers initialization of its super interfaces.
 971     // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
 972     // having a superinterface that declares, non-static, concrete methods
 973     if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
 974       initialize_super_interfaces(THREAD);
 975     }
 976 
 977     // If any exceptions, complete abruptly, throwing the same exception as above.
 978     if (HAS_PENDING_EXCEPTION) {
 979       Handle e(THREAD, PENDING_EXCEPTION);
 980       CLEAR_PENDING_EXCEPTION;
 981       {
 982         EXCEPTION_MARK;
 983         // Locks object, set state, and notify all waiting threads
 984         set_initialization_state_and_notify(initialization_error, THREAD);
 985         CLEAR_PENDING_EXCEPTION;
 986       }
 987       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
 988       THROW_OOP(e());
 989     }
 990   }
 991 
 992 
 993   // Look for aot compiled methods for this klass, including class initializer.
 994   AOTLoader::load_for_klass(this, THREAD);
 995 
 996   // Step 8
 997   {
 998     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
 999     JavaThread* jt = (JavaThread*)THREAD;
1000     DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1001     // Timer includes any side effects of class initialization (resolution,
1002     // etc), but not recursive entry into call_class_initializer().
1003     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1004                              ClassLoader::perf_class_init_selftime(),
1005                              ClassLoader::perf_classes_inited(),
1006                              jt->get_thread_stat()->perf_recursion_counts_addr(),
1007                              jt->get_thread_stat()->perf_timers_addr(),
1008                              PerfClassTraceTime::CLASS_CLINIT);
1009     call_class_initializer(THREAD);
1010   }
1011 
1012   // Step 9
1013   if (!HAS_PENDING_EXCEPTION) {
1014     set_initialization_state_and_notify(fully_initialized, CHECK);
1015     {
1016       debug_only(vtable().verify(tty, true);)
1017     }
1018   }
1019   else {
1020     // Step 10 and 11
1021     Handle e(THREAD, PENDING_EXCEPTION);
1022     CLEAR_PENDING_EXCEPTION;
1023     // JVMTI has already reported the pending exception
1024     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1025     JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
1026     {
1027       EXCEPTION_MARK;
1028       set_initialization_state_and_notify(initialization_error, THREAD);
1029       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1030       // JVMTI has already reported the pending exception
1031       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1032       JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
1033     }
1034     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1035     if (e->is_a(SystemDictionary::Error_klass())) {
1036       THROW_OOP(e());
1037     } else {
1038       JavaCallArguments args(e);
1039       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1040                 vmSymbols::throwable_void_signature(),
1041                 &args);
1042     }
1043   }
1044   DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1045 }
1046 
1047 
1048 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1049   Handle h_init_lock(THREAD, init_lock());
1050   if (h_init_lock() != NULL) {
1051     ObjectLocker ol(h_init_lock, THREAD);
1052     set_init_state(state);
1053     fence_and_clear_init_lock();
1054     ol.notify_all(CHECK);
1055   } else {
1056     assert(h_init_lock() != NULL, "The initialization state should never be set twice");
1057     set_init_state(state);
1058   }
1059 }
1060 
1061 Klass* InstanceKlass::implementor() const {
1062   assert_locked_or_safepoint(Compile_lock);
1063   Klass** k = adr_implementor();
1064   if (k == NULL) {
1065     return NULL;
1066   } else {
1067     return *k;
1068   }
1069 }
1070 
1071 void InstanceKlass::set_implementor(Klass* k) {
1072   assert_lock_strong(Compile_lock);
1073   assert(is_interface(), "not interface");
1074   Klass** addr = adr_implementor();
1075   assert(addr != NULL, "null addr");
1076   if (addr != NULL) {
1077     *addr = k;
1078   }
1079 }
1080 
1081 int  InstanceKlass::nof_implementors() const {
1082   assert_lock_strong(Compile_lock);
1083   Klass* k = implementor();
1084   if (k == NULL) {
1085     return 0;
1086   } else if (k != this) {
1087     return 1;
1088   } else {
1089     return 2;
1090   }
1091 }
1092 
1093 // The embedded _implementor field can only record one implementor.
1094 // When there are more than one implementors, the _implementor field
1095 // is set to the interface Klass* itself. Following are the possible
1096 // values for the _implementor field:
1097 //   NULL                  - no implementor
1098 //   implementor Klass*    - one implementor
1099 //   self                  - more than one implementor
1100 //
1101 // The _implementor field only exists for interfaces.
1102 void InstanceKlass::add_implementor(Klass* k) {
1103   assert_lock_strong(Compile_lock);
1104   assert(is_interface(), "not interface");
1105   // Filter out my subinterfaces.
1106   // (Note: Interfaces are never on the subklass list.)
1107   if (InstanceKlass::cast(k)->is_interface()) return;
1108 
1109   // Filter out subclasses whose supers already implement me.
1110   // (Note: CHA must walk subclasses of direct implementors
1111   // in order to locate indirect implementors.)
1112   Klass* sk = k->super();
1113   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
1114     // We only need to check one immediate superclass, since the
1115     // implements_interface query looks at transitive_interfaces.
1116     // Any supers of the super have the same (or fewer) transitive_interfaces.
1117     return;
1118 
1119   Klass* ik = implementor();
1120   if (ik == NULL) {
1121     set_implementor(k);
1122   } else if (ik != this) {
1123     // There is already an implementor. Use itself as an indicator of
1124     // more than one implementors.
1125     set_implementor(this);
1126   }
1127 
1128   // The implementor also implements the transitive_interfaces
1129   for (int index = 0; index < local_interfaces()->length(); index++) {
1130     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
1131   }
1132 }
1133 
1134 void InstanceKlass::init_implementor() {
1135   if (is_interface()) {
1136     set_implementor(NULL);
1137   }
1138 }
1139 
1140 
1141 void InstanceKlass::process_interfaces(Thread *thread) {
1142   // link this class into the implementors list of every interface it implements
1143   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
1144     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
1145     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
1146     assert(interf->is_interface(), "expected interface");
1147     interf->add_implementor(this);
1148   }
1149 }
1150 
1151 bool InstanceKlass::can_be_primary_super_slow() const {
1152   if (is_interface())
1153     return false;
1154   else
1155     return Klass::can_be_primary_super_slow();
1156 }
1157 
1158 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots,
1159                                                                Array<InstanceKlass*>* transitive_interfaces) {
1160   // The secondaries are the implemented interfaces.
1161   Array<InstanceKlass*>* interfaces = transitive_interfaces;
1162   int num_secondaries = num_extra_slots + interfaces->length();
1163   if (num_secondaries == 0) {
1164     // Must share this for correct bootstrapping!
1165     set_secondary_supers(Universe::the_empty_klass_array());
1166     return NULL;
1167   } else if (num_extra_slots == 0) {
1168     // The secondary super list is exactly the same as the transitive interfaces, so
1169     // let's use it instead of making a copy.
1170     // Redefine classes has to be careful not to delete this!
1171     // We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>,
1172     // (but it's safe to do here because we won't write into _secondary_supers from this point on).
1173     set_secondary_supers((Array<Klass*>*)(address)interfaces);
1174     return NULL;
1175   } else {
1176     // Copy transitive interfaces to a temporary growable array to be constructed
1177     // into the secondary super list with extra slots.
1178     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
1179     for (int i = 0; i < interfaces->length(); i++) {
1180       secondaries->push(interfaces->at(i));
1181     }
1182     return secondaries;
1183   }
1184 }
1185 
1186 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
1187   if (k->is_interface()) {
1188     return implements_interface(k);
1189   } else {
1190     return Klass::compute_is_subtype_of(k);
1191   }
1192 }
1193 
1194 bool InstanceKlass::implements_interface(Klass* k) const {
1195   if (this == k) return true;
1196   assert(k->is_interface(), "should be an interface class");
1197   for (int i = 0; i < transitive_interfaces()->length(); i++) {
1198     if (transitive_interfaces()->at(i) == k) {
1199       return true;
1200     }
1201   }
1202   return false;
1203 }
1204 
1205 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1206   // Verify direct super interface
1207   if (this == k) return true;
1208   assert(k->is_interface(), "should be an interface class");
1209   for (int i = 0; i < local_interfaces()->length(); i++) {
1210     if (local_interfaces()->at(i) == k) {
1211       return true;
1212     }
1213   }
1214   return false;
1215 }
1216 
1217 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
1218   if (length < 0)  {
1219     THROW_MSG_0(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", length));
1220   }
1221   if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
1222     report_java_out_of_memory("Requested array size exceeds VM limit");
1223     JvmtiExport::post_array_size_exhausted();
1224     THROW_OOP_0(Universe::out_of_memory_error_array_size());
1225   }
1226   int size = objArrayOopDesc::object_size(length);
1227   Klass* ak = array_klass(n, CHECK_NULL);
1228   objArrayOop o = (objArrayOop)Universe::heap()->array_allocate(ak, size, length,
1229                                                                 /* do_zero */ true, CHECK_NULL);
1230   return o;
1231 }
1232 
1233 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1234   if (TraceFinalizerRegistration) {
1235     tty->print("Registered ");
1236     i->print_value_on(tty);
1237     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", p2i(i));
1238   }
1239   instanceHandle h_i(THREAD, i);
1240   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1241   JavaValue result(T_VOID);
1242   JavaCallArguments args(h_i);
1243   methodHandle mh (THREAD, Universe::finalizer_register_method());
1244   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1245   return h_i();
1246 }
1247 
1248 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1249   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
1250   int size = size_helper();  // Query before forming handle.
1251 
1252   instanceOop i;
1253 
1254   i = (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1255   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
1256     i = register_finalizer(i, CHECK_NULL);
1257   }
1258   return i;
1259 }
1260 
1261 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1262   return instanceHandle(THREAD, allocate_instance(THREAD));
1263 }
1264 
1265 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1266   if (is_interface() || is_abstract()) {
1267     ResourceMark rm(THREAD);
1268     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1269               : vmSymbols::java_lang_InstantiationException(), external_name());
1270   }
1271   if (this == SystemDictionary::Class_klass()) {
1272     ResourceMark rm(THREAD);
1273     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1274               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1275   }
1276 }
1277 
1278 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
1279   // Need load-acquire for lock-free read
1280   if (array_klasses_acquire() == NULL) {
1281     if (or_null) return NULL;
1282 
1283     ResourceMark rm;
1284     JavaThread *jt = (JavaThread *)THREAD;
1285     {
1286       // Atomic creation of array_klasses
1287       MutexLocker mc(Compile_lock, THREAD);   // for vtables
1288       MutexLocker ma(MultiArray_lock, THREAD);
1289 
1290       // Check if update has already taken place
1291       if (array_klasses() == NULL) {
1292         Klass*    k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1293         // use 'release' to pair with lock-free load
1294         release_set_array_klasses(k);
1295       }
1296     }
1297   }
1298   // _this will always be set at this point
1299   ObjArrayKlass* oak = (ObjArrayKlass*)array_klasses();
1300   if (or_null) {
1301     return oak->array_klass_or_null(n);
1302   }
1303   return oak->array_klass(n, THREAD);
1304 }
1305 
1306 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
1307   return array_klass_impl(or_null, 1, THREAD);
1308 }
1309 
1310 static int call_class_initializer_counter = 0;   // for debugging
1311 
1312 Method* InstanceKlass::class_initializer() const {
1313   Method* clinit = find_method(
1314       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1315   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1316     return clinit;
1317   }
1318   return NULL;
1319 }
1320 
1321 void InstanceKlass::call_class_initializer(TRAPS) {
1322   if (ReplayCompiles &&
1323       (ReplaySuppressInitializers == 1 ||
1324        (ReplaySuppressInitializers >= 2 && class_loader() != NULL))) {
1325     // Hide the existence of the initializer for the purpose of replaying the compile
1326     return;
1327   }
1328 
1329   methodHandle h_method(THREAD, class_initializer());
1330   assert(!is_initialized(), "we cannot initialize twice");
1331   LogTarget(Info, class, init) lt;
1332   if (lt.is_enabled()) {
1333     ResourceMark rm;
1334     LogStream ls(lt);
1335     ls.print("%d Initializing ", call_class_initializer_counter++);
1336     name()->print_value_on(&ls);
1337     ls.print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this));
1338   }
1339   if (h_method() != NULL) {
1340     JavaCallArguments args; // No arguments
1341     JavaValue result(T_VOID);
1342     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1343   }
1344 }
1345 
1346 
1347 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1348   InterpreterOopMap* entry_for) {
1349   // Lazily create the _oop_map_cache at first request
1350   // Lock-free access requires load_acquire.
1351   OopMapCache* oop_map_cache = OrderAccess::load_acquire(&_oop_map_cache);
1352   if (oop_map_cache == NULL) {
1353     MutexLocker x(OopMapCacheAlloc_lock);
1354     // Check if _oop_map_cache was allocated while we were waiting for this lock
1355     if ((oop_map_cache = _oop_map_cache) == NULL) {
1356       oop_map_cache = new OopMapCache();
1357       // Ensure _oop_map_cache is stable, since it is examined without a lock
1358       OrderAccess::release_store(&_oop_map_cache, oop_map_cache);
1359     }
1360   }
1361   // _oop_map_cache is constant after init; lookup below does its own locking.
1362   oop_map_cache->lookup(method, bci, entry_for);
1363 }
1364 
1365 
1366 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1367   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1368     Symbol* f_name = fs.name();
1369     Symbol* f_sig  = fs.signature();
1370     if (f_name == name && f_sig == sig) {
1371       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1372       return true;
1373     }
1374   }
1375   return false;
1376 }
1377 
1378 
1379 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1380   const int n = local_interfaces()->length();
1381   for (int i = 0; i < n; i++) {
1382     Klass* intf1 = local_interfaces()->at(i);
1383     assert(intf1->is_interface(), "just checking type");
1384     // search for field in current interface
1385     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1386       assert(fd->is_static(), "interface field must be static");
1387       return intf1;
1388     }
1389     // search for field in direct superinterfaces
1390     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1391     if (intf2 != NULL) return intf2;
1392   }
1393   // otherwise field lookup fails
1394   return NULL;
1395 }
1396 
1397 
1398 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1399   // search order according to newest JVM spec (5.4.3.2, p.167).
1400   // 1) search for field in current klass
1401   if (find_local_field(name, sig, fd)) {
1402     return const_cast<InstanceKlass*>(this);
1403   }
1404   // 2) search for field recursively in direct superinterfaces
1405   { Klass* intf = find_interface_field(name, sig, fd);
1406     if (intf != NULL) return intf;
1407   }
1408   // 3) apply field lookup recursively if superclass exists
1409   { Klass* supr = super();
1410     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
1411   }
1412   // 4) otherwise field lookup fails
1413   return NULL;
1414 }
1415 
1416 
1417 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1418   // search order according to newest JVM spec (5.4.3.2, p.167).
1419   // 1) search for field in current klass
1420   if (find_local_field(name, sig, fd)) {
1421     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1422   }
1423   // 2) search for field recursively in direct superinterfaces
1424   if (is_static) {
1425     Klass* intf = find_interface_field(name, sig, fd);
1426     if (intf != NULL) return intf;
1427   }
1428   // 3) apply field lookup recursively if superclass exists
1429   { Klass* supr = super();
1430     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1431   }
1432   // 4) otherwise field lookup fails
1433   return NULL;
1434 }
1435 
1436 
1437 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1438   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1439     if (fs.offset() == offset) {
1440       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1441       if (fd->is_static() == is_static) return true;
1442     }
1443   }
1444   return false;
1445 }
1446 
1447 
1448 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1449   Klass* klass = const_cast<InstanceKlass*>(this);
1450   while (klass != NULL) {
1451     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1452       return true;
1453     }
1454     klass = klass->super();
1455   }
1456   return false;
1457 }
1458 
1459 
1460 void InstanceKlass::methods_do(void f(Method* method)) {
1461   // Methods aren't stable until they are loaded.  This can be read outside
1462   // a lock through the ClassLoaderData for profiling
1463   if (!is_loaded()) {
1464     return;
1465   }
1466 
1467   int len = methods()->length();
1468   for (int index = 0; index < len; index++) {
1469     Method* m = methods()->at(index);
1470     assert(m->is_method(), "must be method");
1471     f(m);
1472   }
1473 }
1474 
1475 
1476 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1477   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1478     if (fs.access_flags().is_static()) {
1479       fieldDescriptor& fd = fs.field_descriptor();
1480       cl->do_field(&fd);
1481     }
1482   }
1483 }
1484 
1485 
1486 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1487   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1488     if (fs.access_flags().is_static()) {
1489       fieldDescriptor& fd = fs.field_descriptor();
1490       f(&fd, mirror, CHECK);
1491     }
1492   }
1493 }
1494 
1495 
1496 static int compare_fields_by_offset(int* a, int* b) {
1497   return a[0] - b[0];
1498 }
1499 
1500 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1501   InstanceKlass* super = superklass();
1502   if (super != NULL) {
1503     super->do_nonstatic_fields(cl);
1504   }
1505   fieldDescriptor fd;
1506   int length = java_fields_count();
1507   // In DebugInfo nonstatic fields are sorted by offset.
1508   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1509   int j = 0;
1510   for (int i = 0; i < length; i += 1) {
1511     fd.reinitialize(this, i);
1512     if (!fd.is_static()) {
1513       fields_sorted[j + 0] = fd.offset();
1514       fields_sorted[j + 1] = i;
1515       j += 2;
1516     }
1517   }
1518   if (j > 0) {
1519     length = j;
1520     // _sort_Fn is defined in growableArray.hpp.
1521     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1522     for (int i = 0; i < length; i += 2) {
1523       fd.reinitialize(this, fields_sorted[i + 1]);
1524       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1525       cl->do_field(&fd);
1526     }
1527   }
1528   FREE_C_HEAP_ARRAY(int, fields_sorted);
1529 }
1530 
1531 
1532 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
1533   if (array_klasses() != NULL)
1534     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
1535 }
1536 
1537 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1538   if (array_klasses() != NULL)
1539     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1540 }
1541 
1542 #ifdef ASSERT
1543 static int linear_search(const Array<Method*>* methods,
1544                          const Symbol* name,
1545                          const Symbol* signature) {
1546   const int len = methods->length();
1547   for (int index = 0; index < len; index++) {
1548     const Method* const m = methods->at(index);
1549     assert(m->is_method(), "must be method");
1550     if (m->signature() == signature && m->name() == name) {
1551        return index;
1552     }
1553   }
1554   return -1;
1555 }
1556 #endif
1557 
1558 static int binary_search(const Array<Method*>* methods, const Symbol* name) {
1559   int len = methods->length();
1560   // methods are sorted, so do binary search
1561   int l = 0;
1562   int h = len - 1;
1563   while (l <= h) {
1564     int mid = (l + h) >> 1;
1565     Method* m = methods->at(mid);
1566     assert(m->is_method(), "must be method");
1567     int res = m->name()->fast_compare(name);
1568     if (res == 0) {
1569       return mid;
1570     } else if (res < 0) {
1571       l = mid + 1;
1572     } else {
1573       h = mid - 1;
1574     }
1575   }
1576   return -1;
1577 }
1578 
1579 // find_method looks up the name/signature in the local methods array
1580 Method* InstanceKlass::find_method(const Symbol* name,
1581                                    const Symbol* signature) const {
1582   return find_method_impl(name, signature, find_overpass, find_static, find_private);
1583 }
1584 
1585 Method* InstanceKlass::find_method_impl(const Symbol* name,
1586                                         const Symbol* signature,
1587                                         OverpassLookupMode overpass_mode,
1588                                         StaticLookupMode static_mode,
1589                                         PrivateLookupMode private_mode) const {
1590   return InstanceKlass::find_method_impl(methods(),
1591                                          name,
1592                                          signature,
1593                                          overpass_mode,
1594                                          static_mode,
1595                                          private_mode);
1596 }
1597 
1598 // find_instance_method looks up the name/signature in the local methods array
1599 // and skips over static methods
1600 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,
1601                                             const Symbol* name,
1602                                             const Symbol* signature,
1603                                             PrivateLookupMode private_mode) {
1604   Method* const meth = InstanceKlass::find_method_impl(methods,
1605                                                  name,
1606                                                  signature,
1607                                                  find_overpass,
1608                                                  skip_static,
1609                                                  private_mode);
1610   assert(((meth == NULL) || !meth->is_static()),
1611     "find_instance_method should have skipped statics");
1612   return meth;
1613 }
1614 
1615 // find_instance_method looks up the name/signature in the local methods array
1616 // and skips over static methods
1617 Method* InstanceKlass::find_instance_method(const Symbol* name,
1618                                             const Symbol* signature,
1619                                             PrivateLookupMode private_mode) const {
1620   return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);
1621 }
1622 
1623 // Find looks up the name/signature in the local methods array
1624 // and filters on the overpass, static and private flags
1625 // This returns the first one found
1626 // note that the local methods array can have up to one overpass, one static
1627 // and one instance (private or not) with the same name/signature
1628 Method* InstanceKlass::find_local_method(const Symbol* name,
1629                                          const Symbol* signature,
1630                                          OverpassLookupMode overpass_mode,
1631                                          StaticLookupMode static_mode,
1632                                          PrivateLookupMode private_mode) const {
1633   return InstanceKlass::find_method_impl(methods(),
1634                                          name,
1635                                          signature,
1636                                          overpass_mode,
1637                                          static_mode,
1638                                          private_mode);
1639 }
1640 
1641 // Find looks up the name/signature in the local methods array
1642 // and filters on the overpass, static and private flags
1643 // This returns the first one found
1644 // note that the local methods array can have up to one overpass, one static
1645 // and one instance (private or not) with the same name/signature
1646 Method* InstanceKlass::find_local_method(const Array<Method*>* methods,
1647                                          const Symbol* name,
1648                                          const Symbol* signature,
1649                                          OverpassLookupMode overpass_mode,
1650                                          StaticLookupMode static_mode,
1651                                          PrivateLookupMode private_mode) {
1652   return InstanceKlass::find_method_impl(methods,
1653                                          name,
1654                                          signature,
1655                                          overpass_mode,
1656                                          static_mode,
1657                                          private_mode);
1658 }
1659 
1660 Method* InstanceKlass::find_method(const Array<Method*>* methods,
1661                                    const Symbol* name,
1662                                    const Symbol* signature) {
1663   return InstanceKlass::find_method_impl(methods,
1664                                          name,
1665                                          signature,
1666                                          find_overpass,
1667                                          find_static,
1668                                          find_private);
1669 }
1670 
1671 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,
1672                                         const Symbol* name,
1673                                         const Symbol* signature,
1674                                         OverpassLookupMode overpass_mode,
1675                                         StaticLookupMode static_mode,
1676                                         PrivateLookupMode private_mode) {
1677   int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
1678   return hit >= 0 ? methods->at(hit): NULL;
1679 }
1680 
1681 // true if method matches signature and conforms to skipping_X conditions.
1682 static bool method_matches(const Method* m,
1683                            const Symbol* signature,
1684                            bool skipping_overpass,
1685                            bool skipping_static,
1686                            bool skipping_private) {
1687   return ((m->signature() == signature) &&
1688     (!skipping_overpass || !m->is_overpass()) &&
1689     (!skipping_static || !m->is_static()) &&
1690     (!skipping_private || !m->is_private()));
1691 }
1692 
1693 // Used directly for default_methods to find the index into the
1694 // default_vtable_indices, and indirectly by find_method
1695 // find_method_index looks in the local methods array to return the index
1696 // of the matching name/signature. If, overpass methods are being ignored,
1697 // the search continues to find a potential non-overpass match.  This capability
1698 // is important during method resolution to prefer a static method, for example,
1699 // over an overpass method.
1700 // There is the possibility in any _method's array to have the same name/signature
1701 // for a static method, an overpass method and a local instance method
1702 // To correctly catch a given method, the search criteria may need
1703 // to explicitly skip the other two. For local instance methods, it
1704 // is often necessary to skip private methods
1705 int InstanceKlass::find_method_index(const Array<Method*>* methods,
1706                                      const Symbol* name,
1707                                      const Symbol* signature,
1708                                      OverpassLookupMode overpass_mode,
1709                                      StaticLookupMode static_mode,
1710                                      PrivateLookupMode private_mode) {
1711   const bool skipping_overpass = (overpass_mode == skip_overpass);
1712   const bool skipping_static = (static_mode == skip_static);
1713   const bool skipping_private = (private_mode == skip_private);
1714   const int hit = binary_search(methods, name);
1715   if (hit != -1) {
1716     const Method* const m = methods->at(hit);
1717 
1718     // Do linear search to find matching signature.  First, quick check
1719     // for common case, ignoring overpasses if requested.
1720     if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1721       return hit;
1722     }
1723 
1724     // search downwards through overloaded methods
1725     int i;
1726     for (i = hit - 1; i >= 0; --i) {
1727         const Method* const m = methods->at(i);
1728         assert(m->is_method(), "must be method");
1729         if (m->name() != name) {
1730           break;
1731         }
1732         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1733           return i;
1734         }
1735     }
1736     // search upwards
1737     for (i = hit + 1; i < methods->length(); ++i) {
1738         const Method* const m = methods->at(i);
1739         assert(m->is_method(), "must be method");
1740         if (m->name() != name) {
1741           break;
1742         }
1743         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1744           return i;
1745         }
1746     }
1747     // not found
1748 #ifdef ASSERT
1749     const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :
1750       linear_search(methods, name, signature);
1751     assert(-1 == index, "binary search should have found entry %d", index);
1752 #endif
1753   }
1754   return -1;
1755 }
1756 
1757 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {
1758   return find_method_by_name(methods(), name, end);
1759 }
1760 
1761 int InstanceKlass::find_method_by_name(const Array<Method*>* methods,
1762                                        const Symbol* name,
1763                                        int* end_ptr) {
1764   assert(end_ptr != NULL, "just checking");
1765   int start = binary_search(methods, name);
1766   int end = start + 1;
1767   if (start != -1) {
1768     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1769     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1770     *end_ptr = end;
1771     return start;
1772   }
1773   return -1;
1774 }
1775 
1776 // uncached_lookup_method searches both the local class methods array and all
1777 // superclasses methods arrays, skipping any overpass methods in superclasses,
1778 // and possibly skipping private methods.
1779 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
1780                                               const Symbol* signature,
1781                                               OverpassLookupMode overpass_mode,
1782                                               PrivateLookupMode private_mode) const {
1783   OverpassLookupMode overpass_local_mode = overpass_mode;
1784   const Klass* klass = this;
1785   while (klass != NULL) {
1786     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
1787                                                                         signature,
1788                                                                         overpass_local_mode,
1789                                                                         find_static,
1790                                                                         private_mode);
1791     if (method != NULL) {
1792       return method;
1793     }
1794     klass = klass->super();
1795     overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1796   }
1797   return NULL;
1798 }
1799 
1800 #ifdef ASSERT
1801 // search through class hierarchy and return true if this class or
1802 // one of the superclasses was redefined
1803 bool InstanceKlass::has_redefined_this_or_super() const {
1804   const Klass* klass = this;
1805   while (klass != NULL) {
1806     if (InstanceKlass::cast(klass)->has_been_redefined()) {
1807       return true;
1808     }
1809     klass = klass->super();
1810   }
1811   return false;
1812 }
1813 #endif
1814 
1815 // lookup a method in the default methods list then in all transitive interfaces
1816 // Do NOT return private or static methods
1817 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
1818                                                          Symbol* signature) const {
1819   Method* m = NULL;
1820   if (default_methods() != NULL) {
1821     m = find_method(default_methods(), name, signature);
1822   }
1823   // Look up interfaces
1824   if (m == NULL) {
1825     m = lookup_method_in_all_interfaces(name, signature, find_defaults);
1826   }
1827   return m;
1828 }
1829 
1830 // lookup a method in all the interfaces that this class implements
1831 // Do NOT return private or static methods, new in JDK8 which are not externally visible
1832 // They should only be found in the initial InterfaceMethodRef
1833 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1834                                                        Symbol* signature,
1835                                                        DefaultsLookupMode defaults_mode) const {
1836   Array<InstanceKlass*>* all_ifs = transitive_interfaces();
1837   int num_ifs = all_ifs->length();
1838   InstanceKlass *ik = NULL;
1839   for (int i = 0; i < num_ifs; i++) {
1840     ik = all_ifs->at(i);
1841     Method* m = ik->lookup_method(name, signature);
1842     if (m != NULL && m->is_public() && !m->is_static() &&
1843         ((defaults_mode != skip_defaults) || !m->is_default_method())) {
1844       return m;
1845     }
1846   }
1847   return NULL;
1848 }
1849 
1850 /* jni_id_for_impl for jfieldIds only */
1851 JNIid* InstanceKlass::jni_id_for_impl(int offset) {
1852   MutexLocker ml(JfieldIdCreation_lock);
1853   // Retry lookup after we got the lock
1854   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1855   if (probe == NULL) {
1856     // Slow case, allocate new static field identifier
1857     probe = new JNIid(this, offset, jni_ids());
1858     set_jni_ids(probe);
1859   }
1860   return probe;
1861 }
1862 
1863 
1864 /* jni_id_for for jfieldIds only */
1865 JNIid* InstanceKlass::jni_id_for(int offset) {
1866   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1867   if (probe == NULL) {
1868     probe = jni_id_for_impl(offset);
1869   }
1870   return probe;
1871 }
1872 
1873 u2 InstanceKlass::enclosing_method_data(int offset) const {
1874   const Array<jushort>* const inner_class_list = inner_classes();
1875   if (inner_class_list == NULL) {
1876     return 0;
1877   }
1878   const int length = inner_class_list->length();
1879   if (length % inner_class_next_offset == 0) {
1880     return 0;
1881   }
1882   const int index = length - enclosing_method_attribute_size;
1883   assert(offset < enclosing_method_attribute_size, "invalid offset");
1884   return inner_class_list->at(index + offset);
1885 }
1886 
1887 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
1888                                                  u2 method_index) {
1889   Array<jushort>* inner_class_list = inner_classes();
1890   assert (inner_class_list != NULL, "_inner_classes list is not set up");
1891   int length = inner_class_list->length();
1892   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
1893     int index = length - enclosing_method_attribute_size;
1894     inner_class_list->at_put(
1895       index + enclosing_method_class_index_offset, class_index);
1896     inner_class_list->at_put(
1897       index + enclosing_method_method_index_offset, method_index);
1898   }
1899 }
1900 
1901 // Lookup or create a jmethodID.
1902 // This code is called by the VMThread and JavaThreads so the
1903 // locking has to be done very carefully to avoid deadlocks
1904 // and/or other cache consistency problems.
1905 //
1906 jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) {
1907   size_t idnum = (size_t)method_h->method_idnum();
1908   jmethodID* jmeths = methods_jmethod_ids_acquire();
1909   size_t length = 0;
1910   jmethodID id = NULL;
1911 
1912   // We use a double-check locking idiom here because this cache is
1913   // performance sensitive. In the normal system, this cache only
1914   // transitions from NULL to non-NULL which is safe because we use
1915   // release_set_methods_jmethod_ids() to advertise the new cache.
1916   // A partially constructed cache should never be seen by a racing
1917   // thread. We also use release_store() to save a new jmethodID
1918   // in the cache so a partially constructed jmethodID should never be
1919   // seen either. Cache reads of existing jmethodIDs proceed without a
1920   // lock, but cache writes of a new jmethodID requires uniqueness and
1921   // creation of the cache itself requires no leaks so a lock is
1922   // generally acquired in those two cases.
1923   //
1924   // If the RedefineClasses() API has been used, then this cache can
1925   // grow and we'll have transitions from non-NULL to bigger non-NULL.
1926   // Cache creation requires no leaks and we require safety between all
1927   // cache accesses and freeing of the old cache so a lock is generally
1928   // acquired when the RedefineClasses() API has been used.
1929 
1930   if (jmeths != NULL) {
1931     // the cache already exists
1932     if (!idnum_can_increment()) {
1933       // the cache can't grow so we can just get the current values
1934       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1935     } else {
1936       // cache can grow so we have to be more careful
1937       if (Threads::number_of_threads() == 0 ||
1938           SafepointSynchronize::is_at_safepoint()) {
1939         // we're single threaded or at a safepoint - no locking needed
1940         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1941       } else {
1942         MutexLocker ml(JmethodIdCreation_lock);
1943         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1944       }
1945     }
1946   }
1947   // implied else:
1948   // we need to allocate a cache so default length and id values are good
1949 
1950   if (jmeths == NULL ||   // no cache yet
1951       length <= idnum ||  // cache is too short
1952       id == NULL) {       // cache doesn't contain entry
1953 
1954     // This function can be called by the VMThread so we have to do all
1955     // things that might block on a safepoint before grabbing the lock.
1956     // Otherwise, we can deadlock with the VMThread or have a cache
1957     // consistency issue. These vars keep track of what we might have
1958     // to free after the lock is dropped.
1959     jmethodID  to_dealloc_id     = NULL;
1960     jmethodID* to_dealloc_jmeths = NULL;
1961 
1962     // may not allocate new_jmeths or use it if we allocate it
1963     jmethodID* new_jmeths = NULL;
1964     if (length <= idnum) {
1965       // allocate a new cache that might be used
1966       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
1967       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
1968       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1969       // cache size is stored in element[0], other elements offset by one
1970       new_jmeths[0] = (jmethodID)size;
1971     }
1972 
1973     // allocate a new jmethodID that might be used
1974     jmethodID new_id = NULL;
1975     if (method_h->is_old() && !method_h->is_obsolete()) {
1976       // The method passed in is old (but not obsolete), we need to use the current version
1977       Method* current_method = method_with_idnum((int)idnum);
1978       assert(current_method != NULL, "old and but not obsolete, so should exist");
1979       new_id = Method::make_jmethod_id(class_loader_data(), current_method);
1980     } else {
1981       // It is the current version of the method or an obsolete method,
1982       // use the version passed in
1983       new_id = Method::make_jmethod_id(class_loader_data(), method_h());
1984     }
1985 
1986     if (Threads::number_of_threads() == 0 ||
1987         SafepointSynchronize::is_at_safepoint()) {
1988       // we're single threaded or at a safepoint - no locking needed
1989       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
1990                                           &to_dealloc_id, &to_dealloc_jmeths);
1991     } else {
1992       MutexLocker ml(JmethodIdCreation_lock);
1993       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
1994                                           &to_dealloc_id, &to_dealloc_jmeths);
1995     }
1996 
1997     // The lock has been dropped so we can free resources.
1998     // Free up either the old cache or the new cache if we allocated one.
1999     if (to_dealloc_jmeths != NULL) {
2000       FreeHeap(to_dealloc_jmeths);
2001     }
2002     // free up the new ID since it wasn't needed
2003     if (to_dealloc_id != NULL) {
2004       Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id);
2005     }
2006   }
2007   return id;
2008 }
2009 
2010 // Figure out how many jmethodIDs haven't been allocated, and make
2011 // sure space for them is pre-allocated.  This makes getting all
2012 // method ids much, much faster with classes with more than 8
2013 // methods, and has a *substantial* effect on performance with jvmti
2014 // code that loads all jmethodIDs for all classes.
2015 void InstanceKlass::ensure_space_for_methodids(int start_offset) {
2016   int new_jmeths = 0;
2017   int length = methods()->length();
2018   for (int index = start_offset; index < length; index++) {
2019     Method* m = methods()->at(index);
2020     jmethodID id = m->find_jmethod_id_or_null();
2021     if (id == NULL) {
2022       new_jmeths++;
2023     }
2024   }
2025   if (new_jmeths != 0) {
2026     Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2027   }
2028 }
2029 
2030 // Common code to fetch the jmethodID from the cache or update the
2031 // cache with the new jmethodID. This function should never do anything
2032 // that causes the caller to go to a safepoint or we can deadlock with
2033 // the VMThread or have cache consistency issues.
2034 //
2035 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
2036             size_t idnum, jmethodID new_id,
2037             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
2038             jmethodID** to_dealloc_jmeths_p) {
2039   assert(new_id != NULL, "sanity check");
2040   assert(to_dealloc_id_p != NULL, "sanity check");
2041   assert(to_dealloc_jmeths_p != NULL, "sanity check");
2042   assert(Threads::number_of_threads() == 0 ||
2043          SafepointSynchronize::is_at_safepoint() ||
2044          JmethodIdCreation_lock->owned_by_self(), "sanity check");
2045 
2046   // reacquire the cache - we are locked, single threaded or at a safepoint
2047   jmethodID* jmeths = methods_jmethod_ids_acquire();
2048   jmethodID  id     = NULL;
2049   size_t     length = 0;
2050 
2051   if (jmeths == NULL ||                         // no cache yet
2052       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
2053     if (jmeths != NULL) {
2054       // copy any existing entries from the old cache
2055       for (size_t index = 0; index < length; index++) {
2056         new_jmeths[index+1] = jmeths[index+1];
2057       }
2058       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
2059     }
2060     release_set_methods_jmethod_ids(jmeths = new_jmeths);
2061   } else {
2062     // fetch jmethodID (if any) from the existing cache
2063     id = jmeths[idnum+1];
2064     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
2065   }
2066   if (id == NULL) {
2067     // No matching jmethodID in the existing cache or we have a new
2068     // cache or we just grew the cache. This cache write is done here
2069     // by the first thread to win the foot race because a jmethodID
2070     // needs to be unique once it is generally available.
2071     id = new_id;
2072 
2073     // The jmethodID cache can be read while unlocked so we have to
2074     // make sure the new jmethodID is complete before installing it
2075     // in the cache.
2076     OrderAccess::release_store(&jmeths[idnum+1], id);
2077   } else {
2078     *to_dealloc_id_p = new_id; // save new id for later delete
2079   }
2080   return id;
2081 }
2082 
2083 
2084 // Common code to get the jmethodID cache length and the jmethodID
2085 // value at index idnum if there is one.
2086 //
2087 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
2088        size_t idnum, size_t *length_p, jmethodID* id_p) {
2089   assert(cache != NULL, "sanity check");
2090   assert(length_p != NULL, "sanity check");
2091   assert(id_p != NULL, "sanity check");
2092 
2093   // cache size is stored in element[0], other elements offset by one
2094   *length_p = (size_t)cache[0];
2095   if (*length_p <= idnum) {  // cache is too short
2096     *id_p = NULL;
2097   } else {
2098     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
2099   }
2100 }
2101 
2102 
2103 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
2104 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2105   size_t idnum = (size_t)method->method_idnum();
2106   jmethodID* jmeths = methods_jmethod_ids_acquire();
2107   size_t length;                                // length assigned as debugging crumb
2108   jmethodID id = NULL;
2109   if (jmeths != NULL &&                         // If there is a cache
2110       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
2111     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
2112   }
2113   return id;
2114 }
2115 
2116 inline DependencyContext InstanceKlass::dependencies() {
2117   DependencyContext dep_context(&_dep_context);
2118   return dep_context;
2119 }
2120 
2121 int InstanceKlass::mark_dependent_nmethods(KlassDepChange& changes) {
2122   return dependencies().mark_dependent_nmethods(changes);
2123 }
2124 
2125 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2126   dependencies().add_dependent_nmethod(nm);
2127 }
2128 
2129 void InstanceKlass::remove_dependent_nmethod(nmethod* nm, bool delete_immediately) {
2130   dependencies().remove_dependent_nmethod(nm, delete_immediately);
2131 }
2132 
2133 #ifndef PRODUCT
2134 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2135   dependencies().print_dependent_nmethods(verbose);
2136 }
2137 
2138 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2139   return dependencies().is_dependent_nmethod(nm);
2140 }
2141 #endif //PRODUCT
2142 
2143 void InstanceKlass::clean_weak_instanceklass_links() {
2144   clean_implementors_list();
2145   clean_method_data();
2146 
2147   // Since GC iterates InstanceKlasses sequentially, it is safe to remove stale entries here.
2148   DependencyContext dep_context(&_dep_context);
2149   dep_context.expunge_stale_entries();
2150 }
2151 
2152 void InstanceKlass::clean_implementors_list() {
2153   assert(is_loader_alive(), "this klass should be live");
2154   if (is_interface()) {
2155     if (ClassUnloading) {
2156       Klass* impl = implementor();
2157       if (impl != NULL) {
2158         if (!impl->is_loader_alive()) {
2159           // remove this guy
2160           Klass** klass = adr_implementor();
2161           assert(klass != NULL, "null klass");
2162           if (klass != NULL) {
2163             *klass = NULL;
2164           }
2165         }
2166       }
2167     }
2168   }
2169 }
2170 
2171 void InstanceKlass::clean_method_data() {
2172   for (int m = 0; m < methods()->length(); m++) {
2173     MethodData* mdo = methods()->at(m)->method_data();
2174     if (mdo != NULL) {
2175       mdo->clean_method_data(/*always_clean*/false);
2176     }
2177   }
2178 }
2179 
2180 bool InstanceKlass::supers_have_passed_fingerprint_checks() {
2181   if (java_super() != NULL && !java_super()->has_passed_fingerprint_check()) {
2182     ResourceMark rm;
2183     log_trace(class, fingerprint)("%s : super %s not fingerprinted", external_name(), java_super()->external_name());
2184     return false;
2185   }
2186 
2187   Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
2188   if (local_interfaces != NULL) {
2189     int length = local_interfaces->length();
2190     for (int i = 0; i < length; i++) {
2191       InstanceKlass* intf = local_interfaces->at(i);
2192       if (!intf->has_passed_fingerprint_check()) {
2193         ResourceMark rm;
2194         log_trace(class, fingerprint)("%s : interface %s not fingerprinted", external_name(), intf->external_name());
2195         return false;
2196       }
2197     }
2198   }
2199 
2200   return true;
2201 }
2202 
2203 bool InstanceKlass::should_store_fingerprint(bool is_unsafe_anonymous) {
2204 #if INCLUDE_AOT
2205   // We store the fingerprint into the InstanceKlass only in the following 2 cases:
2206   if (CalculateClassFingerprint) {
2207     // (1) We are running AOT to generate a shared library.
2208     return true;
2209   }
2210   if (DumpSharedSpaces) {
2211     // (2) We are running -Xshare:dump to create a shared archive
2212     return true;
2213   }
2214   if (UseAOT && is_unsafe_anonymous) {
2215     // (3) We are using AOT code from a shared library and see an unsafe anonymous class
2216     return true;
2217   }
2218 #endif
2219 
2220   // In all other cases we might set the _misc_has_passed_fingerprint_check bit,
2221   // but do not store the 64-bit fingerprint to save space.
2222   return false;
2223 }
2224 
2225 bool InstanceKlass::has_stored_fingerprint() const {
2226 #if INCLUDE_AOT
2227   return should_store_fingerprint() || is_shared();
2228 #else
2229   return false;
2230 #endif
2231 }
2232 
2233 uint64_t InstanceKlass::get_stored_fingerprint() const {
2234   address adr = adr_fingerprint();
2235   if (adr != NULL) {
2236     return (uint64_t)Bytes::get_native_u8(adr); // adr may not be 64-bit aligned
2237   }
2238   return 0;
2239 }
2240 
2241 void InstanceKlass::store_fingerprint(uint64_t fingerprint) {
2242   address adr = adr_fingerprint();
2243   if (adr != NULL) {
2244     Bytes::put_native_u8(adr, (u8)fingerprint); // adr may not be 64-bit aligned
2245 
2246     ResourceMark rm;
2247     log_trace(class, fingerprint)("stored as " PTR64_FORMAT " for class %s", fingerprint, external_name());
2248   }
2249 }
2250 
2251 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {
2252   Klass::metaspace_pointers_do(it);
2253 
2254   if (log_is_enabled(Trace, cds)) {
2255     ResourceMark rm;
2256     log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name());
2257   }
2258 
2259   it->push(&_annotations);
2260   it->push((Klass**)&_array_klasses);
2261   it->push(&_constants);
2262   it->push(&_inner_classes);
2263   it->push(&_array_name);
2264 #if INCLUDE_JVMTI
2265   it->push(&_previous_versions);
2266 #endif
2267   it->push(&_methods);
2268   it->push(&_default_methods);
2269   it->push(&_local_interfaces);
2270   it->push(&_transitive_interfaces);
2271   it->push(&_method_ordering);
2272   it->push(&_default_vtable_indices);
2273   it->push(&_fields);
2274 
2275   if (itable_length() > 0) {
2276     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2277     int method_table_offset_in_words = ioe->offset()/wordSize;
2278     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2279                          / itableOffsetEntry::size();
2280 
2281     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2282       if (ioe->interface_klass() != NULL) {
2283         it->push(ioe->interface_klass_addr());
2284         itableMethodEntry* ime = ioe->first_method_entry(this);
2285         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2286         for (int index = 0; index < n; index ++) {
2287           it->push(ime[index].method_addr());
2288         }
2289       }
2290     }
2291   }
2292 
2293   it->push(&_nest_members);
2294 }
2295 
2296 void InstanceKlass::remove_unshareable_info() {
2297   Klass::remove_unshareable_info();
2298 
2299   if (is_in_error_state()) {
2300     // Classes are attempted to link during dumping and may fail,
2301     // but these classes are still in the dictionary and class list in CLD.
2302     // Check in_error state first because in_error is > linked state, so
2303     // is_linked() is true.
2304     // If there's a linking error, there is nothing else to remove.
2305     return;
2306   }
2307 
2308   // Unlink the class
2309   if (is_linked()) {
2310     unlink_class();
2311   }
2312   {
2313     MutexLocker ml(Compile_lock);
2314     init_implementor();
2315   }
2316 
2317   constants()->remove_unshareable_info();
2318 
2319   for (int i = 0; i < methods()->length(); i++) {
2320     Method* m = methods()->at(i);
2321     m->remove_unshareable_info();
2322   }
2323 
2324   // do array classes also.
2325   if (array_klasses() != NULL) {
2326     array_klasses()->remove_unshareable_info();
2327   }
2328 
2329   // These are not allocated from metaspace, but they should should all be empty
2330   // during dump time, so we don't need to worry about them in InstanceKlass::iterate().
2331   guarantee(_source_debug_extension == NULL, "must be");
2332   guarantee(_dep_context == DependencyContext::EMPTY, "must be");
2333   guarantee(_osr_nmethods_head == NULL, "must be");
2334 
2335 #if INCLUDE_JVMTI
2336   guarantee(_breakpoints == NULL, "must be");
2337   guarantee(_previous_versions == NULL, "must be");
2338 #endif
2339 
2340   _init_thread = NULL;
2341   _methods_jmethod_ids = NULL;
2342   _jni_ids = NULL;
2343   _oop_map_cache = NULL;
2344   // clear _nest_host to ensure re-load at runtime
2345   _nest_host = NULL;
2346 }
2347 
2348 void InstanceKlass::remove_java_mirror() {
2349   Klass::remove_java_mirror();
2350 
2351   // do array classes also.
2352   if (array_klasses() != NULL) {
2353     array_klasses()->remove_java_mirror();
2354   }
2355 }
2356 
2357 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
2358   set_package(loader_data, CHECK);
2359   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2360 
2361   Array<Method*>* methods = this->methods();
2362   int num_methods = methods->length();
2363   for (int index2 = 0; index2 < num_methods; ++index2) {
2364     methodHandle m(THREAD, methods->at(index2));
2365     m->restore_unshareable_info(CHECK);
2366   }
2367   if (JvmtiExport::has_redefined_a_class()) {
2368     // Reinitialize vtable because RedefineClasses may have changed some
2369     // entries in this vtable for super classes so the CDS vtable might
2370     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2371     // vtables in the shared system dictionary, only the main one.
2372     // It also redefines the itable too so fix that too.
2373     vtable().initialize_vtable(false, CHECK);
2374     itable().initialize_itable(false, CHECK);
2375   }
2376 
2377   // restore constant pool resolved references
2378   constants()->restore_unshareable_info(CHECK);
2379 
2380   if (array_klasses() != NULL) {
2381     // Array classes have null protection domain.
2382     // --> see ArrayKlass::complete_create_array_klass()
2383     array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2384   }
2385 }
2386 
2387 // returns true IFF is_in_error_state() has been changed as a result of this call.
2388 bool InstanceKlass::check_sharing_error_state() {
2389   assert(DumpSharedSpaces, "should only be called during dumping");
2390   bool old_state = is_in_error_state();
2391 
2392   if (!is_in_error_state()) {
2393     bool bad = false;
2394     for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
2395       if (sup->is_in_error_state()) {
2396         bad = true;
2397         break;
2398       }
2399     }
2400     if (!bad) {
2401       Array<InstanceKlass*>* interfaces = transitive_interfaces();
2402       for (int i = 0; i < interfaces->length(); i++) {
2403         InstanceKlass* iface = interfaces->at(i);
2404         if (iface->is_in_error_state()) {
2405           bad = true;
2406           break;
2407         }
2408       }
2409     }
2410 
2411     if (bad) {
2412       set_in_error_state();
2413     }
2414   }
2415 
2416   return (old_state != is_in_error_state());
2417 }
2418 
2419 #if INCLUDE_JVMTI
2420 static void clear_all_breakpoints(Method* m) {
2421   m->clear_all_breakpoints();
2422 }
2423 #endif
2424 
2425 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
2426   // notify the debugger
2427   if (JvmtiExport::should_post_class_unload()) {
2428     JvmtiExport::post_class_unload(ik);
2429   }
2430 
2431   // notify ClassLoadingService of class unload
2432   ClassLoadingService::notify_class_unloaded(ik);
2433 
2434 #if INCLUDE_JFR
2435   if (Jfr::is_enabled()) {
2436     assert(ik != NULL, "invariant");
2437     EventClassUnload event(UNTIMED);
2438     event.set_endtime(class_unload_time());
2439     event.set_unloadedClass(ik);
2440     event.set_definingClassLoader(ik->class_loader_data());
2441     event.commit();
2442   }
2443 #endif
2444 
2445 }
2446 
2447 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
2448   // Clean up C heap
2449   ik->release_C_heap_structures();
2450   ik->constants()->release_C_heap_structures();
2451 }
2452 
2453 void InstanceKlass::release_C_heap_structures() {
2454   // Can't release the constant pool here because the constant pool can be
2455   // deallocated separately from the InstanceKlass for default methods and
2456   // redefine classes.
2457 
2458   // Deallocate oop map cache
2459   if (_oop_map_cache != NULL) {
2460     delete _oop_map_cache;
2461     _oop_map_cache = NULL;
2462   }
2463 
2464   // Deallocate JNI identifiers for jfieldIDs
2465   JNIid::deallocate(jni_ids());
2466   set_jni_ids(NULL);
2467 
2468   jmethodID* jmeths = methods_jmethod_ids_acquire();
2469   if (jmeths != (jmethodID*)NULL) {
2470     release_set_methods_jmethod_ids(NULL);
2471     FreeHeap(jmeths);
2472   }
2473 
2474   // Release dependencies.
2475   // It is desirable to use DC::remove_all_dependents() here, but, unfortunately,
2476   // it is not safe (see JDK-8143408). The problem is that the klass dependency
2477   // context can contain live dependencies, since there's a race between nmethod &
2478   // klass unloading. If the klass is dead when nmethod unloading happens, relevant
2479   // dependencies aren't removed from the context associated with the class (see
2480   // nmethod::flush_dependencies). It ends up during klass unloading as seemingly
2481   // live dependencies pointing to unloaded nmethods and causes a crash in
2482   // DC::remove_all_dependents() when it touches unloaded nmethod.
2483   dependencies().wipe();
2484 
2485 #if INCLUDE_JVMTI
2486   // Deallocate breakpoint records
2487   if (breakpoints() != 0x0) {
2488     methods_do(clear_all_breakpoints);
2489     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2490   }
2491 
2492   // deallocate the cached class file
2493   if (_cached_class_file != NULL && !MetaspaceShared::is_in_shared_metaspace(_cached_class_file)) {
2494     os::free(_cached_class_file);
2495     _cached_class_file = NULL;
2496   }
2497 #endif
2498 
2499   // Decrement symbol reference counts associated with the unloaded class.
2500   if (_name != NULL) _name->decrement_refcount();
2501   // unreference array name derived from this class name (arrays of an unloaded
2502   // class can't be referenced anymore).
2503   if (_array_name != NULL)  _array_name->decrement_refcount();
2504   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension);
2505 }
2506 
2507 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
2508   if (array == NULL) {
2509     _source_debug_extension = NULL;
2510   } else {
2511     // Adding one to the attribute length in order to store a null terminator
2512     // character could cause an overflow because the attribute length is
2513     // already coded with an u4 in the classfile, but in practice, it's
2514     // unlikely to happen.
2515     assert((length+1) > length, "Overflow checking");
2516     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2517     for (int i = 0; i < length; i++) {
2518       sde[i] = array[i];
2519     }
2520     sde[length] = '\0';
2521     _source_debug_extension = sde;
2522   }
2523 }
2524 
2525 const char* InstanceKlass::signature_name() const {
2526   int hash_len = 0;
2527   char hash_buf[40];
2528 
2529   // If this is an unsafe anonymous class, append a hash to make the name unique
2530   if (is_unsafe_anonymous()) {
2531     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2532     jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash);
2533     hash_len = (int)strlen(hash_buf);
2534   }
2535 
2536   // Get the internal name as a c string
2537   const char* src = (const char*) (name()->as_C_string());
2538   const int src_length = (int)strlen(src);
2539 
2540   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2541 
2542   // Add L as type indicator
2543   int dest_index = 0;
2544   dest[dest_index++] = 'L';
2545 
2546   // Add the actual class name
2547   for (int src_index = 0; src_index < src_length; ) {
2548     dest[dest_index++] = src[src_index++];
2549   }
2550 
2551   // If we have a hash, append it
2552   for (int hash_index = 0; hash_index < hash_len; ) {
2553     dest[dest_index++] = hash_buf[hash_index++];
2554   }
2555 
2556   // Add the semicolon and the NULL
2557   dest[dest_index++] = ';';
2558   dest[dest_index] = '\0';
2559   return dest;
2560 }
2561 
2562 // Used to obtain the package name from a fully qualified class name.
2563 Symbol* InstanceKlass::package_from_name(const Symbol* name, TRAPS) {
2564   if (name == NULL) {
2565     return NULL;
2566   } else {
2567     if (name->utf8_length() <= 0) {
2568       return NULL;
2569     }
2570     ResourceMark rm;
2571     const char* package_name = ClassLoader::package_from_name((const char*) name->as_C_string());
2572     if (package_name == NULL) {
2573       return NULL;
2574     }
2575     Symbol* pkg_name = SymbolTable::new_symbol(package_name, THREAD);
2576     return pkg_name;
2577   }
2578 }
2579 
2580 ModuleEntry* InstanceKlass::module() const {
2581   // For an unsafe anonymous class return the host class' module
2582   if (is_unsafe_anonymous()) {
2583     assert(unsafe_anonymous_host() != NULL, "unsafe anonymous class must have a host class");
2584     return unsafe_anonymous_host()->module();
2585   }
2586 
2587   // Class is in a named package
2588   if (!in_unnamed_package()) {
2589     return _package_entry->module();
2590   }
2591 
2592   // Class is in an unnamed package, return its loader's unnamed module
2593   return class_loader_data()->unnamed_module();
2594 }
2595 
2596 void InstanceKlass::set_package(ClassLoaderData* loader_data, TRAPS) {
2597 
2598   // ensure java/ packages only loaded by boot or platform builtin loaders
2599   check_prohibited_package(name(), loader_data, CHECK);
2600 
2601   TempNewSymbol pkg_name = package_from_name(name(), CHECK);
2602 
2603   if (pkg_name != NULL && loader_data != NULL) {
2604 
2605     // Find in class loader's package entry table.
2606     _package_entry = loader_data->packages()->lookup_only(pkg_name);
2607 
2608     // If the package name is not found in the loader's package
2609     // entry table, it is an indication that the package has not
2610     // been defined. Consider it defined within the unnamed module.
2611     if (_package_entry == NULL) {
2612       ResourceMark rm;
2613 
2614       if (!ModuleEntryTable::javabase_defined()) {
2615         // Before java.base is defined during bootstrapping, define all packages in
2616         // the java.base module.  If a non-java.base package is erroneously placed
2617         // in the java.base module it will be caught later when java.base
2618         // is defined by ModuleEntryTable::verify_javabase_packages check.
2619         assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL");
2620         _package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry());
2621       } else {
2622         assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL");
2623         _package_entry = loader_data->packages()->lookup(pkg_name,
2624                                                          loader_data->unnamed_module());
2625       }
2626 
2627       // A package should have been successfully created
2628       assert(_package_entry != NULL, "Package entry for class %s not found, loader %s",
2629              name()->as_C_string(), loader_data->loader_name_and_id());
2630     }
2631 
2632     if (log_is_enabled(Debug, module)) {
2633       ResourceMark rm;
2634       ModuleEntry* m = _package_entry->module();
2635       log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",
2636                         external_name(),
2637                         pkg_name->as_C_string(),
2638                         loader_data->loader_name_and_id(),
2639                         (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));
2640     }
2641   } else {
2642     ResourceMark rm;
2643     log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",
2644                       external_name(),
2645                       (loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL",
2646                       UNNAMED_MODULE);
2647   }
2648 }
2649 
2650 
2651 // different versions of is_same_class_package
2652 
2653 bool InstanceKlass::is_same_class_package(const Klass* class2) const {
2654   oop classloader1 = this->class_loader();
2655   PackageEntry* classpkg1 = this->package();
2656   if (class2->is_objArray_klass()) {
2657     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2658   }
2659 
2660   oop classloader2;
2661   PackageEntry* classpkg2;
2662   if (class2->is_instance_klass()) {
2663     classloader2 = class2->class_loader();
2664     classpkg2 = class2->package();
2665   } else {
2666     assert(class2->is_typeArray_klass(), "should be type array");
2667     classloader2 = NULL;
2668     classpkg2 = NULL;
2669   }
2670 
2671   // Same package is determined by comparing class loader
2672   // and package entries. Both must be the same. This rule
2673   // applies even to classes that are defined in the unnamed
2674   // package, they still must have the same class loader.
2675   if (oopDesc::equals(classloader1, classloader2) && (classpkg1 == classpkg2)) {
2676     return true;
2677   }
2678 
2679   return false;
2680 }
2681 
2682 // return true if this class and other_class are in the same package. Classloader
2683 // and classname information is enough to determine a class's package
2684 bool InstanceKlass::is_same_class_package(oop other_class_loader,
2685                                           const Symbol* other_class_name) const {
2686   if (!oopDesc::equals(class_loader(), other_class_loader)) {
2687     return false;
2688   }
2689   if (name()->fast_compare(other_class_name) == 0) {
2690      return true;
2691   }
2692 
2693   {
2694     ResourceMark rm;
2695 
2696     bool bad_class_name = false;
2697     const char* other_pkg =
2698       ClassLoader::package_from_name((const char*) other_class_name->as_C_string(), &bad_class_name);
2699     if (bad_class_name) {
2700       return false;
2701     }
2702     // Check that package_from_name() returns NULL, not "", if there is no package.
2703     assert(other_pkg == NULL || strlen(other_pkg) > 0, "package name is empty string");
2704 
2705     const Symbol* const this_package_name =
2706       this->package() != NULL ? this->package()->name() : NULL;
2707 
2708     if (this_package_name == NULL || other_pkg == NULL) {
2709       // One of the two doesn't have a package.  Only return true if the other
2710       // one also doesn't have a package.
2711       return (const char*)this_package_name == other_pkg;
2712     }
2713 
2714     // Check if package is identical
2715     return this_package_name->equals(other_pkg);
2716   }
2717 }
2718 
2719 // Returns true iff super_method can be overridden by a method in targetclassname
2720 // See JLS 3rd edition 8.4.6.1
2721 // Assumes name-signature match
2722 // "this" is InstanceKlass of super_method which must exist
2723 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2724 bool InstanceKlass::is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2725    // Private methods can not be overridden
2726    if (super_method->is_private()) {
2727      return false;
2728    }
2729    // If super method is accessible, then override
2730    if ((super_method->is_protected()) ||
2731        (super_method->is_public())) {
2732      return true;
2733    }
2734    // Package-private methods are not inherited outside of package
2735    assert(super_method->is_package_private(), "must be package private");
2736    return(is_same_class_package(targetclassloader(), targetclassname));
2737 }
2738 
2739 // Only boot and platform class loaders can define classes in "java/" packages.
2740 void InstanceKlass::check_prohibited_package(Symbol* class_name,
2741                                              ClassLoaderData* loader_data,
2742                                              TRAPS) {
2743   if (!loader_data->is_boot_class_loader_data() &&
2744       !loader_data->is_platform_class_loader_data() &&
2745       class_name != NULL) {
2746     ResourceMark rm(THREAD);
2747     char* name = class_name->as_C_string();
2748     if (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/') {
2749       TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK);
2750       assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");
2751       name = pkg_name->as_C_string();
2752       const char* class_loader_name = loader_data->loader_name_and_id();
2753       StringUtils::replace_no_expand(name, "/", ".");
2754       const char* msg_text1 = "Class loader (instance of): ";
2755       const char* msg_text2 = " tried to load prohibited package name: ";
2756       size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;
2757       char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
2758       jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);
2759       THROW_MSG(vmSymbols::java_lang_SecurityException(), message);
2760     }
2761   }
2762   return;
2763 }
2764 
2765 // tell if two classes have the same enclosing class (at package level)
2766 bool InstanceKlass::is_same_package_member(const Klass* class2, TRAPS) const {
2767   if (class2 == this) return true;
2768   if (!class2->is_instance_klass())  return false;
2769 
2770   // must be in same package before we try anything else
2771   if (!is_same_class_package(class2))
2772     return false;
2773 
2774   // As long as there is an outer_this.getEnclosingClass,
2775   // shift the search outward.
2776   const InstanceKlass* outer_this = this;
2777   for (;;) {
2778     // As we walk along, look for equalities between outer_this and class2.
2779     // Eventually, the walks will terminate as outer_this stops
2780     // at the top-level class around the original class.
2781     bool ignore_inner_is_member;
2782     const Klass* next = outer_this->compute_enclosing_class(&ignore_inner_is_member,
2783                                                             CHECK_false);
2784     if (next == NULL)  break;
2785     if (next == class2)  return true;
2786     outer_this = InstanceKlass::cast(next);
2787   }
2788 
2789   // Now do the same for class2.
2790   const InstanceKlass* outer2 = InstanceKlass::cast(class2);
2791   for (;;) {
2792     bool ignore_inner_is_member;
2793     Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2794                                                     CHECK_false);
2795     if (next == NULL)  break;
2796     // Might as well check the new outer against all available values.
2797     if (next == this)  return true;
2798     if (next == outer_this)  return true;
2799     outer2 = InstanceKlass::cast(next);
2800   }
2801 
2802   // If by this point we have not found an equality between the
2803   // two classes, we know they are in separate package members.
2804   return false;
2805 }
2806 
2807 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
2808   constantPoolHandle i_cp(THREAD, constants());
2809   for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
2810     int ioff = iter.inner_class_info_index();
2811     if (ioff != 0) {
2812       // Check to see if the name matches the class we're looking for
2813       // before attempting to find the class.
2814       if (i_cp->klass_name_at_matches(this, ioff)) {
2815         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
2816         if (this == inner_klass) {
2817           *ooff = iter.outer_class_info_index();
2818           *noff = iter.inner_name_index();
2819           return true;
2820         }
2821       }
2822     }
2823   }
2824   return false;
2825 }
2826 
2827 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
2828   InstanceKlass* outer_klass = NULL;
2829   *inner_is_member = false;
2830   int ooff = 0, noff = 0;
2831   bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
2832   if (has_inner_classes_attr) {
2833     constantPoolHandle i_cp(THREAD, constants());
2834     if (ooff != 0) {
2835       Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
2836       outer_klass = InstanceKlass::cast(ok);
2837       *inner_is_member = true;
2838     }
2839     if (NULL == outer_klass) {
2840       // It may be unsafe anonymous; try for that.
2841       int encl_method_class_idx = enclosing_method_class_index();
2842       if (encl_method_class_idx != 0) {
2843         Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
2844         outer_klass = InstanceKlass::cast(ok);
2845         *inner_is_member = false;
2846       }
2847     }
2848   }
2849 
2850   // If no inner class attribute found for this class.
2851   if (NULL == outer_klass) return NULL;
2852 
2853   // Throws an exception if outer klass has not declared k as an inner klass
2854   // We need evidence that each klass knows about the other, or else
2855   // the system could allow a spoof of an inner class to gain access rights.
2856   Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);
2857   return outer_klass;
2858 }
2859 
2860 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2861   jint access = access_flags().as_int();
2862 
2863   // But check if it happens to be member class.
2864   InnerClassesIterator iter(this);
2865   for (; !iter.done(); iter.next()) {
2866     int ioff = iter.inner_class_info_index();
2867     // Inner class attribute can be zero, skip it.
2868     // Strange but true:  JVM spec. allows null inner class refs.
2869     if (ioff == 0) continue;
2870 
2871     // only look at classes that are already loaded
2872     // since we are looking for the flags for our self.
2873     Symbol* inner_name = constants()->klass_name_at(ioff);
2874     if (name() == inner_name) {
2875       // This is really a member class.
2876       access = iter.inner_access_flags();
2877       break;
2878     }
2879   }
2880   // Remember to strip ACC_SUPER bit
2881   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2882 }
2883 
2884 jint InstanceKlass::jvmti_class_status() const {
2885   jint result = 0;
2886 
2887   if (is_linked()) {
2888     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2889   }
2890 
2891   if (is_initialized()) {
2892     assert(is_linked(), "Class status is not consistent");
2893     result |= JVMTI_CLASS_STATUS_INITIALIZED;
2894   }
2895   if (is_in_error_state()) {
2896     result |= JVMTI_CLASS_STATUS_ERROR;
2897   }
2898   return result;
2899 }
2900 
2901 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
2902   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2903   int method_table_offset_in_words = ioe->offset()/wordSize;
2904   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2905                        / itableOffsetEntry::size();
2906 
2907   for (int cnt = 0 ; ; cnt ++, ioe ++) {
2908     // If the interface isn't implemented by the receiver class,
2909     // the VM should throw IncompatibleClassChangeError.
2910     if (cnt >= nof_interfaces) {
2911       ResourceMark rm(THREAD);
2912       stringStream ss;
2913       bool same_module = (module() == holder->module());
2914       ss.print("Receiver class %s does not implement "
2915                "the interface %s defining the method to be called "
2916                "(%s%s%s)",
2917                external_name(), holder->external_name(),
2918                (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),
2919                (same_module) ? "" : "; ",
2920                (same_module) ? "" : holder->class_in_module_of_loader());
2921       THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
2922     }
2923 
2924     Klass* ik = ioe->interface_klass();
2925     if (ik == holder) break;
2926   }
2927 
2928   itableMethodEntry* ime = ioe->first_method_entry(this);
2929   Method* m = ime[index].method();
2930   if (m == NULL) {
2931     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
2932   }
2933   return m;
2934 }
2935 
2936 
2937 #if INCLUDE_JVMTI
2938 // update default_methods for redefineclasses for methods that are
2939 // not yet in the vtable due to concurrent subclass define and superinterface
2940 // redefinition
2941 // Note: those in the vtable, should have been updated via adjust_method_entries
2942 void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) {
2943   // search the default_methods for uses of either obsolete or EMCP methods
2944   if (default_methods() != NULL) {
2945     for (int index = 0; index < default_methods()->length(); index ++) {
2946       Method* old_method = default_methods()->at(index);
2947       if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
2948         continue; // skip uninteresting entries
2949       }
2950       assert(!old_method->is_deleted(), "default methods may not be deleted");
2951 
2952       Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
2953 
2954       assert(new_method != NULL, "method_with_idnum() should not be NULL");
2955       assert(old_method != new_method, "sanity check");
2956 
2957       default_methods()->at_put(index, new_method);
2958       if (log_is_enabled(Info, redefine, class, update)) {
2959         ResourceMark rm;
2960         if (!(*trace_name_printed)) {
2961           log_info(redefine, class, update)
2962             ("adjust: klassname=%s default methods from name=%s",
2963              external_name(), old_method->method_holder()->external_name());
2964           *trace_name_printed = true;
2965         }
2966         log_debug(redefine, class, update, vtables)
2967           ("default method update: %s(%s) ",
2968            new_method->name()->as_C_string(), new_method->signature()->as_C_string());
2969       }
2970     }
2971   }
2972 }
2973 #endif // INCLUDE_JVMTI
2974 
2975 // On-stack replacement stuff
2976 void InstanceKlass::add_osr_nmethod(nmethod* n) {
2977   // only one compilation can be active
2978   {
2979     // This is a short non-blocking critical region, so the no safepoint check is ok.
2980     MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2981     assert(n->is_osr_method(), "wrong kind of nmethod");
2982     n->set_osr_link(osr_nmethods_head());
2983     set_osr_nmethods_head(n);
2984     // Raise the highest osr level if necessary
2985     if (TieredCompilation) {
2986       Method* m = n->method();
2987       m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2988     }
2989   }
2990 
2991   // Get rid of the osr methods for the same bci that have lower levels.
2992   if (TieredCompilation) {
2993     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2994       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2995       if (inv != NULL && inv->is_in_use()) {
2996         inv->make_not_entrant();
2997       }
2998     }
2999   }
3000 }
3001 
3002 // Remove osr nmethod from the list. Return true if found and removed.
3003 bool InstanceKlass::remove_osr_nmethod(nmethod* n) {
3004   // This is a short non-blocking critical region, so the no safepoint check is ok.
3005   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3006   assert(n->is_osr_method(), "wrong kind of nmethod");
3007   nmethod* last = NULL;
3008   nmethod* cur  = osr_nmethods_head();
3009   int max_level = CompLevel_none;  // Find the max comp level excluding n
3010   Method* m = n->method();
3011   // Search for match
3012   bool found = false;
3013   while(cur != NULL && cur != n) {
3014     if (TieredCompilation && m == cur->method()) {
3015       // Find max level before n
3016       max_level = MAX2(max_level, cur->comp_level());
3017     }
3018     last = cur;
3019     cur = cur->osr_link();
3020   }
3021   nmethod* next = NULL;
3022   if (cur == n) {
3023     found = true;
3024     next = cur->osr_link();
3025     if (last == NULL) {
3026       // Remove first element
3027       set_osr_nmethods_head(next);
3028     } else {
3029       last->set_osr_link(next);
3030     }
3031   }
3032   n->set_osr_link(NULL);
3033   if (TieredCompilation) {
3034     cur = next;
3035     while (cur != NULL) {
3036       // Find max level after n
3037       if (m == cur->method()) {
3038         max_level = MAX2(max_level, cur->comp_level());
3039       }
3040       cur = cur->osr_link();
3041     }
3042     m->set_highest_osr_comp_level(max_level);
3043   }
3044   return found;
3045 }
3046 
3047 int InstanceKlass::mark_osr_nmethods(const Method* m) {
3048   // This is a short non-blocking critical region, so the no safepoint check is ok.
3049   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3050   nmethod* osr = osr_nmethods_head();
3051   int found = 0;
3052   while (osr != NULL) {
3053     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3054     if (osr->method() == m) {
3055       osr->mark_for_deoptimization();
3056       found++;
3057     }
3058     osr = osr->osr_link();
3059   }
3060   return found;
3061 }
3062 
3063 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3064   // This is a short non-blocking critical region, so the no safepoint check is ok.
3065   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3066   nmethod* osr = osr_nmethods_head();
3067   nmethod* best = NULL;
3068   while (osr != NULL) {
3069     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3070     // There can be a time when a c1 osr method exists but we are waiting
3071     // for a c2 version. When c2 completes its osr nmethod we will trash
3072     // the c1 version and only be able to find the c2 version. However
3073     // while we overflow in the c1 code at back branches we don't want to
3074     // try and switch to the same code as we are already running
3075 
3076     if (osr->method() == m &&
3077         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3078       if (match_level) {
3079         if (osr->comp_level() == comp_level) {
3080           // Found a match - return it.
3081           return osr;
3082         }
3083       } else {
3084         if (best == NULL || (osr->comp_level() > best->comp_level())) {
3085           if (osr->comp_level() == CompLevel_highest_tier) {
3086             // Found the best possible - return it.
3087             return osr;
3088           }
3089           best = osr;
3090         }
3091       }
3092     }
3093     osr = osr->osr_link();
3094   }
3095   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
3096     return best;
3097   }
3098   return NULL;
3099 }
3100 
3101 // -----------------------------------------------------------------------------------------------------
3102 // Printing
3103 
3104 #ifndef PRODUCT
3105 
3106 #define BULLET  " - "
3107 
3108 static const char* state_names[] = {
3109   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3110 };
3111 
3112 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3113   for (int i = 0; i < len; i++) {
3114     intptr_t e = start[i];
3115     st->print("%d : " INTPTR_FORMAT, i, e);
3116     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
3117       st->print(" ");
3118       ((Metadata*)e)->print_value_on(st);
3119     }
3120     st->cr();
3121   }
3122 }
3123 
3124 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3125   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3126 }
3127 
3128 void InstanceKlass::print_on(outputStream* st) const {
3129   assert(is_klass(), "must be klass");
3130   Klass::print_on(st);
3131 
3132   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3133   st->print(BULLET"klass size:        %d", size());                               st->cr();
3134   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3135   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3136   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3137   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3138   st->print(BULLET"sub:               ");
3139   Klass* sub = subklass();
3140   int n;
3141   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3142     if (n < MaxSubklassPrintSize) {
3143       sub->print_value_on(st);
3144       st->print("   ");
3145     }
3146   }
3147   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3148   st->cr();
3149 
3150   if (is_interface()) {
3151     MutexLocker ml(Compile_lock);
3152     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3153     if (nof_implementors() == 1) {
3154       st->print_cr(BULLET"implementor:    ");
3155       st->print("   ");
3156       implementor()->print_value_on(st);
3157       st->cr();
3158     }
3159   }
3160 
3161   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3162   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
3163   if (Verbose || WizardMode) {
3164     Array<Method*>* method_array = methods();
3165     for (int i = 0; i < method_array->length(); i++) {
3166       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3167     }
3168   }
3169   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
3170   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
3171   if (Verbose && default_methods() != NULL) {
3172     Array<Method*>* method_array = default_methods();
3173     for (int i = 0; i < method_array->length(); i++) {
3174       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3175     }
3176   }
3177   if (default_vtable_indices() != NULL) {
3178     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
3179   }
3180   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
3181   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3182   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3183   if (class_loader_data() != NULL) {
3184     st->print(BULLET"class loader data:  ");
3185     class_loader_data()->print_value_on(st);
3186     st->cr();
3187   }
3188   st->print(BULLET"unsafe anonymous host class:        "); Metadata::print_value_on_maybe_null(st, unsafe_anonymous_host()); st->cr();
3189   if (source_file_name() != NULL) {
3190     st->print(BULLET"source file:       ");
3191     source_file_name()->print_value_on(st);
3192     st->cr();
3193   }
3194   if (source_debug_extension() != NULL) {
3195     st->print(BULLET"source debug extension:       ");
3196     st->print("%s", source_debug_extension());
3197     st->cr();
3198   }
3199   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3200   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3201   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3202   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
3203   {
3204     bool have_pv = false;
3205     // previous versions are linked together through the InstanceKlass
3206     for (InstanceKlass* pv_node = previous_versions();
3207          pv_node != NULL;
3208          pv_node = pv_node->previous_versions()) {
3209       if (!have_pv)
3210         st->print(BULLET"previous version:  ");
3211       have_pv = true;
3212       pv_node->constants()->print_value_on(st);
3213     }
3214     if (have_pv) st->cr();
3215   }
3216 
3217   if (generic_signature() != NULL) {
3218     st->print(BULLET"generic signature: ");
3219     generic_signature()->print_value_on(st);
3220     st->cr();
3221   }
3222   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3223   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3224   if (java_mirror() != NULL) {
3225     st->print(BULLET"java mirror:       ");
3226     java_mirror()->print_value_on(st);
3227     st->cr();
3228   } else {
3229     st->print_cr(BULLET"java mirror:       NULL");
3230   }
3231   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3232   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3233   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3234   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3235   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3236   FieldPrinter print_static_field(st);
3237   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3238   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3239   FieldPrinter print_nonstatic_field(st);
3240   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3241   ik->do_nonstatic_fields(&print_nonstatic_field);
3242 
3243   st->print(BULLET"non-static oop maps: ");
3244   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3245   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3246   while (map < end_map) {
3247     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3248     map++;
3249   }
3250   st->cr();
3251 }
3252 
3253 #endif //PRODUCT
3254 
3255 void InstanceKlass::print_value_on(outputStream* st) const {
3256   assert(is_klass(), "must be klass");
3257   if (Verbose || WizardMode)  access_flags().print_on(st);
3258   name()->print_value_on(st);
3259 }
3260 
3261 #ifndef PRODUCT
3262 
3263 void FieldPrinter::do_field(fieldDescriptor* fd) {
3264   _st->print(BULLET);
3265    if (_obj == NULL) {
3266      fd->print_on(_st);
3267      _st->cr();
3268    } else {
3269      fd->print_on_for(_st, _obj);
3270      _st->cr();
3271    }
3272 }
3273 
3274 
3275 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3276   Klass::oop_print_on(obj, st);
3277 
3278   if (this == SystemDictionary::String_klass()) {
3279     typeArrayOop value  = java_lang_String::value(obj);
3280     juint        length = java_lang_String::length(obj);
3281     if (value != NULL &&
3282         value->is_typeArray() &&
3283         length <= (juint) value->length()) {
3284       st->print(BULLET"string: ");
3285       java_lang_String::print(obj, st);
3286       st->cr();
3287       if (!WizardMode)  return;  // that is enough
3288     }
3289   }
3290 
3291   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3292   FieldPrinter print_field(st, obj);
3293   do_nonstatic_fields(&print_field);
3294 
3295   if (this == SystemDictionary::Class_klass()) {
3296     st->print(BULLET"signature: ");
3297     java_lang_Class::print_signature(obj, st);
3298     st->cr();
3299     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3300     st->print(BULLET"fake entry for mirror: ");
3301     Metadata::print_value_on_maybe_null(st, mirrored_klass);
3302     st->cr();
3303     Klass* array_klass = java_lang_Class::array_klass_acquire(obj);
3304     st->print(BULLET"fake entry for array: ");
3305     Metadata::print_value_on_maybe_null(st, array_klass);
3306     st->cr();
3307     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3308     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3309     Klass* real_klass = java_lang_Class::as_Klass(obj);
3310     if (real_klass != NULL && real_klass->is_instance_klass()) {
3311       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3312     }
3313   } else if (this == SystemDictionary::MethodType_klass()) {
3314     st->print(BULLET"signature: ");
3315     java_lang_invoke_MethodType::print_signature(obj, st);
3316     st->cr();
3317   }
3318 }
3319 
3320 bool InstanceKlass::verify_itable_index(int i) {
3321   int method_count = klassItable::method_count_for_interface(this);
3322   assert(i >= 0 && i < method_count, "index out of bounds");
3323   return true;
3324 }
3325 
3326 #endif //PRODUCT
3327 
3328 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3329   st->print("a ");
3330   name()->print_value_on(st);
3331   obj->print_address_on(st);
3332   if (this == SystemDictionary::String_klass()
3333       && java_lang_String::value(obj) != NULL) {
3334     ResourceMark rm;
3335     int len = java_lang_String::length(obj);
3336     int plen = (len < 24 ? len : 12);
3337     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3338     st->print(" = \"%s\"", str);
3339     if (len > plen)
3340       st->print("...[%d]", len);
3341   } else if (this == SystemDictionary::Class_klass()) {
3342     Klass* k = java_lang_Class::as_Klass(obj);
3343     st->print(" = ");
3344     if (k != NULL) {
3345       k->print_value_on(st);
3346     } else {
3347       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3348       st->print("%s", tname ? tname : "type?");
3349     }
3350   } else if (this == SystemDictionary::MethodType_klass()) {
3351     st->print(" = ");
3352     java_lang_invoke_MethodType::print_signature(obj, st);
3353   } else if (java_lang_boxing_object::is_instance(obj)) {
3354     st->print(" = ");
3355     java_lang_boxing_object::print(obj, st);
3356   } else if (this == SystemDictionary::LambdaForm_klass()) {
3357     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3358     if (vmentry != NULL) {
3359       st->print(" => ");
3360       vmentry->print_value_on(st);
3361     }
3362   } else if (this == SystemDictionary::MemberName_klass()) {
3363     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3364     if (vmtarget != NULL) {
3365       st->print(" = ");
3366       vmtarget->print_value_on(st);
3367     } else {
3368       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3369       st->print(".");
3370       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3371     }
3372   }
3373 }
3374 
3375 const char* InstanceKlass::internal_name() const {
3376   return external_name();
3377 }
3378 
3379 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,
3380                                              const char* module_name,
3381                                              const ClassFileStream* cfs) const {
3382   if (!log_is_enabled(Info, class, load)) {
3383     return;
3384   }
3385 
3386   ResourceMark rm;
3387   LogMessage(class, load) msg;
3388   stringStream info_stream;
3389 
3390   // Name and class hierarchy info
3391   info_stream.print("%s", external_name());
3392 
3393   // Source
3394   if (cfs != NULL) {
3395     if (cfs->source() != NULL) {
3396       if (module_name != NULL) {
3397         if (ClassLoader::is_modules_image(cfs->source())) {
3398           info_stream.print(" source: jrt:/%s", module_name);
3399         } else {
3400           info_stream.print(" source: %s", cfs->source());
3401         }
3402       } else {
3403         info_stream.print(" source: %s", cfs->source());
3404       }
3405     } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
3406       Thread* THREAD = Thread::current();
3407       Klass* caller =
3408             THREAD->is_Java_thread()
3409                 ? ((JavaThread*)THREAD)->security_get_caller_class(1)
3410                 : NULL;
3411       // caller can be NULL, for example, during a JVMTI VM_Init hook
3412       if (caller != NULL) {
3413         info_stream.print(" source: instance of %s", caller->external_name());
3414       } else {
3415         // source is unknown
3416       }
3417     } else {
3418       oop class_loader = loader_data->class_loader();
3419       info_stream.print(" source: %s", class_loader->klass()->external_name());
3420     }
3421   } else {
3422     info_stream.print(" source: shared objects file");
3423   }
3424 
3425   msg.info("%s", info_stream.as_string());
3426 
3427   if (log_is_enabled(Debug, class, load)) {
3428     stringStream debug_stream;
3429 
3430     // Class hierarchy info
3431     debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT,
3432                        p2i(this),  p2i(superklass()));
3433 
3434     // Interfaces
3435     if (local_interfaces() != NULL && local_interfaces()->length() > 0) {
3436       debug_stream.print(" interfaces:");
3437       int length = local_interfaces()->length();
3438       for (int i = 0; i < length; i++) {
3439         debug_stream.print(" " INTPTR_FORMAT,
3440                            p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3441       }
3442     }
3443 
3444     // Class loader
3445     debug_stream.print(" loader: [");
3446     loader_data->print_value_on(&debug_stream);
3447     debug_stream.print("]");
3448 
3449     // Classfile checksum
3450     if (cfs) {
3451       debug_stream.print(" bytes: %d checksum: %08x",
3452                          cfs->length(),
3453                          ClassLoader::crc32(0, (const char*)cfs->buffer(),
3454                          cfs->length()));
3455     }
3456 
3457     msg.debug("%s", debug_stream.as_string());
3458   }
3459 }
3460 
3461 #if INCLUDE_SERVICES
3462 // Size Statistics
3463 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
3464   Klass::collect_statistics(sz);
3465 
3466   sz->_inst_size  = wordSize * size_helper();
3467   sz->_vtab_bytes = wordSize * vtable_length();
3468   sz->_itab_bytes = wordSize * itable_length();
3469   sz->_nonstatic_oopmap_bytes = wordSize * nonstatic_oop_map_size();
3470 
3471   int n = 0;
3472   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
3473   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
3474   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
3475   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
3476   n += (sz->_fields_bytes                = sz->count_array(fields()));
3477   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
3478   n += (sz->_nest_members_bytes          = sz->count_array(nest_members()));
3479   sz->_ro_bytes += n;
3480 
3481   const ConstantPool* cp = constants();
3482   if (cp) {
3483     cp->collect_statistics(sz);
3484   }
3485 
3486   const Annotations* anno = annotations();
3487   if (anno) {
3488     anno->collect_statistics(sz);
3489   }
3490 
3491   const Array<Method*>* methods_array = methods();
3492   if (methods()) {
3493     for (int i = 0; i < methods_array->length(); i++) {
3494       Method* method = methods_array->at(i);
3495       if (method) {
3496         sz->_method_count ++;
3497         method->collect_statistics(sz);
3498       }
3499     }
3500   }
3501 }
3502 #endif // INCLUDE_SERVICES
3503 
3504 // Verification
3505 
3506 class VerifyFieldClosure: public BasicOopIterateClosure {
3507  protected:
3508   template <class T> void do_oop_work(T* p) {
3509     oop obj = RawAccess<>::oop_load(p);
3510     if (!oopDesc::is_oop_or_null(obj)) {
3511       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
3512       Universe::print_on(tty);
3513       guarantee(false, "boom");
3514     }
3515   }
3516  public:
3517   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3518   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3519 };
3520 
3521 void InstanceKlass::verify_on(outputStream* st) {
3522 #ifndef PRODUCT
3523   // Avoid redundant verifies, this really should be in product.
3524   if (_verify_count == Universe::verify_count()) return;
3525   _verify_count = Universe::verify_count();
3526 #endif
3527 
3528   // Verify Klass
3529   Klass::verify_on(st);
3530 
3531   // Verify that klass is present in ClassLoaderData
3532   guarantee(class_loader_data()->contains_klass(this),
3533             "this class isn't found in class loader data");
3534 
3535   // Verify vtables
3536   if (is_linked()) {
3537     // $$$ This used to be done only for m/s collections.  Doing it
3538     // always seemed a valid generalization.  (DLD -- 6/00)
3539     vtable().verify(st);
3540   }
3541 
3542   // Verify first subklass
3543   if (subklass() != NULL) {
3544     guarantee(subklass()->is_klass(), "should be klass");
3545   }
3546 
3547   // Verify siblings
3548   Klass* super = this->super();
3549   Klass* sib = next_sibling();
3550   if (sib != NULL) {
3551     if (sib == this) {
3552       fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
3553     }
3554 
3555     guarantee(sib->is_klass(), "should be klass");
3556     guarantee(sib->super() == super, "siblings should have same superklass");
3557   }
3558 
3559   // Verify implementor fields requires the Compile_lock, but this is sometimes
3560   // called inside a safepoint, so don't verify.
3561 
3562   // Verify local interfaces
3563   if (local_interfaces()) {
3564     Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
3565     for (int j = 0; j < local_interfaces->length(); j++) {
3566       InstanceKlass* e = local_interfaces->at(j);
3567       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3568     }
3569   }
3570 
3571   // Verify transitive interfaces
3572   if (transitive_interfaces() != NULL) {
3573     Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();
3574     for (int j = 0; j < transitive_interfaces->length(); j++) {
3575       InstanceKlass* e = transitive_interfaces->at(j);
3576       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3577     }
3578   }
3579 
3580   // Verify methods
3581   if (methods() != NULL) {
3582     Array<Method*>* methods = this->methods();
3583     for (int j = 0; j < methods->length(); j++) {
3584       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3585     }
3586     for (int j = 0; j < methods->length() - 1; j++) {
3587       Method* m1 = methods->at(j);
3588       Method* m2 = methods->at(j + 1);
3589       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3590     }
3591   }
3592 
3593   // Verify method ordering
3594   if (method_ordering() != NULL) {
3595     Array<int>* method_ordering = this->method_ordering();
3596     int length = method_ordering->length();
3597     if (JvmtiExport::can_maintain_original_method_order() ||
3598         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3599       guarantee(length == methods()->length(), "invalid method ordering length");
3600       jlong sum = 0;
3601       for (int j = 0; j < length; j++) {
3602         int original_index = method_ordering->at(j);
3603         guarantee(original_index >= 0, "invalid method ordering index");
3604         guarantee(original_index < length, "invalid method ordering index");
3605         sum += original_index;
3606       }
3607       // Verify sum of indices 0,1,...,length-1
3608       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3609     } else {
3610       guarantee(length == 0, "invalid method ordering length");
3611     }
3612   }
3613 
3614   // Verify default methods
3615   if (default_methods() != NULL) {
3616     Array<Method*>* methods = this->default_methods();
3617     for (int j = 0; j < methods->length(); j++) {
3618       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3619     }
3620     for (int j = 0; j < methods->length() - 1; j++) {
3621       Method* m1 = methods->at(j);
3622       Method* m2 = methods->at(j + 1);
3623       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3624     }
3625   }
3626 
3627   // Verify JNI static field identifiers
3628   if (jni_ids() != NULL) {
3629     jni_ids()->verify(this);
3630   }
3631 
3632   // Verify other fields
3633   if (array_klasses() != NULL) {
3634     guarantee(array_klasses()->is_klass(), "should be klass");
3635   }
3636   if (constants() != NULL) {
3637     guarantee(constants()->is_constantPool(), "should be constant pool");
3638   }
3639   const Klass* anonymous_host = unsafe_anonymous_host();
3640   if (anonymous_host != NULL) {
3641     guarantee(anonymous_host->is_klass(), "should be klass");
3642   }
3643 }
3644 
3645 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3646   Klass::oop_verify_on(obj, st);
3647   VerifyFieldClosure blk;
3648   obj->oop_iterate(&blk);
3649 }
3650 
3651 
3652 // JNIid class for jfieldIDs only
3653 // Note to reviewers:
3654 // These JNI functions are just moved over to column 1 and not changed
3655 // in the compressed oops workspace.
3656 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3657   _holder = holder;
3658   _offset = offset;
3659   _next = next;
3660   debug_only(_is_static_field_id = false;)
3661 }
3662 
3663 
3664 JNIid* JNIid::find(int offset) {
3665   JNIid* current = this;
3666   while (current != NULL) {
3667     if (current->offset() == offset) return current;
3668     current = current->next();
3669   }
3670   return NULL;
3671 }
3672 
3673 void JNIid::deallocate(JNIid* current) {
3674   while (current != NULL) {
3675     JNIid* next = current->next();
3676     delete current;
3677     current = next;
3678   }
3679 }
3680 
3681 
3682 void JNIid::verify(Klass* holder) {
3683   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3684   int end_field_offset;
3685   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3686 
3687   JNIid* current = this;
3688   while (current != NULL) {
3689     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3690 #ifdef ASSERT
3691     int o = current->offset();
3692     if (current->is_static_field_id()) {
3693       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3694     }
3695 #endif
3696     current = current->next();
3697   }
3698 }
3699 
3700 #ifdef ASSERT
3701 void InstanceKlass::set_init_state(ClassState state) {
3702   bool good_state = is_shared() ? (_init_state <= state)
3703                                                : (_init_state < state);
3704   assert(good_state || state == allocated, "illegal state transition");
3705   _init_state = (u1)state;
3706 }
3707 #endif
3708 
3709 #if INCLUDE_JVMTI
3710 
3711 // RedefineClasses() support for previous versions
3712 
3713 // Globally, there is at least one previous version of a class to walk
3714 // during class unloading, which is saved because old methods in the class
3715 // are still running.   Otherwise the previous version list is cleaned up.
3716 bool InstanceKlass::_has_previous_versions = false;
3717 
3718 // Returns true if there are previous versions of a class for class
3719 // unloading only. Also resets the flag to false. purge_previous_version
3720 // will set the flag to true if there are any left, i.e., if there's any
3721 // work to do for next time. This is to avoid the expensive code cache
3722 // walk in CLDG::clean_deallocate_lists().
3723 bool InstanceKlass::has_previous_versions_and_reset() {
3724   bool ret = _has_previous_versions;
3725   log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",
3726      ret ? "true" : "false");
3727   _has_previous_versions = false;
3728   return ret;
3729 }
3730 
3731 // Purge previous versions before adding new previous versions of the class and
3732 // during class unloading.
3733 void InstanceKlass::purge_previous_version_list() {
3734   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3735   assert(has_been_redefined(), "Should only be called for main class");
3736 
3737   // Quick exit.
3738   if (previous_versions() == NULL) {
3739     return;
3740   }
3741 
3742   // This klass has previous versions so see what we can cleanup
3743   // while it is safe to do so.
3744 
3745   int deleted_count = 0;    // leave debugging breadcrumbs
3746   int live_count = 0;
3747   ClassLoaderData* loader_data = class_loader_data();
3748   assert(loader_data != NULL, "should never be null");
3749 
3750   ResourceMark rm;
3751   log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
3752 
3753   // previous versions are linked together through the InstanceKlass
3754   InstanceKlass* pv_node = previous_versions();
3755   InstanceKlass* last = this;
3756   int version = 0;
3757 
3758   // check the previous versions list
3759   for (; pv_node != NULL; ) {
3760 
3761     ConstantPool* pvcp = pv_node->constants();
3762     assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3763 
3764     if (!pvcp->on_stack()) {
3765       // If the constant pool isn't on stack, none of the methods
3766       // are executing.  Unlink this previous_version.
3767       // The previous version InstanceKlass is on the ClassLoaderData deallocate list
3768       // so will be deallocated during the next phase of class unloading.
3769       log_trace(redefine, class, iklass, purge)
3770         ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));
3771       // For debugging purposes.
3772       pv_node->set_is_scratch_class();
3773       // Unlink from previous version list.
3774       assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
3775       InstanceKlass* next = pv_node->previous_versions();
3776       pv_node->link_previous_versions(NULL);   // point next to NULL
3777       last->link_previous_versions(next);
3778       // Add to the deallocate list after unlinking
3779       loader_data->add_to_deallocate_list(pv_node);
3780       pv_node = next;
3781       deleted_count++;
3782       version++;
3783       continue;
3784     } else {
3785       log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));
3786       assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3787       guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3788       live_count++;
3789       // found a previous version for next time we do class unloading
3790       _has_previous_versions = true;
3791     }
3792 
3793     // At least one method is live in this previous version.
3794     // Reset dead EMCP methods not to get breakpoints.
3795     // All methods are deallocated when all of the methods for this class are no
3796     // longer running.
3797     Array<Method*>* method_refs = pv_node->methods();
3798     if (method_refs != NULL) {
3799       log_trace(redefine, class, iklass, purge)("previous methods length=%d", method_refs->length());
3800       for (int j = 0; j < method_refs->length(); j++) {
3801         Method* method = method_refs->at(j);
3802 
3803         if (!method->on_stack()) {
3804           // no breakpoints for non-running methods
3805           if (method->is_running_emcp()) {
3806             method->set_running_emcp(false);
3807           }
3808         } else {
3809           assert (method->is_obsolete() || method->is_running_emcp(),
3810                   "emcp method cannot run after emcp bit is cleared");
3811           log_trace(redefine, class, iklass, purge)
3812             ("purge: %s(%s): prev method @%d in version @%d is alive",
3813              method->name()->as_C_string(), method->signature()->as_C_string(), j, version);
3814         }
3815       }
3816     }
3817     // next previous version
3818     last = pv_node;
3819     pv_node = pv_node->previous_versions();
3820     version++;
3821   }
3822   log_trace(redefine, class, iklass, purge)
3823     ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
3824 }
3825 
3826 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
3827                                                 int emcp_method_count) {
3828   int obsolete_method_count = old_methods->length() - emcp_method_count;
3829 
3830   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3831       _previous_versions != NULL) {
3832     // We have a mix of obsolete and EMCP methods so we have to
3833     // clear out any matching EMCP method entries the hard way.
3834     int local_count = 0;
3835     for (int i = 0; i < old_methods->length(); i++) {
3836       Method* old_method = old_methods->at(i);
3837       if (old_method->is_obsolete()) {
3838         // only obsolete methods are interesting
3839         Symbol* m_name = old_method->name();
3840         Symbol* m_signature = old_method->signature();
3841 
3842         // previous versions are linked together through the InstanceKlass
3843         int j = 0;
3844         for (InstanceKlass* prev_version = _previous_versions;
3845              prev_version != NULL;
3846              prev_version = prev_version->previous_versions(), j++) {
3847 
3848           Array<Method*>* method_refs = prev_version->methods();
3849           for (int k = 0; k < method_refs->length(); k++) {
3850             Method* method = method_refs->at(k);
3851 
3852             if (!method->is_obsolete() &&
3853                 method->name() == m_name &&
3854                 method->signature() == m_signature) {
3855               // The current RedefineClasses() call has made all EMCP
3856               // versions of this method obsolete so mark it as obsolete
3857               log_trace(redefine, class, iklass, add)
3858                 ("%s(%s): flush obsolete method @%d in version @%d",
3859                  m_name->as_C_string(), m_signature->as_C_string(), k, j);
3860 
3861               method->set_is_obsolete();
3862               break;
3863             }
3864           }
3865 
3866           // The previous loop may not find a matching EMCP method, but
3867           // that doesn't mean that we can optimize and not go any
3868           // further back in the PreviousVersion generations. The EMCP
3869           // method for this generation could have already been made obsolete,
3870           // but there still may be an older EMCP method that has not
3871           // been made obsolete.
3872         }
3873 
3874         if (++local_count >= obsolete_method_count) {
3875           // no more obsolete methods so bail out now
3876           break;
3877         }
3878       }
3879     }
3880   }
3881 }
3882 
3883 // Save the scratch_class as the previous version if any of the methods are running.
3884 // The previous_versions are used to set breakpoints in EMCP methods and they are
3885 // also used to clean MethodData links to redefined methods that are no longer running.
3886 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,
3887                                          int emcp_method_count) {
3888   assert(Thread::current()->is_VM_thread(),
3889          "only VMThread can add previous versions");
3890 
3891   ResourceMark rm;
3892   log_trace(redefine, class, iklass, add)
3893     ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
3894 
3895   // Clean out old previous versions for this class
3896   purge_previous_version_list();
3897 
3898   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
3899   // a previous redefinition may be made obsolete by this redefinition.
3900   Array<Method*>* old_methods = scratch_class->methods();
3901   mark_newly_obsolete_methods(old_methods, emcp_method_count);
3902 
3903   // If the constant pool for this previous version of the class
3904   // is not marked as being on the stack, then none of the methods
3905   // in this previous version of the class are on the stack so
3906   // we don't need to add this as a previous version.
3907   ConstantPool* cp_ref = scratch_class->constants();
3908   if (!cp_ref->on_stack()) {
3909     log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");
3910     // For debugging purposes.
3911     scratch_class->set_is_scratch_class();
3912     scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);
3913     return;
3914   }
3915 
3916   if (emcp_method_count != 0) {
3917     // At least one method is still running, check for EMCP methods
3918     for (int i = 0; i < old_methods->length(); i++) {
3919       Method* old_method = old_methods->at(i);
3920       if (!old_method->is_obsolete() && old_method->on_stack()) {
3921         // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
3922         // we can add breakpoints for it.
3923 
3924         // We set the method->on_stack bit during safepoints for class redefinition
3925         // and use this bit to set the is_running_emcp bit.
3926         // After the safepoint, the on_stack bit is cleared and the running emcp
3927         // method may exit.   If so, we would set a breakpoint in a method that
3928         // is never reached, but this won't be noticeable to the programmer.
3929         old_method->set_running_emcp(true);
3930         log_trace(redefine, class, iklass, add)
3931           ("EMCP method %s is on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
3932       } else if (!old_method->is_obsolete()) {
3933         log_trace(redefine, class, iklass, add)
3934           ("EMCP method %s is NOT on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
3935       }
3936     }
3937   }
3938 
3939   // Add previous version if any methods are still running.
3940   // Set has_previous_version flag for processing during class unloading.
3941   _has_previous_versions = true;
3942   log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
3943   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
3944   scratch_class->link_previous_versions(previous_versions());
3945   link_previous_versions(scratch_class);
3946 } // end add_previous_version()
3947 
3948 #endif // INCLUDE_JVMTI
3949 
3950 Method* InstanceKlass::method_with_idnum(int idnum) {
3951   Method* m = NULL;
3952   if (idnum < methods()->length()) {
3953     m = methods()->at(idnum);
3954   }
3955   if (m == NULL || m->method_idnum() != idnum) {
3956     for (int index = 0; index < methods()->length(); ++index) {
3957       m = methods()->at(index);
3958       if (m->method_idnum() == idnum) {
3959         return m;
3960       }
3961     }
3962     // None found, return null for the caller to handle.
3963     return NULL;
3964   }
3965   return m;
3966 }
3967 
3968 
3969 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
3970   if (idnum >= methods()->length()) {
3971     return NULL;
3972   }
3973   Method* m = methods()->at(idnum);
3974   if (m != NULL && m->orig_method_idnum() == idnum) {
3975     return m;
3976   }
3977   // Obsolete method idnum does not match the original idnum
3978   for (int index = 0; index < methods()->length(); ++index) {
3979     m = methods()->at(index);
3980     if (m->orig_method_idnum() == idnum) {
3981       return m;
3982     }
3983   }
3984   // None found, return null for the caller to handle.
3985   return NULL;
3986 }
3987 
3988 
3989 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
3990   InstanceKlass* holder = get_klass_version(version);
3991   if (holder == NULL) {
3992     return NULL; // The version of klass is gone, no method is found
3993   }
3994   Method* method = holder->method_with_orig_idnum(idnum);
3995   return method;
3996 }
3997 
3998 #if INCLUDE_JVMTI
3999 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4000   if (MetaspaceShared::is_in_shared_metaspace(_cached_class_file)) {
4001     // Ignore the archived class stream data
4002     return NULL;
4003   } else {
4004     return _cached_class_file;
4005   }
4006 }
4007 
4008 jint InstanceKlass::get_cached_class_file_len() {
4009   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4010 }
4011 
4012 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4013   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4014 }
4015 
4016 #if INCLUDE_CDS
4017 JvmtiCachedClassFileData* InstanceKlass::get_archived_class_data() {
4018   if (DumpSharedSpaces) {
4019     return _cached_class_file;
4020   } else {
4021     assert(this->is_shared(), "class should be shared");
4022     if (MetaspaceShared::is_in_shared_metaspace(_cached_class_file)) {
4023       return _cached_class_file;
4024     } else {
4025       return NULL;
4026     }
4027   }
4028 }
4029 #endif
4030 #endif