1 /*
  2  * Copyright (c) 2021, 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 "classfile/classLoader.hpp"
 28 #include "classfile/classLoaderData.hpp"
 29 #include "classfile/dictionary.hpp"
 30 #include "classfile/javaClasses.hpp"
 31 #include "classfile/systemDictionary.hpp"
 32 #include "classfile/vmClasses.hpp"
 33 #include "classfile/vmSymbols.hpp"
 34 #include "gc/shared/collectedHeap.hpp"
 35 #include "memory/metaspaceClosure.hpp"
 36 #include "memory/universe.hpp"
 37 #include "oops/instanceKlass.hpp"
 38 #include "oops/instanceRefKlass.hpp"
 39 #include "oops/instanceStackChunkKlass.hpp"
 40 #include "prims/jvmtiExport.hpp"
 41 #include "runtime/globals.hpp"
 42 
 43 InstanceKlass* vmClasses::_klasses[static_cast<int>(vmClassID::LIMIT)]
 44                                                  =  { nullptr /*, nullptr...*/ };
 45 InstanceKlass* vmClasses::_box_klasses[T_VOID+1] =  { nullptr /*, nullptr...*/ };
 46 
 47 
 48 // CDS: scan and relocate all classes referenced by _klasses[].
 49 void vmClasses::metaspace_pointers_do(MetaspaceClosure* it) {
 50   for (auto id : EnumRange<vmClassID>{}) {
 51     it->push(klass_addr_at(id));
 52   }
 53 }
 54 
 55 bool vmClasses::is_loaded(InstanceKlass* klass) {
 56   return klass != nullptr && klass->is_loaded();
 57 }
 58 
 59 // Compact table of the vmSymbolIDs of all the VM classes (stored as short to save space)
 60 static const short vm_class_name_ids[] = {
 61   #define VM_CLASS_NAME(name, symbol) ((short)VM_SYMBOL_ENUM_NAME(symbol)),
 62   VM_CLASSES_DO(VM_CLASS_NAME)
 63   #undef VM_CLASS_NAME
 64   0
 65 };
 66 
 67 
 68 #ifdef ASSERT
 69 bool vmClasses::contain(Symbol* class_name) {
 70   int sid;
 71   for (int i = 0; (sid = vm_class_name_ids[i]) != 0; i++) {
 72     Symbol* symbol = vmSymbols::symbol_at(vmSymbols::as_SID(sid));
 73     if (class_name == symbol) {
 74       return true;
 75     }
 76   }
 77   return false;
 78 }
 79 
 80 bool vmClasses::contain(Klass* k) {
 81   return contain(k->name());
 82 }
 83 #endif
 84 
 85 bool vmClasses::resolve(vmClassID id, TRAPS) {
 86   InstanceKlass** klassp = &_klasses[as_int(id)];
 87 
 88 #if INCLUDE_CDS
 89   if (UseSharedSpaces && !JvmtiExport::should_post_class_prepare()) {
 90     InstanceKlass* k = *klassp;
 91     assert(k->is_shared_boot_class(), "must be");
 92 
 93     ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 94     resolve_shared_class(k, loader_data, Handle(), CHECK_false);
 95     return true;
 96   }
 97 #endif // INCLUDE_CDS
 98 
 99   if (!is_loaded(*klassp)) {
100     int sid = vm_class_name_ids[as_int(id)];
101     Symbol* symbol = vmSymbols::symbol_at(vmSymbols::as_SID(sid));
102     Klass* k = SystemDictionary::resolve_or_fail(symbol, true, CHECK_false);
103     (*klassp) = InstanceKlass::cast(k);
104   }
105   return ((*klassp) != nullptr);
106 }
107 
108 void vmClasses::resolve_until(vmClassID limit_id, vmClassID &start_id, TRAPS) {
109   assert((int)start_id <= (int)limit_id, "IDs are out of order!");
110   for (auto id : EnumRange<vmClassID>{start_id, limit_id}) { // (inclusive start, exclusive end)
111     resolve(id, CHECK);
112   }
113 
114   // move the starting value forward to the limit:
115   start_id = limit_id;
116 }
117 
118 void vmClasses::resolve_all(TRAPS) {
119   assert(!Object_klass_loaded(), "well-known classes should only be initialized once");
120 
121   // Create the ModuleEntry for java.base.  This call needs to be done here,
122   // after vmSymbols::initialize() is called but before any classes are pre-loaded.
123   ClassLoader::classLoader_init2(THREAD);
124 
125   // Preload commonly used klasses
126   vmClassID scan = vmClassID::FIRST;
127   // first do Object, then String, Class
128   resolve_through(VM_CLASS_ID(Object_klass), scan, CHECK);
129   CollectedHeap::set_filler_object_klass(vmClasses::Object_klass());
130 #if INCLUDE_CDS
131   if (UseSharedSpaces) {
132     // It's unsafe to access the archived heap regions before they
133     // are fixed up, so we must do the fixup as early as possible
134     // before the archived java objects are accessed by functions
135     // such as java_lang_Class::restore_archived_mirror and
136     // ConstantPool::restore_unshareable_info (restores the archived
137     // resolved_references array object).
138     //
139     // ArchiveHeapLoader::fixup_regions fills the empty
140     // spaces in the archived heap regions and may use
141     // vmClasses::Object_klass(), so we can do this only after
142     // Object_klass is resolved. See the above resolve_through()
143     // call. No mirror objects are accessed/restored in the above call.
144     // Mirrors are restored after java.lang.Class is loaded.
145     ArchiveHeapLoader::fixup_region();
146 
147     // Initialize the constant pool for the Object_class
148     assert(Object_klass()->is_shared(), "must be");
149     Object_klass()->constants()->restore_unshareable_info(CHECK);
150     resolve_through(VM_CLASS_ID(Class_klass), scan, CHECK);
151   } else
152 #endif
153   {
154     resolve_through(VM_CLASS_ID(Class_klass), scan, CHECK);
155   }
156 
157   assert(vmClasses::Object_klass() != nullptr, "well-known classes should now be initialized");
158 
159   java_lang_Object::register_natives(CHECK);
160 
161   // Calculate offsets for String and Class classes since they are loaded and
162   // can be used after this point. These are no-op when CDS is enabled.
163   java_lang_String::compute_offsets();
164   java_lang_Class::compute_offsets();
165 
166   // Fixup mirrors for classes loaded before java.lang.Class.
167   Universe::initialize_basic_type_mirrors(CHECK);
168   Universe::fixup_mirrors(CHECK);
169 
170   if (UseSharedSpaces) {
171     // These should already have been initialized during CDS dump.
172     assert(vmClasses::Reference_klass()->reference_type() == REF_NONE, "sanity");
173     assert(vmClasses::SoftReference_klass()->reference_type() == REF_SOFT, "sanity");
174     assert(vmClasses::WeakReference_klass()->reference_type() == REF_WEAK, "sanity");
175     assert(vmClasses::FinalReference_klass()->reference_type() == REF_FINAL, "sanity");
176     assert(vmClasses::PhantomReference_klass()->reference_type() == REF_PHANTOM, "sanity");
177   } else {
178     // If CDS is not enabled, the references classes must be initialized in
179     // this order before the rest of the vmClasses can be resolved.
180     resolve_through(VM_CLASS_ID(Reference_klass), scan, CHECK);
181 
182     // The offsets for jlr.Reference must be computed before
183     // InstanceRefKlass::update_nonstatic_oop_maps is called. That function uses
184     // the offsets to remove the referent and discovered fields from the oop maps,
185     // as they are treated in a special way by the GC. Removing these oops from the
186     // oop maps must be done before the usual subclasses of jlr.Reference are loaded.
187     java_lang_ref_Reference::compute_offsets();
188 
189     // Preload ref klasses and set reference types
190     InstanceRefKlass::update_nonstatic_oop_maps(vmClasses::Reference_klass());
191 
192     resolve_through(VM_CLASS_ID(PhantomReference_klass), scan, CHECK);
193   }
194 
195   resolve_until(vmClassID::LIMIT, scan, CHECK);
196 
197   CollectedHeap::set_filler_object_klass(vmClasses::FillerObject_klass());
198 
199   _box_klasses[T_BOOLEAN] = vmClasses::Boolean_klass();
200   _box_klasses[T_CHAR]    = vmClasses::Character_klass();
201   _box_klasses[T_FLOAT]   = vmClasses::Float_klass();
202   _box_klasses[T_DOUBLE]  = vmClasses::Double_klass();
203   _box_klasses[T_BYTE]    = vmClasses::Byte_klass();
204   _box_klasses[T_SHORT]   = vmClasses::Short_klass();
205   _box_klasses[T_INT]     = vmClasses::Integer_klass();
206   _box_klasses[T_LONG]    = vmClasses::Long_klass();
207   //_box_klasses[T_OBJECT]  = vmClasses::object_klass();
208   //_box_klasses[T_ARRAY]   = vmClasses::object_klass();
209 
210 #ifdef ASSERT
211   if (UseSharedSpaces) {
212     JVMTI_ONLY(assert(JvmtiExport::is_early_phase(),
213                       "All well known classes must be resolved in JVMTI early phase"));
214     for (auto id : EnumRange<vmClassID>{}) {
215       InstanceKlass* k = _klasses[as_int(id)];
216       assert(k->is_shared(), "must not be replaced by JVMTI class file load hook");
217     }
218   }
219 #endif
220 
221   InstanceStackChunkKlass::init_offset_of_stack();
222 }
223 
224 #if INCLUDE_CDS
225 
226 void vmClasses::resolve_shared_class(InstanceKlass* klass, ClassLoaderData* loader_data, Handle domain, TRAPS) {
227   assert(!Universe::is_fully_initialized(), "We can make short cuts only during VM initialization");
228   assert(klass->is_shared(), "Must be shared class");
229   if (klass->class_loader_data() != nullptr) {
230     return;
231   }
232 
233   // add super and interfaces first
234   Klass* super = klass->super();
235   if (super != nullptr && super->class_loader_data() == nullptr) {
236     assert(super->is_instance_klass(), "Super should be instance klass");
237     resolve_shared_class(InstanceKlass::cast(super), loader_data, domain, CHECK);
238   }
239 
240   Array<InstanceKlass*>* ifs = klass->local_interfaces();
241   for (int i = 0; i < ifs->length(); i++) {
242     InstanceKlass* ik = ifs->at(i);
243     if (ik->class_loader_data()  == nullptr) {
244       resolve_shared_class(ik, loader_data, domain, CHECK);
245     }
246   }
247 
248   klass->restore_unshareable_info(loader_data, domain, nullptr, THREAD);
249   SystemDictionary::load_shared_class_misc(klass, loader_data);
250   Dictionary* dictionary = loader_data->dictionary();
251   dictionary->add_klass(THREAD, klass->name(), klass);
252   klass->add_to_hierarchy(THREAD);
253   assert(klass->is_loaded(), "Must be in at least loaded state");
254 }
255 
256 #endif // INCLUDE_CDS
257 
258 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
259 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
260 BasicType vmClasses::box_klass_type(Klass* k) {
261   assert(k != nullptr, "");
262   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
263     if (_box_klasses[i] == k)
264       return (BasicType)i;
265   }
266   return T_OBJECT;
267 }