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