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