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