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/archiveBuilder.hpp"
 27 #include "cds/cdsConfig.hpp"
 28 #include "cds/heapShared.hpp"
 29 #include "cds/regeneratedClasses.hpp"
 30 #include "classfile/symbolTable.hpp"
 31 #include "classfile/systemDictionaryShared.hpp"
 32 #include "classfile/vmSymbols.hpp"
 33 #include "dumpTimeClassInfo.inline.hpp"
 34 #include "memory/resourceArea.hpp"
 35 #include "oops/fieldStreams.inline.hpp"
 36 #include "oops/instanceKlass.inline.hpp"
 37 #include "oops/symbol.hpp"
 38 #include "runtime/fieldDescriptor.inline.hpp"
 39 #include "runtime/java.hpp"
 40 #include "runtime/javaCalls.hpp"
 41 #include "runtime/mutexLocker.hpp"
 42 
 43 DEBUG_ONLY(InstanceKlass* _aot_init_class = nullptr;)
 44 
 45 bool AOTClassInitializer::can_archive_initialized_mirror(InstanceKlass* ik) {
 46   assert(!ArchiveBuilder::is_active() || !ArchiveBuilder::current()->is_in_buffer_space(ik), "must be source klass");
 47   if (!CDSConfig::is_initing_classes_at_dump_time()) {
 48     return false;
 49   }
 50 
 51   if (RegeneratedClasses::is_regenerated_object(ik)) {
 52     ik = RegeneratedClasses::get_original_object(ik);
 53   }
 54 
 55   if (!ik->is_initialized() && !ik->is_being_initialized()) {
 56     return false;
 57   }
 58 
 59   // About "static field that may hold a different value" errors:
 60   //
 61   // Automatic selection for aot-inited classes
 62   // ==========================================
 63   //
 64   // When CDSConfig::is_initing_classes_at_dump_time is enabled,
 65   // AOTArtifactFinder::find_artifacts() finds the classes of all
 66   // heap objects that are reachable from HeapShared::_run_time_special_subgraph,
 67   // and mark these classes as aot-inited. This preserves the initialized
 68   // mirrors of these classes, and their <clinit> methods are NOT executed
 69   // at runtime. See aotArtifactFinder.hpp for more info.
 70   //
 71   // For example, with -XX:+AOTInvokeDynamicLinking, _run_time_special_subgraph
 72   // will contain some DirectMethodHandle objects. As a result, the DirectMethodHandle
 73   // class is automatically marked as aot-inited.
 74   //
 75   // When a class is aot-inited, its static fields are already set up
 76   // by executing the <clinit> method at AOT assembly time.  Later on
 77   // in the production run, when the class would normally be
 78   // initialized, the VM performs guarding and synchronization as if
 79   // it were going to run the <clinit> again, but instead it simply
 80   // observes that that class was aot-inited.  The VM assumes that, if
 81   // it were to run <clinit> again, it would get a semantically
 82   // equivalent set of final field values, so it just adopts the
 83   // existing field values (from AOT assembly) and skips the call to
 84   // <clinit>.  There may at that point be fixups performed by ad hoc
 85   // code, if the VM recognizes a request in the library.
 86   //
 87   // It is true that this is not generally correct for all possible
 88   // Java code.  A <clinit> method might have a side effect beyond
 89   // initializing the static fields.  It might send an email somewhere
 90   // noting the current time of day.  In that case, such an email
 91   // would have been sent during the AOT assembly phase, and the email
 92   // would NOT be sent again during production.  This is clearly NOT
 93   // what a user would want, if this were a general purpose facility.
 94   // But in fact it is only for certain well-behaved classes, which
 95   // are known NOT to have such side effects.  We know this because
 96   // the optimization (of skipping <clinit> for aot-init classes) is
 97   // only applied to classes fully defined by the JDK.
 98   //
 99   // (A day may come when we figure out how to gracefully extend this
100   // optimization to untrusted third parties, but it is not this day.)
101   //
102   // Manual selection
103   // ================
104   //
105   // There are important cases where one aot-init class has a side
106   // effect on another aot-class, a side effect which is not captured
107   // in any static field value in either class.  The simplest example
108   // is class A forces the initialization of class B.  In that case,
109   // we need to aot-init either both classes or neither.  From looking
110   // at the JDK state after AOT assembly is done, it is hard to tell
111   // that A "touched" B and B might escape our notice.  Another common
112   // example is A copying a field value from B.  We don't know where A
113   // got the value, but it would be wrong to re-initialize B at
114   // startup, while keeping the snapshot of the old B value in A.  In
115   // general, if we aot-init A, we need to aot-init every class B that
116   // somehow contributed to A's initial state, and every class C that
117   // was somehow side-effected by A's initialization.  We say that the
118   // aot-init of A is "init-coupled" to those of B and C.
119   //
120   // So there are init-coupled classes that cannot be automatically discovered. For
121   // example, DirectMethodHandle::IMPL_NAMES points to MethodHandles::IMPL_NAMES,
122   // but the MethodHandles class is not automatically marked because there are
123   // no archived instances of the MethodHandles type.
124   //
125   // If we aot-initialize DirectMethodHandle, but allow MethodHandles to be
126   // initialized at runtime, MethodHandles::IMPL_NAMES will get a different
127   // value than DirectMethodHandle::IMPL_NAMES. This *may or may not* be a problem,
128   // but to ensure compatibility, we should try to preserve the identity equality
129   // of these two fields.
130   //
131   // To do that, we add MethodHandles to the indy_specs[] table below.
132   //
133   // Luckily we do not need to be all-knowing in order to choose which
134   // items to add to that table.  We have tools to help detect couplings.
135   //
136   // Automatic validation
137   // ====================
138   //
139   // CDSHeapVerifier is used to detect potential problems with identity equality.
140   //
141   // A class B is assumed to be init-coupled to some aot-init class if
142   // B has a field which points to a live object X in the AOT heap.
143   // The live object X was created by some other class A which somehow
144   // used B's reference to X, perhaps with the help of an intermediate
145   // class Z.  Or, B pulled the reference to X from some other class
146   // Y, and B obtained that reference from Y (or an intermediate Z).
147   // It is not certain how X got into the heap, nor whether B
148   // contributed it, but it is a good heuristic that B is init-coupled
149   // to X's class or some other aot-init class.  In any case, B should
150   // be made an aot-init class as well, unless a manual inspection
151   // shows that would be a problem.  If there is a problem, then the
152   // JDK code for B and/or X probably needs refactoring.  If there is
153   // no problem, we add B to the list.  Typically the same scan will
154   // find any other accomplices Y, Z, etc.  One failure would be a
155   // class Q whose only initialization action is to scribble a special
156   // value into B, from which the value X is derived and then makes
157   // its way into the heap.  In that case, the heuristic does not
158   // identify Q.  It is (currently) a human responsibility, of JDK
159   // engineers, not to write such dirty JDK code, or to repair it if
160   // it crops up.  Eventually we may have tools, or even a user mode
161   // with design rules and checks, that will vet our code base more
162   // automatically.
163   //
164   // To see how the tool detects the problem with MethodHandles::IMPL_NAMES:
165   //
166   // - Comment out all the lines in indy_specs[] except the {nullptr} line.
167   // - Rebuild the JDK
168   //
169   // Then run the following:
170   //    java -XX:AOTMode=record -XX:AOTConfiguration=jc.aotconfig com.sun.tools.javac.Main
171   //    java -XX:AOTMode=create -Xlog:aot -XX:AOTCache=jc.aot -XX:AOTConfiguration=jc.aotconfig
172   //
173   // You will see an error like this:
174   //
175   // Archive heap points to a static field that may hold a different value at runtime:
176   // Field: java/lang/invoke/MethodHandles::IMPL_NAMES
177   // Value: java.lang.invoke.MemberName$Factory
178   // {0x000000060e906ae8} - klass: 'java/lang/invoke/MemberName$Factory' - flags:
179   //
180   //  - ---- fields (total size 2 words):
181   // --- trace begin ---
182   // [ 0] {0x000000060e8deeb0} java.lang.Class (java.lang.invoke.DirectMethodHandle::IMPL_NAMES)
183   // [ 1] {0x000000060e906ae8} java.lang.invoke.MemberName$Factory
184   // --- trace end ---
185   //
186   // Trouble-shooting
187   // ================
188   //
189   // If you see a "static field that may hold a different value" error, it's probably
190   // because you've made some changes in the JDK core libraries (most likely
191   // java.lang.invoke).
192   //
193   //  - Did you add a new static field to a class that could be referenced by
194   //    cached object instances of MethodType, MethodHandle, etc? You may need
195   //    to add that class to indy_specs[].
196   //  - Did you modify the <clinit> of the classes in java.lang.invoke such that
197   //    a static field now points to an object that should not be cached (e.g.,
198   //    a native resource such as a file descriptior, or a Thread)?
199   //
200   // Note that these potential problems only occur when one class gets
201   // the aot-init treatment, AND another class is init-coupled to it,
202   // AND the coupling is not detected.  Currently there are a number
203   // classes that get the aot-init treatment, in java.lang.invoke
204   // because of invokedynamic.  They are few enough for now to be
205   // manually tracked.  There may be more in the future.
206 
207   {
208     if (ik == vmClasses::Object_klass()) {
209       // everybody's favorite super
210       return true;
211     }
212   }
213 
214   if (CDSConfig::is_dumping_method_handles()) {
215     // The minimal list of @AOTSafeClassInitializer was created with the help of CDSHeapVerifier.
216     // Also, some $Holder classes are needed. E.g., Invokers.<clinit> explicitly
217     // initializes Invokers$Holder. Since Invokers.<clinit> won't be executed
218     // at runtime, we need to make sure Invokers$Holder is also aot-inited.
219     if (ik->has_aot_safe_initializer()) {
220       return true;
221     }
222   }
223 
224 #ifdef ASSERT
225   if (ik == _aot_init_class) {
226     return true;
227   }
228 #endif
229 
230   return false;
231 }
232 
233 void AOTClassInitializer::call_runtime_setup(JavaThread* current, InstanceKlass* ik) {
234   assert(ik->has_aot_initialized_mirror(), "sanity");
235   if (ik->is_runtime_setup_required()) {
236     if (log_is_enabled(Info, aot, init)) {
237       ResourceMark rm;
238       log_info(aot, init)("Calling %s::runtimeSetup()", ik->external_name());
239     }
240     JavaValue result(T_VOID);
241     JavaCalls::call_static(&result, ik,
242                            vmSymbols::runtimeSetup(),
243                            vmSymbols::void_method_signature(), current);
244     if (current->has_pending_exception()) {
245       // We cannot continue, as we might have cached instances of ik in the heap, but propagating the
246       // exception would cause ik to be in an error state.
247       AOTLinkedClassBulkLoader::exit_on_exception(current);
248     }
249   }
250 }
251 
252 // check_can_be_preinited() is quite costly, so we cache the results inside
253 // DumpTimeClassInfo::_can_be_preinited. See also AOTClassInitializer::reset_preinit_check().
254 bool AOTClassInitializer::check_can_be_preinited(InstanceKlass* ik) {
255   ResourceMark rm;
256 
257   if (!SystemDictionaryShared::is_builtin(ik)) {
258     log_info(cds, init)("cannot initialize %s (not built-in loader)", ik->external_name());
259     return false;
260   }
261 
262   InstanceKlass* super = ik->java_super();
263   if (super != nullptr && !can_be_preinited_locked(super)) {
264     log_info(cds, init)("cannot initialize %s (super %s not initable)", ik->external_name(), super->external_name());
265     return false;
266   }
267 
268   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
269   for (int i = 0; i < interfaces->length(); i++) {
270     if (!can_be_preinited_locked(interfaces->at(i))) {
271       log_info(cds, init)("cannot initialize %s (interface %s not initable)",
272                           ik->external_name(), interfaces->at(i)->external_name());
273       return false;
274     }
275   }
276 
277   if (HeapShared::is_lambda_form_klass(ik)) {
278     // We allow only these to have <clinit> or non-default static fields
279     return true;
280   }
281 
282   if (ik->class_initializer() != nullptr) {
283     log_info(cds, init)("cannot initialize %s (has <clinit>)", ik->external_name());
284     return false;
285   }
286   if (ik->is_initialized() && !has_default_static_fields(ik)) {
287     return false;
288   }
289 
290   return true;
291 }
292 
293 bool AOTClassInitializer::has_default_static_fields(InstanceKlass* ik) {
294   oop mirror = ik->java_mirror();
295 
296   for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
297     if (fs.access_flags().is_static()) {
298       fieldDescriptor& fd = fs.field_descriptor();
299       int offset = fd.offset();
300       bool is_default = true;
301       bool has_initval = fd.has_initial_value();
302       switch (fd.field_type()) {
303       case T_OBJECT:
304       case T_ARRAY:
305         is_default = mirror->obj_field(offset) == nullptr;
306         break;
307       case T_BOOLEAN:
308         is_default = mirror->bool_field(offset) == (has_initval ? fd.int_initial_value() : 0);
309         break;
310       case T_BYTE:
311         is_default = mirror->byte_field(offset) == (has_initval ? fd.int_initial_value() : 0);
312         break;
313       case T_SHORT:
314         is_default = mirror->short_field(offset) == (has_initval ? fd.int_initial_value() : 0);
315         break;
316       case T_CHAR:
317         is_default = mirror->char_field(offset) == (has_initval ? fd.int_initial_value() : 0);
318         break;
319       case T_INT:
320         is_default = mirror->int_field(offset) == (has_initval ? fd.int_initial_value() : 0);
321         break;
322       case T_LONG:
323         is_default = mirror->long_field(offset) == (has_initval ? fd.long_initial_value() : 0);
324         break;
325       case T_FLOAT:
326         is_default = mirror->float_field(offset) == (has_initval ? fd.float_initial_value() : 0);
327         break;
328       case T_DOUBLE:
329         is_default = mirror->double_field(offset) == (has_initval ? fd.double_initial_value() : 0);
330         break;
331       default:
332         ShouldNotReachHere();
333       }
334 
335       if (!is_default) {
336         log_info(cds, init)("cannot initialize %s (static field %s has non-default value)",
337                             ik->external_name(), fd.name()->as_C_string());
338         return false;
339       }
340     }
341   }
342 
343   return true;
344 }
345 
346 bool AOTClassInitializer::can_be_preinited(InstanceKlass* ik) {
347   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
348   return can_be_preinited_locked(ik);
349 }
350 
351 bool AOTClassInitializer::can_be_preinited_locked(InstanceKlass* ik) {
352   if (!CDSConfig::is_initing_classes_at_dump_time()) {
353     return false;
354   }
355 
356   assert_lock_strong(DumpTimeTable_lock);
357   DumpTimeClassInfo* info = SystemDictionaryShared::get_info_locked(ik);
358   if (!info->has_done_preinit_check()) {
359     info->set_can_be_preinited(AOTClassInitializer::check_can_be_preinited(ik));
360   }
361   return info->can_be_preinited();
362 }
363 
364 // Initialize a class at dump time, if possible.
365 void AOTClassInitializer::maybe_preinit_class(InstanceKlass* ik, TRAPS) {
366 #if 0 // FIXME -- leyden+JEP483 merge
367   if (!ik->is_initialized() && AOTClassInitializer::can_be_preinited(ik)) {
368     if (log_is_enabled(Info, cds, init)) {
369       ResourceMark rm;
370       log_info(cds, init)("preinitializing %s", ik->external_name());
371     }
372     ik->initialize(CHECK);
373   }
374 #endif
375 }
376 
377 #ifdef ASSERT
378 void AOTClassInitializer::init_test_class(TRAPS) {
379   // -XX:AOTInitTestClass is used in regression tests for adding additional AOT-initialized classes
380   // and heap objects into the AOT cache. The tests must be carefully written to avoid including
381   // any classes that cannot be AOT-initialized.
382   //
383   // -XX:AOTInitTestClass is NOT a general mechanism for including user-defined objects into
384   // the AOT cache. Therefore, this option is NOT available in product JVM.
385   if (AOTInitTestClass != nullptr && CDSConfig::is_initing_classes_at_dump_time()) {
386     log_info(aot)("Debug build only: force initialization of AOTInitTestClass %s", AOTInitTestClass);
387     TempNewSymbol class_name = SymbolTable::new_symbol(AOTInitTestClass);
388     Handle app_loader(THREAD, SystemDictionary::java_system_loader());
389     Klass* k = SystemDictionary::resolve_or_null(class_name, app_loader, CHECK);
390     if (k == nullptr) {
391       vm_exit_during_initialization("AOTInitTestClass not found", AOTInitTestClass);
392     }
393     if (!k->is_instance_klass()) {
394       vm_exit_during_initialization("Invalid name for AOTInitTestClass", AOTInitTestClass);
395     }
396 
397     _aot_init_class = InstanceKlass::cast(k);
398     _aot_init_class->initialize(CHECK);
399   }
400 }
401 
402 bool AOTClassInitializer::has_test_class() {
403   return _aot_init_class != nullptr;
404 }
405 #endif