1 /*
   2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "cds/cdsConfig.hpp"
  26 #include "cds/heapShared.inline.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoaderData.inline.hpp"
  29 #include "classfile/classLoaderDataGraph.inline.hpp"
  30 #include "classfile/javaClasses.inline.hpp"
  31 #include "classfile/moduleEntry.hpp"
  32 #include "classfile/systemDictionary.hpp"
  33 #include "classfile/systemDictionaryShared.hpp"
  34 #include "classfile/vmClasses.hpp"
  35 #include "classfile/vmSymbols.hpp"
  36 #include "gc/shared/collectedHeap.inline.hpp"
  37 #include "jvm_io.h"
  38 #include "logging/log.hpp"
  39 #include "memory/metadataFactory.hpp"
  40 #include "memory/metaspaceClosure.hpp"
  41 #include "memory/oopFactory.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "memory/universe.hpp"
  44 #include "oops/compressedKlass.inline.hpp"
  45 #include "oops/compressedOops.inline.hpp"
  46 #include "oops/instanceKlass.hpp"
  47 #include "oops/klass.inline.hpp"
  48 #include "oops/objArrayKlass.hpp"
  49 #include "oops/oop.inline.hpp"
  50 #include "oops/oopHandle.inline.hpp"
  51 #include "prims/jvmtiExport.hpp"
  52 #include "runtime/atomicAccess.hpp"
  53 #include "runtime/handles.inline.hpp"
  54 #include "runtime/perfData.hpp"
  55 #include "utilities/macros.hpp"
  56 #include "utilities/powerOfTwo.hpp"
  57 #include "utilities/rotate_bits.hpp"
  58 #include "utilities/stack.inline.hpp"
  59 
  60 #if INCLUDE_JFR
  61 #include "jfr/jfr.hpp"
  62 #endif
  63 
  64 void Klass::set_java_mirror(Handle m) {
  65   assert(!m.is_null(), "New mirror should never be null.");
  66   assert(_java_mirror.is_empty(), "should only be used to initialize mirror");
  67   _java_mirror = class_loader_data()->add_handle(m);
  68 }
  69 
  70 bool Klass::is_cloneable() const {
  71   return _misc_flags.is_cloneable_fast() ||
  72          is_subtype_of(vmClasses::Cloneable_klass());
  73 }
  74 
  75 void Klass::set_is_cloneable() {
  76   if (name() == vmSymbols::java_lang_invoke_MemberName()) {
  77     assert(is_final(), "no subclasses allowed");
  78     // MemberName cloning should not be intrinsified and always happen in JVM_Clone.
  79   } else if (is_instance_klass() && InstanceKlass::cast(this)->reference_type() != REF_NONE) {
  80     // Reference cloning should not be intrinsified and always happen in JVM_Clone.
  81   } else {
  82     _misc_flags.set_is_cloneable_fast(true);
  83   }
  84 }
  85 
  86 uint8_t Klass::compute_hash_slot(Symbol* n) {
  87   uint hash_code;
  88   // Special cases for the two superclasses of all Array instances.
  89   // Code elsewhere assumes, for all instances of ArrayKlass, that
  90   // these two interfaces will be in this order.
  91 
  92   // We ensure there are some empty slots in the hash table between
  93   // these two very common interfaces because if they were adjacent
  94   // (e.g. Slots 0 and 1), then any other class which hashed to 0 or 1
  95   // would result in a probe length of 3.
  96   if (n == vmSymbols::java_lang_Cloneable()) {
  97     hash_code = 0;
  98   } else if (n == vmSymbols::java_io_Serializable()) {
  99     hash_code = SECONDARY_SUPERS_TABLE_SIZE / 2;
 100   } else {
 101     auto s = (const jbyte*) n->bytes();
 102     hash_code = java_lang_String::hash_code(s, n->utf8_length());
 103     // We use String::hash_code here (rather than e.g.
 104     // Symbol::identity_hash()) in order to have a hash code that
 105     // does not change from run to run. We want that because the
 106     // hash value for a secondary superclass appears in generated
 107     // code as a constant.
 108 
 109     // This constant is magic: see Knuth, "Fibonacci Hashing".
 110     constexpr uint multiplier
 111       = 2654435769; // (uint)(((u8)1 << 32) / ((1 + sqrt(5)) / 2 ))
 112     constexpr uint hash_shift = sizeof(hash_code) * 8 - 6;
 113     // The leading bits of the least significant half of the product.
 114     hash_code = (hash_code * multiplier) >> hash_shift;
 115 
 116     if (StressSecondarySupers) {
 117       // Generate many hash collisions in order to stress-test the
 118       // linear search fallback.
 119       hash_code = hash_code % 3;
 120       hash_code = hash_code * (SECONDARY_SUPERS_TABLE_SIZE / 3);
 121     }
 122   }
 123 
 124   return (hash_code & SECONDARY_SUPERS_TABLE_MASK);
 125 }
 126 
 127 void Klass::set_name(Symbol* n) {
 128   _name = n;
 129 
 130   if (_name != nullptr) {
 131     _name->increment_refcount();
 132   }
 133 
 134   {
 135     elapsedTimer selftime;
 136     selftime.start();
 137 
 138     _hash_slot = compute_hash_slot(n);
 139     assert(_hash_slot < SECONDARY_SUPERS_TABLE_SIZE, "required");
 140 
 141     selftime.stop();
 142     if (UsePerfData) {
 143       ClassLoader::perf_secondary_hash_time()->inc(selftime.ticks());
 144     }
 145   }
 146 
 147   if (CDSConfig::is_dumping_archive() && is_instance_klass()) {
 148     SystemDictionaryShared::init_dumptime_info(InstanceKlass::cast(this));
 149   }
 150 }
 151 
 152 bool Klass::is_subclass_of(const Klass* k) const {
 153   // Run up the super chain and check
 154   if (this == k) return true;
 155 
 156   Klass* t = const_cast<Klass*>(this)->super();
 157 
 158   while (t != nullptr) {
 159     if (t == k) return true;
 160     t = t->super();
 161   }
 162   return false;
 163 }
 164 
 165 void Klass::release_C_heap_structures(bool release_constant_pool) {
 166   if (_name != nullptr) _name->decrement_refcount();
 167 }
 168 
 169 bool Klass::linear_search_secondary_supers(const Klass* k) const {
 170   // Scan the array-of-objects for a match
 171   // FIXME: We could do something smarter here, maybe a vectorized
 172   // comparison or a binary search, but is that worth any added
 173   // complexity?
 174   int cnt = secondary_supers()->length();
 175   for (int i = 0; i < cnt; i++) {
 176     if (secondary_supers()->at(i) == k) {
 177       return true;
 178     }
 179   }
 180   return false;
 181 }
 182 
 183 // Given a secondary superklass k, an initial array index, and an
 184 // occupancy bitmap rotated such that Bit 1 is the next bit to test,
 185 // search for k.
 186 bool Klass::fallback_search_secondary_supers(const Klass* k, int index, uintx rotated_bitmap) const {
 187   // Once the occupancy bitmap is almost full, it's faster to use a
 188   // linear search.
 189   if (secondary_supers()->length() > SECONDARY_SUPERS_TABLE_SIZE - 2) {
 190     return linear_search_secondary_supers(k);
 191   }
 192 
 193   // This is conventional linear probing, but instead of terminating
 194   // when a null entry is found in the table, we maintain a bitmap
 195   // in which a 0 indicates missing entries.
 196 
 197   precond((int)population_count(rotated_bitmap) == secondary_supers()->length());
 198 
 199   // The check for secondary_supers()->length() <= SECONDARY_SUPERS_TABLE_SIZE - 2
 200   // at the start of this function guarantees there are 0s in the
 201   // bitmap, so this loop eventually terminates.
 202   while ((rotated_bitmap & 2) != 0) {
 203     if (++index == secondary_supers()->length()) {
 204       index = 0;
 205     }
 206     if (secondary_supers()->at(index) == k) {
 207       return true;
 208     }
 209     rotated_bitmap = rotate_right(rotated_bitmap, 1);
 210   }
 211   return false;
 212 }
 213 
 214 // Return self, except for abstract classes with exactly 1
 215 // implementor.  Then return the 1 concrete implementation.
 216 Klass *Klass::up_cast_abstract() {
 217   Klass *r = this;
 218   while( r->is_abstract() ) {   // Receiver is abstract?
 219     Klass *s = r->subklass();   // Check for exactly 1 subklass
 220     if (s == nullptr || s->next_sibling() != nullptr) // Oops; wrong count; give up
 221       return this;              // Return 'this' as a no-progress flag
 222     r = s;                    // Loop till find concrete class
 223   }
 224   return r;                   // Return the 1 concrete class
 225 }
 226 
 227 // Find LCA in class hierarchy
 228 Klass *Klass::LCA( Klass *k2 ) {
 229   Klass *k1 = this;
 230   while( 1 ) {
 231     if( k1->is_subtype_of(k2) ) return k2;
 232     if( k2->is_subtype_of(k1) ) return k1;
 233     k1 = k1->super();
 234     k2 = k2->super();
 235   }
 236 }
 237 
 238 
 239 void Klass::check_valid_for_instantiation(bool throwError, TRAPS) {
 240   ResourceMark rm(THREAD);
 241   THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
 242             : vmSymbols::java_lang_InstantiationException(), external_name());
 243 }
 244 
 245 
 246 void Klass::copy_array(arrayOop s, int src_pos, arrayOop d, int dst_pos, int length, TRAPS) {
 247   ResourceMark rm(THREAD);
 248   assert(s != nullptr, "Throw NPE!");
 249   THROW_MSG(vmSymbols::java_lang_ArrayStoreException(),
 250             err_msg("arraycopy: source type %s is not an array", s->klass()->external_name()));
 251 }
 252 
 253 
 254 void Klass::initialize(TRAPS) {
 255   ShouldNotReachHere();
 256 }
 257 
 258 void Klass::initialize_preemptable(TRAPS) {
 259   ShouldNotReachHere();
 260 }
 261 
 262 Klass* Klass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
 263 #ifdef ASSERT
 264   tty->print_cr("Error: find_field called on a klass oop."
 265                 " Likely error: reflection method does not correctly"
 266                 " wrap return value in a mirror object.");
 267 #endif
 268   ShouldNotReachHere();
 269   return nullptr;
 270 }
 271 
 272 Method* Klass::uncached_lookup_method(const Symbol* name, const Symbol* signature,
 273                                       OverpassLookupMode overpass_mode,
 274                                       PrivateLookupMode private_mode) const {
 275 #ifdef ASSERT
 276   tty->print_cr("Error: uncached_lookup_method called on a klass oop."
 277                 " Likely error: reflection method does not correctly"
 278                 " wrap return value in a mirror object.");
 279 #endif
 280   ShouldNotReachHere();
 281   return nullptr;
 282 }
 283 
 284 static markWord make_prototype(const Klass* kls) {
 285   markWord prototype = markWord::prototype();
 286 #ifdef _LP64
 287   if (UseCompactObjectHeaders) {
 288     // With compact object headers, the narrow Klass ID is part of the mark word.
 289     // We therefore seed the mark word with the narrow Klass ID.
 290     precond(CompressedKlassPointers::is_encodable(kls));
 291     const narrowKlass nk = CompressedKlassPointers::encode(const_cast<Klass*>(kls));
 292     prototype = prototype.set_narrow_klass(nk);
 293   }
 294 #endif
 295   return prototype;
 296 }
 297 
 298 void* Klass::operator new(size_t size, ClassLoaderData* loader_data, size_t word_size, TRAPS) throw() {
 299   return Metaspace::allocate(loader_data, word_size, MetaspaceObj::ClassType, THREAD);
 300 }
 301 
 302 Klass::Klass() : _kind(UnknownKlassKind) {
 303   assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for cds");
 304 }
 305 
 306 // "Normal" instantiation is preceded by a MetaspaceObj allocation
 307 // which zeros out memory - calloc equivalent.
 308 // The constructor is also used from CppVtableCloner,
 309 // which doesn't zero out the memory before calling the constructor.
 310 Klass::Klass(KlassKind kind) : _kind(kind),
 311                                _prototype_header(make_prototype(this)),
 312                                _shared_class_path_index(-1) {

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