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



2647     return NULL;
2648   } else {
2649     if (name->utf8_length() <= 0) {


2650       return NULL;
2651     }
2652     ResourceMark rm(THREAD);
2653     const char* package_name = ClassLoader::package_from_name((const char*) name->as_C_string());
2654     if (package_name == NULL) {

2655       return NULL;
2656     }
2657     Symbol* pkg_name = SymbolTable::new_symbol(package_name);
2658     return pkg_name;











2659   }












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