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