1 /*
   2  * Copyright (c) 1997, 2026, 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 "cds/cdsConfig.hpp"
  26 #include "cds/heapShared.inline.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoaderData.inline.hpp"
  29 #include "classfile/classLoaderDataGraph.inline.hpp"
  30 #include "classfile/javaClasses.inline.hpp"
  31 #include "classfile/moduleEntry.hpp"
  32 #include "classfile/systemDictionary.hpp"
  33 #include "classfile/systemDictionaryShared.hpp"
  34 #include "classfile/vmClasses.hpp"
  35 #include "classfile/vmSymbols.hpp"
  36 #include "gc/shared/collectedHeap.inline.hpp"
  37 #include "jvm_io.h"
  38 #include "logging/log.hpp"
  39 #include "memory/metadataFactory.hpp"
  40 #include "memory/metaspaceClosure.hpp"
  41 #include "memory/oopFactory.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "memory/universe.hpp"
  44 #include "oops/compressedKlass.inline.hpp"
  45 #include "oops/compressedOops.inline.hpp"
  46 #include "oops/instanceKlass.hpp"
  47 #include "oops/klass.inline.hpp"
  48 #include "oops/objArrayKlass.hpp"
  49 #include "oops/oop.inline.hpp"
  50 #include "oops/oopHandle.inline.hpp"
  51 #include "prims/jvmtiExport.hpp"
  52 #include "runtime/atomicAccess.hpp"
  53 #include "runtime/handles.inline.hpp"
  54 #include "runtime/perfData.hpp"
  55 #include "utilities/macros.hpp"
  56 #include "utilities/powerOfTwo.hpp"
  57 #include "utilities/rotate_bits.hpp"
  58 #include "utilities/stack.inline.hpp"
  59 
  60 #if INCLUDE_JFR
  61 #include "jfr/jfr.hpp"
  62 #endif
  63 
  64 void Klass::set_java_mirror(Handle m) {
  65   assert(!m.is_null(), "New mirror should never be null.");
  66   assert(_java_mirror.is_empty(), "should only be used to initialize mirror");
  67   _java_mirror = class_loader_data()->add_handle(m);
  68 }
  69 
  70 bool Klass::is_cloneable() const {
  71   return _misc_flags.is_cloneable_fast() ||
  72          is_subtype_of(vmClasses::Cloneable_klass());
  73 }
  74 
  75 uint8_t Klass::compute_hash_slot(Symbol* n) {
  76   uint hash_code;
  77   // Special cases for the two superclasses of all Array instances.
  78   // Code elsewhere assumes, for all instances of ArrayKlass, that
  79   // these two interfaces will be in this order.
  80 
  81   // We ensure there are some empty slots in the hash table between
  82   // these two very common interfaces because if they were adjacent
  83   // (e.g. Slots 0 and 1), then any other class which hashed to 0 or 1
  84   // would result in a probe length of 3.
  85   if (n == vmSymbols::java_lang_Cloneable()) {
  86     hash_code = 0;
  87   } else if (n == vmSymbols::java_io_Serializable()) {
  88     hash_code = SECONDARY_SUPERS_TABLE_SIZE / 2;
  89   } else {
  90     auto s = (const jbyte*) n->bytes();
  91     hash_code = java_lang_String::hash_code(s, n->utf8_length());
  92     // We use String::hash_code here (rather than e.g.
  93     // Symbol::identity_hash()) in order to have a hash code that
  94     // does not change from run to run. We want that because the
  95     // hash value for a secondary superclass appears in generated
  96     // code as a constant.
  97 
  98     // This constant is magic: see Knuth, "Fibonacci Hashing".
  99     constexpr uint multiplier
 100       = 2654435769; // (uint)(((u8)1 << 32) / ((1 + sqrt(5)) / 2 ))
 101     constexpr uint hash_shift = sizeof(hash_code) * 8 - 6;
 102     // The leading bits of the least significant half of the product.
 103     hash_code = (hash_code * multiplier) >> hash_shift;
 104 
 105     if (StressSecondarySupers) {
 106       // Generate many hash collisions in order to stress-test the
 107       // linear search fallback.
 108       hash_code = hash_code % 3;
 109       hash_code = hash_code * (SECONDARY_SUPERS_TABLE_SIZE / 3);
 110     }
 111   }
 112 
 113   return (hash_code & SECONDARY_SUPERS_TABLE_MASK);
 114 }
 115 
 116 void Klass::set_name(Symbol* n) {
 117   _name = n;
 118 
 119   if (_name != nullptr) {
 120     _name->increment_refcount();
 121   }
 122 
 123   {
 124     elapsedTimer selftime;
 125     selftime.start();
 126 
 127     _hash_slot = compute_hash_slot(n);
 128     assert(_hash_slot < SECONDARY_SUPERS_TABLE_SIZE, "required");
 129 
 130     selftime.stop();
 131     if (UsePerfData) {
 132       ClassLoader::perf_secondary_hash_time()->inc(selftime.ticks());
 133     }
 134   }
 135 
 136   if (CDSConfig::is_dumping_archive() && is_instance_klass()) {
 137     SystemDictionaryShared::init_dumptime_info(InstanceKlass::cast(this));
 138   }
 139 }
 140 
 141 bool Klass::is_subclass_of(const Klass* k) const {
 142   // Run up the super chain and check
 143   if (this == k) return true;
 144 
 145   Klass* t = const_cast<Klass*>(this)->super();
 146 
 147   while (t != nullptr) {
 148     if (t == k) return true;
 149     t = t->super();
 150   }
 151   return false;
 152 }
 153 
 154 void Klass::release_C_heap_structures(bool release_constant_pool) {
 155   if (_name != nullptr) _name->decrement_refcount();
 156 }
 157 
 158 bool Klass::linear_search_secondary_supers(const Klass* k) const {
 159   // Scan the array-of-objects for a match
 160   // FIXME: We could do something smarter here, maybe a vectorized
 161   // comparison or a binary search, but is that worth any added
 162   // complexity?
 163   int cnt = secondary_supers()->length();
 164   for (int i = 0; i < cnt; i++) {
 165     if (secondary_supers()->at(i) == k) {
 166       return true;
 167     }
 168   }
 169   return false;
 170 }
 171 
 172 // Given a secondary superklass k, an initial array index, and an
 173 // occupancy bitmap rotated such that Bit 1 is the next bit to test,
 174 // search for k.
 175 bool Klass::fallback_search_secondary_supers(const Klass* k, int index, uintx rotated_bitmap) const {
 176   // Once the occupancy bitmap is almost full, it's faster to use a
 177   // linear search.
 178   if (secondary_supers()->length() > SECONDARY_SUPERS_TABLE_SIZE - 2) {
 179     return linear_search_secondary_supers(k);
 180   }
 181 
 182   // This is conventional linear probing, but instead of terminating
 183   // when a null entry is found in the table, we maintain a bitmap
 184   // in which a 0 indicates missing entries.
 185 
 186   precond((int)population_count(rotated_bitmap) == secondary_supers()->length());
 187 
 188   // The check for secondary_supers()->length() <= SECONDARY_SUPERS_TABLE_SIZE - 2
 189   // at the start of this function guarantees there are 0s in the
 190   // bitmap, so this loop eventually terminates.
 191   while ((rotated_bitmap & 2) != 0) {
 192     if (++index == secondary_supers()->length()) {
 193       index = 0;
 194     }
 195     if (secondary_supers()->at(index) == k) {
 196       return true;
 197     }
 198     rotated_bitmap = rotate_right(rotated_bitmap, 1);
 199   }
 200   return false;
 201 }
 202 
 203 // Return self, except for abstract classes with exactly 1
 204 // implementor.  Then return the 1 concrete implementation.
 205 Klass *Klass::up_cast_abstract() {
 206   Klass *r = this;
 207   while( r->is_abstract() ) {   // Receiver is abstract?
 208     Klass *s = r->subklass();   // Check for exactly 1 subklass
 209     if (s == nullptr || s->next_sibling() != nullptr) // Oops; wrong count; give up
 210       return this;              // Return 'this' as a no-progress flag
 211     r = s;                    // Loop till find concrete class
 212   }
 213   return r;                   // Return the 1 concrete class
 214 }
 215 
 216 // Find LCA in class hierarchy
 217 Klass *Klass::LCA( Klass *k2 ) {
 218   Klass *k1 = this;
 219   while( 1 ) {
 220     if( k1->is_subtype_of(k2) ) return k2;
 221     if( k2->is_subtype_of(k1) ) return k1;
 222     k1 = k1->super();
 223     k2 = k2->super();
 224   }
 225 }
 226 
 227 
 228 void Klass::check_valid_for_instantiation(bool throwError, TRAPS) {
 229   ResourceMark rm(THREAD);
 230   THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
 231             : vmSymbols::java_lang_InstantiationException(), external_name());
 232 }
 233 
 234 
 235 void Klass::copy_array(arrayOop s, int src_pos, arrayOop d, int dst_pos, int length, TRAPS) {
 236   ResourceMark rm(THREAD);
 237   assert(s != nullptr, "Throw NPE!");
 238   THROW_MSG(vmSymbols::java_lang_ArrayStoreException(),
 239             err_msg("arraycopy: source type %s is not an array", s->klass()->external_name()));
 240 }
 241 
 242 
 243 void Klass::initialize(TRAPS) {
 244   ShouldNotReachHere();
 245 }
 246 
 247 void Klass::initialize_preemptable(TRAPS) {
 248   ShouldNotReachHere();
 249 }
 250 
 251 Klass* Klass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
 252 #ifdef ASSERT
 253   tty->print_cr("Error: find_field called on a klass oop."
 254                 " Likely error: reflection method does not correctly"
 255                 " wrap return value in a mirror object.");
 256 #endif
 257   ShouldNotReachHere();
 258   return nullptr;
 259 }
 260 
 261 Method* Klass::uncached_lookup_method(const Symbol* name, const Symbol* signature,
 262                                       OverpassLookupMode overpass_mode,
 263                                       PrivateLookupMode private_mode) const {
 264 #ifdef ASSERT
 265   tty->print_cr("Error: uncached_lookup_method called on a klass oop."
 266                 " Likely error: reflection method does not correctly"
 267                 " wrap return value in a mirror object.");
 268 #endif
 269   ShouldNotReachHere();
 270   return nullptr;
 271 }
 272 
 273 void* Klass::operator new(size_t size, ClassLoaderData* loader_data, size_t word_size, TRAPS) throw() {
 274   return Metaspace::allocate(loader_data, word_size, MetaspaceObj::ClassType, THREAD);
 275 }
 276 
 277 Klass::Klass() : _kind(UnknownKlassKind) {
 278   assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for cds");
 279 }
 280 
 281 // "Normal" instantiation is preceded by a MetaspaceObj allocation
 282 // which zeros out memory - calloc equivalent.
 283 // The constructor is also used from CppVtableCloner,
 284 // which doesn't zero out the memory before calling the constructor.
 285 Klass::Klass(KlassKind kind, markWord prototype_header) : _kind(kind),
 286                                _shared_class_path_index(-1) {
 287   set_prototype_header(make_prototype_header(this, prototype_header));
 288   CDS_ONLY(_aot_class_flags = 0;)
 289   CDS_JAVA_HEAP_ONLY(_archived_mirror_index = -1;)
 290   _primary_supers[0] = this;
 291   set_super_check_offset(in_bytes(primary_supers_offset()));
 292 }
 293 
 294 jint Klass::array_layout_helper(BasicType etype) {
 295   assert(etype >= T_BOOLEAN && etype <= T_OBJECT, "valid etype");
 296   // Note that T_ARRAY is not allowed here.
 297   int  hsize = arrayOopDesc::base_offset_in_bytes(etype);
 298   int  esize = type2aelembytes(etype);
 299   bool isobj = (etype == T_OBJECT);
 300   int  tag   =  isobj ? _lh_array_tag_ref_value : _lh_array_tag_type_value;
 301   int lh = array_layout_helper(tag, false, hsize, etype, exact_log2(esize));
 302 
 303   assert(lh < (int)_lh_neutral_value, "must look like an array layout");
 304   assert(layout_helper_is_array(lh), "correct kind");
 305   assert(layout_helper_is_refArray(lh) == isobj, "correct kind");
 306   assert(layout_helper_is_typeArray(lh) == !isobj, "correct kind");
 307   assert(layout_helper_header_size(lh) == hsize, "correct decode");
 308   assert(layout_helper_element_type(lh) == etype, "correct decode");
 309   assert(1 << layout_helper_log2_element_size(lh) == esize, "correct decode");
 310 
 311   return lh;
 312 }
 313 
 314 int Klass::modifier_flags() const {
 315   int mods = java_lang_Class::modifiers(java_mirror());
 316   assert(mods == compute_modifier_flags(), "should be same");
 317   return mods;
 318 }
 319 
 320 bool Klass::can_be_primary_super_slow() const {
 321   if (super() == nullptr)
 322     return true;
 323   else if (super()->super_depth() >= primary_super_limit()-1)
 324     return false;
 325   else
 326     return true;
 327 }
 328 
 329 void Klass::set_secondary_supers(Array<Klass*>* secondaries, uintx bitmap) {
 330 #ifdef ASSERT
 331   if (secondaries != nullptr) {
 332     uintx real_bitmap = compute_secondary_supers_bitmap(secondaries);
 333     assert(bitmap == real_bitmap, "must be");
 334     assert(secondaries->length() >= (int)population_count(bitmap), "must be");
 335   }
 336 #endif
 337   _secondary_supers_bitmap = bitmap;
 338   _secondary_supers = secondaries;
 339 
 340   if (secondaries != nullptr) {
 341     LogMessage(class, load) msg;
 342     NonInterleavingLogStream log {LogLevel::Debug, msg};
 343     if (log.is_enabled()) {
 344       ResourceMark rm;
 345       log.print_cr("set_secondary_supers: hash_slot: %d; klass: %s", hash_slot(), external_name());
 346       print_secondary_supers_on(&log);
 347     }
 348   }
 349 }
 350 
 351 // Hashed secondary superclasses
 352 //
 353 // We use a compressed 64-entry hash table with linear probing. We
 354 // start by creating a hash table in the usual way, followed by a pass
 355 // that removes all the null entries. To indicate which entries would
 356 // have been null we use a bitmap that contains a 1 in each position
 357 // where an entry is present, 0 otherwise. This bitmap also serves as
 358 // a kind of Bloom filter, which in many cases allows us quickly to
 359 // eliminate the possibility that something is a member of a set of
 360 // secondaries.
 361 uintx Klass::hash_secondary_supers(Array<Klass*>* secondaries, bool rewrite) {
 362   const int length = secondaries->length();
 363 
 364   if (length == 0) {
 365     return SECONDARY_SUPERS_BITMAP_EMPTY;
 366   }
 367 
 368   if (length == 1) {
 369     int hash_slot = secondaries->at(0)->hash_slot();
 370     return uintx(1) << hash_slot;
 371   }
 372 
 373   // Invariant: _secondary_supers.length >= population_count(_secondary_supers_bitmap)
 374 
 375   // Don't attempt to hash a table that's completely full, because in
 376   // the case of an absent interface linear probing would not
 377   // terminate.
 378   if (length >= SECONDARY_SUPERS_TABLE_SIZE) {
 379     return SECONDARY_SUPERS_BITMAP_FULL;
 380   }
 381 
 382   {
 383     PerfTraceTime ptt(ClassLoader::perf_secondary_hash_time());
 384 
 385     ResourceMark rm;
 386     uintx bitmap = SECONDARY_SUPERS_BITMAP_EMPTY;
 387     auto hashed_secondaries = new GrowableArray<Klass*>(SECONDARY_SUPERS_TABLE_SIZE,
 388                                                         SECONDARY_SUPERS_TABLE_SIZE, nullptr);
 389 
 390     for (int j = 0; j < length; j++) {
 391       Klass* k = secondaries->at(j);
 392       hash_insert(k, hashed_secondaries, bitmap);
 393     }
 394 
 395     // Pack the hashed secondaries array by copying it into the
 396     // secondaries array, sans nulls, if modification is allowed.
 397     // Otherwise, validate the order.
 398     int i = 0;
 399     for (int slot = 0; slot < SECONDARY_SUPERS_TABLE_SIZE; slot++) {
 400       bool has_element = ((bitmap >> slot) & 1) != 0;
 401       assert(has_element == (hashed_secondaries->at(slot) != nullptr), "");
 402       if (has_element) {
 403         Klass* k = hashed_secondaries->at(slot);
 404         if (rewrite) {
 405           secondaries->at_put(i, k);
 406         } else if (secondaries->at(i) != k) {
 407           assert(false, "broken secondary supers hash table");
 408           return SECONDARY_SUPERS_BITMAP_FULL;
 409         }
 410         i++;
 411       }
 412     }
 413     assert(i == secondaries->length(), "mismatch");
 414     postcond((int)population_count(bitmap) == secondaries->length());
 415 
 416     return bitmap;
 417   }
 418 }
 419 
 420 void Klass::hash_insert(Klass* klass, GrowableArray<Klass*>* secondaries, uintx& bitmap) {
 421   assert(bitmap != SECONDARY_SUPERS_BITMAP_FULL, "");
 422 
 423   int dist = 0;
 424   for (int slot = klass->hash_slot(); true; slot = (slot + 1) & SECONDARY_SUPERS_TABLE_MASK) {
 425     Klass* existing = secondaries->at(slot);
 426     assert(((bitmap >> slot) & 1) == (existing != nullptr), "mismatch");
 427     if (existing == nullptr) { // no conflict
 428       secondaries->at_put(slot, klass);
 429       bitmap |= uintx(1) << slot;
 430       assert(bitmap != SECONDARY_SUPERS_BITMAP_FULL, "");
 431       return;
 432     } else {
 433       // Use Robin Hood hashing to minimize the worst case search.
 434       // Also, every permutation of the insertion sequence produces
 435       // the same final Robin Hood hash table, provided that a
 436       // consistent tie breaker is used.
 437       int existing_dist = (slot - existing->hash_slot()) & SECONDARY_SUPERS_TABLE_MASK;
 438       if (existing_dist < dist
 439           // This tie breaker ensures that the hash order is maintained.
 440           || ((existing_dist == dist)
 441               && (uintptr_t(existing) < uintptr_t(klass)))) {
 442         Klass* tmp = secondaries->at(slot);
 443         secondaries->at_put(slot, klass);
 444         klass = tmp;
 445         dist = existing_dist;
 446       }
 447       ++dist;
 448     }
 449   }
 450 }
 451 
 452 Array<Klass*>* Klass::pack_secondary_supers(ClassLoaderData* loader_data,
 453                                             GrowableArray<Klass*>* primaries,
 454                                             GrowableArray<Klass*>* secondaries,
 455                                             uintx& bitmap, TRAPS) {
 456   int new_length = primaries->length() + secondaries->length();
 457   Array<Klass*>* secondary_supers = MetadataFactory::new_array<Klass*>(loader_data, new_length, CHECK_NULL);
 458 
 459   // Combine the two arrays into a metadata object to pack the array.
 460   // The primaries are added in the reverse order, then the secondaries.
 461   int fill_p = primaries->length();
 462   for (int j = 0; j < fill_p; j++) {
 463     secondary_supers->at_put(j, primaries->pop());  // add primaries in reverse order.
 464   }
 465   for( int j = 0; j < secondaries->length(); j++ ) {
 466     secondary_supers->at_put(j+fill_p, secondaries->at(j));  // add secondaries on the end.
 467   }
 468 #ifdef ASSERT
 469   // We must not copy any null placeholders left over from bootstrap.
 470   for (int j = 0; j < secondary_supers->length(); j++) {
 471     assert(secondary_supers->at(j) != nullptr, "correct bootstrapping order");
 472   }
 473 #endif
 474 
 475   bitmap = hash_secondary_supers(secondary_supers, /*rewrite=*/true); // rewrites freshly allocated array
 476   return secondary_supers;
 477 }
 478 
 479 uintx Klass::compute_secondary_supers_bitmap(Array<Klass*>* secondary_supers) {
 480   return hash_secondary_supers(secondary_supers, /*rewrite=*/false); // no rewrites allowed
 481 }
 482 
 483 uint8_t Klass::compute_home_slot(Klass* k, uintx bitmap) {
 484   uint8_t hash = k->hash_slot();
 485   if (hash > 0) {
 486     return population_count(bitmap << (SECONDARY_SUPERS_TABLE_SIZE - hash));
 487   }
 488   return 0;
 489 }
 490 
 491 
 492 void Klass::initialize_supers(Klass* k, Array<InstanceKlass*>* transitive_interfaces, TRAPS) {
 493   if (k == nullptr) {
 494     set_super(nullptr);
 495     _primary_supers[0] = this;
 496     assert(super_depth() == 0, "Object must already be initialized properly");
 497   } else if (k != super() || k == vmClasses::Object_klass()) {
 498     assert(super() == nullptr || super() == vmClasses::Object_klass(),
 499            "initialize this only once to a non-trivial value");
 500     set_super(k);
 501     Klass* sup = k;
 502     int sup_depth = sup->super_depth();
 503     juint my_depth  = MIN2(sup_depth + 1, (int)primary_super_limit());
 504     if (!can_be_primary_super_slow())
 505       my_depth = primary_super_limit();
 506     for (juint i = 0; i < my_depth; i++) {
 507       _primary_supers[i] = sup->_primary_supers[i];
 508     }
 509     Klass* *super_check_cell;
 510     if (my_depth < primary_super_limit()) {
 511       _primary_supers[my_depth] = this;
 512       super_check_cell = &_primary_supers[my_depth];
 513     } else {
 514       // Overflow of the primary_supers array forces me to be secondary.
 515       super_check_cell = &_secondary_super_cache;
 516     }
 517     set_super_check_offset(u4((address)super_check_cell - (address) this));
 518 
 519 #ifdef ASSERT
 520     {
 521       juint j = super_depth();
 522       assert(j == my_depth, "computed accessor gets right answer");
 523       Klass* t = this;
 524       while (!t->can_be_primary_super()) {
 525         t = t->super();
 526         j = t->super_depth();
 527       }
 528       for (juint j1 = j+1; j1 < primary_super_limit(); j1++) {
 529         assert(primary_super_of_depth(j1) == nullptr, "super list padding");
 530       }
 531       while (t != nullptr) {
 532         assert(primary_super_of_depth(j) == t, "super list initialization");
 533         t = t->super();
 534         --j;
 535       }
 536       assert(j == (juint)-1, "correct depth count");
 537     }
 538 #endif
 539   }
 540 
 541   if (secondary_supers() == nullptr) {
 542 
 543     // Now compute the list of secondary supertypes.
 544     // Secondaries can occasionally be on the super chain,
 545     // if the inline "_primary_supers" array overflows.
 546     int extras = 0;
 547     Klass* p;
 548     for (p = super(); !(p == nullptr || p->can_be_primary_super()); p = p->super()) {
 549       ++extras;
 550     }
 551 
 552     ResourceMark rm(THREAD);  // need to reclaim GrowableArrays allocated below
 553 
 554     // Compute the "real" non-extra secondaries.
 555     GrowableArray<Klass*>* secondaries = compute_secondary_supers(extras, transitive_interfaces);
 556     if (secondaries == nullptr) {
 557       // secondary_supers set by compute_secondary_supers
 558       return;
 559     }
 560 
 561     GrowableArray<Klass*>* primaries = new GrowableArray<Klass*>(extras);
 562 
 563     for (p = super(); !(p == nullptr || p->can_be_primary_super()); p = p->super()) {
 564       int i;                    // Scan for overflow primaries being duplicates of 2nd'arys
 565 
 566       // This happens frequently for very deeply nested arrays: the
 567       // primary superclass chain overflows into the secondary.  The
 568       // secondary list contains the element_klass's secondaries with
 569       // an extra array dimension added.  If the element_klass's
 570       // secondary list already contains some primary overflows, they
 571       // (with the extra level of array-ness) will collide with the
 572       // normal primary superclass overflows.
 573       for( i = 0; i < secondaries->length(); i++ ) {
 574         if( secondaries->at(i) == p )
 575           break;
 576       }
 577       if( i < secondaries->length() )
 578         continue;               // It's a dup, don't put it in
 579       primaries->push(p);
 580     }
 581     // Combine the two arrays into a metadata object to pack the array.
 582     uintx bitmap = 0;
 583     Array<Klass*>* s2 = pack_secondary_supers(class_loader_data(), primaries, secondaries, bitmap, CHECK);
 584     set_secondary_supers(s2, bitmap);
 585   }
 586 }
 587 
 588 GrowableArray<Klass*>* Klass::compute_secondary_supers(int num_extra_slots,
 589                                                        Array<InstanceKlass*>* transitive_interfaces) {
 590   assert(num_extra_slots == 0, "override for complex klasses");
 591   assert(transitive_interfaces == nullptr, "sanity");
 592   set_secondary_supers(Universe::the_empty_klass_array(), Universe::the_empty_klass_bitmap());
 593   return nullptr;
 594 }
 595 
 596 // subklass links.  Used by the compiler (and vtable initialization)
 597 // May be cleaned concurrently, so must use the Compile_lock.
 598 Klass* Klass::subklass() const {
 599   // Need load_acquire on the _subklass, because it races with inserts that
 600   // publishes freshly initialized data.
 601   for (Klass* chain = AtomicAccess::load_acquire(&_subklass);
 602        chain != nullptr;
 603        // Do not need load_acquire on _next_sibling, because inserts never
 604        // create _next_sibling edges to dead data.
 605        chain = AtomicAccess::load(&chain->_next_sibling))
 606   {
 607     if (chain->is_loader_alive()) {
 608       return chain;
 609     }
 610   }
 611   return nullptr;
 612 }
 613 
 614 Klass* Klass::next_sibling(bool log) const {
 615   // Do not need load_acquire on _next_sibling, because inserts never
 616   // create _next_sibling edges to dead data.
 617   for (Klass* chain = AtomicAccess::load(&_next_sibling);
 618        chain != nullptr;
 619        chain = AtomicAccess::load(&chain->_next_sibling)) {
 620     // Only return alive klass, there may be stale klass
 621     // in this chain if cleaned concurrently.
 622     if (chain->is_loader_alive()) {
 623       return chain;
 624     } else if (log) {
 625       if (log_is_enabled(Trace, class, unload)) {
 626         ResourceMark rm;
 627         log_trace(class, unload)("unlinking class (sibling): %s", chain->external_name());
 628       }
 629     }
 630   }
 631   return nullptr;
 632 }
 633 
 634 void Klass::set_subklass(Klass* s) {
 635   assert(s != this, "sanity check");
 636   AtomicAccess::release_store(&_subklass, s);
 637 }
 638 
 639 void Klass::set_next_sibling(Klass* s) {
 640   assert(s != this, "sanity check");
 641   // Does not need release semantics. If used by cleanup, it will link to
 642   // already safely published data, and if used by inserts, will be published
 643   // safely using cmpxchg.
 644   AtomicAccess::store(&_next_sibling, s);
 645 }
 646 
 647 void Klass::append_to_sibling_list() {
 648   if (Universe::is_fully_initialized()) {
 649     assert_locked_or_safepoint(Compile_lock);
 650   }
 651   DEBUG_ONLY(verify();)
 652   // add ourselves to super' subklass list
 653   InstanceKlass* super = java_super();
 654   if (super == nullptr) return;     // special case: class Object
 655   assert((!super->is_interface()    // interfaces cannot be supers
 656           && (super->java_super() == nullptr || !is_interface())),
 657          "an interface can only be a subklass of Object");
 658 
 659   // Make sure there is no stale subklass head
 660   super->clean_subklass();
 661 
 662   for (;;) {
 663     Klass* prev_first_subklass = AtomicAccess::load_acquire(&_super->_subklass);
 664     if (prev_first_subklass != nullptr) {
 665       // set our sibling to be the super' previous first subklass
 666       assert(prev_first_subklass->is_loader_alive(), "May not attach not alive klasses");
 667       set_next_sibling(prev_first_subklass);
 668     }
 669     // Note that the prev_first_subklass is always alive, meaning no sibling_next links
 670     // are ever created to not alive klasses. This is an important invariant of the lock-free
 671     // cleaning protocol, that allows us to safely unlink dead klasses from the sibling list.
 672     if (AtomicAccess::cmpxchg(&super->_subklass, prev_first_subklass, this) == prev_first_subklass) {
 673       return;
 674     }
 675   }
 676   DEBUG_ONLY(verify();)
 677 }
 678 
 679 // The log parameter is for clean_weak_klass_links to report unlinked classes.
 680 Klass* Klass::clean_subklass(bool log) {
 681   for (;;) {
 682     // Need load_acquire, due to contending with concurrent inserts
 683     Klass* subklass = AtomicAccess::load_acquire(&_subklass);
 684     if (subklass == nullptr || subklass->is_loader_alive()) {
 685       return subklass;
 686     }
 687     if (log && log_is_enabled(Trace, class, unload)) {
 688       ResourceMark rm;
 689       log_trace(class, unload)("unlinking class (subclass): %s", subklass->external_name());
 690     }
 691     // Try to fix _subklass until it points at something not dead.
 692     AtomicAccess::cmpxchg(&_subklass, subklass, subklass->next_sibling(log));
 693   }
 694 }
 695 
 696 void Klass::clean_weak_klass_links(bool unloading_occurred, bool clean_alive_klasses) {
 697   if (!ClassUnloading || !unloading_occurred) {
 698     return;
 699   }
 700 
 701   Klass* root = vmClasses::Object_klass();
 702   Stack<Klass*, mtGC> stack;
 703 
 704   stack.push(root);
 705   while (!stack.is_empty()) {
 706     Klass* current = stack.pop();
 707 
 708     assert(current->is_loader_alive(), "just checking, this should be live");
 709 
 710     // Find and set the first alive subklass
 711     Klass* sub = current->clean_subklass(true);
 712     if (sub != nullptr) {
 713       stack.push(sub);
 714     }
 715 
 716     // Find and set the first alive sibling
 717     Klass* sibling = current->next_sibling(true);
 718     current->set_next_sibling(sibling);
 719     if (sibling != nullptr) {
 720       stack.push(sibling);
 721     }
 722 
 723     // Clean the implementors list and method data.
 724     if (clean_alive_klasses && current->is_instance_klass()) {
 725       InstanceKlass* ik = InstanceKlass::cast(current);
 726       clean_weak_instanceklass_links(ik);
 727     }
 728   }
 729 }
 730 
 731 void Klass::clean_weak_instanceklass_links(InstanceKlass* ik) {
 732   ik->clean_weak_instanceklass_links();
 733   // JVMTI RedefineClasses creates previous versions that are not in
 734   // the class hierarchy, so process them here.
 735   while ((ik = ik->previous_versions()) != nullptr) {
 736     ik->clean_weak_instanceklass_links();
 737   }
 738 }
 739 
 740 void Klass::metaspace_pointers_do(MetaspaceClosure* it) {
 741   if (log_is_enabled(Trace, aot)) {
 742     ResourceMark rm;
 743     log_trace(aot)("Iter(Klass): %p (%s)", this, external_name());
 744   }
 745 
 746   it->push(&_name);
 747   it->push(&_secondary_supers);
 748   for (int i = 0; i < _primary_super_limit; i++) {
 749     it->push(&_primary_supers[i]);
 750   }
 751   it->push(&_super);
 752   if (!CDSConfig::is_dumping_archive()) {
 753     // If dumping archive, these may point to excluded classes. There's no need
 754     // to follow these pointers anyway, as they will be set to null in
 755     // remove_unshareable_info().
 756     it->push((Klass**)&_subklass);
 757     it->push((Klass**)&_next_sibling);
 758     it->push(&_next_link);
 759   }
 760 
 761   vtableEntry* vt = start_of_vtable();
 762   for (int i=0; i<vtable_length(); i++) {
 763     it->push(vt[i].method_addr());
 764   }
 765 }
 766 
 767 #if INCLUDE_CDS
 768 void Klass::remove_unshareable_info() {
 769   assert(CDSConfig::is_dumping_archive(),
 770           "only called during CDS dump time");
 771   JFR_ONLY(REMOVE_ID(this);)
 772   if (log_is_enabled(Trace, aot, unshareable)) {
 773     ResourceMark rm;
 774     log_trace(aot, unshareable)("remove: %s", external_name());
 775   }
 776 
 777   // _secondary_super_cache may be updated by an is_subtype_of() call
 778   // while ArchiveBuilder is copying metaspace objects. Let's reset it to
 779   // null and let it be repopulated at runtime.
 780   set_secondary_super_cache(nullptr);
 781 
 782   set_subklass(nullptr);
 783   set_next_sibling(nullptr);
 784   set_next_link(nullptr);
 785 
 786   // Null out class_loader_data because we don't share that yet.
 787   set_class_loader_data(nullptr);
 788   set_in_aot_cache();
 789 
 790   if (CDSConfig::is_dumping_classic_static_archive()) {
 791     // "Classic" static archives are required to have deterministic contents.
 792     // The elements in _secondary_supers are addresses in the ArchiveBuilder
 793     // output buffer, so they should have deterministic values. If we rehash
 794     // _secondary_supers, its elements will appear in a deterministic order.
 795     //
 796     // Note that the bitmap is guaranteed to be deterministic, regardless of the
 797     // actual addresses of the elements in _secondary_supers. So rehashing shouldn't
 798     // change it.
 799     uintx bitmap = hash_secondary_supers(secondary_supers(), true);
 800     assert(bitmap == _secondary_supers_bitmap, "bitmap should not be changed due to rehashing");
 801   }
 802 }
 803 
 804 void Klass::remove_java_mirror() {
 805   assert(CDSConfig::is_dumping_archive(), "sanity");
 806   if (log_is_enabled(Trace, aot, unshareable)) {
 807     ResourceMark rm;
 808     log_trace(aot, unshareable)("remove java_mirror: %s", external_name());
 809   }
 810 
 811 #if INCLUDE_CDS_JAVA_HEAP
 812   _archived_mirror_index = -1;
 813   if (CDSConfig::is_dumping_heap()) {
 814     Klass* src_k = ArchiveBuilder::current()->get_source_addr(this);
 815     oop orig_mirror = src_k->java_mirror();
 816     if (orig_mirror == nullptr) {
 817       assert(CDSConfig::is_dumping_final_static_archive(), "sanity");
 818       if (is_instance_klass()) {
 819         assert(InstanceKlass::cast(this)->defined_by_other_loaders(), "sanity");
 820       } else {
 821         precond(is_objArray_klass());
 822         Klass *k = ObjArrayKlass::cast(this)->bottom_klass();
 823         precond(k->is_instance_klass());
 824         assert(InstanceKlass::cast(k)->defined_by_other_loaders(), "sanity");
 825       }
 826     } else {
 827       oop scratch_mirror = HeapShared::scratch_java_mirror(orig_mirror);
 828       if (scratch_mirror != nullptr) {
 829         _archived_mirror_index = HeapShared::append_root(scratch_mirror);
 830       }
 831     }
 832   }
 833 #endif
 834 
 835   // Just null out the mirror.  The class_loader_data() no longer exists.
 836   clear_java_mirror_handle();
 837 }
 838 
 839 void Klass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
 840   assert(is_klass(), "ensure C++ vtable is restored");
 841   assert(in_aot_cache(), "must be set");
 842   assert(secondary_supers()->length() >= (int)population_count(_secondary_supers_bitmap), "must be");
 843   if (log_is_enabled(Trace, aot, unshareable)) {
 844     ResourceMark rm(THREAD);
 845     oop class_loader = loader_data->class_loader();
 846     log_trace(aot, unshareable)("restore: %s with class loader: %s", external_name(),
 847       class_loader != nullptr ? class_loader->klass()->external_name() : "boot");
 848   }
 849 
 850   // If an exception happened during CDS restore, some of these fields may already be
 851   // set.  We leave the class on the CLD list, even if incomplete so that we don't
 852   // modify the CLD list outside a safepoint.
 853   if (class_loader_data() == nullptr) {
 854     set_class_loader_data(loader_data);
 855   }
 856 
 857   // Add to class loader list first before creating the mirror
 858   // (same order as class file parsing)
 859   loader_data->add_class(this);
 860 
 861   JFR_ONLY(Jfr::on_restoration(this, THREAD);)
 862 
 863   Handle loader(THREAD, loader_data->class_loader());
 864   ModuleEntry* module_entry = nullptr;
 865   Klass* k = this;
 866   if (k->is_objArray_klass()) {
 867     k = ObjArrayKlass::cast(k)->bottom_klass();
 868   }
 869   // Obtain klass' module.
 870   if (k->is_instance_klass()) {
 871     InstanceKlass* ik = (InstanceKlass*) k;
 872     module_entry = ik->module();
 873   } else {
 874     module_entry = ModuleEntryTable::javabase_moduleEntry();
 875   }
 876   // Obtain java.lang.Module, if available
 877   Handle module_handle(THREAD, ((module_entry != nullptr) ? module_entry->module_oop() : (oop)nullptr));
 878 
 879   if (this->has_archived_mirror_index()) {
 880     ResourceMark rm(THREAD);
 881     log_debug(aot, mirror)("%s has raw archived mirror", external_name());
 882     if (HeapShared::is_archived_heap_in_use()) {
 883       bool present = java_lang_Class::restore_archived_mirror(this, loader, module_handle,
 884                                                               protection_domain,
 885                                                               CHECK);
 886       if (present) {
 887         return;
 888       }
 889     }
 890 
 891     // No archived mirror data
 892     log_debug(aot, mirror)("No archived mirror data for %s", external_name());
 893     clear_java_mirror_handle();
 894     this->clear_archived_mirror_index();
 895   }
 896 
 897   // Only recreate it if not present.  A previous attempt to restore may have
 898   // gotten an OOM later but keep the mirror if it was created.
 899   if (java_mirror() == nullptr) {
 900     ResourceMark rm(THREAD);
 901     log_trace(aot, mirror)("Recreate mirror for %s", external_name());
 902     java_lang_Class::create_mirror(this, loader, module_handle, protection_domain, Handle(), CHECK);
 903   }
 904 }
 905 #endif // INCLUDE_CDS
 906 
 907 #if INCLUDE_CDS_JAVA_HEAP
 908 oop Klass::archived_java_mirror() {
 909   assert(has_archived_mirror_index(), "must have archived mirror");
 910   return HeapShared::get_root(_archived_mirror_index);
 911 }
 912 
 913 void Klass::clear_archived_mirror_index() {
 914   if (_archived_mirror_index >= 0) {
 915     HeapShared::clear_root(_archived_mirror_index);
 916   }
 917   _archived_mirror_index = -1;
 918 }
 919 #endif // INCLUDE_CDS_JAVA_HEAP
 920 
 921 void Klass::check_array_allocation_length(int length, int max_length, TRAPS) {
 922   if (length > max_length) {
 923     if (!THREAD->is_in_internal_oome_mark()) {
 924       report_java_out_of_memory("Requested array size exceeds VM limit");
 925       JvmtiExport::post_array_size_exhausted();
 926       THROW_OOP(Universe::out_of_memory_error_array_size());
 927     } else {
 928       THROW_OOP(Universe::out_of_memory_error_java_heap_without_backtrace());
 929     }
 930   } else if (length < 0) {
 931     THROW_MSG(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", length));
 932   }
 933 }
 934 
 935 // Replace the last '+' char with '/'.
 936 static char* convert_hidden_name_to_java(Symbol* name) {
 937   size_t name_len = name->utf8_length();
 938   char* result = NEW_RESOURCE_ARRAY(char, name_len + 1);
 939   name->as_klass_external_name(result, (int)name_len + 1);
 940   for (int index = (int)name_len; index > 0; index--) {
 941     if (result[index] == '+') {
 942       result[index] = JVM_SIGNATURE_SLASH;
 943       break;
 944     }
 945   }
 946   return result;
 947 }
 948 
 949 // In product mode, this function doesn't have virtual function calls so
 950 // there might be some performance advantage to handling InstanceKlass here.
 951 const char* Klass::external_name() const {
 952   if (is_instance_klass()) {
 953     const InstanceKlass* ik = static_cast<const InstanceKlass*>(this);
 954     if (ik->is_hidden()) {
 955       char* result = convert_hidden_name_to_java(name());
 956       return result;
 957     }
 958   } else if (is_objArray_klass() && ObjArrayKlass::cast(this)->bottom_klass()->is_hidden()) {
 959     char* result = convert_hidden_name_to_java(name());
 960     return result;
 961   }
 962   if (name() == nullptr)  return "<unknown>";
 963   return name()->as_klass_external_name();
 964 }
 965 
 966 const char* Klass::signature_name() const {
 967   if (name() == nullptr)  return "<unknown>";
 968   if (is_objArray_klass() && ObjArrayKlass::cast(this)->bottom_klass()->is_hidden()) {
 969     size_t name_len = name()->utf8_length();
 970     char* result = NEW_RESOURCE_ARRAY(char, name_len + 1);
 971     name()->as_C_string(result, (int)name_len + 1);
 972     for (int index = (int)name_len; index > 0; index--) {
 973       if (result[index] == '+') {
 974         result[index] = JVM_SIGNATURE_DOT;
 975         break;
 976       }
 977     }
 978     return result;
 979   }
 980   return name()->as_C_string();
 981 }
 982 
 983 const char* Klass::external_kind() const {
 984   if (is_interface()) return "interface";
 985   if (is_abstract()) return "abstract class";
 986   return "class";
 987 }
 988 
 989 // Unless overridden, jvmti_class_status has no flags set.
 990 jint Klass::jvmti_class_status() const {
 991   return 0;
 992 }
 993 
 994 
 995 // Printing
 996 
 997 void Klass::print_on(outputStream* st) const {
 998   ResourceMark rm;
 999   // print title
1000   st->print("%s", internal_name());
1001   print_address_on(st);
1002   st->cr();
1003 }
1004 
1005 #define BULLET  " - "
1006 
1007 // Caller needs ResourceMark
1008 void Klass::oop_print_on(oop obj, outputStream* st) {
1009   // print title
1010   st->print_cr("%s ", internal_name());
1011   obj->print_address_on(st);
1012 
1013   if (WizardMode) {
1014      // print header
1015      obj->mark().print_on(st);
1016      st->cr();
1017      st->print(BULLET"prototype_header: " INTPTR_FORMAT, _prototype_header.value());
1018      st->cr();
1019   }
1020 
1021   // print class
1022   st->print(BULLET"klass: ");
1023   obj->klass()->print_value_on(st);
1024   st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
1025   st->cr();
1026 }
1027 
1028 void Klass::oop_print_value_on(oop obj, outputStream* st) {
1029   // print title
1030   ResourceMark rm;              // Cannot print in debug mode without this
1031   st->print("%s", internal_name());
1032   obj->print_address_on(st);
1033 }
1034 
1035 // Verification
1036 
1037 void Klass::verify_on(outputStream* st) {
1038 
1039   // This can be expensive, but it is worth checking that this klass is actually
1040   // in the CLD graph but not in production.
1041 #ifdef ASSERT
1042   if (UseCompressedClassPointers) {
1043     // Stricter checks for both correct alignment and placement
1044     CompressedKlassPointers::check_encodable(this);
1045   } else {
1046     assert(Metaspace::contains((address)this), "Should be");
1047   }
1048 #endif // ASSERT
1049 
1050   guarantee(this->is_klass(),"should be klass");
1051 
1052   if (super() != nullptr) {
1053     guarantee(super()->is_klass(), "should be klass");
1054   }
1055   if (secondary_super_cache() != nullptr) {
1056     Klass* ko = secondary_super_cache();
1057     guarantee(ko->is_klass(), "should be klass");
1058   }
1059   for ( uint i = 0; i < primary_super_limit(); i++ ) {
1060     Klass* ko = _primary_supers[i];
1061     if (ko != nullptr) {
1062       guarantee(ko->is_klass(), "should be klass");
1063     }
1064   }
1065 
1066   if (java_mirror_no_keepalive() != nullptr) {
1067     guarantee(java_lang_Class::is_instance(java_mirror_no_keepalive()), "should be instance");
1068   }
1069 }
1070 
1071 void Klass::oop_verify_on(oop obj, outputStream* st) {
1072   guarantee(oopDesc::is_oop(obj),  "should be oop");
1073   guarantee(obj->klass()->is_klass(), "klass field is not a klass");
1074 }
1075 
1076 #ifdef ASSERT
1077 void Klass::validate_array_description(const ArrayDescription& ad) {
1078   if (is_identity_class() || is_array_klass() || is_interface() ||
1079       (is_instance_klass() && InstanceKlass::cast(this)->access_flags().is_abstract())) {
1080     assert(ad._layout_kind == LayoutKind::REFERENCE, "Cannot support flattening");
1081     assert(ad._kind == KlassKind::RefArrayKlassKind, "Must be a reference array");
1082   } else {
1083     assert(is_inline_klass(), "Must be");
1084     InlineKlass* ik = InlineKlass::cast(this);
1085     switch(ad._layout_kind) {
1086       case LayoutKind::BUFFERED:
1087         fatal("Invalid layout for an array");
1088         break;
1089       case LayoutKind::NULL_FREE_ATOMIC_FLAT:
1090         assert(ik->has_null_free_atomic_layout(), "Sanity check");
1091         break;
1092       case LayoutKind::NULL_FREE_NON_ATOMIC_FLAT:
1093         assert(ik->has_null_free_non_atomic_layout(), "Sanity check");
1094         break;
1095       case LayoutKind::NULLABLE_ATOMIC_FLAT:
1096         assert(ik->has_nullable_atomic_layout(), "Sanity check");
1097         break;
1098       case LayoutKind::NULLABLE_NON_ATOMIC_FLAT:
1099         assert(ik->has_nullable_non_atomic_layout(), "Sanity check)");
1100         break;
1101       case LayoutKind::REFERENCE:
1102         break;
1103       default:
1104         ShouldNotReachHere();
1105     }
1106   }
1107 }
1108 #endif // ASSERT
1109 
1110 // Note: this function is called with an address that may or may not be a Klass.
1111 // The point is not to assert it is but to check if it could be.
1112 bool Klass::is_valid(Klass* k) {
1113   if (!is_aligned(k, sizeof(MetaWord))) return false;
1114   if ((size_t)k < os::min_page_size()) return false;
1115 
1116   if (!os::is_readable_range(k, k + 1)) return false;
1117   if (!Metaspace::contains(k)) return false;
1118 
1119   if (!Symbol::is_valid(k->name())) return false;
1120   return ClassLoaderDataGraph::is_valid(k->class_loader_data());
1121 }
1122 
1123 Method* Klass::method_at_vtable(int index)  {
1124 #ifndef PRODUCT
1125   assert(index >= 0, "valid vtable index");
1126   if (DebugVtables) {
1127     verify_vtable_index(index);
1128   }
1129 #endif
1130   return start_of_vtable()[index].method();
1131 }
1132 
1133 
1134 #ifndef PRODUCT
1135 
1136 bool Klass::verify_vtable_index(int i) {
1137   int limit = vtable_length()/vtableEntry::size();
1138   assert(i >= 0 && i < limit, "index %d out of bounds %d", i, limit);
1139   return true;
1140 }
1141 
1142 #endif // PRODUCT
1143 
1144 // Caller needs ResourceMark
1145 // joint_in_module_of_loader provides an optimization if 2 classes are in
1146 // the same module to succinctly print out relevant information about their
1147 // module name and class loader's name_and_id for error messages.
1148 // Format:
1149 //   <fully-qualified-external-class-name1> and <fully-qualified-external-class-name2>
1150 //                      are in module <module-name>[@<version>]
1151 //                      of loader <loader-name_and_id>[, parent loader <parent-loader-name_and_id>]
1152 const char* Klass::joint_in_module_of_loader(const Klass* class2, bool include_parent_loader) const {
1153   assert(module() == class2->module(), "classes do not have the same module");
1154   const char* class1_name = external_name();
1155   size_t len = strlen(class1_name) + 1;
1156 
1157   const char* class2_description = class2->class_in_module_of_loader(true, include_parent_loader);
1158   len += strlen(class2_description);
1159 
1160   len += strlen(" and ");
1161 
1162   char* joint_description = NEW_RESOURCE_ARRAY_RETURN_NULL(char, len);
1163 
1164   // Just return the FQN if error when allocating string
1165   if (joint_description == nullptr) {
1166     return class1_name;
1167   }
1168 
1169   jio_snprintf(joint_description, len, "%s and %s",
1170                class1_name,
1171                class2_description);
1172 
1173   return joint_description;
1174 }
1175 
1176 // Caller needs ResourceMark
1177 // class_in_module_of_loader provides a standard way to include
1178 // relevant information about a class, such as its module name as
1179 // well as its class loader's name_and_id, in error messages and logging.
1180 // Format:
1181 //   <fully-qualified-external-class-name> is in module <module-name>[@<version>]
1182 //                                         of loader <loader-name_and_id>[, parent loader <parent-loader-name_and_id>]
1183 const char* Klass::class_in_module_of_loader(bool use_are, bool include_parent_loader) const {
1184   // 1. fully qualified external name of class
1185   const char* klass_name = external_name();
1186   size_t len = strlen(klass_name) + 1;
1187 
1188   // 2. module name + @version
1189   const char* module_name = "";
1190   const char* version = "";
1191   bool has_version = false;
1192   bool module_is_named = false;
1193   const char* module_name_phrase = "";
1194   const Klass* bottom_klass = is_objArray_klass() ?
1195                                 ObjArrayKlass::cast(this)->bottom_klass() : this;
1196   if (bottom_klass->is_instance_klass()) {
1197     ModuleEntry* module = InstanceKlass::cast(bottom_klass)->module();
1198     if (module->is_named()) {
1199       module_is_named = true;
1200       module_name_phrase = "module ";
1201       module_name = module->name()->as_C_string();
1202       len += strlen(module_name);
1203       // Use version if exists and is not a jdk module
1204       if (module->should_show_version()) {
1205         has_version = true;
1206         version = module->version()->as_C_string();
1207         // Include stlen(version) + 1 for the "@"
1208         len += strlen(version) + 1;
1209       }
1210     } else {
1211       module_name = UNNAMED_MODULE;
1212       len += UNNAMED_MODULE_LEN;
1213     }
1214   } else {
1215     // klass is an array of primitives, module is java.base
1216     module_is_named = true;
1217     module_name_phrase = "module ";
1218     module_name = JAVA_BASE_NAME;
1219     len += JAVA_BASE_NAME_LEN;
1220   }
1221 
1222   // 3. class loader's name_and_id
1223   ClassLoaderData* cld = class_loader_data();
1224   assert(cld != nullptr, "class_loader_data should not be null");
1225   const char* loader_name_and_id = cld->loader_name_and_id();
1226   len += strlen(loader_name_and_id);
1227 
1228   // 4. include parent loader information
1229   const char* parent_loader_phrase = "";
1230   const char* parent_loader_name_and_id = "";
1231   if (include_parent_loader &&
1232       !cld->is_builtin_class_loader_data()) {
1233     oop parent_loader = java_lang_ClassLoader::parent(class_loader());
1234     ClassLoaderData *parent_cld = ClassLoaderData::class_loader_data_or_null(parent_loader);
1235     // The parent loader's ClassLoaderData could be null if it is
1236     // a delegating class loader that has never defined a class.
1237     // In this case the loader's name must be obtained via the parent loader's oop.
1238     if (parent_cld == nullptr) {
1239       oop cl_name_and_id = java_lang_ClassLoader::nameAndId(parent_loader);
1240       if (cl_name_and_id != nullptr) {
1241         parent_loader_name_and_id = java_lang_String::as_utf8_string(cl_name_and_id);
1242       }
1243     } else {
1244       parent_loader_name_and_id = parent_cld->loader_name_and_id();
1245     }
1246     parent_loader_phrase = ", parent loader ";
1247     len += strlen(parent_loader_phrase) + strlen(parent_loader_name_and_id);
1248   }
1249 
1250   // Start to construct final full class description string
1251   len += ((use_are) ? strlen(" are in ") : strlen(" is in "));
1252   len += strlen(module_name_phrase) + strlen(" of loader ");
1253 
1254   char* class_description = NEW_RESOURCE_ARRAY_RETURN_NULL(char, len);
1255 
1256   // Just return the FQN if error when allocating string
1257   if (class_description == nullptr) {
1258     return klass_name;
1259   }
1260 
1261   jio_snprintf(class_description, len, "%s %s in %s%s%s%s of loader %s%s%s",
1262                klass_name,
1263                (use_are) ? "are" : "is",
1264                module_name_phrase,
1265                module_name,
1266                (has_version) ? "@" : "",
1267                (has_version) ? version : "",
1268                loader_name_and_id,
1269                parent_loader_phrase,
1270                parent_loader_name_and_id);
1271 
1272   return class_description;
1273 }
1274 
1275 class LookupStats : StackObj {
1276  private:
1277   uint _no_of_samples;
1278   uint _worst;
1279   uint _worst_count;
1280   uint _average;
1281   uint _best;
1282   uint _best_count;
1283  public:
1284   LookupStats() : _no_of_samples(0), _worst(0), _worst_count(0), _average(0), _best(INT_MAX), _best_count(0) {}
1285 
1286   ~LookupStats() {
1287     assert(_best <= _worst || _no_of_samples == 0, "sanity");
1288   }
1289 
1290   void sample(uint value) {
1291     ++_no_of_samples;
1292     _average += value;
1293 
1294     if (_worst < value) {
1295       _worst = value;
1296       _worst_count = 1;
1297     } else if (_worst == value) {
1298       ++_worst_count;
1299     }
1300 
1301     if (_best > value) {
1302       _best = value;
1303       _best_count = 1;
1304     } else if (_best == value) {
1305       ++_best_count;
1306     }
1307   }
1308 
1309   void print_on(outputStream* st) const {
1310     st->print("best: %2d (%4.1f%%)", _best, (100.0 * _best_count) / _no_of_samples);
1311     if (_best_count < _no_of_samples) {
1312       st->print("; average: %4.1f; worst: %2d (%4.1f%%)",
1313                 (1.0 * _average) / _no_of_samples,
1314                 _worst, (100.0 * _worst_count) / _no_of_samples);
1315     }
1316   }
1317 };
1318 
1319 static void print_positive_lookup_stats(Array<Klass*>* secondary_supers, uintx bitmap, outputStream* st) {
1320   int num_of_supers = secondary_supers->length();
1321 
1322   LookupStats s;
1323   for (int i = 0; i < num_of_supers; i++) {
1324     Klass* secondary_super = secondary_supers->at(i);
1325     int home_slot = Klass::compute_home_slot(secondary_super, bitmap);
1326     uint score = 1 + ((i - home_slot) & Klass::SECONDARY_SUPERS_TABLE_MASK);
1327     s.sample(score);
1328   }
1329   st->print("positive_lookup: "); s.print_on(st);
1330 }
1331 
1332 static uint compute_distance_to_nearest_zero(int slot, uintx bitmap) {
1333   assert(~bitmap != 0, "no zeroes");
1334   uintx start = rotate_right(bitmap, slot);
1335   return count_trailing_zeros(~start);
1336 }
1337 
1338 static void print_negative_lookup_stats(uintx bitmap, outputStream* st) {
1339   LookupStats s;
1340   for (int slot = 0; slot < Klass::SECONDARY_SUPERS_TABLE_SIZE; slot++) {
1341     uint score = compute_distance_to_nearest_zero(slot, bitmap);
1342     s.sample(score);
1343   }
1344   st->print("negative_lookup: "); s.print_on(st);
1345 }
1346 
1347 void Klass::print_secondary_supers_on(outputStream* st) const {
1348   if (secondary_supers() != nullptr) {
1349     st->print("  - "); st->print("%d elements;", _secondary_supers->length());
1350     st->print_cr(" bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap);
1351     if (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_EMPTY &&
1352         _secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL) {
1353       st->print("  - "); print_positive_lookup_stats(secondary_supers(),
1354                                                      _secondary_supers_bitmap, st); st->cr();
1355       st->print("  - "); print_negative_lookup_stats(_secondary_supers_bitmap, st); st->cr();
1356     }
1357   } else {
1358     st->print("null");
1359   }
1360 }
1361 
1362 void Klass::on_secondary_supers_verification_failure(Klass* super, Klass* sub, bool linear_result, bool table_result, const char* msg) {
1363   ResourceMark rm;
1364   super->print();
1365   sub->print();
1366   fatal("%s: %s implements %s: linear_search: %d; table_lookup: %d",
1367         msg, sub->external_name(), super->external_name(), linear_result, table_result);
1368 }