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