1 /*
  2  * Copyright (c) 1997, 2023, 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 "precompiled.hpp"
 26 #include "cds/archiveHeapLoader.hpp"
 27 #include "cds/heapShared.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/compressedOops.inline.hpp"
 45 #include "oops/instanceKlass.hpp"
 46 #include "oops/klass.inline.hpp"
 47 #include "oops/objArrayKlass.hpp"
 48 #include "oops/oop.inline.hpp"
 49 #include "oops/oopHandle.inline.hpp"
 50 #include "prims/jvmtiExport.hpp"
 51 #include "runtime/arguments.hpp"
 52 #include "runtime/atomic.hpp"
 53 #include "runtime/handles.inline.hpp"
 54 #include "utilities/macros.hpp"
 55 #include "utilities/powerOfTwo.hpp"
 56 #include "utilities/stack.inline.hpp"
 57 
 58 void Klass::set_java_mirror(Handle m) {
 59   assert(!m.is_null(), "New mirror should never be null.");
 60   assert(_java_mirror.is_empty(), "should only be used to initialize mirror");
 61   _java_mirror = class_loader_data()->add_handle(m);
 62 }
 63 
 64 bool Klass::is_cloneable() const {
 65   return _access_flags.is_cloneable_fast() ||
 66          is_subtype_of(vmClasses::Cloneable_klass());
 67 }
 68 
 69 void Klass::set_is_cloneable() {
 70   if (name() == vmSymbols::java_lang_invoke_MemberName()) {
 71     assert(is_final(), "no subclasses allowed");
 72     // MemberName cloning should not be intrinsified and always happen in JVM_Clone.
 73   } else if (is_instance_klass() && InstanceKlass::cast(this)->reference_type() != REF_NONE) {
 74     // Reference cloning should not be intrinsified and always happen in JVM_Clone.
 75   } else {
 76     _access_flags.set_is_cloneable_fast();
 77   }
 78 }
 79 
 80 void Klass::set_name(Symbol* n) {
 81   _name = n;
 82   if (_name != nullptr) _name->increment_refcount();
 83 
 84   if (Arguments::is_dumping_archive() && is_instance_klass()) {
 85     SystemDictionaryShared::init_dumptime_info(InstanceKlass::cast(this));
 86   }
 87 }
 88 
 89 bool Klass::is_subclass_of(const Klass* k) const {
 90   // Run up the super chain and check
 91   if (this == k) return true;
 92 
 93   Klass* t = const_cast<Klass*>(this)->super();
 94 
 95   while (t != nullptr) {
 96     if (t == k) return true;
 97     t = t->super();
 98   }
 99   return false;
100 }
101 
102 void Klass::release_C_heap_structures(bool release_constant_pool) {
103   if (_name != nullptr) _name->decrement_refcount();
104 }
105 
106 bool Klass::search_secondary_supers(Klass* k) const {
107   // Put some extra logic here out-of-line, before the search proper.
108   // This cuts down the size of the inline method.
109 
110   // This is necessary, since I am never in my own secondary_super list.
111   if (this == k)
112     return true;
113   // Scan the array-of-objects for a match
114   int cnt = secondary_supers()->length();
115   for (int i = 0; i < cnt; i++) {
116     if (secondary_supers()->at(i) == k) {
117       ((Klass*)this)->set_secondary_super_cache(k);
118       return true;
119     }
120   }
121   return false;
122 }
123 
124 // Return self, except for abstract classes with exactly 1
125 // implementor.  Then return the 1 concrete implementation.
126 Klass *Klass::up_cast_abstract() {
127   Klass *r = this;
128   while( r->is_abstract() ) {   // Receiver is abstract?
129     Klass *s = r->subklass();   // Check for exactly 1 subklass
130     if (s == nullptr || s->next_sibling() != nullptr) // Oops; wrong count; give up
131       return this;              // Return 'this' as a no-progress flag
132     r = s;                    // Loop till find concrete class
133   }
134   return r;                   // Return the 1 concrete class
135 }
136 
137 // Find LCA in class hierarchy
138 Klass *Klass::LCA( Klass *k2 ) {
139   Klass *k1 = this;
140   while( 1 ) {
141     if( k1->is_subtype_of(k2) ) return k2;
142     if( k2->is_subtype_of(k1) ) return k1;
143     k1 = k1->super();
144     k2 = k2->super();
145   }
146 }
147 
148 
149 void Klass::check_valid_for_instantiation(bool throwError, TRAPS) {
150   ResourceMark rm(THREAD);
151   THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
152             : vmSymbols::java_lang_InstantiationException(), external_name());
153 }
154 
155 
156 void Klass::copy_array(arrayOop s, int src_pos, arrayOop d, int dst_pos, int length, TRAPS) {
157   ResourceMark rm(THREAD);
158   assert(s != nullptr, "Throw NPE!");
159   THROW_MSG(vmSymbols::java_lang_ArrayStoreException(),
160             err_msg("arraycopy: source type %s is not an array", s->klass()->external_name()));
161 }
162 
163 
164 void Klass::initialize(TRAPS) {
165   ShouldNotReachHere();
166 }
167 
168 Klass* Klass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
169 #ifdef ASSERT
170   tty->print_cr("Error: find_field called on a klass oop."
171                 " Likely error: reflection method does not correctly"
172                 " wrap return value in a mirror object.");
173 #endif
174   ShouldNotReachHere();
175   return nullptr;
176 }
177 
178 Method* Klass::uncached_lookup_method(const Symbol* name, const Symbol* signature,
179                                       OverpassLookupMode overpass_mode,
180                                       PrivateLookupMode private_mode) const {
181 #ifdef ASSERT
182   tty->print_cr("Error: uncached_lookup_method called on a klass oop."
183                 " Likely error: reflection method does not correctly"
184                 " wrap return value in a mirror object.");
185 #endif
186   ShouldNotReachHere();
187   return nullptr;
188 }
189 
190 void* Klass::operator new(size_t size, ClassLoaderData* loader_data, size_t word_size, TRAPS) throw() {
191   return Metaspace::allocate(loader_data, word_size, MetaspaceObj::ClassType, THREAD);
192 }
193 
194 // "Normal" instantiation is preceded by a MetaspaceObj allocation
195 // which zeros out memory - calloc equivalent.
196 // The constructor is also used from CppVtableCloner,
197 // which doesn't zero out the memory before calling the constructor.
198 Klass::Klass(KlassKind kind) : _kind(kind),
199                            _shared_class_path_index(-1) {
200   CDS_ONLY(_shared_class_flags = 0;)
201   CDS_JAVA_HEAP_ONLY(_archived_mirror_index = -1;)
202   _primary_supers[0] = this;
203   set_super_check_offset(in_bytes(primary_supers_offset()));
204 }
205 
206 jint Klass::array_layout_helper(BasicType etype) {
207   assert(etype >= T_BOOLEAN && etype <= T_OBJECT, "valid etype");
208   // Note that T_ARRAY is not allowed here.
209   int  hsize = arrayOopDesc::base_offset_in_bytes(etype);
210   int  esize = type2aelembytes(etype);
211   bool isobj = (etype == T_OBJECT);
212   int  tag   =  isobj ? _lh_array_tag_obj_value : _lh_array_tag_type_value;
213   int lh = array_layout_helper(tag, hsize, etype, exact_log2(esize));
214 
215   assert(lh < (int)_lh_neutral_value, "must look like an array layout");
216   assert(layout_helper_is_array(lh), "correct kind");
217   assert(layout_helper_is_objArray(lh) == isobj, "correct kind");
218   assert(layout_helper_is_typeArray(lh) == !isobj, "correct kind");
219   assert(layout_helper_header_size(lh) == hsize, "correct decode");
220   assert(layout_helper_element_type(lh) == etype, "correct decode");
221   assert(1 << layout_helper_log2_element_size(lh) == esize, "correct decode");
222 
223   return lh;
224 }
225 
226 bool Klass::can_be_primary_super_slow() const {
227   if (super() == nullptr)
228     return true;
229   else if (super()->super_depth() >= primary_super_limit()-1)
230     return false;
231   else
232     return true;
233 }
234 
235 void Klass::initialize_supers(Klass* k, Array<InstanceKlass*>* transitive_interfaces, TRAPS) {
236   if (k == nullptr) {
237     set_super(nullptr);
238     _primary_supers[0] = this;
239     assert(super_depth() == 0, "Object must already be initialized properly");
240   } else if (k != super() || k == vmClasses::Object_klass()) {
241     assert(super() == nullptr || super() == vmClasses::Object_klass(),
242            "initialize this only once to a non-trivial value");
243     set_super(k);
244     Klass* sup = k;
245     int sup_depth = sup->super_depth();
246     juint my_depth  = MIN2(sup_depth + 1, (int)primary_super_limit());
247     if (!can_be_primary_super_slow())
248       my_depth = primary_super_limit();
249     for (juint i = 0; i < my_depth; i++) {
250       _primary_supers[i] = sup->_primary_supers[i];
251     }
252     Klass* *super_check_cell;
253     if (my_depth < primary_super_limit()) {
254       _primary_supers[my_depth] = this;
255       super_check_cell = &_primary_supers[my_depth];
256     } else {
257       // Overflow of the primary_supers array forces me to be secondary.
258       super_check_cell = &_secondary_super_cache;
259     }
260     set_super_check_offset(u4((address)super_check_cell - (address) this));
261 
262 #ifdef ASSERT
263     {
264       juint j = super_depth();
265       assert(j == my_depth, "computed accessor gets right answer");
266       Klass* t = this;
267       while (!t->can_be_primary_super()) {
268         t = t->super();
269         j = t->super_depth();
270       }
271       for (juint j1 = j+1; j1 < primary_super_limit(); j1++) {
272         assert(primary_super_of_depth(j1) == nullptr, "super list padding");
273       }
274       while (t != nullptr) {
275         assert(primary_super_of_depth(j) == t, "super list initialization");
276         t = t->super();
277         --j;
278       }
279       assert(j == (juint)-1, "correct depth count");
280     }
281 #endif
282   }
283 
284   if (secondary_supers() == nullptr) {
285 
286     // Now compute the list of secondary supertypes.
287     // Secondaries can occasionally be on the super chain,
288     // if the inline "_primary_supers" array overflows.
289     int extras = 0;
290     Klass* p;
291     for (p = super(); !(p == nullptr || p->can_be_primary_super()); p = p->super()) {
292       ++extras;
293     }
294 
295     ResourceMark rm(THREAD);  // need to reclaim GrowableArrays allocated below
296 
297     // Compute the "real" non-extra secondaries.
298     GrowableArray<Klass*>* secondaries = compute_secondary_supers(extras, transitive_interfaces);
299     if (secondaries == nullptr) {
300       // secondary_supers set by compute_secondary_supers
301       return;
302     }
303 
304     GrowableArray<Klass*>* primaries = new GrowableArray<Klass*>(extras);
305 
306     for (p = super(); !(p == nullptr || p->can_be_primary_super()); p = p->super()) {
307       int i;                    // Scan for overflow primaries being duplicates of 2nd'arys
308 
309       // This happens frequently for very deeply nested arrays: the
310       // primary superclass chain overflows into the secondary.  The
311       // secondary list contains the element_klass's secondaries with
312       // an extra array dimension added.  If the element_klass's
313       // secondary list already contains some primary overflows, they
314       // (with the extra level of array-ness) will collide with the
315       // normal primary superclass overflows.
316       for( i = 0; i < secondaries->length(); i++ ) {
317         if( secondaries->at(i) == p )
318           break;
319       }
320       if( i < secondaries->length() )
321         continue;               // It's a dup, don't put it in
322       primaries->push(p);
323     }
324     // Combine the two arrays into a metadata object to pack the array.
325     // The primaries are added in the reverse order, then the secondaries.
326     int new_length = primaries->length() + secondaries->length();
327     Array<Klass*>* s2 = MetadataFactory::new_array<Klass*>(
328                                        class_loader_data(), new_length, CHECK);
329     int fill_p = primaries->length();
330     for (int j = 0; j < fill_p; j++) {
331       s2->at_put(j, primaries->pop());  // add primaries in reverse order.
332     }
333     for( int j = 0; j < secondaries->length(); j++ ) {
334       s2->at_put(j+fill_p, secondaries->at(j));  // add secondaries on the end.
335     }
336 
337   #ifdef ASSERT
338       // We must not copy any null placeholders left over from bootstrap.
339     for (int j = 0; j < s2->length(); j++) {
340       assert(s2->at(j) != nullptr, "correct bootstrapping order");
341     }
342   #endif
343 
344     set_secondary_supers(s2);
345   }
346 }
347 
348 GrowableArray<Klass*>* Klass::compute_secondary_supers(int num_extra_slots,
349                                                        Array<InstanceKlass*>* transitive_interfaces) {
350   assert(num_extra_slots == 0, "override for complex klasses");
351   assert(transitive_interfaces == nullptr, "sanity");
352   set_secondary_supers(Universe::the_empty_klass_array());
353   return nullptr;
354 }
355 
356 
357 // superklass links
358 InstanceKlass* Klass::superklass() const {
359   assert(super() == nullptr || super()->is_instance_klass(), "must be instance klass");
360   return _super == nullptr ? nullptr : InstanceKlass::cast(_super);
361 }
362 
363 // subklass links.  Used by the compiler (and vtable initialization)
364 // May be cleaned concurrently, so must use the Compile_lock.
365 // The log parameter is for clean_weak_klass_links to report unlinked classes.
366 Klass* Klass::subklass(bool log) const {
367   // Need load_acquire on the _subklass, because it races with inserts that
368   // publishes freshly initialized data.
369   for (Klass* chain = Atomic::load_acquire(&_subklass);
370        chain != nullptr;
371        // Do not need load_acquire on _next_sibling, because inserts never
372        // create _next_sibling edges to dead data.
373        chain = Atomic::load(&chain->_next_sibling))
374   {
375     if (chain->is_loader_alive()) {
376       return chain;
377     } else if (log) {
378       if (log_is_enabled(Trace, class, unload)) {
379         ResourceMark rm;
380         log_trace(class, unload)("unlinking class (subclass): %s", chain->external_name());
381       }
382     }
383   }
384   return nullptr;
385 }
386 
387 Klass* Klass::next_sibling(bool log) const {
388   // Do not need load_acquire on _next_sibling, because inserts never
389   // create _next_sibling edges to dead data.
390   for (Klass* chain = Atomic::load(&_next_sibling);
391        chain != nullptr;
392        chain = Atomic::load(&chain->_next_sibling)) {
393     // Only return alive klass, there may be stale klass
394     // in this chain if cleaned concurrently.
395     if (chain->is_loader_alive()) {
396       return chain;
397     } else if (log) {
398       if (log_is_enabled(Trace, class, unload)) {
399         ResourceMark rm;
400         log_trace(class, unload)("unlinking class (sibling): %s", chain->external_name());
401       }
402     }
403   }
404   return nullptr;
405 }
406 
407 void Klass::set_subklass(Klass* s) {
408   assert(s != this, "sanity check");
409   Atomic::release_store(&_subklass, s);
410 }
411 
412 void Klass::set_next_sibling(Klass* s) {
413   assert(s != this, "sanity check");
414   // Does not need release semantics. If used by cleanup, it will link to
415   // already safely published data, and if used by inserts, will be published
416   // safely using cmpxchg.
417   Atomic::store(&_next_sibling, s);
418 }
419 
420 void Klass::append_to_sibling_list() {
421   if (Universe::is_fully_initialized()) {
422     assert_locked_or_safepoint(Compile_lock);
423   }
424   debug_only(verify();)
425   // add ourselves to superklass' subklass list
426   InstanceKlass* super = superklass();
427   if (super == nullptr) return;     // special case: class Object
428   assert((!super->is_interface()    // interfaces cannot be supers
429           && (super->superklass() == nullptr || !is_interface())),
430          "an interface can only be a subklass of Object");
431 
432   // Make sure there is no stale subklass head
433   super->clean_subklass();
434 
435   for (;;) {
436     Klass* prev_first_subklass = Atomic::load_acquire(&_super->_subklass);
437     if (prev_first_subklass != nullptr) {
438       // set our sibling to be the superklass' previous first subklass
439       assert(prev_first_subklass->is_loader_alive(), "May not attach not alive klasses");
440       set_next_sibling(prev_first_subklass);
441     }
442     // Note that the prev_first_subklass is always alive, meaning no sibling_next links
443     // are ever created to not alive klasses. This is an important invariant of the lock-free
444     // cleaning protocol, that allows us to safely unlink dead klasses from the sibling list.
445     if (Atomic::cmpxchg(&super->_subklass, prev_first_subklass, this) == prev_first_subklass) {
446       return;
447     }
448   }
449   debug_only(verify();)
450 }
451 
452 void Klass::clean_subklass() {
453   for (;;) {
454     // Need load_acquire, due to contending with concurrent inserts
455     Klass* subklass = Atomic::load_acquire(&_subklass);
456     if (subklass == nullptr || subklass->is_loader_alive()) {
457       return;
458     }
459     // Try to fix _subklass until it points at something not dead.
460     Atomic::cmpxchg(&_subklass, subklass, subklass->next_sibling());
461   }
462 }
463 
464 void Klass::clean_weak_klass_links(bool unloading_occurred, bool clean_alive_klasses) {
465   if (!ClassUnloading || !unloading_occurred) {
466     return;
467   }
468 
469   Klass* root = vmClasses::Object_klass();
470   Stack<Klass*, mtGC> stack;
471 
472   stack.push(root);
473   while (!stack.is_empty()) {
474     Klass* current = stack.pop();
475 
476     assert(current->is_loader_alive(), "just checking, this should be live");
477 
478     // Find and set the first alive subklass
479     Klass* sub = current->subklass(true);
480     current->clean_subklass();
481     if (sub != nullptr) {
482       stack.push(sub);
483     }
484 
485     // Find and set the first alive sibling
486     Klass* sibling = current->next_sibling(true);
487     current->set_next_sibling(sibling);
488     if (sibling != nullptr) {
489       stack.push(sibling);
490     }
491 
492     // Clean the implementors list and method data.
493     if (clean_alive_klasses && current->is_instance_klass()) {
494       InstanceKlass* ik = InstanceKlass::cast(current);
495       ik->clean_weak_instanceklass_links();
496 
497       // JVMTI RedefineClasses creates previous versions that are not in
498       // the class hierarchy, so process them here.
499       while ((ik = ik->previous_versions()) != nullptr) {
500         ik->clean_weak_instanceklass_links();
501       }
502     }
503   }
504 }
505 
506 void Klass::metaspace_pointers_do(MetaspaceClosure* it) {
507   if (log_is_enabled(Trace, cds)) {
508     ResourceMark rm;
509     log_trace(cds)("Iter(Klass): %p (%s)", this, external_name());
510   }
511 
512   it->push(&_name);
513   it->push(&_secondary_super_cache);
514   it->push(&_secondary_supers);
515   for (int i = 0; i < _primary_super_limit; i++) {
516     it->push(&_primary_supers[i]);
517   }
518   it->push(&_super);
519   if (!Arguments::is_dumping_archive()) {
520     // If dumping archive, these may point to excluded classes. There's no need
521     // to follow these pointers anyway, as they will be set to null in
522     // remove_unshareable_info().
523     it->push((Klass**)&_subklass);
524     it->push((Klass**)&_next_sibling);
525     it->push(&_next_link);
526   }
527 
528   vtableEntry* vt = start_of_vtable();
529   for (int i=0; i<vtable_length(); i++) {
530     it->push(vt[i].method_addr());
531   }
532 }
533 
534 #if INCLUDE_CDS
535 void Klass::remove_unshareable_info() {
536   assert (Arguments::is_dumping_archive(),
537           "only called during CDS dump time");
538   JFR_ONLY(REMOVE_ID(this);)
539   if (log_is_enabled(Trace, cds, unshareable)) {
540     ResourceMark rm;
541     log_trace(cds, unshareable)("remove: %s", external_name());
542   }
543 
544   set_subklass(nullptr);
545   set_next_sibling(nullptr);
546   set_next_link(nullptr);
547 
548   // Null out class_loader_data because we don't share that yet.
549   set_class_loader_data(nullptr);
550   set_is_shared();
551 }
552 
553 void Klass::remove_java_mirror() {
554   Arguments::assert_is_dumping_archive();
555   if (log_is_enabled(Trace, cds, unshareable)) {
556     ResourceMark rm;
557     log_trace(cds, unshareable)("remove java_mirror: %s", external_name());
558   }
559   // Just null out the mirror.  The class_loader_data() no longer exists.
560   clear_java_mirror_handle();
561 }
562 
563 void Klass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
564   assert(is_klass(), "ensure C++ vtable is restored");
565   assert(is_shared(), "must be set");
566   JFR_ONLY(RESTORE_ID(this);)
567   if (log_is_enabled(Trace, cds, unshareable)) {
568     ResourceMark rm(THREAD);
569     log_trace(cds, unshareable)("restore: %s", external_name());
570   }
571 
572   // If an exception happened during CDS restore, some of these fields may already be
573   // set.  We leave the class on the CLD list, even if incomplete so that we don't
574   // modify the CLD list outside a safepoint.
575   if (class_loader_data() == nullptr) {
576     set_class_loader_data(loader_data);
577 
578     // Add to class loader list first before creating the mirror
579     // (same order as class file parsing)
580     loader_data->add_class(this);
581   }
582 
583   Handle loader(THREAD, loader_data->class_loader());
584   ModuleEntry* module_entry = nullptr;
585   Klass* k = this;
586   if (k->is_objArray_klass()) {
587     k = ObjArrayKlass::cast(k)->bottom_klass();
588   }
589   // Obtain klass' module.
590   if (k->is_instance_klass()) {
591     InstanceKlass* ik = (InstanceKlass*) k;
592     module_entry = ik->module();
593   } else {
594     module_entry = ModuleEntryTable::javabase_moduleEntry();
595   }
596   // Obtain java.lang.Module, if available
597   Handle module_handle(THREAD, ((module_entry != nullptr) ? module_entry->module() : (oop)nullptr));
598 
599   if (this->has_archived_mirror_index()) {
600     ResourceMark rm(THREAD);
601     log_debug(cds, mirror)("%s has raw archived mirror", external_name());
602     if (ArchiveHeapLoader::is_in_use()) {
603       bool present = java_lang_Class::restore_archived_mirror(this, loader, module_handle,
604                                                               protection_domain,
605                                                               CHECK);
606       if (present) {
607         return;
608       }
609     }
610 
611     // No archived mirror data
612     log_debug(cds, mirror)("No archived mirror data for %s", external_name());
613     clear_java_mirror_handle();
614     this->clear_archived_mirror_index();
615   }
616 
617   // Only recreate it if not present.  A previous attempt to restore may have
618   // gotten an OOM later but keep the mirror if it was created.
619   if (java_mirror() == nullptr) {
620     ResourceMark rm(THREAD);
621     log_trace(cds, mirror)("Recreate mirror for %s", external_name());
622     java_lang_Class::create_mirror(this, loader, module_handle, protection_domain, Handle(), CHECK);
623   }
624 }
625 #endif // INCLUDE_CDS
626 
627 #if INCLUDE_CDS_JAVA_HEAP
628 oop Klass::archived_java_mirror() {
629   assert(has_archived_mirror_index(), "must have archived mirror");
630   return HeapShared::get_root(_archived_mirror_index);
631 }
632 
633 void Klass::clear_archived_mirror_index() {
634   if (_archived_mirror_index >= 0) {
635     HeapShared::clear_root(_archived_mirror_index);
636   }
637   _archived_mirror_index = -1;
638 }
639 
640 // No GC barrier
641 void Klass::set_archived_java_mirror(int mirror_index) {
642   assert(DumpSharedSpaces, "called only during dumptime");
643   _archived_mirror_index = mirror_index;
644 }
645 #endif // INCLUDE_CDS_JAVA_HEAP
646 
647 void Klass::check_array_allocation_length(int length, int max_length, TRAPS) {
648   if (length > max_length) {
649     if (!THREAD->in_retryable_allocation()) {
650       report_java_out_of_memory("Requested array size exceeds VM limit");
651       JvmtiExport::post_array_size_exhausted();
652       THROW_OOP(Universe::out_of_memory_error_array_size());
653     } else {
654       THROW_OOP(Universe::out_of_memory_error_retry());
655     }
656   } else if (length < 0) {
657     THROW_MSG(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", length));
658   }
659 }
660 
661 // Replace the last '+' char with '/'.
662 static char* convert_hidden_name_to_java(Symbol* name) {
663   size_t name_len = name->utf8_length();
664   char* result = NEW_RESOURCE_ARRAY(char, name_len + 1);
665   name->as_klass_external_name(result, (int)name_len + 1);
666   for (int index = (int)name_len; index > 0; index--) {
667     if (result[index] == '+') {
668       result[index] = JVM_SIGNATURE_SLASH;
669       break;
670     }
671   }
672   return result;
673 }
674 
675 // In product mode, this function doesn't have virtual function calls so
676 // there might be some performance advantage to handling InstanceKlass here.
677 const char* Klass::external_name() const {
678   if (is_instance_klass()) {
679     const InstanceKlass* ik = static_cast<const InstanceKlass*>(this);
680     if (ik->is_hidden()) {
681       char* result = convert_hidden_name_to_java(name());
682       return result;
683     }
684   } else if (is_objArray_klass() && ObjArrayKlass::cast(this)->bottom_klass()->is_hidden()) {
685     char* result = convert_hidden_name_to_java(name());
686     return result;
687   }
688   if (name() == nullptr)  return "<unknown>";
689   return name()->as_klass_external_name();
690 }
691 
692 const char* Klass::signature_name() const {
693   if (name() == nullptr)  return "<unknown>";
694   if (is_objArray_klass() && ObjArrayKlass::cast(this)->bottom_klass()->is_hidden()) {
695     size_t name_len = name()->utf8_length();
696     char* result = NEW_RESOURCE_ARRAY(char, name_len + 1);
697     name()->as_C_string(result, (int)name_len + 1);
698     for (int index = (int)name_len; index > 0; index--) {
699       if (result[index] == '+') {
700         result[index] = JVM_SIGNATURE_DOT;
701         break;
702       }
703     }
704     return result;
705   }
706   return name()->as_C_string();
707 }
708 
709 const char* Klass::external_kind() const {
710   if (is_interface()) return "interface";
711   if (is_abstract()) return "abstract class";
712   return "class";
713 }
714 
715 // Unless overridden, jvmti_class_status has no flags set.
716 jint Klass::jvmti_class_status() const {
717   return 0;
718 }
719 
720 
721 // Printing
722 
723 void Klass::print_on(outputStream* st) const {
724   ResourceMark rm;
725   // print title
726   st->print("%s", internal_name());
727   print_address_on(st);
728   st->cr();
729 }
730 
731 #define BULLET  " - "
732 
733 // Caller needs ResourceMark
734 void Klass::oop_print_on(oop obj, outputStream* st) {
735   // print title
736   st->print_cr("%s ", internal_name());
737   obj->print_address_on(st);
738 
739   if (WizardMode) {
740      // print header
741      obj->mark().print_on(st);
742      st->cr();
743   }
744 
745   // print class
746   st->print(BULLET"klass: ");
747   obj->klass()->print_value_on(st);
748   st->cr();
749 }
750 
751 void Klass::oop_print_value_on(oop obj, outputStream* st) {
752   // print title
753   ResourceMark rm;              // Cannot print in debug mode without this
754   st->print("%s", internal_name());
755   obj->print_address_on(st);
756 }
757 
758 // Verification
759 
760 void Klass::verify_on(outputStream* st) {
761 
762   // This can be expensive, but it is worth checking that this klass is actually
763   // in the CLD graph but not in production.
764   assert(Metaspace::contains((address)this), "Should be");
765 
766   guarantee(this->is_klass(),"should be klass");
767 
768   if (super() != nullptr) {
769     guarantee(super()->is_klass(), "should be klass");
770   }
771   if (secondary_super_cache() != nullptr) {
772     Klass* ko = secondary_super_cache();
773     guarantee(ko->is_klass(), "should be klass");
774   }
775   for ( uint i = 0; i < primary_super_limit(); i++ ) {
776     Klass* ko = _primary_supers[i];
777     if (ko != nullptr) {
778       guarantee(ko->is_klass(), "should be klass");
779     }
780   }
781 
782   if (java_mirror_no_keepalive() != nullptr) {
783     guarantee(java_lang_Class::is_instance(java_mirror_no_keepalive()), "should be instance");
784   }
785 }
786 
787 void Klass::oop_verify_on(oop obj, outputStream* st) {
788   guarantee(oopDesc::is_oop(obj),  "should be oop");
789   guarantee(obj->klass()->is_klass(), "klass field is not a klass");
790 }
791 
792 bool Klass::is_valid(Klass* k) {
793   if (!is_aligned(k, sizeof(MetaWord))) return false;
794   if ((size_t)k < os::min_page_size()) return false;
795 
796   if (!os::is_readable_range(k, k + 1)) return false;
797   if (!Metaspace::contains(k)) return false;
798 
799   if (!Symbol::is_valid(k->name())) return false;
800   return ClassLoaderDataGraph::is_valid(k->class_loader_data());
801 }
802 
803 Method* Klass::method_at_vtable(int index)  {
804 #ifndef PRODUCT
805   assert(index >= 0, "valid vtable index");
806   if (DebugVtables) {
807     verify_vtable_index(index);
808   }
809 #endif
810   return start_of_vtable()[index].method();
811 }
812 
813 
814 #ifndef PRODUCT
815 
816 bool Klass::verify_vtable_index(int i) {
817   int limit = vtable_length()/vtableEntry::size();
818   assert(i >= 0 && i < limit, "index %d out of bounds %d", i, limit);
819   return true;
820 }
821 
822 #endif // PRODUCT
823 
824 // Caller needs ResourceMark
825 // joint_in_module_of_loader provides an optimization if 2 classes are in
826 // the same module to succinctly print out relevant information about their
827 // module name and class loader's name_and_id for error messages.
828 // Format:
829 //   <fully-qualified-external-class-name1> and <fully-qualified-external-class-name2>
830 //                      are in module <module-name>[@<version>]
831 //                      of loader <loader-name_and_id>[, parent loader <parent-loader-name_and_id>]
832 const char* Klass::joint_in_module_of_loader(const Klass* class2, bool include_parent_loader) const {
833   assert(module() == class2->module(), "classes do not have the same module");
834   const char* class1_name = external_name();
835   size_t len = strlen(class1_name) + 1;
836 
837   const char* class2_description = class2->class_in_module_of_loader(true, include_parent_loader);
838   len += strlen(class2_description);
839 
840   len += strlen(" and ");
841 
842   char* joint_description = NEW_RESOURCE_ARRAY_RETURN_NULL(char, len);
843 
844   // Just return the FQN if error when allocating string
845   if (joint_description == nullptr) {
846     return class1_name;
847   }
848 
849   jio_snprintf(joint_description, len, "%s and %s",
850                class1_name,
851                class2_description);
852 
853   return joint_description;
854 }
855 
856 // Caller needs ResourceMark
857 // class_in_module_of_loader provides a standard way to include
858 // relevant information about a class, such as its module name as
859 // well as its class loader's name_and_id, in error messages and logging.
860 // Format:
861 //   <fully-qualified-external-class-name> is in module <module-name>[@<version>]
862 //                                         of loader <loader-name_and_id>[, parent loader <parent-loader-name_and_id>]
863 const char* Klass::class_in_module_of_loader(bool use_are, bool include_parent_loader) const {
864   // 1. fully qualified external name of class
865   const char* klass_name = external_name();
866   size_t len = strlen(klass_name) + 1;
867 
868   // 2. module name + @version
869   const char* module_name = "";
870   const char* version = "";
871   bool has_version = false;
872   bool module_is_named = false;
873   const char* module_name_phrase = "";
874   const Klass* bottom_klass = is_objArray_klass() ?
875                                 ObjArrayKlass::cast(this)->bottom_klass() : this;
876   if (bottom_klass->is_instance_klass()) {
877     ModuleEntry* module = InstanceKlass::cast(bottom_klass)->module();
878     if (module->is_named()) {
879       module_is_named = true;
880       module_name_phrase = "module ";
881       module_name = module->name()->as_C_string();
882       len += strlen(module_name);
883       // Use version if exists and is not a jdk module
884       if (module->should_show_version()) {
885         has_version = true;
886         version = module->version()->as_C_string();
887         // Include stlen(version) + 1 for the "@"
888         len += strlen(version) + 1;
889       }
890     } else {
891       module_name = UNNAMED_MODULE;
892       len += UNNAMED_MODULE_LEN;
893     }
894   } else {
895     // klass is an array of primitives, module is java.base
896     module_is_named = true;
897     module_name_phrase = "module ";
898     module_name = JAVA_BASE_NAME;
899     len += JAVA_BASE_NAME_LEN;
900   }
901 
902   // 3. class loader's name_and_id
903   ClassLoaderData* cld = class_loader_data();
904   assert(cld != nullptr, "class_loader_data should not be null");
905   const char* loader_name_and_id = cld->loader_name_and_id();
906   len += strlen(loader_name_and_id);
907 
908   // 4. include parent loader information
909   const char* parent_loader_phrase = "";
910   const char* parent_loader_name_and_id = "";
911   if (include_parent_loader &&
912       !cld->is_builtin_class_loader_data()) {
913     oop parent_loader = java_lang_ClassLoader::parent(class_loader());
914     ClassLoaderData *parent_cld = ClassLoaderData::class_loader_data_or_null(parent_loader);
915     // The parent loader's ClassLoaderData could be null if it is
916     // a delegating class loader that has never defined a class.
917     // In this case the loader's name must be obtained via the parent loader's oop.
918     if (parent_cld == nullptr) {
919       oop cl_name_and_id = java_lang_ClassLoader::nameAndId(parent_loader);
920       if (cl_name_and_id != nullptr) {
921         parent_loader_name_and_id = java_lang_String::as_utf8_string(cl_name_and_id);
922       }
923     } else {
924       parent_loader_name_and_id = parent_cld->loader_name_and_id();
925     }
926     parent_loader_phrase = ", parent loader ";
927     len += strlen(parent_loader_phrase) + strlen(parent_loader_name_and_id);
928   }
929 
930   // Start to construct final full class description string
931   len += ((use_are) ? strlen(" are in ") : strlen(" is in "));
932   len += strlen(module_name_phrase) + strlen(" of loader ");
933 
934   char* class_description = NEW_RESOURCE_ARRAY_RETURN_NULL(char, len);
935 
936   // Just return the FQN if error when allocating string
937   if (class_description == nullptr) {
938     return klass_name;
939   }
940 
941   jio_snprintf(class_description, len, "%s %s in %s%s%s%s of loader %s%s%s",
942                klass_name,
943                (use_are) ? "are" : "is",
944                module_name_phrase,
945                module_name,
946                (has_version) ? "@" : "",
947                (has_version) ? version : "",
948                loader_name_and_id,
949                parent_loader_phrase,
950                parent_loader_name_and_id);
951 
952   return class_description;
953 }