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