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