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