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