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