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