rev 58452 : imported patch pkg_name_from_class

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

2810     if (bad_class_name) {
2811       return false;
2812     }
2813     // Check that package_from_name() returns NULL, not "", if there is no package.
2814     assert(other_pkg == NULL || other_pkg->utf8_length() > 0, "package name is empty string");
2815 
2816     const Symbol* const this_package_name =
2817       this->package() != NULL ? this->package()->name() : NULL;
2818 
2819     if (this_package_name == NULL || other_pkg == NULL) {
2820       // One of the two doesn't have a package.  Only return true if the other
2821       // one also doesn't have a package.
2822       return this_package_name == other_pkg;
2823     }
2824 
2825     // Check if package is identical
2826     return this_package_name->fast_compare(other_pkg) == 0;
2827   }
2828 }
2829 
2830 // Returns true iff super_method can be overridden by a method in targetclassname
2831 // See JLS 3rd edition 8.4.6.1
2832 // Assumes name-signature match
2833 // "this" is InstanceKlass of super_method which must exist
2834 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2835 bool InstanceKlass::is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2836    // Private methods can not be overridden
2837    if (super_method->is_private()) {
2838      return false;
2839    }
2840    // If super method is accessible, then override
2841    if ((super_method->is_protected()) ||
2842        (super_method->is_public())) {
2843      return true;
2844    }
2845    // Package-private methods are not inherited outside of package
2846    assert(super_method->is_package_private(), "must be package private");
2847    return(is_same_class_package(targetclassloader(), targetclassname));
2848 }
2849 
2850 // Only boot and platform class loaders can define classes in "java/" packages.
2851 void InstanceKlass::check_prohibited_package(Symbol* class_name,
2852                                              ClassLoaderData* loader_data,
2853                                              TRAPS) {
2854   if (!loader_data->is_boot_class_loader_data() &&
2855       !loader_data->is_platform_class_loader_data() &&
2856       class_name != NULL) {
2857     ResourceMark rm(THREAD);
2858     char* name = class_name->as_C_string();
2859     if (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/') {
2860       TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name);
2861       assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");
2862       name = pkg_name->as_C_string();
2863       const char* class_loader_name = loader_data->loader_name_and_id();
2864       StringUtils::replace_no_expand(name, "/", ".");
2865       const char* msg_text1 = "Class loader (instance of): ";
2866       const char* msg_text2 = " tried to load prohibited package name: ";
2867       size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;
2868       char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
2869       jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);
2870       THROW_MSG(vmSymbols::java_lang_SecurityException(), message);
2871     }
2872   }
2873   return;
2874 }
2875 
2876 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
2877   constantPoolHandle i_cp(THREAD, constants());
2878   for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
2879     int ioff = iter.inner_class_info_index();
2880     if (ioff != 0) {
2881       // Check to see if the name matches the class we're looking for
2882       // before attempting to find the class.
2883       if (i_cp->klass_name_at_matches(this, ioff)) {
2884         Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
2885         if (this == inner_klass) {
2886           *ooff = iter.outer_class_info_index();
2887           *noff = iter.inner_name_index();
2888           return true;
2889         }
2890       }
2891     }
2892   }
2893   return false;
2894 }
2895 
2896 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
2897   InstanceKlass* outer_klass = NULL;
2898   *inner_is_member = false;
2899   int ooff = 0, noff = 0;
2900   bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
2901   if (has_inner_classes_attr) {
2902     constantPoolHandle i_cp(THREAD, constants());
2903     if (ooff != 0) {
2904       Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
2905       outer_klass = InstanceKlass::cast(ok);
2906       *inner_is_member = true;
2907     }
2908     if (NULL == outer_klass) {
2909       // It may be unsafe anonymous; try for that.
2910       int encl_method_class_idx = enclosing_method_class_index();
2911       if (encl_method_class_idx != 0) {
2912         Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
2913         outer_klass = InstanceKlass::cast(ok);
2914         *inner_is_member = false;
2915       }
2916     }
2917   }
2918 
2919   // If no inner class attribute found for this class.
2920   if (NULL == outer_klass) return NULL;
2921 
2922   // Throws an exception if outer klass has not declared k as an inner klass
2923   // We need evidence that each klass knows about the other, or else
2924   // the system could allow a spoof of an inner class to gain access rights.
2925   Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);
2926   return outer_klass;
2927 }
2928 
2929 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2930   jint access = access_flags().as_int();
2931 
2932   // But check if it happens to be member class.
2933   InnerClassesIterator iter(this);
2934   for (; !iter.done(); iter.next()) {
2935     int ioff = iter.inner_class_info_index();
2936     // Inner class attribute can be zero, skip it.
2937     // Strange but true:  JVM spec. allows null inner class refs.
2938     if (ioff == 0) continue;
2939 
2940     // only look at classes that are already loaded
2941     // since we are looking for the flags for our self.
2942     Symbol* inner_name = constants()->klass_name_at(ioff);
2943     if (name() == inner_name) {
2944       // This is really a member class.
2945       access = iter.inner_access_flags();
2946       break;
2947     }
2948   }
2949   // Remember to strip ACC_SUPER bit
2950   return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2951 }
2952 
2953 jint InstanceKlass::jvmti_class_status() const {
2954   jint result = 0;
2955 
2956   if (is_linked()) {
2957     result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2958   }
2959 
2960   if (is_initialized()) {
2961     assert(is_linked(), "Class status is not consistent");
2962     result |= JVMTI_CLASS_STATUS_INITIALIZED;
2963   }
2964   if (is_in_error_state()) {
2965     result |= JVMTI_CLASS_STATUS_ERROR;
2966   }
2967   return result;
2968 }
2969 
2970 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
2971   itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2972   int method_table_offset_in_words = ioe->offset()/wordSize;
2973   int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2974                        / itableOffsetEntry::size();
2975 
2976   for (int cnt = 0 ; ; cnt ++, ioe ++) {
2977     // If the interface isn't implemented by the receiver class,
2978     // the VM should throw IncompatibleClassChangeError.
2979     if (cnt >= nof_interfaces) {
2980       ResourceMark rm(THREAD);
2981       stringStream ss;
2982       bool same_module = (module() == holder->module());
2983       ss.print("Receiver class %s does not implement "
2984                "the interface %s defining the method to be called "
2985                "(%s%s%s)",
2986                external_name(), holder->external_name(),
2987                (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),
2988                (same_module) ? "" : "; ",
2989                (same_module) ? "" : holder->class_in_module_of_loader());
2990       THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
2991     }
2992 
2993     Klass* ik = ioe->interface_klass();
2994     if (ik == holder) break;
2995   }
2996 
2997   itableMethodEntry* ime = ioe->first_method_entry(this);
2998   Method* m = ime[index].method();
2999   if (m == NULL) {
3000     THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
3001   }
3002   return m;
3003 }
3004 
3005 
3006 #if INCLUDE_JVMTI
3007 // update default_methods for redefineclasses for methods that are
3008 // not yet in the vtable due to concurrent subclass define and superinterface
3009 // redefinition
3010 // Note: those in the vtable, should have been updated via adjust_method_entries
3011 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {
3012   // search the default_methods for uses of either obsolete or EMCP methods
3013   if (default_methods() != NULL) {
3014     for (int index = 0; index < default_methods()->length(); index ++) {
3015       Method* old_method = default_methods()->at(index);
3016       if (old_method == NULL || !old_method->is_old()) {
3017         continue; // skip uninteresting entries
3018       }
3019       assert(!old_method->is_deleted(), "default methods may not be deleted");
3020       Method* new_method = old_method->get_new_method();
3021       default_methods()->at_put(index, new_method);
3022 
3023       if (log_is_enabled(Info, redefine, class, update)) {
3024         ResourceMark rm;
3025         if (!(*trace_name_printed)) {
3026           log_info(redefine, class, update)
3027             ("adjust: klassname=%s default methods from name=%s",
3028              external_name(), old_method->method_holder()->external_name());
3029           *trace_name_printed = true;
3030         }
3031         log_debug(redefine, class, update, vtables)
3032           ("default method update: %s(%s) ",
3033            new_method->name()->as_C_string(), new_method->signature()->as_C_string());
3034       }
3035     }
3036   }
3037 }
3038 #endif // INCLUDE_JVMTI
3039 
3040 // On-stack replacement stuff
3041 void InstanceKlass::add_osr_nmethod(nmethod* n) {
3042   assert_lock_strong(CompiledMethod_lock);
3043 #ifndef PRODUCT
3044   if (TieredCompilation) {
3045       nmethod * prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);
3046       assert(prev == NULL || !prev->is_in_use(),
3047       "redundunt OSR recompilation detected. memory leak in CodeCache!");
3048   }
3049 #endif
3050   // only one compilation can be active
3051   {
3052     assert(n->is_osr_method(), "wrong kind of nmethod");
3053     n->set_osr_link(osr_nmethods_head());
3054     set_osr_nmethods_head(n);
3055     // Raise the highest osr level if necessary
3056     if (TieredCompilation) {
3057       Method* m = n->method();
3058       m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
3059     }
3060   }
3061 
3062   // Get rid of the osr methods for the same bci that have lower levels.
3063   if (TieredCompilation) {
3064     for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
3065       nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
3066       if (inv != NULL && inv->is_in_use()) {
3067         inv->make_not_entrant();
3068       }
3069     }
3070   }
3071 }
3072 
3073 // Remove osr nmethod from the list. Return true if found and removed.
3074 bool InstanceKlass::remove_osr_nmethod(nmethod* n) {
3075   // This is a short non-blocking critical region, so the no safepoint check is ok.
3076   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock
3077                  , Mutex::_no_safepoint_check_flag);
3078   assert(n->is_osr_method(), "wrong kind of nmethod");
3079   nmethod* last = NULL;
3080   nmethod* cur  = osr_nmethods_head();
3081   int max_level = CompLevel_none;  // Find the max comp level excluding n
3082   Method* m = n->method();
3083   // Search for match
3084   bool found = false;
3085   while(cur != NULL && cur != n) {
3086     if (TieredCompilation && m == cur->method()) {
3087       // Find max level before n
3088       max_level = MAX2(max_level, cur->comp_level());
3089     }
3090     last = cur;
3091     cur = cur->osr_link();
3092   }
3093   nmethod* next = NULL;
3094   if (cur == n) {
3095     found = true;
3096     next = cur->osr_link();
3097     if (last == NULL) {
3098       // Remove first element
3099       set_osr_nmethods_head(next);
3100     } else {
3101       last->set_osr_link(next);
3102     }
3103   }
3104   n->set_osr_link(NULL);
3105   if (TieredCompilation) {
3106     cur = next;
3107     while (cur != NULL) {
3108       // Find max level after n
3109       if (m == cur->method()) {
3110         max_level = MAX2(max_level, cur->comp_level());
3111       }
3112       cur = cur->osr_link();
3113     }
3114     m->set_highest_osr_comp_level(max_level);
3115   }
3116   return found;
3117 }
3118 
3119 int InstanceKlass::mark_osr_nmethods(const Method* m) {
3120   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
3121                  Mutex::_no_safepoint_check_flag);
3122   nmethod* osr = osr_nmethods_head();
3123   int found = 0;
3124   while (osr != NULL) {
3125     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3126     if (osr->method() == m) {
3127       osr->mark_for_deoptimization();
3128       found++;
3129     }
3130     osr = osr->osr_link();
3131   }
3132   return found;
3133 }
3134 
3135 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3136   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
3137                  Mutex::_no_safepoint_check_flag);
3138   nmethod* osr = osr_nmethods_head();
3139   nmethod* best = NULL;
3140   while (osr != NULL) {
3141     assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3142     // There can be a time when a c1 osr method exists but we are waiting
3143     // for a c2 version. When c2 completes its osr nmethod we will trash
3144     // the c1 version and only be able to find the c2 version. However
3145     // while we overflow in the c1 code at back branches we don't want to
3146     // try and switch to the same code as we are already running
3147 
3148     if (osr->method() == m &&
3149         (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3150       if (match_level) {
3151         if (osr->comp_level() == comp_level) {
3152           // Found a match - return it.
3153           return osr;
3154         }
3155       } else {
3156         if (best == NULL || (osr->comp_level() > best->comp_level())) {
3157           if (osr->comp_level() == CompLevel_highest_tier) {
3158             // Found the best possible - return it.
3159             return osr;
3160           }
3161           best = osr;
3162         }
3163       }
3164     }
3165     osr = osr->osr_link();
3166   }
3167 
3168   assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");
3169   if (best != NULL && best->comp_level() >= comp_level) {
3170     return best;
3171   }
3172   return NULL;
3173 }
3174 
3175 // -----------------------------------------------------------------------------------------------------
3176 // Printing
3177 
3178 #ifndef PRODUCT
3179 
3180 #define BULLET  " - "
3181 
3182 static const char* state_names[] = {
3183   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3184 };
3185 
3186 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3187   for (int i = 0; i < len; i++) {
3188     intptr_t e = start[i];
3189     st->print("%d : " INTPTR_FORMAT, i, e);
3190     if (MetaspaceObj::is_valid((Metadata*)e)) {
3191       st->print(" ");
3192       ((Metadata*)e)->print_value_on(st);
3193     }
3194     st->cr();
3195   }
3196 }
3197 
3198 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3199   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);
3200 }
3201 
3202 void InstanceKlass::print_on(outputStream* st) const {
3203   assert(is_klass(), "must be klass");
3204   Klass::print_on(st);
3205 
3206   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3207   st->print(BULLET"klass size:        %d", size());                               st->cr();
3208   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3209   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3210   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3211   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3212   st->print(BULLET"sub:               ");
3213   Klass* sub = subklass();
3214   int n;
3215   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3216     if (n < MaxSubklassPrintSize) {
3217       sub->print_value_on(st);
3218       st->print("   ");
3219     }
3220   }
3221   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3222   st->cr();
3223 
3224   if (is_interface()) {
3225     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3226     if (nof_implementors() == 1) {
3227       st->print_cr(BULLET"implementor:    ");
3228       st->print("   ");
3229       implementor()->print_value_on(st);
3230       st->cr();
3231     }
3232   }
3233 
3234   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3235   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
3236   if (Verbose || WizardMode) {
3237     Array<Method*>* method_array = methods();
3238     for (int i = 0; i < method_array->length(); i++) {
3239       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3240     }
3241   }
3242   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
3243   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
3244   if (Verbose && default_methods() != NULL) {
3245     Array<Method*>* method_array = default_methods();
3246     for (int i = 0; i < method_array->length(); i++) {
3247       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3248     }
3249   }
3250   if (default_vtable_indices() != NULL) {
3251     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
3252   }
3253   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
3254   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3255   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3256   if (class_loader_data() != NULL) {
3257     st->print(BULLET"class loader data:  ");
3258     class_loader_data()->print_value_on(st);
3259     st->cr();
3260   }
3261   st->print(BULLET"unsafe anonymous host class:        "); Metadata::print_value_on_maybe_null(st, unsafe_anonymous_host()); st->cr();
3262   if (source_file_name() != NULL) {
3263     st->print(BULLET"source file:       ");
3264     source_file_name()->print_value_on(st);
3265     st->cr();
3266   }
3267   if (source_debug_extension() != NULL) {
3268     st->print(BULLET"source debug extension:       ");
3269     st->print("%s", source_debug_extension());
3270     st->cr();
3271   }
3272   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3273   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3274   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
3275   st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
3276   {
3277     bool have_pv = false;
3278     // previous versions are linked together through the InstanceKlass
3279     for (InstanceKlass* pv_node = previous_versions();
3280          pv_node != NULL;
3281          pv_node = pv_node->previous_versions()) {
3282       if (!have_pv)
3283         st->print(BULLET"previous version:  ");
3284       have_pv = true;
3285       pv_node->constants()->print_value_on(st);
3286     }
3287     if (have_pv) st->cr();
3288   }
3289 
3290   if (generic_signature() != NULL) {
3291     st->print(BULLET"generic signature: ");
3292     generic_signature()->print_value_on(st);
3293     st->cr();
3294   }
3295   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3296   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3297   if (record_components() != NULL) {
3298     st->print(BULLET"record components:     "); record_components()->print_value_on(st);     st->cr();
3299   }
3300   if (java_mirror() != NULL) {
3301     st->print(BULLET"java mirror:       ");
3302     java_mirror()->print_value_on(st);
3303     st->cr();
3304   } else {
3305     st->print_cr(BULLET"java mirror:       NULL");
3306   }
3307   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3308   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3309   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3310   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3311   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3312   FieldPrinter print_static_field(st);
3313   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3314   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3315   FieldPrinter print_nonstatic_field(st);
3316   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3317   ik->do_nonstatic_fields(&print_nonstatic_field);
3318 
3319   st->print(BULLET"non-static oop maps: ");
3320   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3321   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3322   while (map < end_map) {
3323     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3324     map++;
3325   }
3326   st->cr();
3327 }
3328 
3329 #endif //PRODUCT
3330 
3331 void InstanceKlass::print_value_on(outputStream* st) const {
3332   assert(is_klass(), "must be klass");
3333   if (Verbose || WizardMode)  access_flags().print_on(st);
3334   name()->print_value_on(st);
3335 }
3336 
3337 #ifndef PRODUCT
3338 
3339 void FieldPrinter::do_field(fieldDescriptor* fd) {
3340   _st->print(BULLET);
3341    if (_obj == NULL) {
3342      fd->print_on(_st);
3343      _st->cr();
3344    } else {
3345      fd->print_on_for(_st, _obj);
3346      _st->cr();
3347    }
3348 }
3349 
3350 
3351 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3352   Klass::oop_print_on(obj, st);
3353 
3354   if (this == SystemDictionary::String_klass()) {
3355     typeArrayOop value  = java_lang_String::value(obj);
3356     juint        length = java_lang_String::length(obj);
3357     if (value != NULL &&
3358         value->is_typeArray() &&
3359         length <= (juint) value->length()) {
3360       st->print(BULLET"string: ");
3361       java_lang_String::print(obj, st);
3362       st->cr();
3363       if (!WizardMode)  return;  // that is enough
3364     }
3365   }
3366 
3367   st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3368   FieldPrinter print_field(st, obj);
3369   do_nonstatic_fields(&print_field);
3370 
3371   if (this == SystemDictionary::Class_klass()) {
3372     st->print(BULLET"signature: ");
3373     java_lang_Class::print_signature(obj, st);
3374     st->cr();
3375     Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3376     st->print(BULLET"fake entry for mirror: ");
3377     Metadata::print_value_on_maybe_null(st, mirrored_klass);
3378     st->cr();
3379     Klass* array_klass = java_lang_Class::array_klass_acquire(obj);
3380     st->print(BULLET"fake entry for array: ");
3381     Metadata::print_value_on_maybe_null(st, array_klass);
3382     st->cr();
3383     st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3384     st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3385     Klass* real_klass = java_lang_Class::as_Klass(obj);
3386     if (real_klass != NULL && real_klass->is_instance_klass()) {
3387       InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3388     }
3389   } else if (this == SystemDictionary::MethodType_klass()) {
3390     st->print(BULLET"signature: ");
3391     java_lang_invoke_MethodType::print_signature(obj, st);
3392     st->cr();
3393   }
3394 }
3395 
3396 bool InstanceKlass::verify_itable_index(int i) {
3397   int method_count = klassItable::method_count_for_interface(this);
3398   assert(i >= 0 && i < method_count, "index out of bounds");
3399   return true;
3400 }
3401 
3402 #endif //PRODUCT
3403 
3404 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3405   st->print("a ");
3406   name()->print_value_on(st);
3407   obj->print_address_on(st);
3408   if (this == SystemDictionary::String_klass()
3409       && java_lang_String::value(obj) != NULL) {
3410     ResourceMark rm;
3411     int len = java_lang_String::length(obj);
3412     int plen = (len < 24 ? len : 12);
3413     char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3414     st->print(" = \"%s\"", str);
3415     if (len > plen)
3416       st->print("...[%d]", len);
3417   } else if (this == SystemDictionary::Class_klass()) {
3418     Klass* k = java_lang_Class::as_Klass(obj);
3419     st->print(" = ");
3420     if (k != NULL) {
3421       k->print_value_on(st);
3422     } else {
3423       const char* tname = type2name(java_lang_Class::primitive_type(obj));
3424       st->print("%s", tname ? tname : "type?");
3425     }
3426   } else if (this == SystemDictionary::MethodType_klass()) {
3427     st->print(" = ");
3428     java_lang_invoke_MethodType::print_signature(obj, st);
3429   } else if (java_lang_boxing_object::is_instance(obj)) {
3430     st->print(" = ");
3431     java_lang_boxing_object::print(obj, st);
3432   } else if (this == SystemDictionary::LambdaForm_klass()) {
3433     oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3434     if (vmentry != NULL) {
3435       st->print(" => ");
3436       vmentry->print_value_on(st);
3437     }
3438   } else if (this == SystemDictionary::MemberName_klass()) {
3439     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3440     if (vmtarget != NULL) {
3441       st->print(" = ");
3442       vmtarget->print_value_on(st);
3443     } else {
3444       java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3445       st->print(".");
3446       java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3447     }
3448   }
3449 }
3450 
3451 const char* InstanceKlass::internal_name() const {
3452   return external_name();
3453 }
3454 
3455 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,
3456                                              const char* module_name,
3457                                              const ClassFileStream* cfs) const {
3458   if (!log_is_enabled(Info, class, load)) {
3459     return;
3460   }
3461 
3462   ResourceMark rm;
3463   LogMessage(class, load) msg;
3464   stringStream info_stream;
3465 
3466   // Name and class hierarchy info
3467   info_stream.print("%s", external_name());
3468 
3469   // Source
3470   if (cfs != NULL) {
3471     if (cfs->source() != NULL) {
3472       if (module_name != NULL) {
3473         // When the boot loader created the stream, it didn't know the module name
3474         // yet. Let's format it now.
3475         if (cfs->from_boot_loader_modules_image()) {
3476           info_stream.print(" source: jrt:/%s", module_name);
3477         } else {
3478           info_stream.print(" source: %s", cfs->source());
3479         }
3480       } else {
3481         info_stream.print(" source: %s", cfs->source());
3482       }
3483     } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
3484       Thread* THREAD = Thread::current();
3485       Klass* caller =
3486             THREAD->is_Java_thread()
3487                 ? ((JavaThread*)THREAD)->security_get_caller_class(1)
3488                 : NULL;
3489       // caller can be NULL, for example, during a JVMTI VM_Init hook
3490       if (caller != NULL) {
3491         info_stream.print(" source: instance of %s", caller->external_name());
3492       } else {
3493         // source is unknown
3494       }
3495     } else {
3496       oop class_loader = loader_data->class_loader();
3497       info_stream.print(" source: %s", class_loader->klass()->external_name());
3498     }
3499   } else {
3500     assert(this->is_shared(), "must be");
3501     if (MetaspaceShared::is_shared_dynamic((void*)this)) {
3502       info_stream.print(" source: shared objects file (top)");
3503     } else {
3504       info_stream.print(" source: shared objects file");
3505     }
3506   }
3507 
3508   msg.info("%s", info_stream.as_string());
3509 
3510   if (log_is_enabled(Debug, class, load)) {
3511     stringStream debug_stream;
3512 
3513     // Class hierarchy info
3514     debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT,
3515                        p2i(this),  p2i(superklass()));
3516 
3517     // Interfaces
3518     if (local_interfaces() != NULL && local_interfaces()->length() > 0) {
3519       debug_stream.print(" interfaces:");
3520       int length = local_interfaces()->length();
3521       for (int i = 0; i < length; i++) {
3522         debug_stream.print(" " INTPTR_FORMAT,
3523                            p2i(InstanceKlass::cast(local_interfaces()->at(i))));
3524       }
3525     }
3526 
3527     // Class loader
3528     debug_stream.print(" loader: [");
3529     loader_data->print_value_on(&debug_stream);
3530     debug_stream.print("]");
3531 
3532     // Classfile checksum
3533     if (cfs) {
3534       debug_stream.print(" bytes: %d checksum: %08x",
3535                          cfs->length(),
3536                          ClassLoader::crc32(0, (const char*)cfs->buffer(),
3537                          cfs->length()));
3538     }
3539 
3540     msg.debug("%s", debug_stream.as_string());
3541   }
3542 }
3543 
3544 // Verification
3545 
3546 class VerifyFieldClosure: public BasicOopIterateClosure {
3547  protected:
3548   template <class T> void do_oop_work(T* p) {
3549     oop obj = RawAccess<>::oop_load(p);
3550     if (!oopDesc::is_oop_or_null(obj)) {
3551       tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
3552       Universe::print_on(tty);
3553       guarantee(false, "boom");
3554     }
3555   }
3556  public:
3557   virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3558   virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3559 };
3560 
3561 void InstanceKlass::verify_on(outputStream* st) {
3562 #ifndef PRODUCT
3563   // Avoid redundant verifies, this really should be in product.
3564   if (_verify_count == Universe::verify_count()) return;
3565   _verify_count = Universe::verify_count();
3566 #endif
3567 
3568   // Verify Klass
3569   Klass::verify_on(st);
3570 
3571   // Verify that klass is present in ClassLoaderData
3572   guarantee(class_loader_data()->contains_klass(this),
3573             "this class isn't found in class loader data");
3574 
3575   // Verify vtables
3576   if (is_linked()) {
3577     // $$$ This used to be done only for m/s collections.  Doing it
3578     // always seemed a valid generalization.  (DLD -- 6/00)
3579     vtable().verify(st);
3580   }
3581 
3582   // Verify first subklass
3583   if (subklass() != NULL) {
3584     guarantee(subklass()->is_klass(), "should be klass");
3585   }
3586 
3587   // Verify siblings
3588   Klass* super = this->super();
3589   Klass* sib = next_sibling();
3590   if (sib != NULL) {
3591     if (sib == this) {
3592       fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
3593     }
3594 
3595     guarantee(sib->is_klass(), "should be klass");
3596     guarantee(sib->super() == super, "siblings should have same superklass");
3597   }
3598 
3599   // Verify local interfaces
3600   if (local_interfaces()) {
3601     Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
3602     for (int j = 0; j < local_interfaces->length(); j++) {
3603       InstanceKlass* e = local_interfaces->at(j);
3604       guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3605     }
3606   }
3607 
3608   // Verify transitive interfaces
3609   if (transitive_interfaces() != NULL) {
3610     Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();
3611     for (int j = 0; j < transitive_interfaces->length(); j++) {
3612       InstanceKlass* e = transitive_interfaces->at(j);
3613       guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3614     }
3615   }
3616 
3617   // Verify methods
3618   if (methods() != NULL) {
3619     Array<Method*>* methods = this->methods();
3620     for (int j = 0; j < methods->length(); j++) {
3621       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3622     }
3623     for (int j = 0; j < methods->length() - 1; j++) {
3624       Method* m1 = methods->at(j);
3625       Method* m2 = methods->at(j + 1);
3626       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3627     }
3628   }
3629 
3630   // Verify method ordering
3631   if (method_ordering() != NULL) {
3632     Array<int>* method_ordering = this->method_ordering();
3633     int length = method_ordering->length();
3634     if (JvmtiExport::can_maintain_original_method_order() ||
3635         ((UseSharedSpaces || Arguments::is_dumping_archive()) && length != 0)) {
3636       guarantee(length == methods()->length(), "invalid method ordering length");
3637       jlong sum = 0;
3638       for (int j = 0; j < length; j++) {
3639         int original_index = method_ordering->at(j);
3640         guarantee(original_index >= 0, "invalid method ordering index");
3641         guarantee(original_index < length, "invalid method ordering index");
3642         sum += original_index;
3643       }
3644       // Verify sum of indices 0,1,...,length-1
3645       guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3646     } else {
3647       guarantee(length == 0, "invalid method ordering length");
3648     }
3649   }
3650 
3651   // Verify default methods
3652   if (default_methods() != NULL) {
3653     Array<Method*>* methods = this->default_methods();
3654     for (int j = 0; j < methods->length(); j++) {
3655       guarantee(methods->at(j)->is_method(), "non-method in methods array");
3656     }
3657     for (int j = 0; j < methods->length() - 1; j++) {
3658       Method* m1 = methods->at(j);
3659       Method* m2 = methods->at(j + 1);
3660       guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3661     }
3662   }
3663 
3664   // Verify JNI static field identifiers
3665   if (jni_ids() != NULL) {
3666     jni_ids()->verify(this);
3667   }
3668 
3669   // Verify other fields
3670   if (array_klasses() != NULL) {
3671     guarantee(array_klasses()->is_klass(), "should be klass");
3672   }
3673   if (constants() != NULL) {
3674     guarantee(constants()->is_constantPool(), "should be constant pool");
3675   }
3676   const Klass* anonymous_host = unsafe_anonymous_host();
3677   if (anonymous_host != NULL) {
3678     guarantee(anonymous_host->is_klass(), "should be klass");
3679   }
3680 }
3681 
3682 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3683   Klass::oop_verify_on(obj, st);
3684   VerifyFieldClosure blk;
3685   obj->oop_iterate(&blk);
3686 }
3687 
3688 
3689 // JNIid class for jfieldIDs only
3690 // Note to reviewers:
3691 // These JNI functions are just moved over to column 1 and not changed
3692 // in the compressed oops workspace.
3693 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3694   _holder = holder;
3695   _offset = offset;
3696   _next = next;
3697   debug_only(_is_static_field_id = false;)
3698 }
3699 
3700 
3701 JNIid* JNIid::find(int offset) {
3702   JNIid* current = this;
3703   while (current != NULL) {
3704     if (current->offset() == offset) return current;
3705     current = current->next();
3706   }
3707   return NULL;
3708 }
3709 
3710 void JNIid::deallocate(JNIid* current) {
3711   while (current != NULL) {
3712     JNIid* next = current->next();
3713     delete current;
3714     current = next;
3715   }
3716 }
3717 
3718 
3719 void JNIid::verify(Klass* holder) {
3720   int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3721   int end_field_offset;
3722   end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3723 
3724   JNIid* current = this;
3725   while (current != NULL) {
3726     guarantee(current->holder() == holder, "Invalid klass in JNIid");
3727 #ifdef ASSERT
3728     int o = current->offset();
3729     if (current->is_static_field_id()) {
3730       guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3731     }
3732 #endif
3733     current = current->next();
3734   }
3735 }
3736 
3737 void InstanceKlass::set_init_state(ClassState state) {
3738 #ifdef ASSERT
3739   bool good_state = is_shared() ? (_init_state <= state)
3740                                                : (_init_state < state);
3741   assert(good_state || state == allocated, "illegal state transition");
3742 #endif
3743   assert(_init_thread == NULL, "should be cleared before state change");
3744   _init_state = (u1)state;
3745 }
3746 
3747 #if INCLUDE_JVMTI
3748 
3749 // RedefineClasses() support for previous versions
3750 
3751 // Globally, there is at least one previous version of a class to walk
3752 // during class unloading, which is saved because old methods in the class
3753 // are still running.   Otherwise the previous version list is cleaned up.
3754 bool InstanceKlass::_has_previous_versions = false;
3755 
3756 // Returns true if there are previous versions of a class for class
3757 // unloading only. Also resets the flag to false. purge_previous_version
3758 // will set the flag to true if there are any left, i.e., if there's any
3759 // work to do for next time. This is to avoid the expensive code cache
3760 // walk in CLDG::clean_deallocate_lists().
3761 bool InstanceKlass::has_previous_versions_and_reset() {
3762   bool ret = _has_previous_versions;
3763   log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s",
3764      ret ? "true" : "false");
3765   _has_previous_versions = false;
3766   return ret;
3767 }
3768 
3769 // Purge previous versions before adding new previous versions of the class and
3770 // during class unloading.
3771 void InstanceKlass::purge_previous_version_list() {
3772   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3773   assert(has_been_redefined(), "Should only be called for main class");
3774 
3775   // Quick exit.
3776   if (previous_versions() == NULL) {
3777     return;
3778   }
3779 
3780   // This klass has previous versions so see what we can cleanup
3781   // while it is safe to do so.
3782 
3783   int deleted_count = 0;    // leave debugging breadcrumbs
3784   int live_count = 0;
3785   ClassLoaderData* loader_data = class_loader_data();
3786   assert(loader_data != NULL, "should never be null");
3787 
3788   ResourceMark rm;
3789   log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
3790 
3791   // previous versions are linked together through the InstanceKlass
3792   InstanceKlass* pv_node = previous_versions();
3793   InstanceKlass* last = this;
3794   int version = 0;
3795 
3796   // check the previous versions list
3797   for (; pv_node != NULL; ) {
3798 
3799     ConstantPool* pvcp = pv_node->constants();
3800     assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3801 
3802     if (!pvcp->on_stack()) {
3803       // If the constant pool isn't on stack, none of the methods
3804       // are executing.  Unlink this previous_version.
3805       // The previous version InstanceKlass is on the ClassLoaderData deallocate list
3806       // so will be deallocated during the next phase of class unloading.
3807       log_trace(redefine, class, iklass, purge)
3808         ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node));
3809       // For debugging purposes.
3810       pv_node->set_is_scratch_class();
3811       // Unlink from previous version list.
3812       assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
3813       InstanceKlass* next = pv_node->previous_versions();
3814       pv_node->link_previous_versions(NULL);   // point next to NULL
3815       last->link_previous_versions(next);
3816       // Add to the deallocate list after unlinking
3817       loader_data->add_to_deallocate_list(pv_node);
3818       pv_node = next;
3819       deleted_count++;
3820       version++;
3821       continue;
3822     } else {
3823       log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node));
3824       assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3825       guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3826       live_count++;
3827       // found a previous version for next time we do class unloading
3828       _has_previous_versions = true;
3829     }
3830 
3831     // At least one method is live in this previous version.
3832     // Reset dead EMCP methods not to get breakpoints.
3833     // All methods are deallocated when all of the methods for this class are no
3834     // longer running.
3835     Array<Method*>* method_refs = pv_node->methods();
3836     if (method_refs != NULL) {
3837       log_trace(redefine, class, iklass, purge)("previous methods length=%d", method_refs->length());
3838       for (int j = 0; j < method_refs->length(); j++) {
3839         Method* method = method_refs->at(j);
3840 
3841         if (!method->on_stack()) {
3842           // no breakpoints for non-running methods
3843           if (method->is_running_emcp()) {
3844             method->set_running_emcp(false);
3845           }
3846         } else {
3847           assert (method->is_obsolete() || method->is_running_emcp(),
3848                   "emcp method cannot run after emcp bit is cleared");
3849           log_trace(redefine, class, iklass, purge)
3850             ("purge: %s(%s): prev method @%d in version @%d is alive",
3851              method->name()->as_C_string(), method->signature()->as_C_string(), j, version);
3852         }
3853       }
3854     }
3855     // next previous version
3856     last = pv_node;
3857     pv_node = pv_node->previous_versions();
3858     version++;
3859   }
3860   log_trace(redefine, class, iklass, purge)
3861     ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
3862 }
3863 
3864 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
3865                                                 int emcp_method_count) {
3866   int obsolete_method_count = old_methods->length() - emcp_method_count;
3867 
3868   if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3869       _previous_versions != NULL) {
3870     // We have a mix of obsolete and EMCP methods so we have to
3871     // clear out any matching EMCP method entries the hard way.
3872     int local_count = 0;
3873     for (int i = 0; i < old_methods->length(); i++) {
3874       Method* old_method = old_methods->at(i);
3875       if (old_method->is_obsolete()) {
3876         // only obsolete methods are interesting
3877         Symbol* m_name = old_method->name();
3878         Symbol* m_signature = old_method->signature();
3879 
3880         // previous versions are linked together through the InstanceKlass
3881         int j = 0;
3882         for (InstanceKlass* prev_version = _previous_versions;
3883              prev_version != NULL;
3884              prev_version = prev_version->previous_versions(), j++) {
3885 
3886           Array<Method*>* method_refs = prev_version->methods();
3887           for (int k = 0; k < method_refs->length(); k++) {
3888             Method* method = method_refs->at(k);
3889 
3890             if (!method->is_obsolete() &&
3891                 method->name() == m_name &&
3892                 method->signature() == m_signature) {
3893               // The current RedefineClasses() call has made all EMCP
3894               // versions of this method obsolete so mark it as obsolete
3895               log_trace(redefine, class, iklass, add)
3896                 ("%s(%s): flush obsolete method @%d in version @%d",
3897                  m_name->as_C_string(), m_signature->as_C_string(), k, j);
3898 
3899               method->set_is_obsolete();
3900               break;
3901             }
3902           }
3903 
3904           // The previous loop may not find a matching EMCP method, but
3905           // that doesn't mean that we can optimize and not go any
3906           // further back in the PreviousVersion generations. The EMCP
3907           // method for this generation could have already been made obsolete,
3908           // but there still may be an older EMCP method that has not
3909           // been made obsolete.
3910         }
3911 
3912         if (++local_count >= obsolete_method_count) {
3913           // no more obsolete methods so bail out now
3914           break;
3915         }
3916       }
3917     }
3918   }
3919 }
3920 
3921 // Save the scratch_class as the previous version if any of the methods are running.
3922 // The previous_versions are used to set breakpoints in EMCP methods and they are
3923 // also used to clean MethodData links to redefined methods that are no longer running.
3924 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,
3925                                          int emcp_method_count) {
3926   assert(Thread::current()->is_VM_thread(),
3927          "only VMThread can add previous versions");
3928 
3929   ResourceMark rm;
3930   log_trace(redefine, class, iklass, add)
3931     ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
3932 
3933   // Clean out old previous versions for this class
3934   purge_previous_version_list();
3935 
3936   // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
3937   // a previous redefinition may be made obsolete by this redefinition.
3938   Array<Method*>* old_methods = scratch_class->methods();
3939   mark_newly_obsolete_methods(old_methods, emcp_method_count);
3940 
3941   // If the constant pool for this previous version of the class
3942   // is not marked as being on the stack, then none of the methods
3943   // in this previous version of the class are on the stack so
3944   // we don't need to add this as a previous version.
3945   ConstantPool* cp_ref = scratch_class->constants();
3946   if (!cp_ref->on_stack()) {
3947     log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");
3948     // For debugging purposes.
3949     scratch_class->set_is_scratch_class();
3950     scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);
3951     return;
3952   }
3953 
3954   if (emcp_method_count != 0) {
3955     // At least one method is still running, check for EMCP methods
3956     for (int i = 0; i < old_methods->length(); i++) {
3957       Method* old_method = old_methods->at(i);
3958       if (!old_method->is_obsolete() && old_method->on_stack()) {
3959         // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
3960         // we can add breakpoints for it.
3961 
3962         // We set the method->on_stack bit during safepoints for class redefinition
3963         // and use this bit to set the is_running_emcp bit.
3964         // After the safepoint, the on_stack bit is cleared and the running emcp
3965         // method may exit.   If so, we would set a breakpoint in a method that
3966         // is never reached, but this won't be noticeable to the programmer.
3967         old_method->set_running_emcp(true);
3968         log_trace(redefine, class, iklass, add)
3969           ("EMCP method %s is on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
3970       } else if (!old_method->is_obsolete()) {
3971         log_trace(redefine, class, iklass, add)
3972           ("EMCP method %s is NOT on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method));
3973       }
3974     }
3975   }
3976 
3977   // Add previous version if any methods are still running.
3978   // Set has_previous_version flag for processing during class unloading.
3979   _has_previous_versions = true;
3980   log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
3981   assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
3982   scratch_class->link_previous_versions(previous_versions());
3983   link_previous_versions(scratch_class);
3984 } // end add_previous_version()
3985 
3986 #endif // INCLUDE_JVMTI
3987 
3988 Method* InstanceKlass::method_with_idnum(int idnum) {
3989   Method* m = NULL;
3990   if (idnum < methods()->length()) {
3991     m = methods()->at(idnum);
3992   }
3993   if (m == NULL || m->method_idnum() != idnum) {
3994     for (int index = 0; index < methods()->length(); ++index) {
3995       m = methods()->at(index);
3996       if (m->method_idnum() == idnum) {
3997         return m;
3998       }
3999     }
4000     // None found, return null for the caller to handle.
4001     return NULL;
4002   }
4003   return m;
4004 }
4005 
4006 
4007 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
4008   if (idnum >= methods()->length()) {
4009     return NULL;
4010   }
4011   Method* m = methods()->at(idnum);
4012   if (m != NULL && m->orig_method_idnum() == idnum) {
4013     return m;
4014   }
4015   // Obsolete method idnum does not match the original idnum
4016   for (int index = 0; index < methods()->length(); ++index) {
4017     m = methods()->at(index);
4018     if (m->orig_method_idnum() == idnum) {
4019       return m;
4020     }
4021   }
4022   // None found, return null for the caller to handle.
4023   return NULL;
4024 }
4025 
4026 
4027 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
4028   InstanceKlass* holder = get_klass_version(version);
4029   if (holder == NULL) {
4030     return NULL; // The version of klass is gone, no method is found
4031   }
4032   Method* method = holder->method_with_orig_idnum(idnum);
4033   return method;
4034 }
4035 
4036 #if INCLUDE_JVMTI
4037 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4038   return _cached_class_file;
4039 }
4040 
4041 jint InstanceKlass::get_cached_class_file_len() {
4042   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4043 }
4044 
4045 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4046   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4047 }
4048 #endif
--- EOF ---