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