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