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