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