1 /*
   2  * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "aot/aotLoader.hpp"
  28 #include "classfile/classFileParser.hpp"
  29 #include "classfile/classFileStream.hpp"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/classLoaderData.inline.hpp"
  32 #include "classfile/javaClasses.hpp"
  33 #include "classfile/moduleEntry.hpp"

  34 #include "classfile/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/constantPool.hpp"
  57 #include "oops/instanceClassLoaderKlass.hpp"
  58 #include "oops/instanceKlass.inline.hpp"
  59 #include "oops/instanceMirrorKlass.hpp"
  60 #include "oops/instanceOop.hpp"
  61 #include "oops/klass.inline.hpp"
  62 #include "oops/method.hpp"
  63 #include "oops/oop.inline.hpp"
  64 #include "oops/symbol.hpp"
  65 #include "prims/jvmtiExport.hpp"
  66 #include "prims/jvmtiRedefineClasses.hpp"
  67 #include "prims/jvmtiThreadState.hpp"
  68 #include "prims/methodComparator.hpp"
  69 #include "runtime/atomic.hpp"
  70 #include "runtime/fieldDescriptor.inline.hpp"
  71 #include "runtime/handles.inline.hpp"
  72 #include "runtime/javaCalls.hpp"
  73 #include "runtime/mutexLocker.hpp"
  74 #include "runtime/orderAccess.hpp"
  75 #include "runtime/thread.inline.hpp"
  76 #include "services/classLoadingService.hpp"
  77 #include "services/threadService.hpp"
  78 #include "utilities/dtrace.hpp"
  79 #include "utilities/events.hpp"
  80 #include "utilities/macros.hpp"
  81 #include "utilities/stringUtils.hpp"
  82 #ifdef COMPILER1
  83 #include "c1/c1_Compiler.hpp"
  84 #endif
  85 #if INCLUDE_JFR
  86 #include "jfr/jfrEvents.hpp"
  87 #endif
  88 
  89 
  90 #ifdef DTRACE_ENABLED
  91 
  92 
  93 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
  94 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
  95 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
  96 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
  97 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
  98 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
  99 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
 100 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
 101 #define DTRACE_CLASSINIT_PROBE(type, thread_type)                \
 102   {                                                              \
 103     char* data = NULL;                                           \
 104     int len = 0;                                                 \
 105     Symbol* clss_name = name();                                  \
 106     if (clss_name != NULL) {                                     \
 107       data = (char*)clss_name->bytes();                          \
 108       len = clss_name->utf8_length();                            \
 109     }                                                            \
 110     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 111       data, len, (void*)class_loader(), thread_type);            \
 112   }
 113 
 114 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)     \
 115   {                                                              \
 116     char* data = NULL;                                           \
 117     int len = 0;                                                 \
 118     Symbol* clss_name = name();                                  \
 119     if (clss_name != NULL) {                                     \
 120       data = (char*)clss_name->bytes();                          \
 121       len = clss_name->utf8_length();                            \
 122     }                                                            \
 123     HOTSPOT_CLASS_INITIALIZATION_##type(                         \
 124       data, len, (void*)class_loader(), thread_type, wait);      \
 125   }
 126 
 127 #else //  ndef DTRACE_ENABLED
 128 
 129 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
 130 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
 131 
 132 #endif //  ndef DTRACE_ENABLED
 133 
 134 static inline bool is_class_loader(const Symbol* class_name,
 135                                    const ClassFileParser& parser) {
 136   assert(class_name != NULL, "invariant");
 137 
 138   if (class_name == vmSymbols::java_lang_ClassLoader()) {
 139     return true;
 140   }
 141 
 142   if (SystemDictionary::ClassLoader_klass_loaded()) {
 143     const Klass* const super_klass = parser.super_klass();
 144     if (super_klass != NULL) {
 145       if (super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass())) {
 146         return true;
 147       }
 148     }
 149   }
 150   return false;
 151 }
 152 
 153 // called to verify that k is a member of this nest
 154 bool InstanceKlass::has_nest_member(InstanceKlass* k, TRAPS) const {
 155   if (_nest_members == NULL || _nest_members == Universe::the_empty_short_array()) {
 156     if (log_is_enabled(Trace, class, nestmates)) {
 157       ResourceMark rm(THREAD);
 158       log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
 159                                   k->external_name(), this->external_name());
 160     }
 161     return false;
 162   }
 163 
 164   if (log_is_enabled(Trace, class, nestmates)) {
 165     ResourceMark rm(THREAD);
 166     log_trace(class, nestmates)("Checking nest membership of %s in %s",
 167                                 k->external_name(), this->external_name());
 168   }
 169 
 170   // Check for a resolved cp entry , else fall back to a name check.
 171   // We don't want to resolve any class other than the one being checked.
 172   for (int i = 0; i < _nest_members->length(); i++) {
 173     int cp_index = _nest_members->at(i);
 174     if (_constants->tag_at(cp_index).is_klass()) {
 175       Klass* k2 = _constants->klass_at(cp_index, CHECK_false);
 176       if (k2 == k) {
 177         log_trace(class, nestmates)("- class is listed at nest_members[%d] => cp[%d]", i, cp_index);
 178         return true;
 179       }
 180     }
 181     else {
 182       Symbol* name = _constants->klass_name_at(cp_index);
 183       if (name == k->name()) {
 184         log_trace(class, nestmates)("- Found it at nest_members[%d] => cp[%d]", i, cp_index);
 185 
 186         // Names match so check actual klass - this may trigger class loading if
 187         // it doesn't match (though that should be impossible). But to be safe we
 188         // have to check for a compiler thread executing here.
 189         if (!THREAD->can_call_java() && !_constants->tag_at(cp_index).is_klass()) {
 190           log_trace(class, nestmates)("- validation required resolution in an unsuitable thread");
 191           return false;
 192         }
 193 
 194         Klass* k2 = _constants->klass_at(cp_index, CHECK_false);
 195         if (k2 == k) {
 196           log_trace(class, nestmates)("- class is listed as a nest member");
 197           return true;
 198         }
 199         else {
 200           // same name but different klass!
 201           log_trace(class, nestmates)(" - klass comparison failed!");
 202           // can't have two names the same, so we're done
 203           return false;
 204         }
 205       }
 206     }
 207   }
 208   log_trace(class, nestmates)("- class is NOT a nest member!");
 209   return false;
 210 }
 211 
 212 // Return nest-host class, resolving, validating and saving it if needed.
 213 // In cases where this is called from a thread that can not do classloading
 214 // (such as a native JIT thread) then we simply return NULL, which in turn
 215 // causes the access check to return false. Such code will retry the access
 216 // from a more suitable environment later.
 217 InstanceKlass* InstanceKlass::nest_host(Symbol* validationException, TRAPS) {
 218   InstanceKlass* nest_host_k = _nest_host;
 219   if (nest_host_k == NULL) {
 220     // need to resolve and save our nest-host class. This could be attempted
 221     // concurrently but as the result is idempotent and we don't use the class
 222     // then we do not need any synchronization beyond what is implicitly used
 223     // during class loading.
 224     if (_nest_host_index != 0) { // we have a real nest_host
 225       // Before trying to resolve check if we're in a suitable context
 226       if (!THREAD->can_call_java() && !_constants->tag_at(_nest_host_index).is_klass()) {
 227         if (log_is_enabled(Trace, class, nestmates)) {
 228           ResourceMark rm(THREAD);
 229           log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread",
 230                                       this->external_name());
 231         }
 232         return NULL;
 233       }
 234 
 235       if (log_is_enabled(Trace, class, nestmates)) {
 236         ResourceMark rm(THREAD);
 237         log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s",
 238                                     this->external_name(),
 239                                     _constants->klass_name_at(_nest_host_index)->as_C_string());
 240       }
 241 
 242       Klass* k = _constants->klass_at(_nest_host_index, THREAD);
 243       if (HAS_PENDING_EXCEPTION) {
 244         Handle exc_h = Handle(THREAD, PENDING_EXCEPTION);
 245         if (exc_h->is_a(SystemDictionary::NoClassDefFoundError_klass())) {
 246           // throw a new CDNFE with the original as its cause, and a clear msg
 247           ResourceMark rm(THREAD);
 248           char buf[200];
 249           CLEAR_PENDING_EXCEPTION;
 250           jio_snprintf(buf, sizeof(buf),
 251                        "Unable to load nest-host class (%s) of %s",
 252                        _constants->klass_name_at(_nest_host_index)->as_C_string(),
 253                        this->external_name());
 254           log_trace(class, nestmates)("%s - NoClassDefFoundError", buf);
 255           THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), buf, exc_h);
 256         }
 257         // All other exceptions pass through (OOME, StackOverflowError, LinkageErrors etc).
 258         return NULL;
 259       }
 260 
 261       // A valid nest-host is an instance class in the current package that lists this
 262       // class as a nest member. If any of these conditions are not met we post the
 263       // requested exception type (if any) and return NULL
 264 
 265       const char* error = NULL;
 266 
 267       // JVMS 5.4.4 indicates package check comes first
 268       if (is_same_class_package(k)) {
 269 
 270         // Now check actual membership. We can't be a member if our "host" is
 271         // not an instance class.
 272         if (k->is_instance_klass()) {
 273           nest_host_k = InstanceKlass::cast(k);
 274 
 275           bool is_member = nest_host_k->has_nest_member(this, CHECK_NULL);
 276           if (is_member) {
 277             // save resolved nest-host value
 278             _nest_host = nest_host_k;
 279 
 280             if (log_is_enabled(Trace, class, nestmates)) {
 281               ResourceMark rm(THREAD);
 282               log_trace(class, nestmates)("Resolved nest-host of %s to %s",
 283                                           this->external_name(), k->external_name());
 284             }
 285             return nest_host_k;
 286           }
 287         }
 288         error = "current type is not listed as a nest member";
 289       } else {
 290         error = "types are in different packages";
 291       }
 292 
 293       if (log_is_enabled(Trace, class, nestmates)) {
 294         ResourceMark rm(THREAD);
 295         log_trace(class, nestmates)
 296           ("Type %s (loader: %s) is not a nest member of "
 297            "resolved type %s (loader: %s): %s",
 298            this->external_name(),
 299            this->class_loader_data()->loader_name_and_id(),
 300            k->external_name(),
 301            k->class_loader_data()->loader_name_and_id(),
 302            error);
 303       }
 304 
 305       if (validationException != NULL && THREAD->can_call_java()) {
 306         ResourceMark rm(THREAD);
 307         Exceptions::fthrow(THREAD_AND_LOCATION,
 308                            validationException,
 309                            "Type %s (loader: %s) is not a nest member of %s (loader: %s): %s",
 310                            this->external_name(),
 311                            this->class_loader_data()->loader_name_and_id(),
 312                            k->external_name(),
 313                            k->class_loader_data()->loader_name_and_id(),
 314                            error
 315                            );
 316       }
 317       return NULL;
 318     } else {
 319       if (log_is_enabled(Trace, class, nestmates)) {
 320         ResourceMark rm(THREAD);
 321         log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self",
 322                                     this->external_name());
 323       }
 324       // save resolved nest-host value
 325       return (_nest_host = this);
 326     }
 327   }
 328   return nest_host_k;
 329 }
 330 
 331 // check if 'this' and k are nestmates (same nest_host), or k is our nest_host,
 332 // or we are k's nest_host - all of which is covered by comparing the two
 333 // resolved_nest_hosts
 334 bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) {
 335 
 336   assert(this != k, "this should be handled by higher-level code");
 337 
 338   // Per JVMS 5.4.4 we first resolve and validate the current class, then
 339   // the target class k. Resolution exceptions will be passed on by upper
 340   // layers. IncompatibleClassChangeErrors from membership validation failures
 341   // will also be passed through.
 342 
 343   Symbol* icce = vmSymbols::java_lang_IncompatibleClassChangeError();
 344   InstanceKlass* cur_host = nest_host(icce, CHECK_false);
 345   if (cur_host == NULL) {
 346     return false;
 347   }
 348 
 349   Klass* k_nest_host = k->nest_host(icce, CHECK_false);
 350   if (k_nest_host == NULL) {
 351     return false;
 352   }
 353 
 354   bool access = (cur_host == k_nest_host);
 355 
 356   if (log_is_enabled(Trace, class, nestmates)) {
 357     ResourceMark rm(THREAD);
 358     log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
 359                                 this->external_name(),
 360                                 access ? "" : "NOT ",
 361                                 k->external_name());
 362   }
 363 
 364   return access;
 365 }
 366 
 367 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
 368   const int size = InstanceKlass::size(parser.vtable_size(),
 369                                        parser.itable_size(),
 370                                        nonstatic_oop_map_size(parser.total_oop_map_count()),
 371                                        parser.is_interface(),
 372                                        parser.is_unsafe_anonymous(),
 373                                        should_store_fingerprint(parser.is_unsafe_anonymous()));
 374 
 375   const Symbol* const class_name = parser.class_name();
 376   assert(class_name != NULL, "invariant");
 377   ClassLoaderData* loader_data = parser.loader_data();
 378   assert(loader_data != NULL, "invariant");
 379 
 380   InstanceKlass* ik;
 381 
 382   // Allocation
 383   if (REF_NONE == parser.reference_type()) {
 384     if (class_name == vmSymbols::java_lang_Class()) {
 385       // mirror
 386       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
 387     }
 388     else if (is_class_loader(class_name, parser)) {
 389       // class loader
 390       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
 391     } else {
 392       // normal
 393       ik = new (loader_data, size, THREAD) InstanceKlass(parser, InstanceKlass::_misc_kind_other);
 394     }
 395   } else {
 396     // reference
 397     ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
 398   }
 399 
 400   // Check for pending exception before adding to the loader data and incrementing
 401   // class count.  Can get OOM here.
 402   if (HAS_PENDING_EXCEPTION) {
 403     return NULL;
 404   }
 405 
 406   return ik;
 407 }
 408 
 409 
 410 // copy method ordering from resource area to Metaspace
 411 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
 412   if (m != NULL) {
 413     // allocate a new array and copy contents (memcpy?)
 414     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 415     for (int i = 0; i < m->length(); i++) {
 416       _method_ordering->at_put(i, m->at(i));
 417     }
 418   } else {
 419     _method_ordering = Universe::the_empty_int_array();
 420   }
 421 }
 422 
 423 // create a new array of vtable_indices for default methods
 424 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 425   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 426   assert(default_vtable_indices() == NULL, "only create once");
 427   set_default_vtable_indices(vtable_indices);
 428   return vtable_indices;
 429 }
 430 
 431 InstanceKlass::InstanceKlass(const ClassFileParser& parser, unsigned kind, KlassID id) :
 432   Klass(id),
 433   _nest_members(NULL),
 434   _nest_host_index(0),
 435   _nest_host(NULL),
 436   _static_field_size(parser.static_field_size()),
 437   _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
 438   _itable_len(parser.itable_size()),


 439   _reference_type(parser.reference_type())
 440 {
 441   set_vtable_length(parser.vtable_size());
 442   set_kind(kind);
 443   set_access_flags(parser.access_flags());
 444   set_is_unsafe_anonymous(parser.is_unsafe_anonymous());
 445   set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
 446                                                     false));
 447 
 448   assert(NULL == _methods, "underlying memory not zeroed?");
 449   assert(is_instance_klass(), "is layout incorrect?");
 450   assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
 451 
 452   if (DumpSharedSpaces) {
 453     SystemDictionaryShared::init_dumptime_info(this);
 454   }
 455 }
 456 
 457 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 458                                        Array<Method*>* methods) {
 459   if (methods != NULL && methods != Universe::the_empty_method_array() &&
 460       !methods->is_shared()) {
 461     for (int i = 0; i < methods->length(); i++) {
 462       Method* method = methods->at(i);
 463       if (method == NULL) continue;  // maybe null if error processing
 464       // Only want to delete methods that are not executing for RedefineClasses.
 465       // The previous version will point to them so they're not totally dangling
 466       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 467       MetadataFactory::free_metadata(loader_data, method);
 468     }
 469     MetadataFactory::free_array<Method*>(loader_data, methods);
 470   }
 471 }
 472 
 473 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 474                                           const Klass* super_klass,
 475                                           Array<InstanceKlass*>* local_interfaces,
 476                                           Array<InstanceKlass*>* transitive_interfaces) {
 477   // Only deallocate transitive interfaces if not empty, same as super class
 478   // or same as local interfaces.  See code in parseClassFile.
 479   Array<InstanceKlass*>* ti = transitive_interfaces;
 480   if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) {
 481     // check that the interfaces don't come from super class
 482     Array<InstanceKlass*>* sti = (super_klass == NULL) ? NULL :
 483                     InstanceKlass::cast(super_klass)->transitive_interfaces();
 484     if (ti != sti && ti != NULL && !ti->is_shared()) {
 485       MetadataFactory::free_array<InstanceKlass*>(loader_data, ti);
 486     }
 487   }
 488 
 489   // local interfaces can be empty
 490   if (local_interfaces != Universe::the_empty_instance_klass_array() &&
 491       local_interfaces != NULL && !local_interfaces->is_shared()) {
 492     MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);
 493   }
 494 }
 495 
 496 // This function deallocates the metadata and C heap pointers that the
 497 // InstanceKlass points to.
 498 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
 499 
 500   // Orphan the mirror first, CMS thinks it's still live.
 501   if (java_mirror() != NULL) {
 502     java_lang_Class::set_klass(java_mirror(), NULL);
 503   }
 504 
 505   // Also remove mirror from handles
 506   loader_data->remove_handle(_java_mirror);
 507 
 508   // Need to take this class off the class loader data list.
 509   loader_data->remove_class(this);
 510 
 511   // The array_klass for this class is created later, after error handling.
 512   // For class redefinition, we keep the original class so this scratch class
 513   // doesn't have an array class.  Either way, assert that there is nothing
 514   // to deallocate.
 515   assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
 516 
 517   // Release C heap allocated data that this might point to, which includes
 518   // reference counting symbol names.
 519   release_C_heap_structures();
 520 
 521   deallocate_methods(loader_data, methods());
 522   set_methods(NULL);
 523 
 524   if (method_ordering() != NULL &&
 525       method_ordering() != Universe::the_empty_int_array() &&
 526       !method_ordering()->is_shared()) {
 527     MetadataFactory::free_array<int>(loader_data, method_ordering());
 528   }
 529   set_method_ordering(NULL);
 530 
 531   // default methods can be empty
 532   if (default_methods() != NULL &&
 533       default_methods() != Universe::the_empty_method_array() &&
 534       !default_methods()->is_shared()) {
 535     MetadataFactory::free_array<Method*>(loader_data, default_methods());
 536   }
 537   // Do NOT deallocate the default methods, they are owned by superinterfaces.
 538   set_default_methods(NULL);
 539 
 540   // default methods vtable indices can be empty
 541   if (default_vtable_indices() != NULL &&
 542       !default_vtable_indices()->is_shared()) {
 543     MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
 544   }
 545   set_default_vtable_indices(NULL);
 546 
 547 
 548   // This array is in Klass, but remove it with the InstanceKlass since
 549   // this place would be the only caller and it can share memory with transitive
 550   // interfaces.
 551   if (secondary_supers() != NULL &&
 552       secondary_supers() != Universe::the_empty_klass_array() &&
 553       // see comments in compute_secondary_supers about the following cast
 554       (address)(secondary_supers()) != (address)(transitive_interfaces()) &&
 555       !secondary_supers()->is_shared()) {
 556     MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
 557   }
 558   set_secondary_supers(NULL);
 559 
 560   deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
 561   set_transitive_interfaces(NULL);
 562   set_local_interfaces(NULL);
 563 
 564   if (fields() != NULL && !fields()->is_shared()) {
 565     MetadataFactory::free_array<jushort>(loader_data, fields());
 566   }
 567   set_fields(NULL, 0);
 568 
 569   // If a method from a redefined class is using this constant pool, don't
 570   // delete it, yet.  The new class's previous version will point to this.
 571   if (constants() != NULL) {
 572     assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
 573     if (!constants()->is_shared()) {
 574       MetadataFactory::free_metadata(loader_data, constants());
 575     }
 576     // Delete any cached resolution errors for the constant pool
 577     SystemDictionary::delete_resolution_error(constants());
 578 
 579     set_constants(NULL);
 580   }
 581 
 582   if (inner_classes() != NULL &&
 583       inner_classes() != Universe::the_empty_short_array() &&
 584       !inner_classes()->is_shared()) {
 585     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
 586   }
 587   set_inner_classes(NULL);
 588 
 589   if (nest_members() != NULL &&
 590       nest_members() != Universe::the_empty_short_array() &&
 591       !nest_members()->is_shared()) {
 592     MetadataFactory::free_array<jushort>(loader_data, nest_members());
 593   }
 594   set_nest_members(NULL);
 595 
 596   // We should deallocate the Annotations instance if it's not in shared spaces.
 597   if (annotations() != NULL && !annotations()->is_shared()) {
 598     MetadataFactory::free_metadata(loader_data, annotations());
 599   }
 600   set_annotations(NULL);
 601 
 602   if (DumpSharedSpaces) {
 603     SystemDictionaryShared::remove_dumptime_info(this);
 604   }
 605 }
 606 
 607 bool InstanceKlass::should_be_initialized() const {
 608   return !is_initialized();
 609 }
 610 
 611 klassItable InstanceKlass::itable() const {
 612   return klassItable(const_cast<InstanceKlass*>(this));
 613 }
 614 
 615 void InstanceKlass::eager_initialize(Thread *thread) {
 616   if (!EagerInitialization) return;
 617 
 618   if (this->is_not_initialized()) {
 619     // abort if the the class has a class initializer
 620     if (this->class_initializer() != NULL) return;
 621 
 622     // abort if it is java.lang.Object (initialization is handled in genesis)
 623     Klass* super_klass = super();
 624     if (super_klass == NULL) return;
 625 
 626     // abort if the super class should be initialized
 627     if (!InstanceKlass::cast(super_klass)->is_initialized()) return;
 628 
 629     // call body to expose the this pointer
 630     eager_initialize_impl();
 631   }
 632 }
 633 
 634 // JVMTI spec thinks there are signers and protection domain in the
 635 // instanceKlass.  These accessors pretend these fields are there.
 636 // The hprof specification also thinks these fields are in InstanceKlass.
 637 oop InstanceKlass::protection_domain() const {
 638   // return the protection_domain from the mirror
 639   return java_lang_Class::protection_domain(java_mirror());
 640 }
 641 
 642 // To remove these from requires an incompatible change and CCC request.
 643 objArrayOop InstanceKlass::signers() const {
 644   // return the signers from the mirror
 645   return java_lang_Class::signers(java_mirror());
 646 }
 647 
 648 oop InstanceKlass::init_lock() const {
 649   // return the init lock from the mirror
 650   oop lock = java_lang_Class::init_lock(java_mirror());
 651   // Prevent reordering with any access of initialization state
 652   OrderAccess::loadload();
 653   assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
 654          "only fully initialized state can have a null lock");
 655   return lock;
 656 }
 657 
 658 // Set the initialization lock to null so the object can be GC'ed.  Any racing
 659 // threads to get this lock will see a null lock and will not lock.
 660 // That's okay because they all check for initialized state after getting
 661 // the lock and return.
 662 void InstanceKlass::fence_and_clear_init_lock() {
 663   // make sure previous stores are all done, notably the init_state.
 664   OrderAccess::storestore();
 665   java_lang_Class::set_init_lock(java_mirror(), NULL);
 666   assert(!is_not_initialized(), "class must be initialized now");
 667 }
 668 
 669 void InstanceKlass::eager_initialize_impl() {
 670   EXCEPTION_MARK;
 671   HandleMark hm(THREAD);
 672   Handle h_init_lock(THREAD, init_lock());
 673   ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
 674 
 675   // abort if someone beat us to the initialization
 676   if (!is_not_initialized()) return;  // note: not equivalent to is_initialized()
 677 
 678   ClassState old_state = init_state();
 679   link_class_impl(THREAD);
 680   if (HAS_PENDING_EXCEPTION) {
 681     CLEAR_PENDING_EXCEPTION;
 682     // Abort if linking the class throws an exception.
 683 
 684     // Use a test to avoid redundantly resetting the state if there's
 685     // no change.  Set_init_state() asserts that state changes make
 686     // progress, whereas here we might just be spinning in place.
 687     if (old_state != _init_state)
 688       set_init_state(old_state);
 689   } else {
 690     // linking successfull, mark class as initialized
 691     set_init_state(fully_initialized);
 692     fence_and_clear_init_lock();
 693     // trace
 694     if (log_is_enabled(Info, class, init)) {
 695       ResourceMark rm(THREAD);
 696       log_info(class, init)("[Initialized %s without side effects]", external_name());
 697     }
 698   }
 699 }
 700 
 701 
 702 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
 703 // process. The step comments refers to the procedure described in that section.
 704 // Note: implementation moved to static method to expose the this pointer.
 705 void InstanceKlass::initialize(TRAPS) {
 706   if (this->should_be_initialized()) {
 707     initialize_impl(CHECK);
 708     // Note: at this point the class may be initialized
 709     //       OR it may be in the state of being initialized
 710     //       in case of recursive initialization!
 711   } else {
 712     assert(is_initialized(), "sanity check");
 713   }
 714 }
 715 
 716 
 717 bool InstanceKlass::verify_code(TRAPS) {
 718   // 1) Verify the bytecodes
 719   return Verifier::verify(this, should_verify_class(), THREAD);
 720 }
 721 
 722 void InstanceKlass::link_class(TRAPS) {
 723   assert(is_loaded(), "must be loaded");
 724   if (!is_linked()) {
 725     link_class_impl(CHECK);
 726   }
 727 }
 728 
 729 // Called to verify that a class can link during initialization, without
 730 // throwing a VerifyError.
 731 bool InstanceKlass::link_class_or_fail(TRAPS) {
 732   assert(is_loaded(), "must be loaded");
 733   if (!is_linked()) {
 734     link_class_impl(CHECK_false);
 735   }
 736   return is_linked();
 737 }
 738 
 739 bool InstanceKlass::link_class_impl(TRAPS) {
 740   if (DumpSharedSpaces && is_in_error_state()) {
 741     // This is for CDS dumping phase only -- we use the in_error_state to indicate that
 742     // the class has failed verification. Throwing the NoClassDefFoundError here is just
 743     // a convenient way to stop repeat attempts to verify the same (bad) class.
 744     //
 745     // Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown
 746     // if we are executing Java code. This is not a problem for CDS dumping phase since
 747     // it doesn't execute any Java code.
 748     ResourceMark rm(THREAD);
 749     Exceptions::fthrow(THREAD_AND_LOCATION,
 750                        vmSymbols::java_lang_NoClassDefFoundError(),
 751                        "Class %s, or one of its supertypes, failed class initialization",
 752                        external_name());
 753     return false;
 754   }
 755   // return if already verified
 756   if (is_linked()) {
 757     return true;
 758   }
 759 
 760   // Timing
 761   // timer handles recursion
 762   assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
 763   JavaThread* jt = (JavaThread*)THREAD;
 764 
 765   // link super class before linking this class
 766   Klass* super_klass = super();
 767   if (super_klass != NULL) {
 768     if (super_klass->is_interface()) {  // check if super class is an interface
 769       ResourceMark rm(THREAD);
 770       Exceptions::fthrow(
 771         THREAD_AND_LOCATION,
 772         vmSymbols::java_lang_IncompatibleClassChangeError(),
 773         "class %s has interface %s as super class",
 774         external_name(),
 775         super_klass->external_name()
 776       );
 777       return false;
 778     }
 779 
 780     InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
 781     ik_super->link_class_impl(CHECK_false);
 782   }
 783 
 784   // link all interfaces implemented by this class before linking this class
 785   Array<InstanceKlass*>* interfaces = local_interfaces();
 786   int num_interfaces = interfaces->length();
 787   for (int index = 0; index < num_interfaces; index++) {
 788     InstanceKlass* interk = interfaces->at(index);
 789     interk->link_class_impl(CHECK_false);
 790   }
 791 
 792   // in case the class is linked in the process of linking its superclasses
 793   if (is_linked()) {
 794     return true;
 795   }
 796 
 797   // trace only the link time for this klass that includes
 798   // the verification time
 799   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 800                              ClassLoader::perf_class_link_selftime(),
 801                              ClassLoader::perf_classes_linked(),
 802                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 803                              jt->get_thread_stat()->perf_timers_addr(),
 804                              PerfClassTraceTime::CLASS_LINK);
 805 
 806   // verification & rewriting
 807   {
 808     HandleMark hm(THREAD);
 809     Handle h_init_lock(THREAD, init_lock());
 810     ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
 811     // rewritten will have been set if loader constraint error found
 812     // on an earlier link attempt
 813     // don't verify or rewrite if already rewritten
 814     //
 815 
 816     if (!is_linked()) {
 817       if (!is_rewritten()) {
 818         {
 819           bool verify_ok = verify_code(THREAD);
 820           if (!verify_ok) {
 821             return false;
 822           }
 823         }
 824 
 825         // Just in case a side-effect of verify linked this class already
 826         // (which can sometimes happen since the verifier loads classes
 827         // using custom class loaders, which are free to initialize things)
 828         if (is_linked()) {
 829           return true;
 830         }
 831 
 832         // also sets rewritten
 833         rewrite_class(CHECK_false);
 834       } else if (is_shared()) {
 835         SystemDictionaryShared::check_verification_constraints(this, CHECK_false);
 836       }
 837 
 838       // relocate jsrs and link methods after they are all rewritten
 839       link_methods(CHECK_false);
 840 
 841       // Initialize the vtable and interface table after
 842       // methods have been rewritten since rewrite may
 843       // fabricate new Method*s.
 844       // also does loader constraint checking
 845       //
 846       // initialize_vtable and initialize_itable need to be rerun for
 847       // a shared class if the class is not loaded by the NULL classloader.
 848       ClassLoaderData * loader_data = class_loader_data();
 849       if (!(is_shared() &&
 850             loader_data->is_the_null_class_loader_data())) {
 851         vtable().initialize_vtable(true, CHECK_false);
 852         itable().initialize_itable(true, CHECK_false);
 853       }
 854 #ifdef ASSERT
 855       else {
 856         vtable().verify(tty, true);
 857         // In case itable verification is ever added.
 858         // itable().verify(tty, true);
 859       }
 860 #endif
 861       set_init_state(linked);
 862       if (JvmtiExport::should_post_class_prepare()) {
 863         Thread *thread = THREAD;
 864         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 865         JvmtiExport::post_class_prepare((JavaThread *) thread, this);
 866       }
 867     }
 868   }
 869   return true;
 870 }
 871 
 872 // Rewrite the byte codes of all of the methods of a class.
 873 // The rewriter must be called exactly once. Rewriting must happen after
 874 // verification but before the first method of the class is executed.
 875 void InstanceKlass::rewrite_class(TRAPS) {
 876   assert(is_loaded(), "must be loaded");
 877   if (is_rewritten()) {
 878     assert(is_shared(), "rewriting an unshared class?");
 879     return;
 880   }
 881   Rewriter::rewrite(this, CHECK);
 882   set_rewritten();
 883 }
 884 
 885 // Now relocate and link method entry points after class is rewritten.
 886 // This is outside is_rewritten flag. In case of an exception, it can be
 887 // executed more than once.
 888 void InstanceKlass::link_methods(TRAPS) {
 889   int len = methods()->length();
 890   for (int i = len-1; i >= 0; i--) {
 891     methodHandle m(THREAD, methods()->at(i));
 892 
 893     // Set up method entry points for compiler and interpreter    .
 894     m->link_method(m, CHECK);
 895   }
 896 }
 897 
 898 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
 899 void InstanceKlass::initialize_super_interfaces(TRAPS) {
 900   assert (has_nonstatic_concrete_methods(), "caller should have checked this");
 901   for (int i = 0; i < local_interfaces()->length(); ++i) {
 902     InstanceKlass* ik = local_interfaces()->at(i);
 903 
 904     // Initialization is depth first search ie. we start with top of the inheritance tree
 905     // has_nonstatic_concrete_methods drives searching superinterfaces since it
 906     // means has_nonstatic_concrete_methods in its superinterface hierarchy
 907     if (ik->has_nonstatic_concrete_methods()) {
 908       ik->initialize_super_interfaces(CHECK);
 909     }
 910 
 911     // Only initialize() interfaces that "declare" concrete methods.
 912     if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) {
 913       ik->initialize(CHECK);
 914     }
 915   }
 916 }
 917 
 918 void InstanceKlass::initialize_impl(TRAPS) {
 919   HandleMark hm(THREAD);
 920 
 921   // Make sure klass is linked (verified) before initialization
 922   // A class could already be verified, since it has been reflected upon.
 923   link_class(CHECK);
 924 
 925   DTRACE_CLASSINIT_PROBE(required, -1);
 926 
 927   bool wait = false;
 928 
 929   assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
 930   JavaThread* jt = (JavaThread*)THREAD;
 931 
 932   // refer to the JVM book page 47 for description of steps
 933   // Step 1
 934   {
 935     Handle h_init_lock(THREAD, init_lock());
 936     ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
 937 
 938     // Step 2
 939     // If we were to use wait() instead of waitInterruptibly() then
 940     // we might end up throwing IE from link/symbol resolution sites
 941     // that aren't expected to throw.  This would wreak havoc.  See 6320309.
 942     while (is_being_initialized() && !is_reentrant_initialization(jt)) {
 943       wait = true;
 944       jt->set_class_to_be_initialized(this);
 945       ol.waitUninterruptibly(jt);
 946       jt->set_class_to_be_initialized(NULL);
 947     }
 948 
 949     // Step 3
 950     if (is_being_initialized() && is_reentrant_initialization(jt)) {
 951       DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait);
 952       return;
 953     }
 954 
 955     // Step 4
 956     if (is_initialized()) {
 957       DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait);
 958       return;
 959     }
 960 
 961     // Step 5
 962     if (is_in_error_state()) {
 963       DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);
 964       ResourceMark rm(THREAD);
 965       const char* desc = "Could not initialize class ";
 966       const char* className = external_name();
 967       size_t msglen = strlen(desc) + strlen(className) + 1;
 968       char* message = NEW_RESOURCE_ARRAY(char, msglen);
 969       if (NULL == message) {
 970         // Out of memory: can't create detailed error message
 971           THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
 972       } else {
 973         jio_snprintf(message, msglen, "%s%s", desc, className);
 974           THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
 975       }
 976     }
 977 
 978     // Step 6
 979     set_init_state(being_initialized);
 980     set_init_thread(jt);
 981   }
 982 
 983   // Step 7
 984   // Next, if C is a class rather than an interface, initialize it's super class and super
 985   // interfaces.
 986   if (!is_interface()) {
 987     Klass* super_klass = super();
 988     if (super_klass != NULL && super_klass->should_be_initialized()) {
 989       super_klass->initialize(THREAD);
 990     }
 991     // If C implements any interface that declares a non-static, concrete method,
 992     // the initialization of C triggers initialization of its super interfaces.
 993     // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
 994     // having a superinterface that declares, non-static, concrete methods
 995     if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
 996       initialize_super_interfaces(THREAD);
 997     }
 998 
 999     // If any exceptions, complete abruptly, throwing the same exception as above.
1000     if (HAS_PENDING_EXCEPTION) {
1001       Handle e(THREAD, PENDING_EXCEPTION);
1002       CLEAR_PENDING_EXCEPTION;
1003       {
1004         EXCEPTION_MARK;
1005         // Locks object, set state, and notify all waiting threads
1006         set_initialization_state_and_notify(initialization_error, THREAD);
1007         CLEAR_PENDING_EXCEPTION;
1008       }
1009       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1010       THROW_OOP(e());
1011     }
1012   }
1013 
1014 
1015   // Look for aot compiled methods for this klass, including class initializer.
1016   AOTLoader::load_for_klass(this, THREAD);
1017 
1018   // Step 8
1019   {
1020     DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1021     // Timer includes any side effects of class initialization (resolution,
1022     // etc), but not recursive entry into call_class_initializer().
1023     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1024                              ClassLoader::perf_class_init_selftime(),
1025                              ClassLoader::perf_classes_inited(),
1026                              jt->get_thread_stat()->perf_recursion_counts_addr(),
1027                              jt->get_thread_stat()->perf_timers_addr(),
1028                              PerfClassTraceTime::CLASS_CLINIT);
1029     call_class_initializer(THREAD);
1030   }
1031 
1032   // Step 9
1033   if (!HAS_PENDING_EXCEPTION) {
1034     set_initialization_state_and_notify(fully_initialized, CHECK);
1035     {
1036       debug_only(vtable().verify(tty, true);)
1037     }
1038   }
1039   else {
1040     // Step 10 and 11
1041     Handle e(THREAD, PENDING_EXCEPTION);
1042     CLEAR_PENDING_EXCEPTION;
1043     // JVMTI has already reported the pending exception
1044     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1045     JvmtiExport::clear_detected_exception(jt);
1046     {
1047       EXCEPTION_MARK;
1048       set_initialization_state_and_notify(initialization_error, THREAD);
1049       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1050       // JVMTI has already reported the pending exception
1051       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1052       JvmtiExport::clear_detected_exception(jt);
1053     }
1054     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1055     if (e->is_a(SystemDictionary::Error_klass())) {
1056       THROW_OOP(e());
1057     } else {
1058       JavaCallArguments args(e);
1059       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1060                 vmSymbols::throwable_void_signature(),
1061                 &args);
1062     }
1063   }
1064   DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1065 }
1066 
1067 
1068 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1069   Handle h_init_lock(THREAD, init_lock());
1070   if (h_init_lock() != NULL) {
1071     ObjectLocker ol(h_init_lock, THREAD);

1072     set_init_state(state);
1073     fence_and_clear_init_lock();
1074     ol.notify_all(CHECK);
1075   } else {
1076     assert(h_init_lock() != NULL, "The initialization state should never be set twice");

1077     set_init_state(state);
1078   }
1079 }
1080 
1081 Klass* InstanceKlass::implementor() const {
1082   Klass* volatile* k = adr_implementor();
1083   if (k == NULL) {
1084     return NULL;
1085   } else {
1086     // This load races with inserts, and therefore needs acquire.
1087     Klass* kls = OrderAccess::load_acquire(k);
1088     if (kls != NULL && !kls->is_loader_alive()) {
1089       return NULL;  // don't return unloaded class
1090     } else {
1091       return kls;
1092     }
1093   }
1094 }
1095 
1096 
1097 void InstanceKlass::set_implementor(Klass* k) {
1098   assert_lock_strong(Compile_lock);
1099   assert(is_interface(), "not interface");
1100   Klass* volatile* addr = adr_implementor();
1101   assert(addr != NULL, "null addr");
1102   if (addr != NULL) {
1103     OrderAccess::release_store(addr, k);
1104   }
1105 }
1106 
1107 int  InstanceKlass::nof_implementors() const {
1108   Klass* k = implementor();
1109   if (k == NULL) {
1110     return 0;
1111   } else if (k != this) {
1112     return 1;
1113   } else {
1114     return 2;
1115   }
1116 }
1117 
1118 // The embedded _implementor field can only record one implementor.
1119 // When there are more than one implementors, the _implementor field
1120 // is set to the interface Klass* itself. Following are the possible
1121 // values for the _implementor field:
1122 //   NULL                  - no implementor
1123 //   implementor Klass*    - one implementor
1124 //   self                  - more than one implementor
1125 //
1126 // The _implementor field only exists for interfaces.
1127 void InstanceKlass::add_implementor(Klass* k) {
1128   assert_lock_strong(Compile_lock);
1129   assert(is_interface(), "not interface");
1130   // Filter out my subinterfaces.
1131   // (Note: Interfaces are never on the subklass list.)
1132   if (InstanceKlass::cast(k)->is_interface()) return;
1133 
1134   // Filter out subclasses whose supers already implement me.
1135   // (Note: CHA must walk subclasses of direct implementors
1136   // in order to locate indirect implementors.)
1137   Klass* sk = k->super();
1138   if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
1139     // We only need to check one immediate superclass, since the
1140     // implements_interface query looks at transitive_interfaces.
1141     // Any supers of the super have the same (or fewer) transitive_interfaces.
1142     return;
1143 
1144   Klass* ik = implementor();
1145   if (ik == NULL) {
1146     set_implementor(k);
1147   } else if (ik != this) {
1148     // There is already an implementor. Use itself as an indicator of
1149     // more than one implementors.
1150     set_implementor(this);
1151   }
1152 
1153   // The implementor also implements the transitive_interfaces
1154   for (int index = 0; index < local_interfaces()->length(); index++) {
1155     InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
1156   }
1157 }
1158 
1159 void InstanceKlass::init_implementor() {
1160   if (is_interface()) {
1161     set_implementor(NULL);
1162   }
1163 }
1164 
1165 
1166 void InstanceKlass::process_interfaces(Thread *thread) {
1167   // link this class into the implementors list of every interface it implements
1168   for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
1169     assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
1170     InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
1171     assert(interf->is_interface(), "expected interface");
1172     interf->add_implementor(this);
1173   }
1174 }
1175 
1176 bool InstanceKlass::can_be_primary_super_slow() const {
1177   if (is_interface())
1178     return false;
1179   else
1180     return Klass::can_be_primary_super_slow();
1181 }
1182 
1183 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots,
1184                                                                Array<InstanceKlass*>* transitive_interfaces) {
1185   // The secondaries are the implemented interfaces.
1186   Array<InstanceKlass*>* interfaces = transitive_interfaces;
1187   int num_secondaries = num_extra_slots + interfaces->length();
1188   if (num_secondaries == 0) {
1189     // Must share this for correct bootstrapping!
1190     set_secondary_supers(Universe::the_empty_klass_array());
1191     return NULL;
1192   } else if (num_extra_slots == 0) {
1193     // The secondary super list is exactly the same as the transitive interfaces, so
1194     // let's use it instead of making a copy.
1195     // Redefine classes has to be careful not to delete this!
1196     // We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>,
1197     // (but it's safe to do here because we won't write into _secondary_supers from this point on).
1198     set_secondary_supers((Array<Klass*>*)(address)interfaces);
1199     return NULL;
1200   } else {
1201     // Copy transitive interfaces to a temporary growable array to be constructed
1202     // into the secondary super list with extra slots.
1203     GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
1204     for (int i = 0; i < interfaces->length(); i++) {
1205       secondaries->push(interfaces->at(i));
1206     }
1207     return secondaries;
1208   }
1209 }
1210 
1211 bool InstanceKlass::implements_interface(Klass* k) const {
1212   if (this == k) return true;
1213   assert(k->is_interface(), "should be an interface class");
1214   for (int i = 0; i < transitive_interfaces()->length(); i++) {
1215     if (transitive_interfaces()->at(i) == k) {
1216       return true;
1217     }
1218   }
1219   return false;
1220 }
1221 
1222 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1223   // Verify direct super interface
1224   if (this == k) return true;
1225   assert(k->is_interface(), "should be an interface class");
1226   for (int i = 0; i < local_interfaces()->length(); i++) {
1227     if (local_interfaces()->at(i) == k) {
1228       return true;
1229     }
1230   }
1231   return false;
1232 }
1233 
1234 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
1235   check_array_allocation_length(length, arrayOopDesc::max_array_length(T_OBJECT), CHECK_NULL);
1236   int size = objArrayOopDesc::object_size(length);
1237   Klass* ak = array_klass(n, CHECK_NULL);
1238   objArrayOop o = (objArrayOop)Universe::heap()->array_allocate(ak, size, length,
1239                                                                 /* do_zero */ true, CHECK_NULL);
1240   return o;
1241 }
1242 
1243 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1244   if (TraceFinalizerRegistration) {
1245     tty->print("Registered ");
1246     i->print_value_on(tty);
1247     tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", p2i(i));
1248   }
1249   instanceHandle h_i(THREAD, i);
1250   // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1251   JavaValue result(T_VOID);
1252   JavaCallArguments args(h_i);
1253   methodHandle mh (THREAD, Universe::finalizer_register_method());
1254   JavaCalls::call(&result, mh, &args, CHECK_NULL);
1255   return h_i();
1256 }
1257 
1258 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1259   bool has_finalizer_flag = has_finalizer(); // Query before possible GC
1260   int size = size_helper();  // Query before forming handle.
1261 
1262   instanceOop i;
1263 
1264   i = (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1265   if (has_finalizer_flag && !RegisterFinalizersAtInit) {
1266     i = register_finalizer(i, CHECK_NULL);
1267   }
1268   return i;
1269 }
1270 
1271 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1272   return instanceHandle(THREAD, allocate_instance(THREAD));
1273 }
1274 
1275 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1276   if (is_interface() || is_abstract()) {
1277     ResourceMark rm(THREAD);
1278     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1279               : vmSymbols::java_lang_InstantiationException(), external_name());
1280   }
1281   if (this == SystemDictionary::Class_klass()) {
1282     ResourceMark rm(THREAD);
1283     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1284               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1285   }
1286 }
1287 
1288 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
1289   // Need load-acquire for lock-free read
1290   if (array_klasses_acquire() == NULL) {
1291     if (or_null) return NULL;
1292 
1293     ResourceMark rm;
1294     JavaThread *jt = (JavaThread *)THREAD;
1295     {
1296       // Atomic creation of array_klasses
1297       MutexLocker ma(MultiArray_lock, THREAD);
1298 
1299       // Check if update has already taken place
1300       if (array_klasses() == NULL) {
1301         Klass*    k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1302         // use 'release' to pair with lock-free load
1303         release_set_array_klasses(k);
1304       }
1305     }
1306   }
1307   // _this will always be set at this point
1308   ObjArrayKlass* oak = (ObjArrayKlass*)array_klasses();
1309   if (or_null) {
1310     return oak->array_klass_or_null(n);
1311   }
1312   return oak->array_klass(n, THREAD);
1313 }
1314 
1315 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
1316   return array_klass_impl(or_null, 1, THREAD);
1317 }
1318 
1319 static int call_class_initializer_counter = 0;   // for debugging
1320 
1321 Method* InstanceKlass::class_initializer() const {
1322   Method* clinit = find_method(
1323       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1324   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1325     return clinit;
1326   }
1327   return NULL;
1328 }
1329 
1330 void InstanceKlass::call_class_initializer(TRAPS) {
1331   if (ReplayCompiles &&
1332       (ReplaySuppressInitializers == 1 ||
1333        (ReplaySuppressInitializers >= 2 && class_loader() != NULL))) {
1334     // Hide the existence of the initializer for the purpose of replaying the compile
1335     return;
1336   }
1337 
1338   methodHandle h_method(THREAD, class_initializer());
1339   assert(!is_initialized(), "we cannot initialize twice");
1340   LogTarget(Info, class, init) lt;
1341   if (lt.is_enabled()) {
1342     ResourceMark rm;
1343     LogStream ls(lt);
1344     ls.print("%d Initializing ", call_class_initializer_counter++);
1345     name()->print_value_on(&ls);
1346     ls.print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this));
1347   }
1348   if (h_method() != NULL) {
1349     JavaCallArguments args; // No arguments
1350     JavaValue result(T_VOID);
1351     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1352   }
1353 }
1354 
1355 
1356 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1357   InterpreterOopMap* entry_for) {
1358   // Lazily create the _oop_map_cache at first request
1359   // Lock-free access requires load_acquire.
1360   OopMapCache* oop_map_cache = OrderAccess::load_acquire(&_oop_map_cache);
1361   if (oop_map_cache == NULL) {
1362     MutexLocker x(OopMapCacheAlloc_lock);
1363     // Check if _oop_map_cache was allocated while we were waiting for this lock
1364     if ((oop_map_cache = _oop_map_cache) == NULL) {
1365       oop_map_cache = new OopMapCache();
1366       // Ensure _oop_map_cache is stable, since it is examined without a lock
1367       OrderAccess::release_store(&_oop_map_cache, oop_map_cache);
1368     }
1369   }
1370   // _oop_map_cache is constant after init; lookup below does its own locking.
1371   oop_map_cache->lookup(method, bci, entry_for);
1372 }
1373 
1374 
1375 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1376   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1377     Symbol* f_name = fs.name();
1378     Symbol* f_sig  = fs.signature();
1379     if (f_name == name && f_sig == sig) {
1380       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1381       return true;
1382     }
1383   }
1384   return false;
1385 }
1386 
1387 
1388 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1389   const int n = local_interfaces()->length();
1390   for (int i = 0; i < n; i++) {
1391     Klass* intf1 = local_interfaces()->at(i);
1392     assert(intf1->is_interface(), "just checking type");
1393     // search for field in current interface
1394     if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1395       assert(fd->is_static(), "interface field must be static");
1396       return intf1;
1397     }
1398     // search for field in direct superinterfaces
1399     Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1400     if (intf2 != NULL) return intf2;
1401   }
1402   // otherwise field lookup fails
1403   return NULL;
1404 }
1405 
1406 
1407 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1408   // search order according to newest JVM spec (5.4.3.2, p.167).
1409   // 1) search for field in current klass
1410   if (find_local_field(name, sig, fd)) {
1411     return const_cast<InstanceKlass*>(this);
1412   }
1413   // 2) search for field recursively in direct superinterfaces
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, fd);
1420   }
1421   // 4) otherwise field lookup fails
1422   return NULL;
1423 }
1424 
1425 
1426 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1427   // search order according to newest JVM spec (5.4.3.2, p.167).
1428   // 1) search for field in current klass
1429   if (find_local_field(name, sig, fd)) {
1430     if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1431   }
1432   // 2) search for field recursively in direct superinterfaces
1433   if (is_static) {
1434     Klass* intf = find_interface_field(name, sig, fd);
1435     if (intf != NULL) return intf;
1436   }
1437   // 3) apply field lookup recursively if superclass exists
1438   { Klass* supr = super();
1439     if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1440   }
1441   // 4) otherwise field lookup fails
1442   return NULL;
1443 }
1444 
1445 
1446 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1447   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1448     if (fs.offset() == offset) {
1449       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1450       if (fd->is_static() == is_static) return true;
1451     }
1452   }
1453   return false;
1454 }
1455 
1456 
1457 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1458   Klass* klass = const_cast<InstanceKlass*>(this);
1459   while (klass != NULL) {
1460     if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1461       return true;
1462     }
1463     klass = klass->super();
1464   }
1465   return false;
1466 }
1467 
1468 
1469 void InstanceKlass::methods_do(void f(Method* method)) {
1470   // Methods aren't stable until they are loaded.  This can be read outside
1471   // a lock through the ClassLoaderData for profiling
1472   if (!is_loaded()) {
1473     return;
1474   }
1475 
1476   int len = methods()->length();
1477   for (int index = 0; index < len; index++) {
1478     Method* m = methods()->at(index);
1479     assert(m->is_method(), "must be method");
1480     f(m);
1481   }
1482 }
1483 
1484 
1485 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1486   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1487     if (fs.access_flags().is_static()) {
1488       fieldDescriptor& fd = fs.field_descriptor();
1489       cl->do_field(&fd);
1490     }
1491   }
1492 }
1493 
1494 
1495 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1496   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1497     if (fs.access_flags().is_static()) {
1498       fieldDescriptor& fd = fs.field_descriptor();
1499       f(&fd, mirror, CHECK);
1500     }
1501   }
1502 }
1503 
1504 
1505 static int compare_fields_by_offset(int* a, int* b) {
1506   return a[0] - b[0];
1507 }
1508 
1509 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1510   InstanceKlass* super = superklass();
1511   if (super != NULL) {
1512     super->do_nonstatic_fields(cl);
1513   }
1514   fieldDescriptor fd;
1515   int length = java_fields_count();
1516   // In DebugInfo nonstatic fields are sorted by offset.
1517   int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1518   int j = 0;
1519   for (int i = 0; i < length; i += 1) {
1520     fd.reinitialize(this, i);
1521     if (!fd.is_static()) {
1522       fields_sorted[j + 0] = fd.offset();
1523       fields_sorted[j + 1] = i;
1524       j += 2;
1525     }
1526   }
1527   if (j > 0) {
1528     length = j;
1529     // _sort_Fn is defined in growableArray.hpp.
1530     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1531     for (int i = 0; i < length; i += 2) {
1532       fd.reinitialize(this, fields_sorted[i + 1]);
1533       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1534       cl->do_field(&fd);
1535     }
1536   }
1537   FREE_C_HEAP_ARRAY(int, fields_sorted);
1538 }
1539 
1540 
1541 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
1542   if (array_klasses() != NULL)
1543     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
1544 }
1545 
1546 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1547   if (array_klasses() != NULL)
1548     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1549 }
1550 
1551 #ifdef ASSERT
1552 static int linear_search(const Array<Method*>* methods,
1553                          const Symbol* name,
1554                          const Symbol* signature) {
1555   const int len = methods->length();
1556   for (int index = 0; index < len; index++) {
1557     const Method* const m = methods->at(index);
1558     assert(m->is_method(), "must be method");
1559     if (m->signature() == signature && m->name() == name) {
1560        return index;
1561     }
1562   }
1563   return -1;
1564 }
1565 #endif
1566 
1567 static int binary_search(const Array<Method*>* methods, const Symbol* name) {
1568   int len = methods->length();
1569   // methods are sorted, so do binary search
1570   int l = 0;
1571   int h = len - 1;
1572   while (l <= h) {
1573     int mid = (l + h) >> 1;
1574     Method* m = methods->at(mid);
1575     assert(m->is_method(), "must be method");
1576     int res = m->name()->fast_compare(name);
1577     if (res == 0) {
1578       return mid;
1579     } else if (res < 0) {
1580       l = mid + 1;
1581     } else {
1582       h = mid - 1;
1583     }
1584   }
1585   return -1;
1586 }
1587 
1588 // find_method looks up the name/signature in the local methods array
1589 Method* InstanceKlass::find_method(const Symbol* name,
1590                                    const Symbol* signature) const {
1591   return find_method_impl(name, signature, find_overpass, find_static, find_private);
1592 }
1593 
1594 Method* InstanceKlass::find_method_impl(const Symbol* name,
1595                                         const Symbol* signature,
1596                                         OverpassLookupMode overpass_mode,
1597                                         StaticLookupMode static_mode,
1598                                         PrivateLookupMode private_mode) const {
1599   return InstanceKlass::find_method_impl(methods(),
1600                                          name,
1601                                          signature,
1602                                          overpass_mode,
1603                                          static_mode,
1604                                          private_mode);
1605 }
1606 
1607 // find_instance_method looks up the name/signature in the local methods array
1608 // and skips over static methods
1609 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,
1610                                             const Symbol* name,
1611                                             const Symbol* signature,
1612                                             PrivateLookupMode private_mode) {
1613   Method* const meth = InstanceKlass::find_method_impl(methods,
1614                                                  name,
1615                                                  signature,
1616                                                  find_overpass,
1617                                                  skip_static,
1618                                                  private_mode);
1619   assert(((meth == NULL) || !meth->is_static()),
1620     "find_instance_method should have skipped statics");
1621   return meth;
1622 }
1623 
1624 // find_instance_method looks up the name/signature in the local methods array
1625 // and skips over static methods
1626 Method* InstanceKlass::find_instance_method(const Symbol* name,
1627                                             const Symbol* signature,
1628                                             PrivateLookupMode private_mode) const {
1629   return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);
1630 }
1631 
1632 // Find looks up the name/signature in the local methods array
1633 // and filters on the overpass, static and private flags
1634 // This returns the first one found
1635 // note that the local methods array can have up to one overpass, one static
1636 // and one instance (private or not) with the same name/signature
1637 Method* InstanceKlass::find_local_method(const Symbol* name,
1638                                          const Symbol* signature,
1639                                          OverpassLookupMode overpass_mode,
1640                                          StaticLookupMode static_mode,
1641                                          PrivateLookupMode private_mode) const {
1642   return InstanceKlass::find_method_impl(methods(),
1643                                          name,
1644                                          signature,
1645                                          overpass_mode,
1646                                          static_mode,
1647                                          private_mode);
1648 }
1649 
1650 // Find looks up the name/signature in the local methods array
1651 // and filters on the overpass, static and private flags
1652 // This returns the first one found
1653 // note that the local methods array can have up to one overpass, one static
1654 // and one instance (private or not) with the same name/signature
1655 Method* InstanceKlass::find_local_method(const Array<Method*>* methods,
1656                                          const Symbol* name,
1657                                          const Symbol* signature,
1658                                          OverpassLookupMode overpass_mode,
1659                                          StaticLookupMode static_mode,
1660                                          PrivateLookupMode private_mode) {
1661   return InstanceKlass::find_method_impl(methods,
1662                                          name,
1663                                          signature,
1664                                          overpass_mode,
1665                                          static_mode,
1666                                          private_mode);
1667 }
1668 
1669 Method* InstanceKlass::find_method(const Array<Method*>* methods,
1670                                    const Symbol* name,
1671                                    const Symbol* signature) {
1672   return InstanceKlass::find_method_impl(methods,
1673                                          name,
1674                                          signature,
1675                                          find_overpass,
1676                                          find_static,
1677                                          find_private);
1678 }
1679 
1680 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,
1681                                         const Symbol* name,
1682                                         const Symbol* signature,
1683                                         OverpassLookupMode overpass_mode,
1684                                         StaticLookupMode static_mode,
1685                                         PrivateLookupMode private_mode) {
1686   int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
1687   return hit >= 0 ? methods->at(hit): NULL;
1688 }
1689 
1690 // true if method matches signature and conforms to skipping_X conditions.
1691 static bool method_matches(const Method* m,
1692                            const Symbol* signature,
1693                            bool skipping_overpass,
1694                            bool skipping_static,
1695                            bool skipping_private) {
1696   return ((m->signature() == signature) &&
1697     (!skipping_overpass || !m->is_overpass()) &&
1698     (!skipping_static || !m->is_static()) &&
1699     (!skipping_private || !m->is_private()));
1700 }
1701 
1702 // Used directly for default_methods to find the index into the
1703 // default_vtable_indices, and indirectly by find_method
1704 // find_method_index looks in the local methods array to return the index
1705 // of the matching name/signature. If, overpass methods are being ignored,
1706 // the search continues to find a potential non-overpass match.  This capability
1707 // is important during method resolution to prefer a static method, for example,
1708 // over an overpass method.
1709 // There is the possibility in any _method's array to have the same name/signature
1710 // for a static method, an overpass method and a local instance method
1711 // To correctly catch a given method, the search criteria may need
1712 // to explicitly skip the other two. For local instance methods, it
1713 // is often necessary to skip private methods
1714 int InstanceKlass::find_method_index(const Array<Method*>* methods,
1715                                      const Symbol* name,
1716                                      const Symbol* signature,
1717                                      OverpassLookupMode overpass_mode,
1718                                      StaticLookupMode static_mode,
1719                                      PrivateLookupMode private_mode) {
1720   const bool skipping_overpass = (overpass_mode == skip_overpass);
1721   const bool skipping_static = (static_mode == skip_static);
1722   const bool skipping_private = (private_mode == skip_private);
1723   const int hit = binary_search(methods, name);
1724   if (hit != -1) {
1725     const Method* const m = methods->at(hit);
1726 
1727     // Do linear search to find matching signature.  First, quick check
1728     // for common case, ignoring overpasses if requested.
1729     if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1730       return hit;
1731     }
1732 
1733     // search downwards through overloaded methods
1734     int i;
1735     for (i = hit - 1; i >= 0; --i) {
1736         const Method* const m = methods->at(i);
1737         assert(m->is_method(), "must be method");
1738         if (m->name() != name) {
1739           break;
1740         }
1741         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1742           return i;
1743         }
1744     }
1745     // search upwards
1746     for (i = hit + 1; i < methods->length(); ++i) {
1747         const Method* const m = methods->at(i);
1748         assert(m->is_method(), "must be method");
1749         if (m->name() != name) {
1750           break;
1751         }
1752         if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
1753           return i;
1754         }
1755     }
1756     // not found
1757 #ifdef ASSERT
1758     const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :
1759       linear_search(methods, name, signature);
1760     assert(-1 == index, "binary search should have found entry %d", index);
1761 #endif
1762   }
1763   return -1;
1764 }
1765 
1766 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {
1767   return find_method_by_name(methods(), name, end);
1768 }
1769 
1770 int InstanceKlass::find_method_by_name(const Array<Method*>* methods,
1771                                        const Symbol* name,
1772                                        int* end_ptr) {
1773   assert(end_ptr != NULL, "just checking");
1774   int start = binary_search(methods, name);
1775   int end = start + 1;
1776   if (start != -1) {
1777     while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1778     while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1779     *end_ptr = end;
1780     return start;
1781   }
1782   return -1;
1783 }
1784 
1785 // uncached_lookup_method searches both the local class methods array and all
1786 // superclasses methods arrays, skipping any overpass methods in superclasses,
1787 // and possibly skipping private methods.
1788 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
1789                                               const Symbol* signature,
1790                                               OverpassLookupMode overpass_mode,
1791                                               PrivateLookupMode private_mode) const {
1792   OverpassLookupMode overpass_local_mode = overpass_mode;
1793   const Klass* klass = this;
1794   while (klass != NULL) {
1795     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
1796                                                                         signature,
1797                                                                         overpass_local_mode,
1798                                                                         find_static,
1799                                                                         private_mode);
1800     if (method != NULL) {
1801       return method;
1802     }
1803     klass = klass->super();
1804     overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1805   }
1806   return NULL;
1807 }
1808 
1809 #ifdef ASSERT
1810 // search through class hierarchy and return true if this class or
1811 // one of the superclasses was redefined
1812 bool InstanceKlass::has_redefined_this_or_super() const {
1813   const Klass* klass = this;
1814   while (klass != NULL) {
1815     if (InstanceKlass::cast(klass)->has_been_redefined()) {
1816       return true;
1817     }
1818     klass = klass->super();
1819   }
1820   return false;
1821 }
1822 #endif
1823 
1824 // lookup a method in the default methods list then in all transitive interfaces
1825 // Do NOT return private or static methods
1826 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
1827                                                          Symbol* signature) const {
1828   Method* m = NULL;
1829   if (default_methods() != NULL) {
1830     m = find_method(default_methods(), name, signature);
1831   }
1832   // Look up interfaces
1833   if (m == NULL) {
1834     m = lookup_method_in_all_interfaces(name, signature, find_defaults);
1835   }
1836   return m;
1837 }
1838 
1839 // lookup a method in all the interfaces that this class implements
1840 // Do NOT return private or static methods, new in JDK8 which are not externally visible
1841 // They should only be found in the initial InterfaceMethodRef
1842 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1843                                                        Symbol* signature,
1844                                                        DefaultsLookupMode defaults_mode) const {
1845   Array<InstanceKlass*>* all_ifs = transitive_interfaces();
1846   int num_ifs = all_ifs->length();
1847   InstanceKlass *ik = NULL;
1848   for (int i = 0; i < num_ifs; i++) {
1849     ik = all_ifs->at(i);
1850     Method* m = ik->lookup_method(name, signature);
1851     if (m != NULL && m->is_public() && !m->is_static() &&
1852         ((defaults_mode != skip_defaults) || !m->is_default_method())) {
1853       return m;
1854     }
1855   }
1856   return NULL;
1857 }
1858 
1859 /* jni_id_for_impl for jfieldIds only */
1860 JNIid* InstanceKlass::jni_id_for_impl(int offset) {
1861   MutexLocker ml(JfieldIdCreation_lock);
1862   // Retry lookup after we got the lock
1863   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1864   if (probe == NULL) {
1865     // Slow case, allocate new static field identifier
1866     probe = new JNIid(this, offset, jni_ids());
1867     set_jni_ids(probe);
1868   }
1869   return probe;
1870 }
1871 
1872 
1873 /* jni_id_for for jfieldIds only */
1874 JNIid* InstanceKlass::jni_id_for(int offset) {
1875   JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1876   if (probe == NULL) {
1877     probe = jni_id_for_impl(offset);
1878   }
1879   return probe;
1880 }
1881 
1882 u2 InstanceKlass::enclosing_method_data(int offset) const {
1883   const Array<jushort>* const inner_class_list = inner_classes();
1884   if (inner_class_list == NULL) {
1885     return 0;
1886   }
1887   const int length = inner_class_list->length();
1888   if (length % inner_class_next_offset == 0) {
1889     return 0;
1890   }
1891   const int index = length - enclosing_method_attribute_size;
1892   assert(offset < enclosing_method_attribute_size, "invalid offset");
1893   return inner_class_list->at(index + offset);
1894 }
1895 
1896 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
1897                                                  u2 method_index) {
1898   Array<jushort>* inner_class_list = inner_classes();
1899   assert (inner_class_list != NULL, "_inner_classes list is not set up");
1900   int length = inner_class_list->length();
1901   if (length % inner_class_next_offset == enclosing_method_attribute_size) {
1902     int index = length - enclosing_method_attribute_size;
1903     inner_class_list->at_put(
1904       index + enclosing_method_class_index_offset, class_index);
1905     inner_class_list->at_put(
1906       index + enclosing_method_method_index_offset, method_index);
1907   }
1908 }
1909 
1910 // Lookup or create a jmethodID.
1911 // This code is called by the VMThread and JavaThreads so the
1912 // locking has to be done very carefully to avoid deadlocks
1913 // and/or other cache consistency problems.
1914 //
1915 jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) {
1916   size_t idnum = (size_t)method_h->method_idnum();
1917   jmethodID* jmeths = methods_jmethod_ids_acquire();
1918   size_t length = 0;
1919   jmethodID id = NULL;
1920 
1921   // We use a double-check locking idiom here because this cache is
1922   // performance sensitive. In the normal system, this cache only
1923   // transitions from NULL to non-NULL which is safe because we use
1924   // release_set_methods_jmethod_ids() to advertise the new cache.
1925   // A partially constructed cache should never be seen by a racing
1926   // thread. We also use release_store() to save a new jmethodID
1927   // in the cache so a partially constructed jmethodID should never be
1928   // seen either. Cache reads of existing jmethodIDs proceed without a
1929   // lock, but cache writes of a new jmethodID requires uniqueness and
1930   // creation of the cache itself requires no leaks so a lock is
1931   // generally acquired in those two cases.
1932   //
1933   // If the RedefineClasses() API has been used, then this cache can
1934   // grow and we'll have transitions from non-NULL to bigger non-NULL.
1935   // Cache creation requires no leaks and we require safety between all
1936   // cache accesses and freeing of the old cache so a lock is generally
1937   // acquired when the RedefineClasses() API has been used.
1938 
1939   if (jmeths != NULL) {
1940     // the cache already exists
1941     if (!idnum_can_increment()) {
1942       // the cache can't grow so we can just get the current values
1943       get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1944     } else {
1945       // cache can grow so we have to be more careful
1946       if (Threads::number_of_threads() == 0 ||
1947           SafepointSynchronize::is_at_safepoint()) {
1948         // we're single threaded or at a safepoint - no locking needed
1949         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1950       } else {
1951         MutexLocker ml(JmethodIdCreation_lock);
1952         get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1953       }
1954     }
1955   }
1956   // implied else:
1957   // we need to allocate a cache so default length and id values are good
1958 
1959   if (jmeths == NULL ||   // no cache yet
1960       length <= idnum ||  // cache is too short
1961       id == NULL) {       // cache doesn't contain entry
1962 
1963     // This function can be called by the VMThread so we have to do all
1964     // things that might block on a safepoint before grabbing the lock.
1965     // Otherwise, we can deadlock with the VMThread or have a cache
1966     // consistency issue. These vars keep track of what we might have
1967     // to free after the lock is dropped.
1968     jmethodID  to_dealloc_id     = NULL;
1969     jmethodID* to_dealloc_jmeths = NULL;
1970 
1971     // may not allocate new_jmeths or use it if we allocate it
1972     jmethodID* new_jmeths = NULL;
1973     if (length <= idnum) {
1974       // allocate a new cache that might be used
1975       size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
1976       new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
1977       memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1978       // cache size is stored in element[0], other elements offset by one
1979       new_jmeths[0] = (jmethodID)size;
1980     }
1981 
1982     // allocate a new jmethodID that might be used
1983     jmethodID new_id = NULL;
1984     if (method_h->is_old() && !method_h->is_obsolete()) {
1985       // The method passed in is old (but not obsolete), we need to use the current version
1986       Method* current_method = method_with_idnum((int)idnum);
1987       assert(current_method != NULL, "old and but not obsolete, so should exist");
1988       new_id = Method::make_jmethod_id(class_loader_data(), current_method);
1989     } else {
1990       // It is the current version of the method or an obsolete method,
1991       // use the version passed in
1992       new_id = Method::make_jmethod_id(class_loader_data(), method_h());
1993     }
1994 
1995     if (Threads::number_of_threads() == 0 ||
1996         SafepointSynchronize::is_at_safepoint()) {
1997       // we're single threaded or at a safepoint - no locking needed
1998       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
1999                                           &to_dealloc_id, &to_dealloc_jmeths);
2000     } else {
2001       MutexLocker ml(JmethodIdCreation_lock);
2002       id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths,
2003                                           &to_dealloc_id, &to_dealloc_jmeths);
2004     }
2005 
2006     // The lock has been dropped so we can free resources.
2007     // Free up either the old cache or the new cache if we allocated one.
2008     if (to_dealloc_jmeths != NULL) {
2009       FreeHeap(to_dealloc_jmeths);
2010     }
2011     // free up the new ID since it wasn't needed
2012     if (to_dealloc_id != NULL) {
2013       Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id);
2014     }
2015   }
2016   return id;
2017 }
2018 
2019 // Figure out how many jmethodIDs haven't been allocated, and make
2020 // sure space for them is pre-allocated.  This makes getting all
2021 // method ids much, much faster with classes with more than 8
2022 // methods, and has a *substantial* effect on performance with jvmti
2023 // code that loads all jmethodIDs for all classes.
2024 void InstanceKlass::ensure_space_for_methodids(int start_offset) {
2025   int new_jmeths = 0;
2026   int length = methods()->length();
2027   for (int index = start_offset; index < length; index++) {
2028     Method* m = methods()->at(index);
2029     jmethodID id = m->find_jmethod_id_or_null();
2030     if (id == NULL) {
2031       new_jmeths++;
2032     }
2033   }
2034   if (new_jmeths != 0) {
2035     Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
2036   }
2037 }
2038 
2039 // Common code to fetch the jmethodID from the cache or update the
2040 // cache with the new jmethodID. This function should never do anything
2041 // that causes the caller to go to a safepoint or we can deadlock with
2042 // the VMThread or have cache consistency issues.
2043 //
2044 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
2045             size_t idnum, jmethodID new_id,
2046             jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
2047             jmethodID** to_dealloc_jmeths_p) {
2048   assert(new_id != NULL, "sanity check");
2049   assert(to_dealloc_id_p != NULL, "sanity check");
2050   assert(to_dealloc_jmeths_p != NULL, "sanity check");
2051   assert(Threads::number_of_threads() == 0 ||
2052          SafepointSynchronize::is_at_safepoint() ||
2053          JmethodIdCreation_lock->owned_by_self(), "sanity check");
2054 
2055   // reacquire the cache - we are locked, single threaded or at a safepoint
2056   jmethodID* jmeths = methods_jmethod_ids_acquire();
2057   jmethodID  id     = NULL;
2058   size_t     length = 0;
2059 
2060   if (jmeths == NULL ||                         // no cache yet
2061       (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
2062     if (jmeths != NULL) {
2063       // copy any existing entries from the old cache
2064       for (size_t index = 0; index < length; index++) {
2065         new_jmeths[index+1] = jmeths[index+1];
2066       }
2067       *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
2068     }
2069     release_set_methods_jmethod_ids(jmeths = new_jmeths);
2070   } else {
2071     // fetch jmethodID (if any) from the existing cache
2072     id = jmeths[idnum+1];
2073     *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
2074   }
2075   if (id == NULL) {
2076     // No matching jmethodID in the existing cache or we have a new
2077     // cache or we just grew the cache. This cache write is done here
2078     // by the first thread to win the foot race because a jmethodID
2079     // needs to be unique once it is generally available.
2080     id = new_id;
2081 
2082     // The jmethodID cache can be read while unlocked so we have to
2083     // make sure the new jmethodID is complete before installing it
2084     // in the cache.
2085     OrderAccess::release_store(&jmeths[idnum+1], id);
2086   } else {
2087     *to_dealloc_id_p = new_id; // save new id for later delete
2088   }
2089   return id;
2090 }
2091 
2092 
2093 // Common code to get the jmethodID cache length and the jmethodID
2094 // value at index idnum if there is one.
2095 //
2096 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
2097        size_t idnum, size_t *length_p, jmethodID* id_p) {
2098   assert(cache != NULL, "sanity check");
2099   assert(length_p != NULL, "sanity check");
2100   assert(id_p != NULL, "sanity check");
2101 
2102   // cache size is stored in element[0], other elements offset by one
2103   *length_p = (size_t)cache[0];
2104   if (*length_p <= idnum) {  // cache is too short
2105     *id_p = NULL;
2106   } else {
2107     *id_p = cache[idnum+1];  // fetch jmethodID (if any)
2108   }
2109 }
2110 
2111 
2112 // Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
2113 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2114   size_t idnum = (size_t)method->method_idnum();
2115   jmethodID* jmeths = methods_jmethod_ids_acquire();
2116   size_t length;                                // length assigned as debugging crumb
2117   jmethodID id = NULL;
2118   if (jmeths != NULL &&                         // If there is a cache
2119       (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
2120     id = jmeths[idnum+1];                       // Look up the id (may be NULL)
2121   }
2122   return id;
2123 }
2124 
2125 inline DependencyContext InstanceKlass::dependencies() {
2126   DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2127   return dep_context;
2128 }
2129 
2130 int InstanceKlass::mark_dependent_nmethods(KlassDepChange& changes) {
2131   return dependencies().mark_dependent_nmethods(changes);
2132 }
2133 
2134 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2135   dependencies().add_dependent_nmethod(nm);
2136 }
2137 
2138 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
2139   dependencies().remove_dependent_nmethod(nm);
2140 }
2141 
2142 void InstanceKlass::clean_dependency_context() {
2143   dependencies().clean_unloading_dependents();
2144 }
2145 
2146 #ifndef PRODUCT
2147 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2148   dependencies().print_dependent_nmethods(verbose);
2149 }
2150 
2151 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2152   return dependencies().is_dependent_nmethod(nm);
2153 }
2154 #endif //PRODUCT
2155 
2156 void InstanceKlass::clean_weak_instanceklass_links() {
2157   clean_implementors_list();
2158   clean_method_data();
2159 }
2160 
2161 void InstanceKlass::clean_implementors_list() {
2162   assert(is_loader_alive(), "this klass should be live");
2163   if (is_interface()) {
2164     assert (ClassUnloading, "only called for ClassUnloading");
2165     for (;;) {
2166       // Use load_acquire due to competing with inserts
2167       Klass* impl = OrderAccess::load_acquire(adr_implementor());
2168       if (impl != NULL && !impl->is_loader_alive()) {
2169         // NULL this field, might be an unloaded klass or NULL
2170         Klass* volatile* klass = adr_implementor();
2171         if (Atomic::cmpxchg((Klass*)NULL, klass, impl) == impl) {
2172           // Successfully unlinking implementor.
2173           if (log_is_enabled(Trace, class, unload)) {
2174             ResourceMark rm;
2175             log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name());
2176           }
2177           return;
2178         }
2179       } else {
2180         return;
2181       }
2182     }
2183   }
2184 }
2185 
2186 void InstanceKlass::clean_method_data() {
2187   for (int m = 0; m < methods()->length(); m++) {
2188     MethodData* mdo = methods()->at(m)->method_data();
2189     if (mdo != NULL) {
2190       MutexLockerEx ml(SafepointSynchronize::is_at_safepoint() ? NULL : mdo->extra_data_lock());
2191       mdo->clean_method_data(/*always_clean*/false);
2192     }
2193   }
2194 }
2195 
2196 bool InstanceKlass::supers_have_passed_fingerprint_checks() {
2197   if (java_super() != NULL && !java_super()->has_passed_fingerprint_check()) {
2198     ResourceMark rm;
2199     log_trace(class, fingerprint)("%s : super %s not fingerprinted", external_name(), java_super()->external_name());
2200     return false;
2201   }
2202 
2203   Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
2204   if (local_interfaces != NULL) {
2205     int length = local_interfaces->length();
2206     for (int i = 0; i < length; i++) {
2207       InstanceKlass* intf = local_interfaces->at(i);
2208       if (!intf->has_passed_fingerprint_check()) {
2209         ResourceMark rm;
2210         log_trace(class, fingerprint)("%s : interface %s not fingerprinted", external_name(), intf->external_name());
2211         return false;
2212       }
2213     }
2214   }
2215 
2216   return true;
2217 }
2218 
2219 bool InstanceKlass::should_store_fingerprint(bool is_unsafe_anonymous) {
2220 #if INCLUDE_AOT
2221   // We store the fingerprint into the InstanceKlass only in the following 2 cases:
2222   if (CalculateClassFingerprint) {
2223     // (1) We are running AOT to generate a shared library.
2224     return true;
2225   }
2226   if (DumpSharedSpaces) {
2227     // (2) We are running -Xshare:dump to create a shared archive
2228     return true;
2229   }
2230   if (UseAOT && is_unsafe_anonymous) {
2231     // (3) We are using AOT code from a shared library and see an unsafe anonymous class
2232     return true;
2233   }
2234 #endif
2235 
2236   // In all other cases we might set the _misc_has_passed_fingerprint_check bit,
2237   // but do not store the 64-bit fingerprint to save space.
2238   return false;
2239 }
2240 
2241 bool InstanceKlass::has_stored_fingerprint() const {
2242 #if INCLUDE_AOT
2243   return should_store_fingerprint() || is_shared();
2244 #else
2245   return false;
2246 #endif
2247 }
2248 
2249 uint64_t InstanceKlass::get_stored_fingerprint() const {
2250   address adr = adr_fingerprint();
2251   if (adr != NULL) {
2252     return (uint64_t)Bytes::get_native_u8(adr); // adr may not be 64-bit aligned
2253   }
2254   return 0;
2255 }
2256 
2257 void InstanceKlass::store_fingerprint(uint64_t fingerprint) {
2258   address adr = adr_fingerprint();
2259   if (adr != NULL) {
2260     Bytes::put_native_u8(adr, (u8)fingerprint); // adr may not be 64-bit aligned
2261 
2262     ResourceMark rm;
2263     log_trace(class, fingerprint)("stored as " PTR64_FORMAT " for class %s", fingerprint, external_name());
2264   }
2265 }
2266 
2267 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {
2268   Klass::metaspace_pointers_do(it);
2269 
2270   if (log_is_enabled(Trace, cds)) {
2271     ResourceMark rm;
2272     log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name());
2273   }
2274 
2275   it->push(&_annotations);
2276   it->push((Klass**)&_array_klasses);
2277   it->push(&_constants);
2278   it->push(&_inner_classes);
2279   it->push(&_array_name);
2280 #if INCLUDE_JVMTI
2281   it->push(&_previous_versions);
2282 #endif
2283   it->push(&_methods);
2284   it->push(&_default_methods);
2285   it->push(&_local_interfaces);
2286   it->push(&_transitive_interfaces);
2287   it->push(&_method_ordering);
2288   it->push(&_default_vtable_indices);
2289   it->push(&_fields);
2290 
2291   if (itable_length() > 0) {
2292     itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2293     int method_table_offset_in_words = ioe->offset()/wordSize;
2294     int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2295                          / itableOffsetEntry::size();
2296 
2297     for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2298       if (ioe->interface_klass() != NULL) {
2299         it->push(ioe->interface_klass_addr());
2300         itableMethodEntry* ime = ioe->first_method_entry(this);
2301         int n = klassItable::method_count_for_interface(ioe->interface_klass());
2302         for (int index = 0; index < n; index ++) {
2303           it->push(ime[index].method_addr());
2304         }
2305       }
2306     }
2307   }
2308 
2309   it->push(&_nest_members);
2310 }
2311 
2312 void InstanceKlass::remove_unshareable_info() {
2313   Klass::remove_unshareable_info();
2314 
2315   if (is_in_error_state()) {
2316     // Classes are attempted to link during dumping and may fail,
2317     // but these classes are still in the dictionary and class list in CLD.
2318     // Check in_error state first because in_error is > linked state, so
2319     // is_linked() is true.
2320     // If there's a linking error, there is nothing else to remove.
2321     return;
2322   }
2323 
2324   // Reset to the 'allocated' state to prevent any premature accessing to
2325   // a shared class at runtime while the class is still being loaded and
2326   // restored. A class' init_state is set to 'loaded' at runtime when it's
2327   // being added to class hierarchy (see SystemDictionary:::add_to_hierarchy()).
2328   _init_state = allocated;
2329 
2330   {
2331     MutexLocker ml(Compile_lock);
2332     init_implementor();
2333   }
2334 
2335   constants()->remove_unshareable_info();
2336 
2337   for (int i = 0; i < methods()->length(); i++) {
2338     Method* m = methods()->at(i);
2339     m->remove_unshareable_info();
2340   }
2341 
2342   // do array classes also.
2343   if (array_klasses() != NULL) {
2344     array_klasses()->remove_unshareable_info();
2345   }
2346 
2347   // These are not allocated from metaspace, but they should should all be empty
2348   // during dump time, so we don't need to worry about them in InstanceKlass::iterate().
2349   guarantee(_source_debug_extension == NULL, "must be");
2350   guarantee(_dep_context == NULL, "must be");
2351   guarantee(_osr_nmethods_head == NULL, "must be");
2352 
2353 #if INCLUDE_JVMTI
2354   guarantee(_breakpoints == NULL, "must be");
2355   guarantee(_previous_versions == NULL, "must be");
2356   _cached_class_file = NULL;
2357 #endif
2358 
2359   _init_thread = NULL;
2360   _methods_jmethod_ids = NULL;
2361   _jni_ids = NULL;
2362   _oop_map_cache = NULL;
2363   // clear _nest_host to ensure re-load at runtime
2364   _nest_host = NULL;
2365 }
2366 
2367 void InstanceKlass::remove_java_mirror() {
2368   Klass::remove_java_mirror();
2369 
2370   // do array classes also.
2371   if (array_klasses() != NULL) {
2372     array_klasses()->remove_java_mirror();
2373   }
2374 }
2375 
2376 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
2377   // SystemDictionary::add_to_hierarchy() sets the init_state to loaded
2378   // before the InstanceKlass is added to the SystemDictionary. Make
2379   // sure the current state is <loaded.
2380   assert(!is_loaded(), "invalid init state");
2381   set_package(loader_data, CHECK);
2382   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2383 
2384   Array<Method*>* methods = this->methods();
2385   int num_methods = methods->length();
2386   for (int index = 0; index < num_methods; ++index) {
2387     methods->at(index)->restore_unshareable_info(CHECK);
2388   }
2389   if (JvmtiExport::has_redefined_a_class()) {
2390     // Reinitialize vtable because RedefineClasses may have changed some
2391     // entries in this vtable for super classes so the CDS vtable might
2392     // point to old or obsolete entries.  RedefineClasses doesn't fix up
2393     // vtables in the shared system dictionary, only the main one.
2394     // It also redefines the itable too so fix that too.
2395     vtable().initialize_vtable(false, CHECK);
2396     itable().initialize_itable(false, CHECK);
2397   }
2398 
2399   // restore constant pool resolved references
2400   constants()->restore_unshareable_info(CHECK);
2401 
2402   if (array_klasses() != NULL) {
2403     // Array classes have null protection domain.
2404     // --> see ArrayKlass::complete_create_array_klass()
2405     array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2406   }
2407 }
2408 
2409 // returns true IFF is_in_error_state() has been changed as a result of this call.
2410 bool InstanceKlass::check_sharing_error_state() {
2411   assert(DumpSharedSpaces, "should only be called during dumping");
2412   bool old_state = is_in_error_state();
2413 
2414   if (!is_in_error_state()) {
2415     bool bad = false;
2416     for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
2417       if (sup->is_in_error_state()) {
2418         bad = true;
2419         break;
2420       }
2421     }
2422     if (!bad) {
2423       Array<InstanceKlass*>* interfaces = transitive_interfaces();
2424       for (int i = 0; i < interfaces->length(); i++) {
2425         InstanceKlass* iface = interfaces->at(i);
2426         if (iface->is_in_error_state()) {
2427           bad = true;
2428           break;
2429         }
2430       }
2431     }
2432 
2433     if (bad) {
2434       set_in_error_state();
2435     }
2436   }
2437 
2438   return (old_state != is_in_error_state());
2439 }
2440 
2441 void InstanceKlass::set_class_loader_type(s2 loader_type) {
2442   switch (loader_type) {
2443   case ClassLoader::BOOT_LOADER:
2444     _misc_flags |= _misc_is_shared_boot_class;
2445     break;
2446   case ClassLoader::PLATFORM_LOADER:
2447     _misc_flags |= _misc_is_shared_platform_class;
2448     break;
2449   case ClassLoader::APP_LOADER:
2450     _misc_flags |= _misc_is_shared_app_class;
2451     break;
2452   default:
2453     ShouldNotReachHere();
2454     break;
2455   }
2456 }
2457 
2458 #if INCLUDE_JVMTI
2459 static void clear_all_breakpoints(Method* m) {
2460   m->clear_all_breakpoints();
2461 }
2462 #endif
2463 
2464 void InstanceKlass::unload_class(InstanceKlass* ik) {
2465   // Release dependencies.
2466   ik->dependencies().remove_all_dependents();
2467 
2468   // notify the debugger
2469   if (JvmtiExport::should_post_class_unload()) {
2470     JvmtiExport::post_class_unload(ik);
2471   }
2472 
2473   // notify ClassLoadingService of class unload
2474   ClassLoadingService::notify_class_unloaded(ik);
2475 




2476   if (log_is_enabled(Info, class, unload)) {
2477     ResourceMark rm;
2478     log_info(class, unload)("unloading class %s " INTPTR_FORMAT, ik->external_name(), p2i(ik));
2479   }
2480 
2481   Events::log_class_unloading(Thread::current(), ik);
2482 
2483 #if INCLUDE_JFR
2484   assert(ik != NULL, "invariant");
2485   EventClassUnload event;
2486   event.set_unloadedClass(ik);
2487   event.set_definingClassLoader(ik->class_loader_data());
2488   event.commit();
2489 #endif
2490 }
2491 
2492 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
2493   // Clean up C heap
2494   ik->release_C_heap_structures();
2495   ik->constants()->release_C_heap_structures();
2496 }
2497 
2498 void InstanceKlass::release_C_heap_structures() {
2499   // Can't release the constant pool here because the constant pool can be
2500   // deallocated separately from the InstanceKlass for default methods and
2501   // redefine classes.
2502 
2503   // Deallocate oop map cache
2504   if (_oop_map_cache != NULL) {
2505     delete _oop_map_cache;
2506     _oop_map_cache = NULL;
2507   }
2508 
2509   // Deallocate JNI identifiers for jfieldIDs
2510   JNIid::deallocate(jni_ids());
2511   set_jni_ids(NULL);
2512 
2513   jmethodID* jmeths = methods_jmethod_ids_acquire();
2514   if (jmeths != (jmethodID*)NULL) {
2515     release_set_methods_jmethod_ids(NULL);
2516     FreeHeap(jmeths);
2517   }
2518 
2519   assert(_dep_context == NULL,
2520          "dependencies should already be cleaned");
2521 
2522 #if INCLUDE_JVMTI
2523   // Deallocate breakpoint records
2524   if (breakpoints() != 0x0) {
2525     methods_do(clear_all_breakpoints);
2526     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2527   }
2528 
2529   // deallocate the cached class file
2530   if (_cached_class_file != NULL) {
2531     os::free(_cached_class_file);
2532     _cached_class_file = NULL;
2533   }
2534 #endif
2535 
2536   // Decrement symbol reference counts associated with the unloaded class.
2537   if (_name != NULL) _name->decrement_refcount();
2538   // unreference array name derived from this class name (arrays of an unloaded
2539   // class can't be referenced anymore).
2540   if (_array_name != NULL)  _array_name->decrement_refcount();
2541   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension);
2542 }
2543 
2544 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
2545   if (array == NULL) {
2546     _source_debug_extension = NULL;
2547   } else {
2548     // Adding one to the attribute length in order to store a null terminator
2549     // character could cause an overflow because the attribute length is
2550     // already coded with an u4 in the classfile, but in practice, it's
2551     // unlikely to happen.
2552     assert((length+1) > length, "Overflow checking");
2553     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2554     for (int i = 0; i < length; i++) {
2555       sde[i] = array[i];
2556     }
2557     sde[length] = '\0';
2558     _source_debug_extension = sde;
2559   }
2560 }
2561 
2562 const char* InstanceKlass::signature_name() const {
2563   int hash_len = 0;
2564   char hash_buf[40];
2565 
2566   // If this is an unsafe anonymous class, append a hash to make the name unique
2567   if (is_unsafe_anonymous()) {
2568     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2569     jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash);
2570     hash_len = (int)strlen(hash_buf);
2571   }
2572 
2573   // Get the internal name as a c string
2574   const char* src = (const char*) (name()->as_C_string());
2575   const int src_length = (int)strlen(src);
2576 
2577   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2578 
2579   // Add L as type indicator
2580   int dest_index = 0;
2581   dest[dest_index++] = 'L';
2582 
2583   // Add the actual class name
2584   for (int src_index = 0; src_index < src_length; ) {
2585     dest[dest_index++] = src[src_index++];
2586   }
2587 
2588   // If we have a hash, append it
2589   for (int hash_index = 0; hash_index < hash_len; ) {
2590     dest[dest_index++] = hash_buf[hash_index++];
2591   }
2592 
2593   // Add the semicolon and the NULL
2594   dest[dest_index++] = ';';
2595   dest[dest_index] = '\0';
2596   return dest;
2597 }
2598 
2599 // Used to obtain the package name from a fully qualified class name.
2600 Symbol* InstanceKlass::package_from_name(const Symbol* name, TRAPS) {
2601   if (name == NULL) {
2602     return NULL;
2603   } else {
2604     if (name->utf8_length() <= 0) {
2605       return NULL;
2606     }
2607     ResourceMark rm;
2608     const char* package_name = ClassLoader::package_from_name((const char*) name->as_C_string());
2609     if (package_name == NULL) {
2610       return NULL;
2611     }
2612     Symbol* pkg_name = SymbolTable::new_symbol(package_name, THREAD);
2613     return pkg_name;
2614   }
2615 }
2616 
2617 ModuleEntry* InstanceKlass::module() const {
2618   // For an unsafe anonymous class return the host class' module
2619   if (is_unsafe_anonymous()) {
2620     assert(unsafe_anonymous_host() != NULL, "unsafe anonymous class must have a host class");
2621     return unsafe_anonymous_host()->module();
2622   }
2623 
2624   // Class is in a named package
2625   if (!in_unnamed_package()) {
2626     return _package_entry->module();
2627   }
2628 
2629   // Class is in an unnamed package, return its loader's unnamed module
2630   return class_loader_data()->unnamed_module();
2631 }
2632 
2633 void InstanceKlass::set_package(ClassLoaderData* loader_data, TRAPS) {
2634 
2635   // ensure java/ packages only loaded by boot or platform builtin loaders
2636   check_prohibited_package(name(), loader_data, CHECK);
2637 
2638   TempNewSymbol pkg_name = package_from_name(name(), CHECK);
2639 
2640   if (pkg_name != NULL && loader_data != NULL) {
2641 
2642     // Find in class loader's package entry table.
2643     _package_entry = loader_data->packages()->lookup_only(pkg_name);
2644 
2645     // If the package name is not found in the loader's package
2646     // entry table, it is an indication that the package has not
2647     // been defined. Consider it defined within the unnamed module.
2648     if (_package_entry == NULL) {
2649       ResourceMark rm;
2650 
2651       if (!ModuleEntryTable::javabase_defined()) {
2652         // Before java.base is defined during bootstrapping, define all packages in
2653         // the java.base module.  If a non-java.base package is erroneously placed
2654         // in the java.base module it will be caught later when java.base
2655         // is defined by ModuleEntryTable::verify_javabase_packages check.
2656         assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL");
2657         _package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry());
2658       } else {
2659         assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL");
2660         _package_entry = loader_data->packages()->lookup(pkg_name,
2661                                                          loader_data->unnamed_module());
2662       }
2663 
2664       // A package should have been successfully created
2665       assert(_package_entry != NULL, "Package entry for class %s not found, loader %s",
2666              name()->as_C_string(), loader_data->loader_name_and_id());
2667     }
2668 
2669     if (log_is_enabled(Debug, module)) {
2670       ResourceMark rm;
2671       ModuleEntry* m = _package_entry->module();
2672       log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",
2673                         external_name(),
2674                         pkg_name->as_C_string(),
2675                         loader_data->loader_name_and_id(),
2676                         (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));
2677     }
2678   } else {
2679     ResourceMark rm;
2680     log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",
2681                       external_name(),
2682                       (loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL",
2683                       UNNAMED_MODULE);
2684   }
2685 }
2686 
2687 
2688 // different versions of is_same_class_package
2689 
2690 bool InstanceKlass::is_same_class_package(const Klass* class2) const {
2691   oop classloader1 = this->class_loader();
2692   PackageEntry* classpkg1 = this->package();
2693   if (class2->is_objArray_klass()) {
2694     class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2695   }
2696 
2697   oop classloader2;
2698   PackageEntry* classpkg2;
2699   if (class2->is_instance_klass()) {
2700     classloader2 = class2->class_loader();
2701     classpkg2 = class2->package();
2702   } else {
2703     assert(class2->is_typeArray_klass(), "should be type array");
2704     classloader2 = NULL;
2705     classpkg2 = NULL;
2706   }
2707 
2708   // Same package is determined by comparing class loader
2709   // and package entries. Both must be the same. This rule
2710   // applies even to classes that are defined in the unnamed
2711   // package, they still must have the same class loader.
2712   if (oopDesc::equals(classloader1, classloader2) && (classpkg1 == classpkg2)) {
2713     return true;
2714   }
2715 
2716   return false;
2717 }
2718 
2719 // return true if this class and other_class are in the same package. Classloader
2720 // and classname information is enough to determine a class's package
2721 bool InstanceKlass::is_same_class_package(oop other_class_loader,
2722                                           const Symbol* other_class_name) const {
2723   if (!oopDesc::equals(class_loader(), other_class_loader)) {
2724     return false;
2725   }
2726   if (name()->fast_compare(other_class_name) == 0) {
2727      return true;
2728   }
2729 
2730   {
2731     ResourceMark rm;
2732 
2733     bool bad_class_name = false;
2734     const char* other_pkg =
2735       ClassLoader::package_from_name((const char*) other_class_name->as_C_string(), &bad_class_name);
2736     if (bad_class_name) {
2737       return false;
2738     }
2739     // Check that package_from_name() returns NULL, not "", if there is no package.
2740     assert(other_pkg == NULL || strlen(other_pkg) > 0, "package name is empty string");
2741 
2742     const Symbol* const this_package_name =
2743       this->package() != NULL ? this->package()->name() : NULL;
2744 
2745     if (this_package_name == NULL || other_pkg == NULL) {
2746       // One of the two doesn't have a package.  Only return true if the other
2747       // one also doesn't have a package.
2748       return (const char*)this_package_name == other_pkg;
2749     }
2750 
2751     // Check if package is identical
2752     return this_package_name->equals(other_pkg);
2753   }
2754 }
2755 
2756 // Returns true iff super_method can be overridden by a method in targetclassname
2757 // See JLS 3rd edition 8.4.6.1
2758 // Assumes name-signature match
2759 // "this" is InstanceKlass of super_method which must exist
2760 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2761 bool InstanceKlass::is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2762    // Private methods can not be overridden
2763    if (super_method->is_private()) {
2764      return false;
2765    }
2766    // If super method is accessible, then override
2767    if ((super_method->is_protected()) ||
2768        (super_method->is_public())) {
2769      return true;
2770    }
2771    // Package-private methods are not inherited outside of package
2772    assert(super_method->is_package_private(), "must be package private");
2773    return(is_same_class_package(targetclassloader(), targetclassname));
2774 }
2775 
2776 // Only boot and platform class loaders can define classes in "java/" packages.
2777 void InstanceKlass::check_prohibited_package(Symbol* class_name,
2778                                              ClassLoaderData* loader_data,
2779                                              TRAPS) {
2780   if (!loader_data->is_boot_class_loader_data() &&
2781       !loader_data->is_platform_class_loader_data() &&
2782       class_name != NULL) {
2783     ResourceMark rm(THREAD);
2784     char* name = class_name->as_C_string();
2785     if (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/') {
2786       TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK);
2787       assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");
2788       name = pkg_name->as_C_string();
2789       const char* class_loader_name = loader_data->loader_name_and_id();
2790       StringUtils::replace_no_expand(name, "/", ".");
2791       const char* msg_text1 = "Class loader (instance of): ";
2792       const char* msg_text2 = " tried to load prohibited package name: ";
2793       size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;
2794       char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
2795       jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);
2796       THROW_MSG(vmSymbols::java_lang_SecurityException(), message);
2797     }
2798   }
2799   return;
2800 }
2801 
2802 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
2803   constantPoolHandle i_cp(THREAD, constants());
2804   for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
2805     int ioff = iter.inner_class_info_index();
2806     if (ioff != 0) {
2807       // Check to see if the name matches the class we're looking for
2808       // before attempting to find the class.
2809       if (i_cp->klass_name_at_matches(this, ioff)) {
2810         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
2811         if (this == inner_klass) {
2812           *ooff = iter.outer_class_info_index();
2813           *noff = iter.inner_name_index();
2814           return true;
2815         }
2816       }
2817     }
2818   }
2819   return false;
2820 }
2821 
2822 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
2823   InstanceKlass* outer_klass = NULL;
2824   *inner_is_member = false;
2825   int ooff = 0, noff = 0;
2826   bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
2827   if (has_inner_classes_attr) {
2828     constantPoolHandle i_cp(THREAD, constants());
2829     if (ooff != 0) {
2830       Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
2831       outer_klass = InstanceKlass::cast(ok);
2832       *inner_is_member = true;
2833     }
2834     if (NULL == outer_klass) {
2835       // It may be unsafe anonymous; try for that.
2836       int encl_method_class_idx = enclosing_method_class_index();
2837       if (encl_method_class_idx != 0) {
2838         Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
2839         outer_klass = InstanceKlass::cast(ok);
2840         *inner_is_member = false;
2841       }
2842     }
2843   }
2844 
2845   // If no inner class attribute found for this class.
2846   if (NULL == outer_klass) return NULL;
2847 
2848   // Throws an exception if outer klass has not declared k as an inner klass
2849   // We need evidence that each klass knows about the other, or else
2850   // the system could allow a spoof of an inner class to gain access rights.
2851   Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);
2852   return outer_klass;
2853 }
2854 
2855 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2856   jint access = access_flags().as_int();
2857 
2858   // But check if it happens to be member class.
2859   InnerClassesIterator iter(this);
2860   for (; !iter.done(); iter.next()) {
2861     int ioff = iter.inner_class_info_index();
2862     // Inner class attribute can be zero, skip it.
2863     // Strange but true:  JVM spec. allows null inner class refs.
2864     if (ioff == 0) continue;
2865 
2866     // only look at classes that are already loaded
2867     // since we are looking for the flags for our self.
2868     Symbol* inner_name = constants()->klass_name_at(ioff);
2869     if (name() == inner_name) {
2870       // This is really a member class.
2871       access = iter.inner_access_flags();
2872       break;
2873     }
2874   }
2875   // Remember to strip ACC_SUPER bit
2876   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2877 }
2878 
2879 jint InstanceKlass::jvmti_class_status() const {
2880   jint result = 0;
2881 
2882   if (is_linked()) {
2883     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2884   }
2885 
2886   if (is_initialized()) {
2887     assert(is_linked(), "Class status is not consistent");
2888     result |= JVMTI_CLASS_STATUS_INITIALIZED;
2889   }
2890   if (is_in_error_state()) {
2891     result |= JVMTI_CLASS_STATUS_ERROR;
2892   }
2893   return result;
2894 }
2895 
2896 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
2897   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2898   int method_table_offset_in_words = ioe->offset()/wordSize;
2899   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2900                        / itableOffsetEntry::size();
2901 
2902   for (int cnt = 0 ; ; cnt ++, ioe ++) {
2903     // If the interface isn't implemented by the receiver class,
2904     // the VM should throw IncompatibleClassChangeError.
2905     if (cnt >= nof_interfaces) {
2906       ResourceMark rm(THREAD);
2907       stringStream ss;
2908       bool same_module = (module() == holder->module());
2909       ss.print("Receiver class %s does not implement "
2910                "the interface %s defining the method to be called "
2911                "(%s%s%s)",
2912                external_name(), holder->external_name(),
2913                (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),
2914                (same_module) ? "" : "; ",
2915                (same_module) ? "" : holder->class_in_module_of_loader());
2916       THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
2917     }
2918 
2919     Klass* ik = ioe->interface_klass();
2920     if (ik == holder) break;
2921   }
2922 
2923   itableMethodEntry* ime = ioe->first_method_entry(this);
2924   Method* m = ime[index].method();
2925   if (m == NULL) {
2926     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
2927   }
2928   return m;
2929 }
2930 
2931 
2932 #if INCLUDE_JVMTI
2933 // update default_methods for redefineclasses for methods that are
2934 // not yet in the vtable due to concurrent subclass define and superinterface
2935 // redefinition
2936 // Note: those in the vtable, should have been updated via adjust_method_entries
2937 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {
2938   // search the default_methods for uses of either obsolete or EMCP methods
2939   if (default_methods() != NULL) {
2940     for (int index = 0; index < default_methods()->length(); index ++) {
2941       Method* old_method = default_methods()->at(index);
2942       if (old_method == NULL || !old_method->is_old()) {
2943         continue; // skip uninteresting entries
2944       }
2945       assert(!old_method->is_deleted(), "default methods may not be deleted");
2946       Method* new_method = old_method->get_new_method();
2947       default_methods()->at_put(index, new_method);
2948 
2949       if (log_is_enabled(Info, redefine, class, update)) {
2950         ResourceMark rm;
2951         if (!(*trace_name_printed)) {
2952           log_info(redefine, class, update)
2953             ("adjust: klassname=%s default methods from name=%s",
2954              external_name(), old_method->method_holder()->external_name());
2955           *trace_name_printed = true;
2956         }
2957         log_debug(redefine, class, update, vtables)
2958           ("default method update: %s(%s) ",
2959            new_method->name()->as_C_string(), new_method->signature()->as_C_string());
2960       }
2961     }
2962   }
2963 }
2964 #endif // INCLUDE_JVMTI
2965 
2966 // On-stack replacement stuff
2967 void InstanceKlass::add_osr_nmethod(nmethod* n) {







2968   // only one compilation can be active
2969   {
2970     // This is a short non-blocking critical region, so the no safepoint check is ok.
2971     MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2972     assert(n->is_osr_method(), "wrong kind of nmethod");
2973     n->set_osr_link(osr_nmethods_head());
2974     set_osr_nmethods_head(n);
2975     // Raise the highest osr level if necessary
2976     if (TieredCompilation) {
2977       Method* m = n->method();
2978       m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2979     }
2980   }
2981 
2982   // Get rid of the osr methods for the same bci that have lower levels.
2983   if (TieredCompilation) {
2984     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2985       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2986       if (inv != NULL && inv->is_in_use()) {
2987         inv->make_not_entrant();
2988       }
2989     }
2990   }
2991 }
2992 
2993 // Remove osr nmethod from the list. Return true if found and removed.
2994 bool InstanceKlass::remove_osr_nmethod(nmethod* n) {
2995   // This is a short non-blocking critical region, so the no safepoint check is ok.
2996   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2997   assert(n->is_osr_method(), "wrong kind of nmethod");
2998   nmethod* last = NULL;
2999   nmethod* cur  = osr_nmethods_head();
3000   int max_level = CompLevel_none;  // Find the max comp level excluding n
3001   Method* m = n->method();
3002   // Search for match
3003   bool found = false;
3004   while(cur != NULL && cur != n) {
3005     if (TieredCompilation && m == cur->method()) {
3006       // Find max level before n
3007       max_level = MAX2(max_level, cur->comp_level());
3008     }
3009     last = cur;
3010     cur = cur->osr_link();
3011   }
3012   nmethod* next = NULL;
3013   if (cur == n) {
3014     found = true;
3015     next = cur->osr_link();
3016     if (last == NULL) {
3017       // Remove first element
3018       set_osr_nmethods_head(next);
3019     } else {
3020       last->set_osr_link(next);
3021     }
3022   }
3023   n->set_osr_link(NULL);
3024   if (TieredCompilation) {
3025     cur = next;
3026     while (cur != NULL) {
3027       // Find max level after n
3028       if (m == cur->method()) {
3029         max_level = MAX2(max_level, cur->comp_level());
3030       }
3031       cur = cur->osr_link();
3032     }
3033     m->set_highest_osr_comp_level(max_level);
3034   }
3035   return found;
3036 }
3037 
3038 int InstanceKlass::mark_osr_nmethods(const Method* m) {
3039   // This is a short non-blocking critical region, so the no safepoint check is ok.
3040   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3041   nmethod* osr = osr_nmethods_head();
3042   int found = 0;
3043   while (osr != NULL) {
3044     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3045     if (osr->method() == m) {
3046       osr->mark_for_deoptimization();
3047       found++;
3048     }
3049     osr = osr->osr_link();
3050   }
3051   return found;
3052 }
3053 
3054 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3055   // This is a short non-blocking critical region, so the no safepoint check is ok.
3056   MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
3057   nmethod* osr = osr_nmethods_head();
3058   nmethod* best = NULL;
3059   while (osr != NULL) {
3060     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3061     // There can be a time when a c1 osr method exists but we are waiting
3062     // for a c2 version. When c2 completes its osr nmethod we will trash
3063     // the c1 version and only be able to find the c2 version. However
3064     // while we overflow in the c1 code at back branches we don't want to
3065     // try and switch to the same code as we are already running
3066 
3067     if (osr->method() == m &&
3068         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3069       if (match_level) {
3070         if (osr->comp_level() == comp_level) {
3071           // Found a match - return it.
3072           return osr;
3073         }
3074       } else {
3075         if (best == NULL || (osr->comp_level() > best->comp_level())) {
3076           if (osr->comp_level() == CompLevel_highest_tier) {
3077             // Found the best possible - return it.
3078             return osr;
3079           }
3080           best = osr;
3081         }
3082       }
3083     }
3084     osr = osr->osr_link();
3085   }
3086   if (best != NULL && best->comp_level() >= comp_level && match_level == false) {


3087     return best;
3088   }
3089   return NULL;
3090 }
3091 
3092 // -----------------------------------------------------------------------------------------------------
3093 // Printing
3094 
3095 #ifndef PRODUCT
3096 
3097 #define BULLET  " - "
3098 
3099 static const char* state_names[] = {
3100   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3101 };
3102 
3103 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3104   for (int i = 0; i < len; i++) {
3105     intptr_t e = start[i];
3106     st->print("%d : " INTPTR_FORMAT, i, e);
3107     if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
3108       st->print(" ");
3109       ((Metadata*)e)->print_value_on(st);
3110     }
3111     st->cr();
3112   }
3113 }
3114 
3115 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3116   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3117 }
3118 
3119 void InstanceKlass::print_on(outputStream* st) const {
3120   assert(is_klass(), "must be klass");
3121   Klass::print_on(st);
3122 
3123   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3124   st->print(BULLET"klass size:        %d", size());                               st->cr();
3125   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3126   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3127   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3128   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3129   st->print(BULLET"sub:               ");
3130   Klass* sub = subklass();
3131   int n;
3132   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3133     if (n < MaxSubklassPrintSize) {
3134       sub->print_value_on(st);
3135       st->print("   ");
3136     }
3137   }
3138   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3139   st->cr();
3140 
3141   if (is_interface()) {
3142     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3143     if (nof_implementors() == 1) {
3144       st->print_cr(BULLET"implementor:    ");
3145       st->print("   ");
3146       implementor()->print_value_on(st);
3147       st->cr();
3148     }
3149   }
3150 
3151   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3152   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
3153   if (Verbose || WizardMode) {
3154     Array<Method*>* method_array = methods();
3155     for (int i = 0; i < method_array->length(); i++) {
3156       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3157     }
3158   }
3159   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
3160   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
3161   if (Verbose && default_methods() != NULL) {
3162     Array<Method*>* method_array = default_methods();
3163     for (int i = 0; i < method_array->length(); i++) {
3164       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3165     }
3166   }
3167   if (default_vtable_indices() != NULL) {
3168     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
3169   }
3170   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
3171   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3172   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3173   if (class_loader_data() != NULL) {
3174     st->print(BULLET"class loader data:  ");
3175     class_loader_data()->print_value_on(st);
3176     st->cr();
3177   }
3178   st->print(BULLET"unsafe anonymous host class:        "); Metadata::print_value_on_maybe_null(st, unsafe_anonymous_host()); st->cr();
3179   if (source_file_name() != NULL) {
3180     st->print(BULLET"source file:       ");
3181     source_file_name()->print_value_on(st);
3182     st->cr();
3183   }
3184   if (source_debug_extension() != NULL) {
3185     st->print(BULLET"source debug extension:       ");
3186     st->print("%s", source_debug_extension());
3187     st->cr();
3188   }
3189   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3190   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3191   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3192   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
3193   {
3194     bool have_pv = false;
3195     // previous versions are linked together through the InstanceKlass
3196     for (InstanceKlass* pv_node = previous_versions();
3197          pv_node != NULL;
3198          pv_node = pv_node->previous_versions()) {
3199       if (!have_pv)
3200         st->print(BULLET"previous version:  ");
3201       have_pv = true;
3202       pv_node->constants()->print_value_on(st);
3203     }
3204     if (have_pv) st->cr();
3205   }
3206 
3207   if (generic_signature() != NULL) {
3208     st->print(BULLET"generic signature: ");
3209     generic_signature()->print_value_on(st);
3210     st->cr();
3211   }
3212   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3213   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3214   if (java_mirror() != NULL) {
3215     st->print(BULLET"java mirror:       ");
3216     java_mirror()->print_value_on(st);
3217     st->cr();
3218   } else {
3219     st->print_cr(BULLET"java mirror:       NULL");
3220   }
3221   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3222   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3223   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3224   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3225   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3226   FieldPrinter print_static_field(st);
3227   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3228   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3229   FieldPrinter print_nonstatic_field(st);
3230   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3231   ik->do_nonstatic_fields(&print_nonstatic_field);
3232 
3233   st->print(BULLET"non-static oop maps: ");
3234   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3235   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3236   while (map < end_map) {
3237     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3238     map++;
3239   }
3240   st->cr();
3241 }
3242 
3243 #endif //PRODUCT
3244 
3245 void InstanceKlass::print_value_on(outputStream* st) const {
3246   assert(is_klass(), "must be klass");
3247   if (Verbose || WizardMode)  access_flags().print_on(st);
3248   name()->print_value_on(st);
3249 }
3250 
3251 #ifndef PRODUCT
3252 
3253 void FieldPrinter::do_field(fieldDescriptor* fd) {
3254   _st->print(BULLET);
3255    if (_obj == NULL) {
3256      fd->print_on(_st);
3257      _st->cr();
3258    } else {
3259      fd->print_on_for(_st, _obj);
3260      _st->cr();
3261    }
3262 }
3263 
3264 
3265 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3266   Klass::oop_print_on(obj, st);
3267 
3268   if (this == SystemDictionary::String_klass()) {
3269     typeArrayOop value  = java_lang_String::value(obj);
3270     juint        length = java_lang_String::length(obj);
3271     if (value != NULL &&
3272         value->is_typeArray() &&
3273         length <= (juint) value->length()) {
3274       st->print(BULLET"string: ");
3275       java_lang_String::print(obj, st);
3276       st->cr();
3277       if (!WizardMode)  return;  // that is enough
3278     }
3279   }
3280 
3281   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3282   FieldPrinter print_field(st, obj);
3283   do_nonstatic_fields(&print_field);
3284 
3285   if (this == SystemDictionary::Class_klass()) {
3286     st->print(BULLET"signature: ");
3287     java_lang_Class::print_signature(obj, st);
3288     st->cr();
3289     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3290     st->print(BULLET"fake entry for mirror: ");
3291     Metadata::print_value_on_maybe_null(st, mirrored_klass);
3292     st->cr();
3293     Klass* array_klass = java_lang_Class::array_klass_acquire(obj);
3294     st->print(BULLET"fake entry for array: ");
3295     Metadata::print_value_on_maybe_null(st, array_klass);
3296     st->cr();
3297     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3298     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3299     Klass* real_klass = java_lang_Class::as_Klass(obj);
3300     if (real_klass != NULL && real_klass->is_instance_klass()) {
3301       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3302     }
3303   } else if (this == SystemDictionary::MethodType_klass()) {
3304     st->print(BULLET"signature: ");
3305     java_lang_invoke_MethodType::print_signature(obj, st);
3306     st->cr();
3307   }
3308 }
3309 
3310 bool InstanceKlass::verify_itable_index(int i) {
3311   int method_count = klassItable::method_count_for_interface(this);
3312   assert(i >= 0 && i < method_count, "index out of bounds");
3313   return true;
3314 }
3315 
3316 #endif //PRODUCT
3317 
3318 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3319   st->print("a ");
3320   name()->print_value_on(st);
3321   obj->print_address_on(st);
3322   if (this == SystemDictionary::String_klass()
3323       && java_lang_String::value(obj) != NULL) {
3324     ResourceMark rm;
3325     int len = java_lang_String::length(obj);
3326     int plen = (len < 24 ? len : 12);
3327     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3328     st->print(" = \"%s\"", str);
3329     if (len > plen)
3330       st->print("...[%d]", len);
3331   } else if (this == SystemDictionary::Class_klass()) {
3332     Klass* k = java_lang_Class::as_Klass(obj);
3333     st->print(" = ");
3334     if (k != NULL) {
3335       k->print_value_on(st);
3336     } else {
3337       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3338       st->print("%s", tname ? tname : "type?");
3339     }
3340   } else if (this == SystemDictionary::MethodType_klass()) {
3341     st->print(" = ");
3342     java_lang_invoke_MethodType::print_signature(obj, st);
3343   } else if (java_lang_boxing_object::is_instance(obj)) {
3344     st->print(" = ");
3345     java_lang_boxing_object::print(obj, st);
3346   } else if (this == SystemDictionary::LambdaForm_klass()) {
3347     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3348     if (vmentry != NULL) {
3349       st->print(" => ");
3350       vmentry->print_value_on(st);
3351     }
3352   } else if (this == SystemDictionary::MemberName_klass()) {
3353     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3354     if (vmtarget != NULL) {
3355       st->print(" = ");
3356       vmtarget->print_value_on(st);
3357     } else {
3358       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3359       st->print(".");
3360       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3361     }
3362   }
3363 }
3364 
3365 const char* InstanceKlass::internal_name() const {
3366   return external_name();
3367 }
3368 
3369 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,
3370                                              const char* module_name,
3371                                              const ClassFileStream* cfs) const {
3372   if (!log_is_enabled(Info, class, load)) {
3373     return;
3374   }
3375 
3376   ResourceMark rm;
3377   LogMessage(class, load) msg;
3378   stringStream info_stream;
3379 
3380   // Name and class hierarchy info
3381   info_stream.print("%s", external_name());
3382 
3383   // Source
3384   if (cfs != NULL) {
3385     if (cfs->source() != NULL) {
3386       if (module_name != NULL) {
3387         // When the boot loader created the stream, it didn't know the module name
3388         // yet. Let's format it now.
3389         if (cfs->from_boot_loader_modules_image()) {
3390           info_stream.print(" source: jrt:/%s", module_name);
3391         } else {
3392           info_stream.print(" source: %s", cfs->source());
3393         }
3394       } else {
3395         info_stream.print(" source: %s", cfs->source());
3396       }
3397     } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
3398       Thread* THREAD = Thread::current();
3399       Klass* caller =
3400             THREAD->is_Java_thread()
3401                 ? ((JavaThread*)THREAD)->security_get_caller_class(1)
3402                 : NULL;
3403       // caller can be NULL, for example, during a JVMTI VM_Init hook
3404       if (caller != NULL) {
3405         info_stream.print(" source: instance of %s", caller->external_name());
3406       } else {
3407         // source is unknown
3408       }
3409     } else {
3410       oop class_loader = loader_data->class_loader();
3411       info_stream.print(" source: %s", class_loader->klass()->external_name());
3412     }
3413   } else {
3414     info_stream.print(" source: shared objects file");





3415   }
3416 
3417   msg.info("%s", info_stream.as_string());
3418 
3419   if (log_is_enabled(Debug, class, load)) {
3420     stringStream debug_stream;
3421 
3422     // Class hierarchy info
3423     debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT,
3424                        p2i(this),  p2i(superklass()));
3425 
3426     // Interfaces
3427     if (local_interfaces() != NULL && local_interfaces()->length() > 0) {
3428       debug_stream.print(" interfaces:");
3429       int length = local_interfaces()->length();
3430       for (int i = 0; i < length; i++) {
3431         debug_stream.print(" " INTPTR_FORMAT,
3432                            p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3433       }
3434     }
3435 
3436     // Class loader
3437     debug_stream.print(" loader: [");
3438     loader_data->print_value_on(&debug_stream);
3439     debug_stream.print("]");
3440 
3441     // Classfile checksum
3442     if (cfs) {
3443       debug_stream.print(" bytes: %d checksum: %08x",
3444                          cfs->length(),
3445                          ClassLoader::crc32(0, (const char*)cfs->buffer(),
3446                          cfs->length()));
3447     }
3448 
3449     msg.debug("%s", debug_stream.as_string());
3450   }
3451 }
3452 
3453 #if INCLUDE_SERVICES
3454 // Size Statistics
3455 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
3456   Klass::collect_statistics(sz);
3457 
3458   sz->_inst_size  = wordSize * size_helper();
3459   sz->_vtab_bytes = wordSize * vtable_length();
3460   sz->_itab_bytes = wordSize * itable_length();
3461   sz->_nonstatic_oopmap_bytes = wordSize * nonstatic_oop_map_size();
3462 
3463   int n = 0;
3464   n += (sz->_methods_array_bytes         = sz->count_array(methods()));
3465   n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
3466   n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
3467   n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
3468   n += (sz->_fields_bytes                = sz->count_array(fields()));
3469   n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
3470   n += (sz->_nest_members_bytes          = sz->count_array(nest_members()));
3471   sz->_ro_bytes += n;
3472 
3473   const ConstantPool* cp = constants();
3474   if (cp) {
3475     cp->collect_statistics(sz);
3476   }
3477 
3478   const Annotations* anno = annotations();
3479   if (anno) {
3480     anno->collect_statistics(sz);
3481   }
3482 
3483   const Array<Method*>* methods_array = methods();
3484   if (methods()) {
3485     for (int i = 0; i < methods_array->length(); i++) {
3486       Method* method = methods_array->at(i);
3487       if (method) {
3488         sz->_method_count ++;
3489         method->collect_statistics(sz);
3490       }
3491     }
3492   }
3493 }
3494 #endif // INCLUDE_SERVICES
3495 
3496 // Verification
3497 
3498 class VerifyFieldClosure: public BasicOopIterateClosure {
3499  protected:
3500   template <class T> void do_oop_work(T* p) {
3501     oop obj = RawAccess<>::oop_load(p);
3502     if (!oopDesc::is_oop_or_null(obj)) {
3503       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
3504       Universe::print_on(tty);
3505       guarantee(false, "boom");
3506     }
3507   }
3508  public:
3509   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3510   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3511 };
3512 
3513 void InstanceKlass::verify_on(outputStream* st) {
3514 #ifndef PRODUCT
3515   // Avoid redundant verifies, this really should be in product.
3516   if (_verify_count == Universe::verify_count()) return;
3517   _verify_count = Universe::verify_count();
3518 #endif
3519 
3520   // Verify Klass
3521   Klass::verify_on(st);
3522 
3523   // Verify that klass is present in ClassLoaderData
3524   guarantee(class_loader_data()->contains_klass(this),
3525             "this class isn't found in class loader data");
3526 
3527   // Verify vtables
3528   if (is_linked()) {
3529     // $$$ This used to be done only for m/s collections.  Doing it
3530     // always seemed a valid generalization.  (DLD -- 6/00)
3531     vtable().verify(st);
3532   }
3533 
3534   // Verify first subklass
3535   if (subklass() != NULL) {
3536     guarantee(subklass()->is_klass(), "should be klass");
3537   }
3538 
3539   // Verify siblings
3540   Klass* super = this->super();
3541   Klass* sib = next_sibling();
3542   if (sib != NULL) {
3543     if (sib == this) {
3544       fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
3545     }
3546 
3547     guarantee(sib->is_klass(), "should be klass");
3548     guarantee(sib->super() == super, "siblings should have same superklass");
3549   }
3550 
3551   // Verify local interfaces
3552   if (local_interfaces()) {
3553     Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
3554     for (int j = 0; j < local_interfaces->length(); j++) {
3555       InstanceKlass* e = local_interfaces->at(j);
3556       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3557     }
3558   }
3559 
3560   // Verify transitive interfaces
3561   if (transitive_interfaces() != NULL) {
3562     Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();
3563     for (int j = 0; j < transitive_interfaces->length(); j++) {
3564       InstanceKlass* e = transitive_interfaces->at(j);
3565       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3566     }
3567   }
3568 
3569   // Verify methods
3570   if (methods() != NULL) {
3571     Array<Method*>* methods = this->methods();
3572     for (int j = 0; j < methods->length(); j++) {
3573       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3574     }
3575     for (int j = 0; j < methods->length() - 1; j++) {
3576       Method* m1 = methods->at(j);
3577       Method* m2 = methods->at(j + 1);
3578       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3579     }
3580   }
3581 
3582   // Verify method ordering
3583   if (method_ordering() != NULL) {
3584     Array<int>* method_ordering = this->method_ordering();
3585     int length = method_ordering->length();
3586     if (JvmtiExport::can_maintain_original_method_order() ||
3587         ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3588       guarantee(length == methods()->length(), "invalid method ordering length");
3589       jlong sum = 0;
3590       for (int j = 0; j < length; j++) {
3591         int original_index = method_ordering->at(j);
3592         guarantee(original_index >= 0, "invalid method ordering index");
3593         guarantee(original_index < length, "invalid method ordering index");
3594         sum += original_index;
3595       }
3596       // Verify sum of indices 0,1,...,length-1
3597       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3598     } else {
3599       guarantee(length == 0, "invalid method ordering length");
3600     }
3601   }
3602 
3603   // Verify default methods
3604   if (default_methods() != NULL) {
3605     Array<Method*>* methods = this->default_methods();
3606     for (int j = 0; j < methods->length(); j++) {
3607       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3608     }
3609     for (int j = 0; j < methods->length() - 1; j++) {
3610       Method* m1 = methods->at(j);
3611       Method* m2 = methods->at(j + 1);
3612       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3613     }
3614   }
3615 
3616   // Verify JNI static field identifiers
3617   if (jni_ids() != NULL) {
3618     jni_ids()->verify(this);
3619   }
3620 
3621   // Verify other fields
3622   if (array_klasses() != NULL) {
3623     guarantee(array_klasses()->is_klass(), "should be klass");
3624   }
3625   if (constants() != NULL) {
3626     guarantee(constants()->is_constantPool(), "should be constant pool");
3627   }
3628   const Klass* anonymous_host = unsafe_anonymous_host();
3629   if (anonymous_host != NULL) {
3630     guarantee(anonymous_host->is_klass(), "should be klass");
3631   }
3632 }
3633 
3634 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3635   Klass::oop_verify_on(obj, st);
3636   VerifyFieldClosure blk;
3637   obj->oop_iterate(&blk);
3638 }
3639 
3640 
3641 // JNIid class for jfieldIDs only
3642 // Note to reviewers:
3643 // These JNI functions are just moved over to column 1 and not changed
3644 // in the compressed oops workspace.
3645 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3646   _holder = holder;
3647   _offset = offset;
3648   _next = next;
3649   debug_only(_is_static_field_id = false;)
3650 }
3651 
3652 
3653 JNIid* JNIid::find(int offset) {
3654   JNIid* current = this;
3655   while (current != NULL) {
3656     if (current->offset() == offset) return current;
3657     current = current->next();
3658   }
3659   return NULL;
3660 }
3661 
3662 void JNIid::deallocate(JNIid* current) {
3663   while (current != NULL) {
3664     JNIid* next = current->next();
3665     delete current;
3666     current = next;
3667   }
3668 }
3669 
3670 
3671 void JNIid::verify(Klass* holder) {
3672   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3673   int end_field_offset;
3674   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3675 
3676   JNIid* current = this;
3677   while (current != NULL) {
3678     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3679 #ifdef ASSERT
3680     int o = current->offset();
3681     if (current->is_static_field_id()) {
3682       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3683     }
3684 #endif
3685     current = current->next();
3686   }
3687 }
3688 
3689 void InstanceKlass::set_init_state(ClassState state) {
3690 #ifdef ASSERT
3691   bool good_state = is_shared() ? (_init_state <= state)
3692                                                : (_init_state < state);
3693   assert(good_state || state == allocated, "illegal state transition");
3694 #endif

3695   _init_state = (u1)state;
3696 }
3697 
3698 #if INCLUDE_JVMTI
3699 
3700 // RedefineClasses() support for previous versions
3701 
3702 // Globally, there is at least one previous version of a class to walk
3703 // during class unloading, which is saved because old methods in the class
3704 // are still running.   Otherwise the previous version list is cleaned up.
3705 bool InstanceKlass::_has_previous_versions = false;
3706 
3707 // Returns true if there are previous versions of a class for class
3708 // unloading only. Also resets the flag to false. purge_previous_version
3709 // will set the flag to true if there are any left, i.e., if there's any
3710 // work to do for next time. This is to avoid the expensive code cache
3711 // walk in CLDG::clean_deallocate_lists().
3712 bool InstanceKlass::has_previous_versions_and_reset() {
3713   bool ret = _has_previous_versions;
3714   log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",
3715      ret ? "true" : "false");
3716   _has_previous_versions = false;
3717   return ret;
3718 }
3719 
3720 // Purge previous versions before adding new previous versions of the class and
3721 // during class unloading.
3722 void InstanceKlass::purge_previous_version_list() {
3723   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3724   assert(has_been_redefined(), "Should only be called for main class");
3725 
3726   // Quick exit.
3727   if (previous_versions() == NULL) {
3728     return;
3729   }
3730 
3731   // This klass has previous versions so see what we can cleanup
3732   // while it is safe to do so.
3733 
3734   int deleted_count = 0;    // leave debugging breadcrumbs
3735   int live_count = 0;
3736   ClassLoaderData* loader_data = class_loader_data();
3737   assert(loader_data != NULL, "should never be null");
3738 
3739   ResourceMark rm;
3740   log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
3741 
3742   // previous versions are linked together through the InstanceKlass
3743   InstanceKlass* pv_node = previous_versions();
3744   InstanceKlass* last = this;
3745   int version = 0;
3746 
3747   // check the previous versions list
3748   for (; pv_node != NULL; ) {
3749 
3750     ConstantPool* pvcp = pv_node->constants();
3751     assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3752 
3753     if (!pvcp->on_stack()) {
3754       // If the constant pool isn't on stack, none of the methods
3755       // are executing.  Unlink this previous_version.
3756       // The previous version InstanceKlass is on the ClassLoaderData deallocate list
3757       // so will be deallocated during the next phase of class unloading.
3758       log_trace(redefine, class, iklass, purge)
3759         ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));
3760       // For debugging purposes.
3761       pv_node->set_is_scratch_class();
3762       // Unlink from previous version list.
3763       assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
3764       InstanceKlass* next = pv_node->previous_versions();
3765       pv_node->link_previous_versions(NULL);   // point next to NULL
3766       last->link_previous_versions(next);
3767       // Add to the deallocate list after unlinking
3768       loader_data->add_to_deallocate_list(pv_node);
3769       pv_node = next;
3770       deleted_count++;
3771       version++;
3772       continue;
3773     } else {
3774       log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));
3775       assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3776       guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3777       live_count++;
3778       // found a previous version for next time we do class unloading
3779       _has_previous_versions = true;
3780     }
3781 
3782     // At least one method is live in this previous version.
3783     // Reset dead EMCP methods not to get breakpoints.
3784     // All methods are deallocated when all of the methods for this class are no
3785     // longer running.
3786     Array<Method*>* method_refs = pv_node->methods();
3787     if (method_refs != NULL) {
3788       log_trace(redefine, class, iklass, purge)("previous methods length=%d", method_refs->length());
3789       for (int j = 0; j < method_refs->length(); j++) {
3790         Method* method = method_refs->at(j);
3791 
3792         if (!method->on_stack()) {
3793           // no breakpoints for non-running methods
3794           if (method->is_running_emcp()) {
3795             method->set_running_emcp(false);
3796           }
3797         } else {
3798           assert (method->is_obsolete() || method->is_running_emcp(),
3799                   "emcp method cannot run after emcp bit is cleared");
3800           log_trace(redefine, class, iklass, purge)
3801             ("purge: %s(%s): prev method @%d in version @%d is alive",
3802              method->name()->as_C_string(), method->signature()->as_C_string(), j, version);
3803         }
3804       }
3805     }
3806     // next previous version
3807     last = pv_node;
3808     pv_node = pv_node->previous_versions();
3809     version++;
3810   }
3811   log_trace(redefine, class, iklass, purge)
3812     ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
3813 }
3814 
3815 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
3816                                                 int emcp_method_count) {
3817   int obsolete_method_count = old_methods->length() - emcp_method_count;
3818 
3819   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3820       _previous_versions != NULL) {
3821     // We have a mix of obsolete and EMCP methods so we have to
3822     // clear out any matching EMCP method entries the hard way.
3823     int local_count = 0;
3824     for (int i = 0; i < old_methods->length(); i++) {
3825       Method* old_method = old_methods->at(i);
3826       if (old_method->is_obsolete()) {
3827         // only obsolete methods are interesting
3828         Symbol* m_name = old_method->name();
3829         Symbol* m_signature = old_method->signature();
3830 
3831         // previous versions are linked together through the InstanceKlass
3832         int j = 0;
3833         for (InstanceKlass* prev_version = _previous_versions;
3834              prev_version != NULL;
3835              prev_version = prev_version->previous_versions(), j++) {
3836 
3837           Array<Method*>* method_refs = prev_version->methods();
3838           for (int k = 0; k < method_refs->length(); k++) {
3839             Method* method = method_refs->at(k);
3840 
3841             if (!method->is_obsolete() &&
3842                 method->name() == m_name &&
3843                 method->signature() == m_signature) {
3844               // The current RedefineClasses() call has made all EMCP
3845               // versions of this method obsolete so mark it as obsolete
3846               log_trace(redefine, class, iklass, add)
3847                 ("%s(%s): flush obsolete method @%d in version @%d",
3848                  m_name->as_C_string(), m_signature->as_C_string(), k, j);
3849 
3850               method->set_is_obsolete();
3851               break;
3852             }
3853           }
3854 
3855           // The previous loop may not find a matching EMCP method, but
3856           // that doesn't mean that we can optimize and not go any
3857           // further back in the PreviousVersion generations. The EMCP
3858           // method for this generation could have already been made obsolete,
3859           // but there still may be an older EMCP method that has not
3860           // been made obsolete.
3861         }
3862 
3863         if (++local_count >= obsolete_method_count) {
3864           // no more obsolete methods so bail out now
3865           break;
3866         }
3867       }
3868     }
3869   }
3870 }
3871 
3872 // Save the scratch_class as the previous version if any of the methods are running.
3873 // The previous_versions are used to set breakpoints in EMCP methods and they are
3874 // also used to clean MethodData links to redefined methods that are no longer running.
3875 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,
3876                                          int emcp_method_count) {
3877   assert(Thread::current()->is_VM_thread(),
3878          "only VMThread can add previous versions");
3879 
3880   ResourceMark rm;
3881   log_trace(redefine, class, iklass, add)
3882     ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
3883 
3884   // Clean out old previous versions for this class
3885   purge_previous_version_list();
3886 
3887   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
3888   // a previous redefinition may be made obsolete by this redefinition.
3889   Array<Method*>* old_methods = scratch_class->methods();
3890   mark_newly_obsolete_methods(old_methods, emcp_method_count);
3891 
3892   // If the constant pool for this previous version of the class
3893   // is not marked as being on the stack, then none of the methods
3894   // in this previous version of the class are on the stack so
3895   // we don't need to add this as a previous version.
3896   ConstantPool* cp_ref = scratch_class->constants();
3897   if (!cp_ref->on_stack()) {
3898     log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");
3899     // For debugging purposes.
3900     scratch_class->set_is_scratch_class();
3901     scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);
3902     return;
3903   }
3904 
3905   if (emcp_method_count != 0) {
3906     // At least one method is still running, check for EMCP methods
3907     for (int i = 0; i < old_methods->length(); i++) {
3908       Method* old_method = old_methods->at(i);
3909       if (!old_method->is_obsolete() && old_method->on_stack()) {
3910         // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
3911         // we can add breakpoints for it.
3912 
3913         // We set the method->on_stack bit during safepoints for class redefinition
3914         // and use this bit to set the is_running_emcp bit.
3915         // After the safepoint, the on_stack bit is cleared and the running emcp
3916         // method may exit.   If so, we would set a breakpoint in a method that
3917         // is never reached, but this won't be noticeable to the programmer.
3918         old_method->set_running_emcp(true);
3919         log_trace(redefine, class, iklass, add)
3920           ("EMCP method %s is on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
3921       } else if (!old_method->is_obsolete()) {
3922         log_trace(redefine, class, iklass, add)
3923           ("EMCP method %s is NOT on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
3924       }
3925     }
3926   }
3927 
3928   // Add previous version if any methods are still running.
3929   // Set has_previous_version flag for processing during class unloading.
3930   _has_previous_versions = true;
3931   log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
3932   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
3933   scratch_class->link_previous_versions(previous_versions());
3934   link_previous_versions(scratch_class);
3935 } // end add_previous_version()
3936 
3937 #endif // INCLUDE_JVMTI
3938 
3939 Method* InstanceKlass::method_with_idnum(int idnum) {
3940   Method* m = NULL;
3941   if (idnum < methods()->length()) {
3942     m = methods()->at(idnum);
3943   }
3944   if (m == NULL || m->method_idnum() != idnum) {
3945     for (int index = 0; index < methods()->length(); ++index) {
3946       m = methods()->at(index);
3947       if (m->method_idnum() == idnum) {
3948         return m;
3949       }
3950     }
3951     // None found, return null for the caller to handle.
3952     return NULL;
3953   }
3954   return m;
3955 }
3956 
3957 
3958 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
3959   if (idnum >= methods()->length()) {
3960     return NULL;
3961   }
3962   Method* m = methods()->at(idnum);
3963   if (m != NULL && m->orig_method_idnum() == idnum) {
3964     return m;
3965   }
3966   // Obsolete method idnum does not match the original idnum
3967   for (int index = 0; index < methods()->length(); ++index) {
3968     m = methods()->at(index);
3969     if (m->orig_method_idnum() == idnum) {
3970       return m;
3971     }
3972   }
3973   // None found, return null for the caller to handle.
3974   return NULL;
3975 }
3976 
3977 
3978 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
3979   InstanceKlass* holder = get_klass_version(version);
3980   if (holder == NULL) {
3981     return NULL; // The version of klass is gone, no method is found
3982   }
3983   Method* method = holder->method_with_orig_idnum(idnum);
3984   return method;
3985 }
3986 
3987 #if INCLUDE_JVMTI
3988 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
3989   return _cached_class_file;
3990 }
3991 
3992 jint InstanceKlass::get_cached_class_file_len() {
3993   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
3994 }
3995 
3996 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
3997   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
3998 }
3999 #endif
--- EOF ---