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