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 #if INCLUDE_JFR
  61 #include "jfr/jfr.hpp"
  62 #endif
  63 
  64 void Klass::set_java_mirror(Handle m) {
  65   assert(!m.is_null(), "New mirror should never be null.");
  66   assert(_java_mirror.is_empty(), "should only be used to initialize mirror");
  67   _java_mirror = class_loader_data()->add_handle(m);
  68 }
  69 
  70 bool Klass::is_cloneable() const {
  71   return _misc_flags.is_cloneable_fast() ||
  72          is_subtype_of(vmClasses::Cloneable_klass());
  73 }
  74 
  75 uint8_t Klass::compute_hash_slot(Symbol* n) {
  76   uint hash_code;
  77   // Special cases for the two superclasses of all Array instances.
  78   // Code elsewhere assumes, for all instances of ArrayKlass, that
  79   // these two interfaces will be in this order.
  80 
  81   // We ensure there are some empty slots in the hash table between
  82   // these two very common interfaces because if they were adjacent
  83   // (e.g. Slots 0 and 1), then any other class which hashed to 0 or 1
  84   // would result in a probe length of 3.
  85   if (n == vmSymbols::java_lang_Cloneable()) {
  86     hash_code = 0;
  87   } else if (n == vmSymbols::java_io_Serializable()) {
  88     hash_code = SECONDARY_SUPERS_TABLE_SIZE / 2;
  89   } else {
  90     auto s = (const jbyte*) n->bytes();
  91     hash_code = java_lang_String::hash_code(s, n->utf8_length());
  92     // We use String::hash_code here (rather than e.g.
  93     // Symbol::identity_hash()) in order to have a hash code that
  94     // does not change from run to run. We want that because the
  95     // hash value for a secondary superclass appears in generated
  96     // code as a constant.
  97 
  98     // This constant is magic: see Knuth, "Fibonacci Hashing".
  99     constexpr uint multiplier
 100       = 2654435769; // (uint)(((u8)1 << 32) / ((1 + sqrt(5)) / 2 ))
 101     constexpr uint hash_shift = sizeof(hash_code) * 8 - 6;
 102     // The leading bits of the least significant half of the product.
 103     hash_code = (hash_code * multiplier) >> hash_shift;
 104 
 105     if (StressSecondarySupers) {
 106       // Generate many hash collisions in order to stress-test the
 107       // linear search fallback.
 108       hash_code = hash_code % 3;
 109       hash_code = hash_code * (SECONDARY_SUPERS_TABLE_SIZE / 3);
 110     }
 111   }
 112 
 113   return (hash_code & SECONDARY_SUPERS_TABLE_MASK);
 114 }
 115 
 116 void Klass::set_name(Symbol* n) {
 117   _name = n;
 118 
 119   if (_name != nullptr) {
 120     _name->increment_refcount();
 121   }
 122 
 123   {
 124     elapsedTimer selftime;
 125     selftime.start();
 126 
 127     _hash_slot = compute_hash_slot(n);
 128     assert(_hash_slot < SECONDARY_SUPERS_TABLE_SIZE, "required");
 129 
 130     selftime.stop();
 131     if (UsePerfData) {
 132       ClassLoader::perf_secondary_hash_time()->inc(selftime.ticks());
 133     }
 134   }
 135 
 136   if (CDSConfig::is_dumping_archive() && is_instance_klass()) {
 137     SystemDictionaryShared::init_dumptime_info(InstanceKlass::cast(this));
 138   }
 139 }
 140 
 141 bool Klass::is_subclass_of(const Klass* k) const {
 142   // Run up the super chain and check
 143   if (this == k) return true;
 144 
 145   Klass* t = const_cast<Klass*>(this)->super();
 146 
 147   while (t != nullptr) {
 148     if (t == k) return true;
 149     t = t->super();
 150   }
 151   return false;
 152 }
 153 
 154 void Klass::release_C_heap_structures(bool release_constant_pool) {
 155   if (_name != nullptr) _name->decrement_refcount();
 156 }
 157 
 158 bool Klass::linear_search_secondary_supers(const Klass* k) const {
 159   // Scan the array-of-objects for a match
 160   // FIXME: We could do something smarter here, maybe a vectorized
 161   // comparison or a binary search, but is that worth any added
 162   // complexity?
 163   int cnt = secondary_supers()->length();
 164   for (int i = 0; i < cnt; i++) {
 165     if (secondary_supers()->at(i) == k) {
 166       return true;
 167     }
 168   }
 169   return false;
 170 }
 171 
 172 // Given a secondary superklass k, an initial array index, and an
 173 // occupancy bitmap rotated such that Bit 1 is the next bit to test,
 174 // search for k.
 175 bool Klass::fallback_search_secondary_supers(const Klass* k, int index, uintx rotated_bitmap) const {
 176   // Once the occupancy bitmap is almost full, it's faster to use a
 177   // linear search.
 178   if (secondary_supers()->length() > SECONDARY_SUPERS_TABLE_SIZE - 2) {
 179     return linear_search_secondary_supers(k);
 180   }
 181 
 182   // This is conventional linear probing, but instead of terminating
 183   // when a null entry is found in the table, we maintain a bitmap
 184   // in which a 0 indicates missing entries.
 185 
 186   precond((int)population_count(rotated_bitmap) == secondary_supers()->length());
 187 
 188   // The check for secondary_supers()->length() <= SECONDARY_SUPERS_TABLE_SIZE - 2
 189   // at the start of this function guarantees there are 0s in the
 190   // bitmap, so this loop eventually terminates.
 191   while ((rotated_bitmap & 2) != 0) {
 192     if (++index == secondary_supers()->length()) {
 193       index = 0;
 194     }
 195     if (secondary_supers()->at(index) == k) {
 196       return true;
 197     }
 198     rotated_bitmap = rotate_right(rotated_bitmap, 1);
 199   }
 200   return false;
 201 }
 202 
 203 // Return self, except for abstract classes with exactly 1
 204 // implementor.  Then return the 1 concrete implementation.
 205 Klass *Klass::up_cast_abstract() {
 206   Klass *r = this;
 207   while( r->is_abstract() ) {   // Receiver is abstract?
 208     Klass *s = r->subklass();   // Check for exactly 1 subklass
 209     if (s == nullptr || s->next_sibling() != nullptr) // Oops; wrong count; give up
 210       return this;              // Return 'this' as a no-progress flag
 211     r = s;                    // Loop till find concrete class
 212   }
 213   return r;                   // Return the 1 concrete class
 214 }
 215 
 216 // Find LCA in class hierarchy
 217 Klass *Klass::LCA( Klass *k2 ) {
 218   Klass *k1 = this;
 219   while( 1 ) {
 220     if( k1->is_subtype_of(k2) ) return k2;
 221     if( k2->is_subtype_of(k1) ) return k1;
 222     k1 = k1->super();
 223     k2 = k2->super();
 224   }
 225 }
 226 
 227 
 228 void Klass::check_valid_for_instantiation(bool throwError, TRAPS) {
 229   ResourceMark rm(THREAD);
 230   THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
 231             : vmSymbols::java_lang_InstantiationException(), external_name());
 232 }
 233 
 234 
 235 void Klass::copy_array(arrayOop s, int src_pos, arrayOop d, int dst_pos, int length, TRAPS) {
 236   ResourceMark rm(THREAD);
 237   assert(s != nullptr, "Throw NPE!");
 238   THROW_MSG(vmSymbols::java_lang_ArrayStoreException(),
 239             err_msg("arraycopy: source type %s is not an array", s->klass()->external_name()));
 240 }
 241 
 242 
 243 void Klass::initialize(TRAPS) {
 244   ShouldNotReachHere();
 245 }
 246 
 247 void Klass::initialize_preemptable(TRAPS) {
 248   ShouldNotReachHere();
 249 }
 250 
 251 Klass* Klass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
 252 #ifdef ASSERT
 253   tty->print_cr("Error: find_field called on a klass oop."
 254                 " Likely error: reflection method does not correctly"
 255                 " wrap return value in a mirror object.");
 256 #endif
 257   ShouldNotReachHere();
 258   return nullptr;
 259 }
 260 
 261 Method* Klass::uncached_lookup_method(const Symbol* name, const Symbol* signature,
 262                                       OverpassLookupMode overpass_mode,
 263                                       PrivateLookupMode private_mode) const {
 264 #ifdef ASSERT
 265   tty->print_cr("Error: uncached_lookup_method called on a klass oop."
 266                 " Likely error: reflection method does not correctly"
 267                 " wrap return value in a mirror object.");
 268 #endif
 269   ShouldNotReachHere();
 270   return nullptr;
 271 }
 272 
 273 static markWord make_prototype(const Klass* kls) {
 274   markWord prototype = markWord::prototype();
 275 #ifdef _LP64
 276   if (UseCompactObjectHeaders) {
 277     // With compact object headers, the narrow Klass ID is part of the mark word.
 278     // We therefore seed the mark word with the narrow Klass ID.
 279     precond(CompressedKlassPointers::is_encodable(kls));
 280     const narrowKlass nk = CompressedKlassPointers::encode(const_cast<Klass*>(kls));
 281     prototype = prototype.set_narrow_klass(nk);
 282   }
 283 #endif
 284   return prototype;
 285 }
 286 
 287 void* Klass::operator new(size_t size, ClassLoaderData* loader_data, size_t word_size, TRAPS) throw() {
 288   return Metaspace::allocate(loader_data, word_size, MetaspaceObj::ClassType, THREAD);
 289 }
 290 
 291 Klass::Klass() : _kind(UnknownKlassKind) {
 292   assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for cds");
 293 }
 294 
 295 // "Normal" instantiation is preceded by a MetaspaceObj allocation
 296 // which zeros out memory - calloc equivalent.
 297 // The constructor is also used from CppVtableCloner,
 298 // which doesn't zero out the memory before calling the constructor.
 299 Klass::Klass(KlassKind kind) : _kind(kind),
 300                                _prototype_header(make_prototype(this)),
 301                                _shared_class_path_index(-1) {

 302   CDS_ONLY(_aot_class_flags = 0;)
 303   CDS_JAVA_HEAP_ONLY(_archived_mirror_index = -1;)
 304   _primary_supers[0] = this;
 305   set_super_check_offset(in_bytes(primary_supers_offset()));
 306 }
 307 
 308 jint Klass::array_layout_helper(BasicType etype) {
 309   assert(etype >= T_BOOLEAN && etype <= T_OBJECT, "valid etype");
 310   // Note that T_ARRAY is not allowed here.
 311   int  hsize = arrayOopDesc::base_offset_in_bytes(etype);
 312   int  esize = type2aelembytes(etype);
 313   bool isobj = (etype == T_OBJECT);
 314   int  tag   =  isobj ? _lh_array_tag_obj_value : _lh_array_tag_type_value;
 315   int lh = array_layout_helper(tag, hsize, etype, exact_log2(esize));
 316 
 317   assert(lh < (int)_lh_neutral_value, "must look like an array layout");
 318   assert(layout_helper_is_array(lh), "correct kind");
 319   assert(layout_helper_is_objArray(lh) == isobj, "correct kind");
 320   assert(layout_helper_is_typeArray(lh) == !isobj, "correct kind");
 321   assert(layout_helper_header_size(lh) == hsize, "correct decode");
 322   assert(layout_helper_element_type(lh) == etype, "correct decode");
 323   assert(1 << layout_helper_log2_element_size(lh) == esize, "correct decode");
 324 
 325   return lh;
 326 }
 327 
 328 int Klass::modifier_flags() const {
 329   int mods = java_lang_Class::modifiers(java_mirror());
 330   assert(mods == compute_modifier_flags(), "should be same");
 331   return mods;
 332 }
 333 
 334 bool Klass::can_be_primary_super_slow() const {
 335   if (super() == nullptr)
 336     return true;
 337   else if (super()->super_depth() >= primary_super_limit()-1)
 338     return false;
 339   else
 340     return true;
 341 }
 342 
 343 void Klass::set_secondary_supers(Array<Klass*>* secondaries, uintx bitmap) {
 344 #ifdef ASSERT
 345   if (secondaries != nullptr) {
 346     uintx real_bitmap = compute_secondary_supers_bitmap(secondaries);
 347     assert(bitmap == real_bitmap, "must be");
 348     assert(secondaries->length() >= (int)population_count(bitmap), "must be");
 349   }
 350 #endif
 351   _secondary_supers_bitmap = bitmap;
 352   _secondary_supers = secondaries;
 353 
 354   if (secondaries != nullptr) {
 355     LogMessage(class, load) msg;
 356     NonInterleavingLogStream log {LogLevel::Debug, msg};
 357     if (log.is_enabled()) {
 358       ResourceMark rm;
 359       log.print_cr("set_secondary_supers: hash_slot: %d; klass: %s", hash_slot(), external_name());
 360       print_secondary_supers_on(&log);
 361     }
 362   }
 363 }
 364 
 365 // Hashed secondary superclasses
 366 //
 367 // We use a compressed 64-entry hash table with linear probing. We
 368 // start by creating a hash table in the usual way, followed by a pass
 369 // that removes all the null entries. To indicate which entries would
 370 // have been null we use a bitmap that contains a 1 in each position
 371 // where an entry is present, 0 otherwise. This bitmap also serves as
 372 // a kind of Bloom filter, which in many cases allows us quickly to
 373 // eliminate the possibility that something is a member of a set of
 374 // secondaries.
 375 uintx Klass::hash_secondary_supers(Array<Klass*>* secondaries, bool rewrite) {
 376   const int length = secondaries->length();
 377 
 378   if (length == 0) {
 379     return SECONDARY_SUPERS_BITMAP_EMPTY;
 380   }
 381 
 382   if (length == 1) {
 383     int hash_slot = secondaries->at(0)->hash_slot();
 384     return uintx(1) << hash_slot;
 385   }
 386 
 387   // Invariant: _secondary_supers.length >= population_count(_secondary_supers_bitmap)
 388 
 389   // Don't attempt to hash a table that's completely full, because in
 390   // the case of an absent interface linear probing would not
 391   // terminate.
 392   if (length >= SECONDARY_SUPERS_TABLE_SIZE) {
 393     return SECONDARY_SUPERS_BITMAP_FULL;
 394   }
 395 
 396   {
 397     PerfTraceTime ptt(ClassLoader::perf_secondary_hash_time());
 398 
 399     ResourceMark rm;
 400     uintx bitmap = SECONDARY_SUPERS_BITMAP_EMPTY;
 401     auto hashed_secondaries = new GrowableArray<Klass*>(SECONDARY_SUPERS_TABLE_SIZE,
 402                                                         SECONDARY_SUPERS_TABLE_SIZE, nullptr);
 403 
 404     for (int j = 0; j < length; j++) {
 405       Klass* k = secondaries->at(j);
 406       hash_insert(k, hashed_secondaries, bitmap);
 407     }
 408 
 409     // Pack the hashed secondaries array by copying it into the
 410     // secondaries array, sans nulls, if modification is allowed.
 411     // Otherwise, validate the order.
 412     int i = 0;
 413     for (int slot = 0; slot < SECONDARY_SUPERS_TABLE_SIZE; slot++) {
 414       bool has_element = ((bitmap >> slot) & 1) != 0;
 415       assert(has_element == (hashed_secondaries->at(slot) != nullptr), "");
 416       if (has_element) {
 417         Klass* k = hashed_secondaries->at(slot);
 418         if (rewrite) {
 419           secondaries->at_put(i, k);
 420         } else if (secondaries->at(i) != k) {
 421           assert(false, "broken secondary supers hash table");
 422           return SECONDARY_SUPERS_BITMAP_FULL;
 423         }
 424         i++;
 425       }
 426     }
 427     assert(i == secondaries->length(), "mismatch");
 428     postcond((int)population_count(bitmap) == secondaries->length());
 429 
 430     return bitmap;
 431   }
 432 }
 433 
 434 void Klass::hash_insert(Klass* klass, GrowableArray<Klass*>* secondaries, uintx& bitmap) {
 435   assert(bitmap != SECONDARY_SUPERS_BITMAP_FULL, "");
 436 
 437   int dist = 0;
 438   for (int slot = klass->hash_slot(); true; slot = (slot + 1) & SECONDARY_SUPERS_TABLE_MASK) {
 439     Klass* existing = secondaries->at(slot);
 440     assert(((bitmap >> slot) & 1) == (existing != nullptr), "mismatch");
 441     if (existing == nullptr) { // no conflict
 442       secondaries->at_put(slot, klass);
 443       bitmap |= uintx(1) << slot;
 444       assert(bitmap != SECONDARY_SUPERS_BITMAP_FULL, "");
 445       return;
 446     } else {
 447       // Use Robin Hood hashing to minimize the worst case search.
 448       // Also, every permutation of the insertion sequence produces
 449       // the same final Robin Hood hash table, provided that a
 450       // consistent tie breaker is used.
 451       int existing_dist = (slot - existing->hash_slot()) & SECONDARY_SUPERS_TABLE_MASK;
 452       if (existing_dist < dist
 453           // This tie breaker ensures that the hash order is maintained.
 454           || ((existing_dist == dist)
 455               && (uintptr_t(existing) < uintptr_t(klass)))) {
 456         Klass* tmp = secondaries->at(slot);
 457         secondaries->at_put(slot, klass);
 458         klass = tmp;
 459         dist = existing_dist;
 460       }
 461       ++dist;
 462     }
 463   }
 464 }
 465 
 466 Array<Klass*>* Klass::pack_secondary_supers(ClassLoaderData* loader_data,
 467                                             GrowableArray<Klass*>* primaries,
 468                                             GrowableArray<Klass*>* secondaries,
 469                                             uintx& bitmap, TRAPS) {
 470   int new_length = primaries->length() + secondaries->length();
 471   Array<Klass*>* secondary_supers = MetadataFactory::new_array<Klass*>(loader_data, new_length, CHECK_NULL);
 472 
 473   // Combine the two arrays into a metadata object to pack the array.
 474   // The primaries are added in the reverse order, then the secondaries.
 475   int fill_p = primaries->length();
 476   for (int j = 0; j < fill_p; j++) {
 477     secondary_supers->at_put(j, primaries->pop());  // add primaries in reverse order.
 478   }
 479   for( int j = 0; j < secondaries->length(); j++ ) {
 480     secondary_supers->at_put(j+fill_p, secondaries->at(j));  // add secondaries on the end.
 481   }
 482 #ifdef ASSERT
 483   // We must not copy any null placeholders left over from bootstrap.
 484   for (int j = 0; j < secondary_supers->length(); j++) {
 485     assert(secondary_supers->at(j) != nullptr, "correct bootstrapping order");
 486   }
 487 #endif
 488 
 489   bitmap = hash_secondary_supers(secondary_supers, /*rewrite=*/true); // rewrites freshly allocated array
 490   return secondary_supers;
 491 }
 492 
 493 uintx Klass::compute_secondary_supers_bitmap(Array<Klass*>* secondary_supers) {
 494   return hash_secondary_supers(secondary_supers, /*rewrite=*/false); // no rewrites allowed
 495 }
 496 
 497 uint8_t Klass::compute_home_slot(Klass* k, uintx bitmap) {
 498   uint8_t hash = k->hash_slot();
 499   if (hash > 0) {
 500     return population_count(bitmap << (SECONDARY_SUPERS_TABLE_SIZE - hash));
 501   }
 502   return 0;
 503 }
 504 
 505 
 506 void Klass::initialize_supers(Klass* k, Array<InstanceKlass*>* transitive_interfaces, TRAPS) {
 507   if (k == nullptr) {
 508     set_super(nullptr);
 509     _primary_supers[0] = this;
 510     assert(super_depth() == 0, "Object must already be initialized properly");
 511   } else if (k != super() || k == vmClasses::Object_klass()) {
 512     assert(super() == nullptr || super() == vmClasses::Object_klass(),
 513            "initialize this only once to a non-trivial value");
 514     set_super(k);
 515     Klass* sup = k;
 516     int sup_depth = sup->super_depth();
 517     juint my_depth  = MIN2(sup_depth + 1, (int)primary_super_limit());
 518     if (!can_be_primary_super_slow())
 519       my_depth = primary_super_limit();
 520     for (juint i = 0; i < my_depth; i++) {
 521       _primary_supers[i] = sup->_primary_supers[i];
 522     }
 523     Klass* *super_check_cell;
 524     if (my_depth < primary_super_limit()) {
 525       _primary_supers[my_depth] = this;
 526       super_check_cell = &_primary_supers[my_depth];
 527     } else {
 528       // Overflow of the primary_supers array forces me to be secondary.
 529       super_check_cell = &_secondary_super_cache;
 530     }
 531     set_super_check_offset(u4((address)super_check_cell - (address) this));
 532 
 533 #ifdef ASSERT
 534     {
 535       juint j = super_depth();
 536       assert(j == my_depth, "computed accessor gets right answer");
 537       Klass* t = this;
 538       while (!t->can_be_primary_super()) {
 539         t = t->super();
 540         j = t->super_depth();
 541       }
 542       for (juint j1 = j+1; j1 < primary_super_limit(); j1++) {
 543         assert(primary_super_of_depth(j1) == nullptr, "super list padding");
 544       }
 545       while (t != nullptr) {
 546         assert(primary_super_of_depth(j) == t, "super list initialization");
 547         t = t->super();
 548         --j;
 549       }
 550       assert(j == (juint)-1, "correct depth count");
 551     }
 552 #endif
 553   }
 554 
 555   if (secondary_supers() == nullptr) {
 556 
 557     // Now compute the list of secondary supertypes.
 558     // Secondaries can occasionally be on the super chain,
 559     // if the inline "_primary_supers" array overflows.
 560     int extras = 0;
 561     Klass* p;
 562     for (p = super(); !(p == nullptr || p->can_be_primary_super()); p = p->super()) {
 563       ++extras;
 564     }
 565 
 566     ResourceMark rm(THREAD);  // need to reclaim GrowableArrays allocated below
 567 
 568     // Compute the "real" non-extra secondaries.
 569     GrowableArray<Klass*>* secondaries = compute_secondary_supers(extras, transitive_interfaces);
 570     if (secondaries == nullptr) {
 571       // secondary_supers set by compute_secondary_supers
 572       return;
 573     }
 574 
 575     GrowableArray<Klass*>* primaries = new GrowableArray<Klass*>(extras);
 576 
 577     for (p = super(); !(p == nullptr || p->can_be_primary_super()); p = p->super()) {
 578       int i;                    // Scan for overflow primaries being duplicates of 2nd'arys
 579 
 580       // This happens frequently for very deeply nested arrays: the
 581       // primary superclass chain overflows into the secondary.  The
 582       // secondary list contains the element_klass's secondaries with
 583       // an extra array dimension added.  If the element_klass's
 584       // secondary list already contains some primary overflows, they
 585       // (with the extra level of array-ness) will collide with the
 586       // normal primary superclass overflows.
 587       for( i = 0; i < secondaries->length(); i++ ) {
 588         if( secondaries->at(i) == p )
 589           break;
 590       }
 591       if( i < secondaries->length() )
 592         continue;               // It's a dup, don't put it in
 593       primaries->push(p);
 594     }
 595     // Combine the two arrays into a metadata object to pack the array.
 596     uintx bitmap = 0;
 597     Array<Klass*>* s2 = pack_secondary_supers(class_loader_data(), primaries, secondaries, bitmap, CHECK);
 598     set_secondary_supers(s2, bitmap);
 599   }
 600 }
 601 
 602 GrowableArray<Klass*>* Klass::compute_secondary_supers(int num_extra_slots,
 603                                                        Array<InstanceKlass*>* transitive_interfaces) {
 604   assert(num_extra_slots == 0, "override for complex klasses");
 605   assert(transitive_interfaces == nullptr, "sanity");
 606   set_secondary_supers(Universe::the_empty_klass_array(), Universe::the_empty_klass_bitmap());
 607   return nullptr;
 608 }
 609 
 610 
 611 // subklass links.  Used by the compiler (and vtable initialization)
 612 // May be cleaned concurrently, so must use the Compile_lock.
 613 Klass* Klass::subklass() const {
 614   // Need load_acquire on the _subklass, because it races with inserts that
 615   // publishes freshly initialized data.
 616   for (Klass* chain = AtomicAccess::load_acquire(&_subklass);
 617        chain != nullptr;
 618        // Do not need load_acquire on _next_sibling, because inserts never
 619        // create _next_sibling edges to dead data.
 620        chain = AtomicAccess::load(&chain->_next_sibling))
 621   {
 622     if (chain->is_loader_alive()) {
 623       return chain;
 624     }
 625   }
 626   return nullptr;
 627 }
 628 
 629 Klass* Klass::next_sibling(bool log) const {
 630   // Do not need load_acquire on _next_sibling, because inserts never
 631   // create _next_sibling edges to dead data.
 632   for (Klass* chain = AtomicAccess::load(&_next_sibling);
 633        chain != nullptr;
 634        chain = AtomicAccess::load(&chain->_next_sibling)) {
 635     // Only return alive klass, there may be stale klass
 636     // in this chain if cleaned concurrently.
 637     if (chain->is_loader_alive()) {
 638       return chain;
 639     } else if (log) {
 640       if (log_is_enabled(Trace, class, unload)) {
 641         ResourceMark rm;
 642         log_trace(class, unload)("unlinking class (sibling): %s", chain->external_name());
 643       }
 644     }
 645   }
 646   return nullptr;
 647 }
 648 
 649 void Klass::set_subklass(Klass* s) {
 650   assert(s != this, "sanity check");
 651   AtomicAccess::release_store(&_subklass, s);
 652 }
 653 
 654 void Klass::set_next_sibling(Klass* s) {
 655   assert(s != this, "sanity check");
 656   // Does not need release semantics. If used by cleanup, it will link to
 657   // already safely published data, and if used by inserts, will be published
 658   // safely using cmpxchg.
 659   AtomicAccess::store(&_next_sibling, s);
 660 }
 661 
 662 void Klass::append_to_sibling_list() {
 663   if (Universe::is_fully_initialized()) {
 664     assert_locked_or_safepoint(Compile_lock);
 665   }
 666   DEBUG_ONLY(verify();)
 667   // add ourselves to super' subklass list
 668   InstanceKlass* super = java_super();
 669   if (super == nullptr) return;     // special case: class Object
 670   assert((!super->is_interface()    // interfaces cannot be supers
 671           && (super->java_super() == nullptr || !is_interface())),
 672          "an interface can only be a subklass of Object");
 673 
 674   // Make sure there is no stale subklass head
 675   super->clean_subklass();
 676 
 677   for (;;) {
 678     Klass* prev_first_subklass = AtomicAccess::load_acquire(&_super->_subklass);
 679     if (prev_first_subklass != nullptr) {
 680       // set our sibling to be the super' previous first subklass
 681       assert(prev_first_subklass->is_loader_alive(), "May not attach not alive klasses");
 682       set_next_sibling(prev_first_subklass);
 683     }
 684     // Note that the prev_first_subklass is always alive, meaning no sibling_next links
 685     // are ever created to not alive klasses. This is an important invariant of the lock-free
 686     // cleaning protocol, that allows us to safely unlink dead klasses from the sibling list.
 687     if (AtomicAccess::cmpxchg(&super->_subklass, prev_first_subklass, this) == prev_first_subklass) {
 688       return;
 689     }
 690   }
 691   DEBUG_ONLY(verify();)
 692 }
 693 
 694 // The log parameter is for clean_weak_klass_links to report unlinked classes.
 695 Klass* Klass::clean_subklass(bool log) {
 696   for (;;) {
 697     // Need load_acquire, due to contending with concurrent inserts
 698     Klass* subklass = AtomicAccess::load_acquire(&_subklass);
 699     if (subklass == nullptr || subklass->is_loader_alive()) {
 700       return subklass;
 701     }
 702     if (log && log_is_enabled(Trace, class, unload)) {
 703       ResourceMark rm;
 704       log_trace(class, unload)("unlinking class (subclass): %s", subklass->external_name());
 705     }
 706     // Try to fix _subklass until it points at something not dead.
 707     AtomicAccess::cmpxchg(&_subklass, subklass, subklass->next_sibling(log));
 708   }
 709 }
 710 
 711 void Klass::clean_weak_klass_links(bool unloading_occurred, bool clean_alive_klasses) {
 712   if (!ClassUnloading || !unloading_occurred) {
 713     return;
 714   }
 715 
 716   Klass* root = vmClasses::Object_klass();
 717   Stack<Klass*, mtGC> stack;
 718 
 719   stack.push(root);
 720   while (!stack.is_empty()) {
 721     Klass* current = stack.pop();
 722 
 723     assert(current->is_loader_alive(), "just checking, this should be live");
 724 
 725     // Find and set the first alive subklass
 726     Klass* sub = current->clean_subklass(true);
 727     if (sub != nullptr) {
 728       stack.push(sub);
 729     }
 730 
 731     // Find and set the first alive sibling
 732     Klass* sibling = current->next_sibling(true);
 733     current->set_next_sibling(sibling);
 734     if (sibling != nullptr) {
 735       stack.push(sibling);
 736     }
 737 
 738     // Clean the implementors list and method data.
 739     if (clean_alive_klasses && current->is_instance_klass()) {
 740       InstanceKlass* ik = InstanceKlass::cast(current);
 741       clean_weak_instanceklass_links(ik);
 742     }
 743   }
 744 }
 745 
 746 void Klass::clean_weak_instanceklass_links(InstanceKlass* ik) {
 747   ik->clean_weak_instanceklass_links();
 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 void Klass::metaspace_pointers_do(MetaspaceClosure* it) {
 756   if (log_is_enabled(Trace, aot)) {
 757     ResourceMark rm;
 758     log_trace(aot)("Iter(Klass): %p (%s)", this, external_name());
 759   }
 760 
 761   it->push(&_name);
 762   it->push(&_secondary_supers);
 763   for (int i = 0; i < _primary_super_limit; i++) {
 764     it->push(&_primary_supers[i]);
 765   }
 766   it->push(&_super);
 767   if (!CDSConfig::is_dumping_archive()) {
 768     // If dumping archive, these may point to excluded classes. There's no need
 769     // to follow these pointers anyway, as they will be set to null in
 770     // remove_unshareable_info().
 771     it->push((Klass**)&_subklass);
 772     it->push((Klass**)&_next_sibling);
 773     it->push(&_next_link);
 774   }
 775 
 776   vtableEntry* vt = start_of_vtable();
 777   for (int i=0; i<vtable_length(); i++) {
 778     it->push(vt[i].method_addr());
 779   }
 780 }
 781 
 782 #if INCLUDE_CDS
 783 void Klass::remove_unshareable_info() {
 784   assert(CDSConfig::is_dumping_archive(),
 785           "only called during CDS dump time");
 786   JFR_ONLY(REMOVE_ID(this);)
 787   if (log_is_enabled(Trace, aot, unshareable)) {
 788     ResourceMark rm;
 789     log_trace(aot, unshareable)("remove: %s", external_name());
 790   }
 791 
 792   // _secondary_super_cache may be updated by an is_subtype_of() call
 793   // while ArchiveBuilder is copying metaspace objects. Let's reset it to
 794   // null and let it be repopulated at runtime.
 795   set_secondary_super_cache(nullptr);
 796 
 797   set_subklass(nullptr);
 798   set_next_sibling(nullptr);
 799   set_next_link(nullptr);
 800 
 801   // Null out class_loader_data because we don't share that yet.
 802   set_class_loader_data(nullptr);
 803   set_in_aot_cache();
 804 
 805   if (CDSConfig::is_dumping_classic_static_archive()) {
 806     // "Classic" static archives are required to have deterministic contents.
 807     // The elements in _secondary_supers are addresses in the ArchiveBuilder
 808     // output buffer, so they should have deterministic values. If we rehash
 809     // _secondary_supers, its elements will appear in a deterministic order.
 810     //
 811     // Note that the bitmap is guaranteed to be deterministic, regardless of the
 812     // actual addresses of the elements in _secondary_supers. So rehashing shouldn't
 813     // change it.
 814     uintx bitmap = hash_secondary_supers(secondary_supers(), true);
 815     assert(bitmap == _secondary_supers_bitmap, "bitmap should not be changed due to rehashing");
 816   }
 817 }
 818 
 819 void Klass::remove_java_mirror() {
 820   assert(CDSConfig::is_dumping_archive(), "sanity");
 821   if (log_is_enabled(Trace, aot, unshareable)) {
 822     ResourceMark rm;
 823     log_trace(aot, unshareable)("remove java_mirror: %s", external_name());
 824   }
 825 
 826 #if INCLUDE_CDS_JAVA_HEAP
 827   _archived_mirror_index = -1;
 828   if (CDSConfig::is_dumping_heap()) {
 829     Klass* src_k = ArchiveBuilder::current()->get_source_addr(this);
 830     oop orig_mirror = src_k->java_mirror();
 831     if (orig_mirror == nullptr) {
 832       assert(CDSConfig::is_dumping_final_static_archive(), "sanity");
 833       if (is_instance_klass()) {
 834         assert(InstanceKlass::cast(this)->defined_by_other_loaders(), "sanity");
 835       } else {
 836         precond(is_objArray_klass());
 837         Klass *k = ObjArrayKlass::cast(this)->bottom_klass();
 838         precond(k->is_instance_klass());
 839         assert(InstanceKlass::cast(k)->defined_by_other_loaders(), "sanity");
 840       }
 841     } else {
 842       oop scratch_mirror = HeapShared::scratch_java_mirror(orig_mirror);
 843       if (scratch_mirror != nullptr) {
 844         _archived_mirror_index = HeapShared::append_root(scratch_mirror);
 845       }
 846     }
 847   }
 848 #endif
 849 
 850   // Just null out the mirror.  The class_loader_data() no longer exists.
 851   clear_java_mirror_handle();
 852 }
 853 
 854 void Klass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
 855   assert(is_klass(), "ensure C++ vtable is restored");
 856   assert(in_aot_cache(), "must be set");
 857   assert(secondary_supers()->length() >= (int)population_count(_secondary_supers_bitmap), "must be");
 858   if (log_is_enabled(Trace, aot, unshareable)) {
 859     ResourceMark rm(THREAD);
 860     oop class_loader = loader_data->class_loader();
 861     log_trace(aot, unshareable)("restore: %s with class loader: %s", external_name(),
 862       class_loader != nullptr ? class_loader->klass()->external_name() : "boot");
 863   }
 864 
 865   // If an exception happened during CDS restore, some of these fields may already be
 866   // set.  We leave the class on the CLD list, even if incomplete so that we don't
 867   // modify the CLD list outside a safepoint.
 868   if (class_loader_data() == nullptr) {
 869     set_class_loader_data(loader_data);
 870   }
 871 
 872   // Add to class loader list first before creating the mirror
 873   // (same order as class file parsing)
 874   loader_data->add_class(this);
 875 
 876   JFR_ONLY(Jfr::on_restoration(this, THREAD);)
 877 
 878   Handle loader(THREAD, loader_data->class_loader());
 879   ModuleEntry* module_entry = nullptr;
 880   Klass* k = this;
 881   if (k->is_objArray_klass()) {
 882     k = ObjArrayKlass::cast(k)->bottom_klass();
 883   }
 884   // Obtain klass' module.
 885   if (k->is_instance_klass()) {
 886     InstanceKlass* ik = (InstanceKlass*) k;
 887     module_entry = ik->module();
 888   } else {
 889     module_entry = ModuleEntryTable::javabase_moduleEntry();
 890   }
 891   // Obtain java.lang.Module, if available
 892   Handle module_handle(THREAD, ((module_entry != nullptr) ? module_entry->module_oop() : (oop)nullptr));
 893 
 894   if (this->has_archived_mirror_index()) {
 895     ResourceMark rm(THREAD);
 896     log_debug(aot, mirror)("%s has raw archived mirror", external_name());
 897     if (HeapShared::is_archived_heap_in_use()) {
 898       bool present = java_lang_Class::restore_archived_mirror(this, loader, module_handle,
 899                                                               protection_domain,
 900                                                               CHECK);
 901       if (present) {
 902         return;
 903       }
 904     }
 905 
 906     // No archived mirror data
 907     log_debug(aot, mirror)("No archived mirror data for %s", external_name());
 908     clear_java_mirror_handle();
 909     this->clear_archived_mirror_index();
 910   }
 911 
 912   // Only recreate it if not present.  A previous attempt to restore may have
 913   // gotten an OOM later but keep the mirror if it was created.
 914   if (java_mirror() == nullptr) {
 915     ResourceMark rm(THREAD);
 916     log_trace(aot, mirror)("Recreate mirror for %s", external_name());
 917     java_lang_Class::create_mirror(this, loader, module_handle, protection_domain, Handle(), CHECK);
 918   }
 919 }
 920 #endif // INCLUDE_CDS
 921 
 922 #if INCLUDE_CDS_JAVA_HEAP
 923 oop Klass::archived_java_mirror() {
 924   assert(has_archived_mirror_index(), "must have archived mirror");
 925   return HeapShared::get_root(_archived_mirror_index);
 926 }
 927 
 928 void Klass::clear_archived_mirror_index() {
 929   if (_archived_mirror_index >= 0) {
 930     HeapShared::clear_root(_archived_mirror_index);
 931   }
 932   _archived_mirror_index = -1;
 933 }
 934 #endif // INCLUDE_CDS_JAVA_HEAP
 935 
 936 void Klass::check_array_allocation_length(int length, int max_length, TRAPS) {
 937   if (length > max_length) {
 938     if (!THREAD->is_in_internal_oome_mark()) {
 939       report_java_out_of_memory("Requested array size exceeds VM limit");
 940       JvmtiExport::post_array_size_exhausted();
 941       THROW_OOP(Universe::out_of_memory_error_array_size());
 942     } else {
 943       THROW_OOP(Universe::out_of_memory_error_java_heap_without_backtrace());
 944     }
 945   } else if (length < 0) {
 946     THROW_MSG(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", length));
 947   }
 948 }
 949 
 950 // Replace the last '+' char with '/'.
 951 static char* convert_hidden_name_to_java(Symbol* name) {
 952   size_t name_len = name->utf8_length();
 953   char* result = NEW_RESOURCE_ARRAY(char, name_len + 1);
 954   name->as_klass_external_name(result, (int)name_len + 1);
 955   for (int index = (int)name_len; index > 0; index--) {
 956     if (result[index] == '+') {
 957       result[index] = JVM_SIGNATURE_SLASH;
 958       break;
 959     }
 960   }
 961   return result;
 962 }
 963 
 964 // In product mode, this function doesn't have virtual function calls so
 965 // there might be some performance advantage to handling InstanceKlass here.
 966 const char* Klass::external_name() const {
 967   if (is_instance_klass()) {
 968     const InstanceKlass* ik = static_cast<const InstanceKlass*>(this);
 969     if (ik->is_hidden()) {
 970       char* result = convert_hidden_name_to_java(name());
 971       return result;
 972     }
 973   } else if (is_objArray_klass() && ObjArrayKlass::cast(this)->bottom_klass()->is_hidden()) {
 974     char* result = convert_hidden_name_to_java(name());
 975     return result;
 976   }
 977   if (name() == nullptr)  return "<unknown>";
 978   return name()->as_klass_external_name();
 979 }
 980 
 981 const char* Klass::signature_name() const {
 982   if (name() == nullptr)  return "<unknown>";
 983   if (is_objArray_klass() && ObjArrayKlass::cast(this)->bottom_klass()->is_hidden()) {
 984     size_t name_len = name()->utf8_length();
 985     char* result = NEW_RESOURCE_ARRAY(char, name_len + 1);
 986     name()->as_C_string(result, (int)name_len + 1);
 987     for (int index = (int)name_len; index > 0; index--) {
 988       if (result[index] == '+') {
 989         result[index] = JVM_SIGNATURE_DOT;
 990         break;
 991       }
 992     }
 993     return result;
 994   }
 995   return name()->as_C_string();
 996 }
 997 
 998 const char* Klass::external_kind() const {
 999   if (is_interface()) return "interface";
1000   if (is_abstract()) return "abstract class";
1001   return "class";
1002 }
1003 
1004 // Unless overridden, jvmti_class_status has no flags set.
1005 jint Klass::jvmti_class_status() const {
1006   return 0;
1007 }
1008 
1009 
1010 // Printing
1011 
1012 void Klass::print_on(outputStream* st) const {
1013   ResourceMark rm;
1014   // print title
1015   st->print("%s", internal_name());
1016   print_address_on(st);
1017   st->cr();
1018 }
1019 
1020 #define BULLET  " - "
1021 
1022 // Caller needs ResourceMark
1023 void Klass::oop_print_on(oop obj, outputStream* st) {
1024   // print title
1025   st->print_cr("%s ", internal_name());
1026   obj->print_address_on(st);
1027 
1028   if (WizardMode) {
1029      // print header
1030      obj->mark().print_on(st);
1031      st->cr();
1032      if (UseCompactObjectHeaders) {
1033        st->print(BULLET"prototype_header: " INTPTR_FORMAT, _prototype_header.value());
1034        st->cr();
1035      }
1036   }
1037 
1038   // print class
1039   st->print(BULLET"klass: ");
1040   obj->klass()->print_value_on(st);
1041   st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
1042   st->cr();
1043 }
1044 
1045 void Klass::oop_print_value_on(oop obj, outputStream* st) {
1046   // print title
1047   ResourceMark rm;              // Cannot print in debug mode without this
1048   st->print("%s", internal_name());
1049   obj->print_address_on(st);
1050 }
1051 
1052 // Verification
1053 
1054 void Klass::verify_on(outputStream* st) {
1055 
1056   // This can be expensive, but it is worth checking that this klass is actually
1057   // in the CLD graph but not in production.
1058 #ifdef ASSERT
1059   if (UseCompressedClassPointers) {
1060     // Stricter checks for both correct alignment and placement
1061     CompressedKlassPointers::check_encodable(this);
1062   } else {
1063     assert(Metaspace::contains((address)this), "Should be");
1064   }
1065 #endif // ASSERT
1066 
1067   guarantee(this->is_klass(),"should be klass");
1068 
1069   if (super() != nullptr) {
1070     guarantee(super()->is_klass(), "should be klass");
1071   }
1072   if (secondary_super_cache() != nullptr) {
1073     Klass* ko = secondary_super_cache();
1074     guarantee(ko->is_klass(), "should be klass");
1075   }
1076   for ( uint i = 0; i < primary_super_limit(); i++ ) {
1077     Klass* ko = _primary_supers[i];
1078     if (ko != nullptr) {
1079       guarantee(ko->is_klass(), "should be klass");
1080     }
1081   }
1082 
1083   if (java_mirror_no_keepalive() != nullptr) {
1084     guarantee(java_lang_Class::is_instance(java_mirror_no_keepalive()), "should be instance");
1085   }
1086 }
1087 
1088 void Klass::oop_verify_on(oop obj, outputStream* st) {
1089   guarantee(oopDesc::is_oop(obj),  "should be oop");
1090   guarantee(obj->klass()->is_klass(), "klass field is not a klass");
1091 }
1092 
1093 // Note: this function is called with an address that may or may not be a Klass.
1094 // The point is not to assert it is but to check if it could be.
1095 bool Klass::is_valid(Klass* k) {
1096   if (!is_aligned(k, sizeof(MetaWord))) return false;
1097   if ((size_t)k < os::min_page_size()) return false;
1098 
1099   if (!os::is_readable_range(k, k + 1)) return false;
1100   if (!Metaspace::contains(k)) return false;
1101 
1102   if (!Symbol::is_valid(k->name())) return false;
1103   return ClassLoaderDataGraph::is_valid(k->class_loader_data());
1104 }
1105 
1106 Method* Klass::method_at_vtable(int index)  {
1107 #ifndef PRODUCT
1108   assert(index >= 0, "valid vtable index");
1109   if (DebugVtables) {
1110     verify_vtable_index(index);
1111   }
1112 #endif
1113   return start_of_vtable()[index].method();
1114 }
1115 
1116 
1117 #ifndef PRODUCT
1118 
1119 bool Klass::verify_vtable_index(int i) {
1120   int limit = vtable_length()/vtableEntry::size();
1121   assert(i >= 0 && i < limit, "index %d out of bounds %d", i, limit);
1122   return true;
1123 }
1124 
1125 #endif // PRODUCT
1126 
1127 // Caller needs ResourceMark
1128 // joint_in_module_of_loader provides an optimization if 2 classes are in
1129 // the same module to succinctly print out relevant information about their
1130 // module name and class loader's name_and_id for error messages.
1131 // Format:
1132 //   <fully-qualified-external-class-name1> and <fully-qualified-external-class-name2>
1133 //                      are in module <module-name>[@<version>]
1134 //                      of loader <loader-name_and_id>[, parent loader <parent-loader-name_and_id>]
1135 const char* Klass::joint_in_module_of_loader(const Klass* class2, bool include_parent_loader) const {
1136   assert(module() == class2->module(), "classes do not have the same module");
1137   const char* class1_name = external_name();
1138   size_t len = strlen(class1_name) + 1;
1139 
1140   const char* class2_description = class2->class_in_module_of_loader(true, include_parent_loader);
1141   len += strlen(class2_description);
1142 
1143   len += strlen(" and ");
1144 
1145   char* joint_description = NEW_RESOURCE_ARRAY_RETURN_NULL(char, len);
1146 
1147   // Just return the FQN if error when allocating string
1148   if (joint_description == nullptr) {
1149     return class1_name;
1150   }
1151 
1152   jio_snprintf(joint_description, len, "%s and %s",
1153                class1_name,
1154                class2_description);
1155 
1156   return joint_description;
1157 }
1158 
1159 // Caller needs ResourceMark
1160 // class_in_module_of_loader provides a standard way to include
1161 // relevant information about a class, such as its module name as
1162 // well as its class loader's name_and_id, in error messages and logging.
1163 // Format:
1164 //   <fully-qualified-external-class-name> is in module <module-name>[@<version>]
1165 //                                         of loader <loader-name_and_id>[, parent loader <parent-loader-name_and_id>]
1166 const char* Klass::class_in_module_of_loader(bool use_are, bool include_parent_loader) const {
1167   // 1. fully qualified external name of class
1168   const char* klass_name = external_name();
1169   size_t len = strlen(klass_name) + 1;
1170 
1171   // 2. module name + @version
1172   const char* module_name = "";
1173   const char* version = "";
1174   bool has_version = false;
1175   bool module_is_named = false;
1176   const char* module_name_phrase = "";
1177   const Klass* bottom_klass = is_objArray_klass() ?
1178                                 ObjArrayKlass::cast(this)->bottom_klass() : this;
1179   if (bottom_klass->is_instance_klass()) {
1180     ModuleEntry* module = InstanceKlass::cast(bottom_klass)->module();
1181     if (module->is_named()) {
1182       module_is_named = true;
1183       module_name_phrase = "module ";
1184       module_name = module->name()->as_C_string();
1185       len += strlen(module_name);
1186       // Use version if exists and is not a jdk module
1187       if (module->should_show_version()) {
1188         has_version = true;
1189         version = module->version()->as_C_string();
1190         // Include stlen(version) + 1 for the "@"
1191         len += strlen(version) + 1;
1192       }
1193     } else {
1194       module_name = UNNAMED_MODULE;
1195       len += UNNAMED_MODULE_LEN;
1196     }
1197   } else {
1198     // klass is an array of primitives, module is java.base
1199     module_is_named = true;
1200     module_name_phrase = "module ";
1201     module_name = JAVA_BASE_NAME;
1202     len += JAVA_BASE_NAME_LEN;
1203   }
1204 
1205   // 3. class loader's name_and_id
1206   ClassLoaderData* cld = class_loader_data();
1207   assert(cld != nullptr, "class_loader_data should not be null");
1208   const char* loader_name_and_id = cld->loader_name_and_id();
1209   len += strlen(loader_name_and_id);
1210 
1211   // 4. include parent loader information
1212   const char* parent_loader_phrase = "";
1213   const char* parent_loader_name_and_id = "";
1214   if (include_parent_loader &&
1215       !cld->is_builtin_class_loader_data()) {
1216     oop parent_loader = java_lang_ClassLoader::parent(class_loader());
1217     ClassLoaderData *parent_cld = ClassLoaderData::class_loader_data_or_null(parent_loader);
1218     // The parent loader's ClassLoaderData could be null if it is
1219     // a delegating class loader that has never defined a class.
1220     // In this case the loader's name must be obtained via the parent loader's oop.
1221     if (parent_cld == nullptr) {
1222       oop cl_name_and_id = java_lang_ClassLoader::nameAndId(parent_loader);
1223       if (cl_name_and_id != nullptr) {
1224         parent_loader_name_and_id = java_lang_String::as_utf8_string(cl_name_and_id);
1225       }
1226     } else {
1227       parent_loader_name_and_id = parent_cld->loader_name_and_id();
1228     }
1229     parent_loader_phrase = ", parent loader ";
1230     len += strlen(parent_loader_phrase) + strlen(parent_loader_name_and_id);
1231   }
1232 
1233   // Start to construct final full class description string
1234   len += ((use_are) ? strlen(" are in ") : strlen(" is in "));
1235   len += strlen(module_name_phrase) + strlen(" of loader ");
1236 
1237   char* class_description = NEW_RESOURCE_ARRAY_RETURN_NULL(char, len);
1238 
1239   // Just return the FQN if error when allocating string
1240   if (class_description == nullptr) {
1241     return klass_name;
1242   }
1243 
1244   jio_snprintf(class_description, len, "%s %s in %s%s%s%s of loader %s%s%s",
1245                klass_name,
1246                (use_are) ? "are" : "is",
1247                module_name_phrase,
1248                module_name,
1249                (has_version) ? "@" : "",
1250                (has_version) ? version : "",
1251                loader_name_and_id,
1252                parent_loader_phrase,
1253                parent_loader_name_and_id);
1254 
1255   return class_description;
1256 }
1257 
1258 class LookupStats : StackObj {
1259  private:
1260   uint _no_of_samples;
1261   uint _worst;
1262   uint _worst_count;
1263   uint _average;
1264   uint _best;
1265   uint _best_count;
1266  public:
1267   LookupStats() : _no_of_samples(0), _worst(0), _worst_count(0), _average(0), _best(INT_MAX), _best_count(0) {}
1268 
1269   ~LookupStats() {
1270     assert(_best <= _worst || _no_of_samples == 0, "sanity");
1271   }
1272 
1273   void sample(uint value) {
1274     ++_no_of_samples;
1275     _average += value;
1276 
1277     if (_worst < value) {
1278       _worst = value;
1279       _worst_count = 1;
1280     } else if (_worst == value) {
1281       ++_worst_count;
1282     }
1283 
1284     if (_best > value) {
1285       _best = value;
1286       _best_count = 1;
1287     } else if (_best == value) {
1288       ++_best_count;
1289     }
1290   }
1291 
1292   void print_on(outputStream* st) const {
1293     st->print("best: %2d (%4.1f%%)", _best, (100.0 * _best_count) / _no_of_samples);
1294     if (_best_count < _no_of_samples) {
1295       st->print("; average: %4.1f; worst: %2d (%4.1f%%)",
1296                 (1.0 * _average) / _no_of_samples,
1297                 _worst, (100.0 * _worst_count) / _no_of_samples);
1298     }
1299   }
1300 };
1301 
1302 static void print_positive_lookup_stats(Array<Klass*>* secondary_supers, uintx bitmap, outputStream* st) {
1303   int num_of_supers = secondary_supers->length();
1304 
1305   LookupStats s;
1306   for (int i = 0; i < num_of_supers; i++) {
1307     Klass* secondary_super = secondary_supers->at(i);
1308     int home_slot = Klass::compute_home_slot(secondary_super, bitmap);
1309     uint score = 1 + ((i - home_slot) & Klass::SECONDARY_SUPERS_TABLE_MASK);
1310     s.sample(score);
1311   }
1312   st->print("positive_lookup: "); s.print_on(st);
1313 }
1314 
1315 static uint compute_distance_to_nearest_zero(int slot, uintx bitmap) {
1316   assert(~bitmap != 0, "no zeroes");
1317   uintx start = rotate_right(bitmap, slot);
1318   return count_trailing_zeros(~start);
1319 }
1320 
1321 static void print_negative_lookup_stats(uintx bitmap, outputStream* st) {
1322   LookupStats s;
1323   for (int slot = 0; slot < Klass::SECONDARY_SUPERS_TABLE_SIZE; slot++) {
1324     uint score = compute_distance_to_nearest_zero(slot, bitmap);
1325     s.sample(score);
1326   }
1327   st->print("negative_lookup: "); s.print_on(st);
1328 }
1329 
1330 void Klass::print_secondary_supers_on(outputStream* st) const {
1331   if (secondary_supers() != nullptr) {
1332     st->print("  - "); st->print("%d elements;", _secondary_supers->length());
1333     st->print_cr(" bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap);
1334     if (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_EMPTY &&
1335         _secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL) {
1336       st->print("  - "); print_positive_lookup_stats(secondary_supers(),
1337                                                      _secondary_supers_bitmap, st); st->cr();
1338       st->print("  - "); print_negative_lookup_stats(_secondary_supers_bitmap, st); st->cr();
1339     }
1340   } else {
1341     st->print("null");
1342   }
1343 }
1344 
1345 void Klass::on_secondary_supers_verification_failure(Klass* super, Klass* sub, bool linear_result, bool table_result, const char* msg) {
1346   ResourceMark rm;
1347   super->print();
1348   sub->print();
1349   fatal("%s: %s implements %s: linear_search: %d; table_lookup: %d",
1350         msg, sub->external_name(), super->external_name(), linear_result, table_result);
1351 }
--- EOF ---