1 /*
  2  * Copyright (c) 2024, 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/aotClassInitializer.hpp"
 26 #include "cds/aotClassLinker.hpp"
 27 #include "cds/aotLinkedClassBulkLoader.hpp"
 28 #include "cds/aotLinkedClassTable.hpp"
 29 #include "cds/cdsConfig.hpp"
 30 #include "cds/heapShared.hpp"
 31 #include "classfile/classLoaderData.hpp"
 32 #include "classfile/systemDictionary.hpp"
 33 #include "classfile/systemDictionaryShared.hpp"
 34 #include "classfile/vmClasses.hpp"
 35 #include "compiler/compilationPolicy.hpp"
 36 #include "gc/shared/gcVMOperations.hpp"
 37 #include "memory/resourceArea.hpp"
 38 #include "oops/instanceKlass.hpp"
 39 #include "oops/klass.inline.hpp"
 40 #include "oops/trainingData.hpp"
 41 #include "runtime/handles.inline.hpp"
 42 #include "runtime/java.hpp"
 43 
 44 bool AOTLinkedClassBulkLoader::_boot2_completed = false;
 45 bool AOTLinkedClassBulkLoader::_platform_completed = false;
 46 bool AOTLinkedClassBulkLoader::_app_completed = false;
 47 bool AOTLinkedClassBulkLoader::_all_completed = false;
 48 
 49 void AOTLinkedClassBulkLoader::serialize(SerializeClosure* soc, bool is_static_archive) {
 50   AOTLinkedClassTable::get(is_static_archive)->serialize(soc);
 51 }
 52 
 53 bool AOTLinkedClassBulkLoader::class_preloading_finished() {
 54   if (!CDSConfig::is_using_aot_linked_classes()) {
 55     return true;
 56   } else {
 57     // The ConstantPools of preloaded classes have references to other preloaded classes. We don't
 58     // want any Java code (including JVMCI compiler) to use these classes until all of them
 59     // are loaded.
 60     return Atomic::load_acquire(&_all_completed);
 61   }
 62 }
 63 
 64 void AOTLinkedClassBulkLoader::load_javabase_classes(JavaThread* current) {
 65   assert(CDSConfig::is_using_aot_linked_classes(), "sanity");
 66   load_classes_in_loader(current, AOTLinkedClassCategory::BOOT1, nullptr); // only java.base classes
 67 }
 68 
 69 void AOTLinkedClassBulkLoader::load_non_javabase_classes(JavaThread* current) {
 70   assert(CDSConfig::is_using_aot_linked_classes(), "sanity");
 71 
 72   // is_using_aot_linked_classes() requires is_using_full_module_graph(). As a result,
 73   // the platform/system class loader should already have been initialized as part
 74   // of the FMG support.
 75   assert(CDSConfig::is_using_full_module_graph(), "must be");
 76   assert(SystemDictionary::java_platform_loader() != nullptr, "must be");
 77   assert(SystemDictionary::java_system_loader() != nullptr,   "must be");
 78 
 79   load_classes_in_loader(current, AOTLinkedClassCategory::BOOT2, nullptr); // all boot classes outside of java.base
 80   _boot2_completed = true;
 81 
 82   load_classes_in_loader(current, AOTLinkedClassCategory::PLATFORM, SystemDictionary::java_platform_loader());
 83   _platform_completed = true;
 84 
 85   load_classes_in_loader(current, AOTLinkedClassCategory::APP, SystemDictionary::java_system_loader());
 86 
 87   if (AOTPrintTrainingInfo) {
 88     tty->print_cr("==================== archived_training_data ** after all classes preloaded ====================");
 89     TrainingData::print_archived_training_data_on(tty);
 90   }
 91 
 92   _app_completed = true;
 93   Atomic::release_store(&_all_completed, true);
 94 }
 95 
 96 void AOTLinkedClassBulkLoader::load_classes_in_loader(JavaThread* current, AOTLinkedClassCategory class_category, oop class_loader_oop) {
 97   load_classes_in_loader_impl(class_category, class_loader_oop, current);
 98   if (current->has_pending_exception()) {
 99     // We cannot continue, as we might have loaded some of the aot-linked classes, which
100     // may have dangling C++ pointers to other aot-linked classes that we have failed to load.
101     exit_on_exception(current);
102   }
103 }
104 
105 void AOTLinkedClassBulkLoader::exit_on_exception(JavaThread* current) {
106   assert(current->has_pending_exception(), "precondition");
107   ResourceMark rm(current);
108   if (current->pending_exception()->is_a(vmClasses::OutOfMemoryError_klass())) {
109     log_error(aot)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
110                    "%zuM", MaxHeapSize/M);
111   } else {
112     log_error(aot)("%s: %s", current->pending_exception()->klass()->external_name(),
113                    java_lang_String::as_utf8_string(java_lang_Throwable::message(current->pending_exception())));
114   }
115   vm_exit_during_initialization("Unexpected exception when loading aot-linked classes.");
116 }
117 
118 void AOTLinkedClassBulkLoader::load_classes_in_loader_impl(AOTLinkedClassCategory class_category, oop class_loader_oop, TRAPS) {
119   Handle h_loader(THREAD, class_loader_oop);
120   load_table(AOTLinkedClassTable::for_static_archive(),  class_category, h_loader, CHECK);
121   load_table(AOTLinkedClassTable::for_dynamic_archive(), class_category, h_loader, CHECK);
122 
123   // Initialize the InstanceKlasses of all archived heap objects that are reachable from the
124   // archived java class mirrors.
125   //
126   // Only the classes in the static archive can have archived mirrors.
127   AOTLinkedClassTable* static_table = AOTLinkedClassTable::for_static_archive();
128   switch (class_category) {
129   case AOTLinkedClassCategory::BOOT1:
130     // Delayed until finish_loading_javabase_classes(), as the VM is not ready to
131     // execute some of the <clinit> methods.
132     break;
133   case AOTLinkedClassCategory::BOOT2:
134     init_required_classes_for_loader(h_loader, static_table->boot2(), CHECK);
135     break;
136   case AOTLinkedClassCategory::PLATFORM:
137     init_required_classes_for_loader(h_loader, static_table->platform(), CHECK);
138     break;
139   case AOTLinkedClassCategory::APP:
140     init_required_classes_for_loader(h_loader, static_table->app(), CHECK);
141     break;
142   case AOTLinkedClassCategory::UNREGISTERED:
143     ShouldNotReachHere();
144     break;
145   }
146 
147   if (Universe::is_fully_initialized() && VerifyDuringStartup) {
148     // Make sure we're still in a clean state.
149     VM_Verify verify_op;
150     VMThread::execute(&verify_op);
151   }
152 }
153 
154 void AOTLinkedClassBulkLoader::load_table(AOTLinkedClassTable* table, AOTLinkedClassCategory class_category, Handle loader, TRAPS) {
155   if (class_category != AOTLinkedClassCategory::BOOT1) {
156     assert(Universe::is_module_initialized(), "sanity");
157   }
158 
159   const char* category_name = AOTClassLinker::class_category_name(class_category);
160   switch (class_category) {
161   case AOTLinkedClassCategory::BOOT1:
162     load_classes_impl(class_category, table->boot(), category_name, loader, CHECK);
163     break;
164 
165   case AOTLinkedClassCategory::BOOT2:
166     load_classes_impl(class_category, table->boot2(), category_name, loader, CHECK);
167     break;
168 
169   case AOTLinkedClassCategory::PLATFORM:
170     {
171       initiate_loading(THREAD, category_name, loader, table->boot());
172       initiate_loading(THREAD, category_name, loader, table->boot2());
173       load_classes_impl(class_category, table->platform(), category_name, loader, CHECK);
174     }
175     break;
176   case AOTLinkedClassCategory::APP:
177     {
178       initiate_loading(THREAD, category_name, loader, table->boot());
179       initiate_loading(THREAD, category_name, loader, table->boot2());
180       initiate_loading(THREAD, category_name, loader, table->platform());
181       load_classes_impl(class_category, table->app(), category_name, loader, CHECK);
182     }
183     break;
184   case AOTLinkedClassCategory::UNREGISTERED:
185   default:
186     ShouldNotReachHere(); // Currently aot-linked classes are not supported for this category.
187     break;
188   }
189 }
190 
191 void AOTLinkedClassBulkLoader::load_classes_impl(AOTLinkedClassCategory class_category, Array<InstanceKlass*>* classes,
192                                                  const char* category_name, Handle loader, TRAPS) {
193   if (classes == nullptr) {
194     return;
195   }
196 
197   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(loader());
198 
199   for (int i = 0; i < classes->length(); i++) {
200     InstanceKlass* ik = classes->at(i);
201     if (log_is_enabled(Info, aot, load)) {
202       ResourceMark rm(THREAD);
203       log_info(aot, load)("%-5s %s%s%s", category_name, ik->external_name(),
204                           ik->is_loaded() ? " (already loaded)" : "",
205                           ik->is_hidden() ? " (hidden)" : "");
206     }
207 
208     if (!ik->is_loaded()) {
209       if (ik->is_hidden()) {
210         load_hidden_class(loader_data, ik, CHECK);
211       } else {
212         InstanceKlass* actual;
213         if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
214           actual = SystemDictionary::load_instance_class(ik->name(), loader, CHECK);
215         } else {
216           actual = SystemDictionaryShared::find_or_load_shared_class(ik->name(), loader, CHECK);
217         }
218 
219         if (actual != ik) {
220           ResourceMark rm(THREAD);
221           log_error(aot)("Unable to resolve %s class from %s: %s", category_name, CDSConfig::type_of_archive_being_loaded(), ik->external_name());
222           log_error(aot)("Expected: " INTPTR_FORMAT ", actual: " INTPTR_FORMAT, p2i(ik), p2i(actual));
223           log_error(aot)("JVMTI class retransformation is not supported when archive was generated with -XX:+AOTClassLinking.");
224           MetaspaceShared::unrecoverable_loading_error();
225         }
226         assert(actual->is_loaded(), "must be");
227       }
228     }
229   }
230 }
231 
232 // Initiate loading of the <classes> in the <initiating_loader>. The <classes> should have already been loaded
233 // by a parent loader of the <initiating_loader>. This is necessary for handling pre-resolved CP entries.
234 //
235 // For example, we initiate the loading of java/lang/String in the AppClassLoader. This will allow
236 // any App classes to have a pre-resolved ConstantPool entry that references java/lang/String.
237 //
238 // TODO: we can limit the number of initiated classes to only those that are actually referenced by
239 // AOT-linked classes loaded by <initiating_loader>.
240 void AOTLinkedClassBulkLoader::initiate_loading(JavaThread* current, const char* category_name,
241                                                 Handle initiating_loader, Array<InstanceKlass*>* classes) {
242   if (classes == nullptr) {
243     return;
244   }
245 
246   assert(initiating_loader() == SystemDictionary::java_platform_loader() ||
247          initiating_loader() == SystemDictionary::java_system_loader(), "must be");
248   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(initiating_loader());
249   MonitorLocker mu1(SystemDictionary_lock);
250 
251   for (int i = 0; i < classes->length(); i++) {
252     InstanceKlass* ik = classes->at(i);
253     assert(ik->is_loaded(), "must have already been loaded by a parent loader");
254     assert(ik->class_loader() != initiating_loader(), "must be a parent loader");
255     assert(ik->class_loader() == nullptr ||
256            ik->class_loader() == SystemDictionary::java_platform_loader(), "must be");
257     if (ik->is_public() && !ik->is_hidden()) {
258       if (log_is_enabled(Info, aot, load)) {
259         ResourceMark rm(current);
260         const char* defining_loader = (ik->class_loader() == nullptr ? "boot" : "plat");
261         log_info(aot, load)("%s %s (initiated, defined by %s)", category_name, ik->external_name(),
262                             defining_loader);
263       }
264       SystemDictionary::add_to_initiating_loader(current, ik, loader_data);
265     }
266   }
267 }
268 
269 // Currently, we archive only three types of hidden classes:
270 //    - LambdaForms
271 //    - lambda proxy classes
272 //    - StringConcat classes
273 // See HeapShared::is_archivable_hidden_klass().
274 //
275 // LambdaForm classes (with names like java/lang/invoke/LambdaForm$MH+0x800000015) logically
276 // belong to the boot loader, but they are usually stored in their own special ClassLoaderData to
277 // facilitate class unloading, as a LambdaForm may refer to a class loaded by a custom loader
278 // that may be unloaded.
279 //
280 // We only support AOT-resolution of indys in the boot/platform/app loader, so there's no need
281 // to support class unloading. For simplicity, we put all archived LambdaForm classes in the
282 // "main" ClassLoaderData of the boot loader.
283 //
284 // (Even if we were to support other loaders, we would still feel free to ignore any requirement
285 // of class unloading, for any class asset in the AOT cache.  Anything that makes it into the AOT
286 // cache has a lifetime dispensation from unloading.  After all, the AOT cache never grows, and
287 // we can assume that the user is content with its size, and doesn't need its footprint to shrink.)
288 //
289 // Lambda proxy classes are normally stored in the same ClassLoaderData as their nest hosts, and
290 // StringConcat are normally stored in the main ClassLoaderData of the boot class loader. We
291 // do the same for the archived copies of such classes.
292 void AOTLinkedClassBulkLoader::load_hidden_class(ClassLoaderData* loader_data, InstanceKlass* ik, TRAPS) {
293   assert(HeapShared::is_lambda_form_klass(ik) ||
294          HeapShared::is_lambda_proxy_klass(ik) ||
295          HeapShared::is_string_concat_klass(ik), "sanity");
296   DEBUG_ONLY({
297       assert(ik->java_super()->is_loaded(), "must be");
298       for (int i = 0; i < ik->local_interfaces()->length(); i++) {
299         assert(ik->local_interfaces()->at(i)->is_loaded(), "must be");
300       }
301     });
302 
303   Handle pd;
304   PackageEntry* pkg_entry = nullptr;
305 
306   // Since a hidden class does not have a name, it cannot be reloaded
307   // normally via the system dictionary. Instead, we have to finish the
308   // loading job here.
309 
310   if (HeapShared::is_lambda_proxy_klass(ik)) {
311     InstanceKlass* nest_host = ik->nest_host_not_null();
312     assert(nest_host->is_loaded(), "must be");
313     pd = Handle(THREAD, nest_host->protection_domain());
314     pkg_entry = nest_host->package();
315   }
316 
317   ik->restore_unshareable_info(loader_data, pd, pkg_entry, CHECK);
318   SystemDictionary::load_shared_class_misc(ik, loader_data);
319   ik->add_to_hierarchy(THREAD);
320   assert(ik->is_loaded(), "Must be in at least loaded state");
321 
322   DEBUG_ONLY({
323       // Make sure we don't make this hidden class available by name, even if we don't
324       // use any special ClassLoaderData.
325       Handle loader(THREAD, loader_data->class_loader());
326       ResourceMark rm(THREAD);
327       assert(SystemDictionary::resolve_or_null(ik->name(), loader, THREAD) == nullptr,
328              "hidden classes cannot be accessible by name: %s", ik->external_name());
329       if (HAS_PENDING_EXCEPTION) {
330         CLEAR_PENDING_EXCEPTION;
331       }
332     });
333 }
334 
335 void AOTLinkedClassBulkLoader::finish_loading_javabase_classes(TRAPS) {
336   init_required_classes_for_loader(Handle(), AOTLinkedClassTable::for_static_archive()->boot(), CHECK);
337 }
338 
339 // Some AOT-linked classes for <class_loader> must be initialized early. This includes
340 // - classes that were AOT-initialized by AOTClassInitializer
341 // - the classes of all objects that are reachable from the archived mirrors of
342 //   the AOT-linked classes for <class_loader>.
343 void AOTLinkedClassBulkLoader::init_required_classes_for_loader(Handle class_loader, Array<InstanceKlass*>* classes, TRAPS) {
344   if (classes != nullptr) {
345     for (int i = 0; i < classes->length(); i++) {
346       InstanceKlass* ik = classes->at(i);
347       if (ik->class_loader_data() == nullptr) {
348         // This class is not yet loaded. We will initialize it in a later phase.
349         // For example, we have loaded only AOTLinkedClassCategory::BOOT1 classes
350         // but k is part of AOTLinkedClassCategory::BOOT2.
351         continue;
352       }
353       if (ik->has_aot_initialized_mirror()) {
354         ik->initialize_with_aot_initialized_mirror(CHECK);
355       } else {
356         // Some cached heap objects may hold references to methods in aot-linked
357         // classes (via MemberName). We need to make sure all classes are
358         // linked to allow such MemberNames to be invoked.
359         ik->link_class(CHECK);
360       }
361     }
362   }
363 
364   HeapShared::init_classes_for_special_subgraph(class_loader, CHECK);
365 }
366 
367 bool AOTLinkedClassBulkLoader::is_pending_aot_linked_class(Klass* k) {
368   if (!CDSConfig::is_using_aot_linked_classes()) {
369     return false;
370   }
371 
372   if (_all_completed) { // no more pending aot-linked classes
373     return false;
374   }
375 
376   if (k->is_objArray_klass()) {
377     k = ObjArrayKlass::cast(k)->bottom_klass();
378   }
379   if (!k->is_instance_klass()) {
380     // type array klasses (and their higher dimensions),
381     // must have been loaded before a GC can ever happen.
382     return false;
383   }
384 
385   // There's a small window during VM start-up where a not-yet loaded aot-linked
386   // class k may be discovered by the GC during VM initialization. This can happen
387   // when the heap contains an aot-cached instance of k, but k is not ready to be
388   // loaded yet. (TODO: JDK-8342429 eliminates this possibility)
389   //
390   // The following checks try to limit this window as much as possible for each of
391   // the four AOTLinkedClassCategory of classes that can be aot-linked.
392 
393   InstanceKlass* ik = InstanceKlass::cast(k);
394   if (ik->defined_by_boot_loader()) {
395     if (ik->module() != nullptr && ik->in_javabase_module()) {
396       // AOTLinkedClassCategory::BOOT1 -- all aot-linked classes in
397       // java.base must have been loaded before a GC can ever happen.
398       return false;
399     } else {
400       // AOTLinkedClassCategory::BOOT2 classes cannot be loaded until
401       // module system is ready.
402       return !_boot2_completed;
403     }
404   } else if (ik->defined_by_platform_loader()) {
405     // AOTLinkedClassCategory::PLATFORM classes cannot be loaded until
406     // the platform class loader is initialized.
407     return !_platform_completed;
408   } else if (ik->defined_by_app_loader()) {
409     // AOTLinkedClassCategory::APP cannot be loaded until the app class loader
410     // is initialized.
411     return !_app_completed;
412   } else {
413     return false;
414   }
415 }
416 
417 void AOTLinkedClassBulkLoader::replay_training_at_init(Array<InstanceKlass*>* classes, TRAPS) {
418   if (classes != nullptr) {
419     for (int i = 0; i < classes->length(); i++) {
420       InstanceKlass* ik = classes->at(i);
421       if (ik->has_aot_initialized_mirror() && ik->is_initialized() && !ik->has_init_deps_processed()) {
422         CompilationPolicy::replay_training_at_init(ik, CHECK);
423       }
424     }
425   }
426 }
427 
428 void AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(TRAPS) {
429   if (CDSConfig::is_using_aot_linked_classes() && TrainingData::have_data()) {
430     // Only static archive can have training data.
431     AOTLinkedClassTable* table = AOTLinkedClassTable::for_static_archive();
432     replay_training_at_init(table->boot(),     CHECK);
433     replay_training_at_init(table->boot2(),    CHECK);
434     replay_training_at_init(table->platform(), CHECK);
435     replay_training_at_init(table->app(),      CHECK);
436   }
437 }