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