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/aotCacheAccess.hpp"
 26 #include "cds/aotClassInitializer.hpp"
 27 #include "cds/aotClassLinker.hpp"
 28 #include "cds/aotLinkedClassBulkLoader.hpp"
 29 #include "cds/aotLinkedClassTable.hpp"
 30 #include "cds/cdsConfig.hpp"
 31 #include "cds/heapShared.hpp"
 32 #include "classfile/classLoaderData.hpp"
 33 #include "classfile/classLoaderDataShared.hpp"
 34 #include "classfile/javaClasses.hpp"
 35 #include "classfile/systemDictionary.hpp"
 36 #include "classfile/systemDictionaryShared.hpp"
 37 #include "classfile/vmClasses.hpp"
 38 #include "compiler/compilationPolicy.hpp"
 39 #include "gc/shared/gcVMOperations.hpp"
 40 #include "memory/resourceArea.hpp"
 41 #include "oops/instanceKlass.hpp"
 42 #include "oops/klass.inline.hpp"
 43 #include "oops/trainingData.hpp"
 44 #include "runtime/handles.inline.hpp"
 45 #include "runtime/java.hpp"
 46 #include "runtime/perfData.inline.hpp"
 47 #include "runtime/serviceThread.hpp"
 48 #include "utilities/growableArray.hpp"
 49 
 50 static PerfCounter* _perf_classes_preloaded = nullptr;
 51 static PerfTickCounters* _perf_class_preload_counters = nullptr;
 52 
 53 void AOTLinkedClassBulkLoader::serialize(SerializeClosure* soc) {
 54   AOTLinkedClassTable::get()->serialize(soc);
 55 
 56   if (soc->reading() && UsePerfData) {
 57     JavaThread* THREAD = JavaThread::current();
 58     NEWPERFEVENTCOUNTER(_perf_classes_preloaded, SUN_CLS, "preloadedClasses");
 59     NEWPERFTICKCOUNTERS(_perf_class_preload_counters, SUN_CLS, "classPreload");
 60   }
 61 }
 62 
 63 // This function is called before the VM executes any Java code (include AOT-compiled Java methods).
 64 //
 65 // We populate the boot/platform/app class loaders with classes from the AOT cache. This is a fundamental
 66 // step in restoring the JVM's state from the snapshot recorded in the AOT cache: other AOT optimizations
 67 // such as AOT compiled methods can make direct references to the preloaded classes, knowing that
 68 // these classes are guaranteed to be in at least the "loaded" state.
 69 //
 70 // Note: we can't link the classes yet because SharedRuntime is not yet ready to generate adapters.
 71 void AOTLinkedClassBulkLoader::preload_classes(JavaThread* current) {
 72   preload_classes_impl(current);
 73   if (current->has_pending_exception()) {
 74     exit_on_exception(current);
 75   }
 76 }
 77 
 78 void AOTLinkedClassBulkLoader::preload_classes_impl(TRAPS) {
 79   precond(CDSConfig::is_using_aot_linked_classes());
 80 
 81   ClassLoaderDataShared::restore_archived_modules_for_preloading_classes(THREAD);
 82   Handle h_platform_loader(THREAD, SystemDictionary::java_platform_loader());
 83   Handle h_system_loader(THREAD, SystemDictionary::java_system_loader());
 84 
 85   AOTLinkedClassTable* table = AOTLinkedClassTable::get();
 86 
 87   preload_classes_in_table(table->boot1(), "boot1", Handle(), CHECK);
 88   preload_classes_in_table(table->boot2(), "boot2", Handle(), CHECK);
 89 
 90   initiate_loading(THREAD, "plat", h_platform_loader, table->boot1());
 91   initiate_loading(THREAD, "plat", h_platform_loader, table->boot2());
 92   preload_classes_in_table(table->platform(), "plat", h_platform_loader, CHECK);
 93 
 94   initiate_loading(THREAD, "app", h_system_loader, table->boot1());
 95   initiate_loading(THREAD, "app", h_system_loader, table->boot2());
 96   initiate_loading(THREAD, "app", h_system_loader, table->platform());
 97   preload_classes_in_table(table->app(), "app", h_system_loader, CHECK);
 98 }
 99 
100 void AOTLinkedClassBulkLoader::preload_classes_in_table(Array<InstanceKlass*>* classes,
101                                                         const char* category_name, Handle loader, TRAPS) {
102   if (classes == nullptr) {
103     return;
104   }
105 
106   for (int i = 0; i < classes->length(); i++) {
107     if (UsePerfData) {
108       _perf_classes_preloaded->inc();
109     }
110 
111     InstanceKlass* ik = classes->at(i);
112     if (log_is_enabled(Info, aot, load)) {
113       ResourceMark rm(THREAD);
114       log_info(aot, load)("%-5s %s%s", category_name, ik->external_name(),
115                           ik->is_hidden() ? " (hidden)" : "");
116     }
117 
118     SystemDictionary::preload_class(loader, ik, CHECK);
119 
120     if (ik->is_hidden()) {
121       DEBUG_ONLY({
122         // Make sure we don't make this hidden class available by name, even if we don't
123         // use any special ClassLoaderData.
124         ResourceMark rm(THREAD);
125         assert(SystemDictionary::find_instance_klass(THREAD, ik->name(), loader) == nullptr,
126                "hidden classes cannot be accessible by name: %s", ik->external_name());
127       });
128     } else {
129       precond(SystemDictionary::find_instance_klass(THREAD, ik->name(), loader) == ik);
130     }
131   }
132 }
133 
134 // Some cached heap objects may hold references to methods in aot-linked
135 // classes (via MemberName). We need to make sure all classes are
136 // linked before executing any bytecode.
137 void AOTLinkedClassBulkLoader::link_classes(JavaThread* current) {
138   link_classes_impl(current);
139   if (current->has_pending_exception()) {
140     exit_on_exception(current);
141   }
142 }
143 
144 void AOTLinkedClassBulkLoader::link_classes_impl(TRAPS) {
145   precond(CDSConfig::is_using_aot_linked_classes());
146 
147   AOTLinkedClassTable* table = AOTLinkedClassTable::get();
148 
149   link_classes_in_table(table->boot1(), CHECK);
150   link_classes_in_table(table->boot2(), CHECK);
151   link_classes_in_table(table->platform(), CHECK);
152   link_classes_in_table(table->app(), CHECK);
153 }
154 
155 void AOTLinkedClassBulkLoader::link_classes_in_table(Array<InstanceKlass*>* classes, TRAPS) {
156   if (classes != nullptr) {
157     for (int i = 0; i < classes->length(); i++) {
158       // NOTE: CDSConfig::is_preserving_verification_constraints() is required
159       // when storing ik in the AOT cache. This means we don't have to verify
160       // ik at all.
161       //
162       // Without is_preserving_verification_constraints(), ik->link_class() may cause
163       // class loading, which may result in invocation of ClassLoader::loadClass() calls,
164       // which CANNOT happen because we are not ready to execute any Java byecodes yet
165       // at this point.
166       InstanceKlass* ik = classes->at(i);
167       ik->link_class(CHECK);
168     }
169   }
170 }
171 
172 #ifdef ASSERT
173 void AOTLinkedClassBulkLoader::validate_module_of_preloaded_classes() {
174   oop javabase_module_oop = ModuleEntryTable::javabase_moduleEntry()->module_oop();
175   for (int i = T_BOOLEAN; i < T_LONG+1; i++) {
176     TypeArrayKlass* tak = Universe::typeArrayKlass((BasicType)i);
177     validate_module(tak, "boot1", javabase_module_oop);
178   }
179 
180   JavaThread* current = JavaThread::current();
181   Handle h_platform_loader(current, SystemDictionary::java_platform_loader());
182   Handle h_system_loader(current, SystemDictionary::java_system_loader());
183   AOTLinkedClassTable* table = AOTLinkedClassTable::get();
184 
185   validate_module_of_preloaded_classes_in_table(table->boot1(), "boot1", Handle());
186   validate_module_of_preloaded_classes_in_table(table->boot2(), "boot2", Handle());
187   validate_module_of_preloaded_classes_in_table(table->platform(), "plat", h_platform_loader);
188   validate_module_of_preloaded_classes_in_table(table->app(), "app", h_system_loader);
189 }
190 
191 void AOTLinkedClassBulkLoader::validate_module_of_preloaded_classes_in_table(Array<InstanceKlass*>* classes,
192                                                                              const char* category_name, Handle loader) {
193   if (classes == nullptr) {
194     return;
195   }
196 
197   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(loader());
198   for (int i = 0; i < classes->length(); i++) {
199     InstanceKlass* ik = classes->at(i);
200     PackageEntry* pkg_entry = ik->package();
201     oop module_oop;
202     if (pkg_entry == nullptr) {
203       module_oop = loader_data->unnamed_module()->module_oop();
204     } else {
205       module_oop = pkg_entry->module()->module_oop();
206     }
207 
208     validate_module(ik, category_name, module_oop);
209   }
210 }
211 
212 void AOTLinkedClassBulkLoader::validate_module(Klass* k, const char* category_name, oop module_oop) {
213   assert(module_oop != nullptr, "module system must have been initialized");
214 
215   if (log_is_enabled(Debug, aot, module)) {
216     ResourceMark rm;
217     log_debug(aot, module)("Validate module of %-5s %s", category_name, k->external_name());
218   }
219   precond(java_lang_Class::module(k->java_mirror()) == module_oop);
220 
221   ArrayKlass* ak = k->array_klass_or_null();
222   while (ak != nullptr) {
223     if (log_is_enabled(Debug, aot, module)) {
224       ResourceMark rm;
225       log_debug(aot, module)("Validate module of %-5s %s", category_name, ak->external_name());
226     }
227     precond(java_lang_Class::module(ak->java_mirror()) == module_oop);
228     ak = ak->array_klass_or_null();
229   }
230 }
231 #endif
232 
233 void AOTLinkedClassBulkLoader::init_javabase_classes(JavaThread* current) {
234   init_classes_for_loader(Handle(), AOTLinkedClassTable::get()->boot1(), current);
235   if (current->has_pending_exception()) {
236     exit_on_exception(current);
237   }
238 }
239 
240 void AOTLinkedClassBulkLoader::init_non_javabase_classes(JavaThread* current) {
241   init_non_javabase_classes_impl(current);
242   if (current->has_pending_exception()) {
243     exit_on_exception(current);
244   }
245 }
246 
247 void AOTLinkedClassBulkLoader::init_non_javabase_classes_impl(TRAPS) {
248   assert(CDSConfig::is_using_aot_linked_classes(), "sanity");
249 
250   DEBUG_ONLY(validate_module_of_preloaded_classes());
251 
252   // is_using_aot_linked_classes() requires is_using_full_module_graph(). As a result,
253   // the platform/system class loader should already have been initialized as part
254   // of the FMG support.
255   assert(CDSConfig::is_using_full_module_graph(), "must be");
256 
257   Handle h_platform_loader(THREAD, SystemDictionary::java_platform_loader());
258   Handle h_system_loader(THREAD, SystemDictionary::java_system_loader());
259 
260   assert(h_platform_loader() != nullptr, "must be");
261   assert(h_system_loader() != nullptr,   "must be");
262 
263   AOTLinkedClassTable* table = AOTLinkedClassTable::get();
264   init_classes_for_loader(Handle(), table->boot2(), CHECK);
265   init_classes_for_loader(h_platform_loader, table->platform(), CHECK);
266   init_classes_for_loader(h_system_loader, table->app(), CHECK);
267 
268   if (Universe::is_fully_initialized() && VerifyDuringStartup) {
269     // Make sure we're still in a clean state.
270     VM_Verify verify_op;
271     VMThread::execute(&verify_op);
272   }
273 
274   if (AOTPrintTrainingInfo) {
275     tty->print_cr("==================== archived_training_data ** after all classes preloaded ====================");
276     TrainingData::print_archived_training_data_on(tty);
277   }
278 }
279 
280 // For the AOT cache to function properly, all classes in the AOTLinkedClassTable
281 // must be loaded and linked. In addition, AOT-initialized classes must be moved to
282 // the initialized state.
283 //
284 // We can encounter a failure during the loading, linking, or initialization of
285 // classes in the AOTLinkedClassTable only if:
286 //   - We ran out of memory,
287 //   - There is a serious error in the VM implemenation
288 // When this happens, the VM may be in an inconsistent state (e.g., we have a cached
289 // heap object of class X, but X is not linked). We must exit the JVM now.
290 
291 void AOTLinkedClassBulkLoader::exit_on_exception(JavaThread* current) {
292   assert(current->has_pending_exception(), "precondition");
293   ResourceMark rm(current);
294   if (current->pending_exception()->is_a(vmClasses::OutOfMemoryError_klass())) {
295     log_error(aot)("Out of memory. Please run with a larger Java heap, current MaxHeapSize = "
296                    "%zuM", MaxHeapSize/M);
297   } else {
298     oop message = java_lang_Throwable::message(current->pending_exception());
299     log_error(aot)("%s: %s", current->pending_exception()->klass()->external_name(),
300                    message == nullptr ? "(no message)" : java_lang_String::as_utf8_string(message));
301   }
302   vm_exit_during_initialization("Unexpected exception when loading aot-linked classes.");
303 }
304 
305 // Initiate loading of the <classes> in the <initiating_loader>. The <classes> should have already been loaded
306 // by a parent loader of the <initiating_loader>. This is necessary for handling pre-resolved CP entries.
307 //
308 // For example, we initiate the loading of java/lang/String in the AppClassLoader. This will allow
309 // any App classes to have a pre-resolved ConstantPool entry that references java/lang/String.
310 //
311 // TODO: we can limit the number of initiated classes to only those that are actually referenced by
312 // AOT-linked classes loaded by <initiating_loader>.
313 void AOTLinkedClassBulkLoader::initiate_loading(JavaThread* current, const char* category_name,
314                                                 Handle initiating_loader, Array<InstanceKlass*>* classes) {
315   if (classes == nullptr) {
316     return;
317   }
318 
319   assert(initiating_loader() == SystemDictionary::java_platform_loader() ||
320          initiating_loader() == SystemDictionary::java_system_loader(), "must be");
321   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(initiating_loader());
322   MonitorLocker mu1(SystemDictionary_lock);
323 
324   for (int i = 0; i < classes->length(); i++) {
325     InstanceKlass* ik = classes->at(i);
326     assert(ik->is_loaded(), "must have already been loaded by a parent loader");
327     assert(ik->class_loader() != initiating_loader(), "must be a parent loader");
328     assert(ik->class_loader() == nullptr ||
329            ik->class_loader() == SystemDictionary::java_platform_loader(), "must be");
330     if (ik->is_public() && !ik->is_hidden()) {
331       if (log_is_enabled(Info, aot, load)) {
332         ResourceMark rm(current);
333         const char* defining_loader = (ik->class_loader() == nullptr ? "boot" : "plat");
334         log_info(aot, load)("%-5s %s (initiated, defined by %s)", category_name, ik->external_name(),
335                             defining_loader);
336       }
337       SystemDictionary::add_to_initiating_loader(current, ik, loader_data);
338     }
339   }
340 }
341 
342 // Some AOT-linked classes for <class_loader> must be initialized early. This includes
343 // - classes that were AOT-initialized by AOTClassInitializer
344 // - the classes of all objects that are reachable from the archived mirrors of
345 //   the AOT-linked classes for <class_loader>.
346 void AOTLinkedClassBulkLoader::init_classes_for_loader(Handle class_loader, Array<InstanceKlass*>* classes, TRAPS) {
347   if (classes != nullptr) {
348     for (int i = 0; i < classes->length(); i++) {
349       InstanceKlass* ik = classes->at(i);
350       assert(ik->class_loader_data() != nullptr, "must be");
351       if (ik->has_aot_initialized_mirror()) {
352         ik->initialize_with_aot_initialized_mirror(CHECK);
353       }
354     }
355   }
356 
357   HeapShared::init_classes_for_special_subgraph(class_loader, CHECK);
358 }
359 
360 void AOTLinkedClassBulkLoader::replay_training_at_init(Array<InstanceKlass*>* classes, TRAPS) {
361   if (classes != nullptr) {
362     for (int i = 0; i < classes->length(); i++) {
363       InstanceKlass* ik = classes->at(i);
364       if (ik->has_aot_initialized_mirror() && ik->is_initialized() && !ik->has_init_deps_processed()) {
365         CompilationPolicy::replay_training_at_init(ik, CHECK);
366       }
367     }
368   }
369 }
370 
371 void AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(TRAPS) {
372   if (CDSConfig::is_using_aot_linked_classes() && TrainingData::have_data()) {
373     AOTLinkedClassTable* table = AOTLinkedClassTable::get();
374     replay_training_at_init(table->boot1(),    CHECK);
375     replay_training_at_init(table->boot2(),    CHECK);
376     replay_training_at_init(table->platform(), CHECK);
377     replay_training_at_init(table->app(),      CHECK);
378   }
379 }
380 
381 void AOTLinkedClassBulkLoader::print_counters_on(outputStream* st) {
382   if (UsePerfData && _perf_class_preload_counters != nullptr) {
383     st->print_cr("AOTLinkedClassBulkLoader:");
384     st->print_cr("  preload:           " JLONG_FORMAT_W(6) "us (elapsed) " JLONG_FORMAT_W(6) " (thread) / " JLONG_FORMAT_W(5) " events",
385                  _perf_class_preload_counters->elapsed_counter_value_us(),
386                  _perf_class_preload_counters->thread_counter_value_us(),
387                  _perf_classes_preloaded->get_value());
388   }
389 }