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