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/aotLinkedClassBulkLoader.hpp" 27 #include "cds/archiveBuilder.hpp" 28 #include "cds/cdsConfig.hpp" 29 #include "cds/heapShared.hpp" 30 #include "cds/regeneratedClasses.hpp" 31 #include "classfile/symbolTable.hpp" 32 #include "classfile/systemDictionaryShared.hpp" 33 #include "classfile/vmSymbols.hpp" 34 #include "oops/instanceKlass.inline.hpp" 35 #include "oops/symbol.hpp" 36 #include "runtime/java.hpp" 37 #include "runtime/javaCalls.hpp" 38 39 DEBUG_ONLY(InstanceKlass* _aot_init_class = nullptr;) 40 41 bool AOTClassInitializer::can_archive_initialized_mirror(InstanceKlass* ik) { 42 assert(!ArchiveBuilder::is_active() || !ArchiveBuilder::current()->is_in_buffer_space(ik), "must be source klass"); 43 if (!CDSConfig::is_initing_classes_at_dump_time()) { 44 return false; 45 } 46 47 if (RegeneratedClasses::is_regenerated_object(ik)) { 48 ik = RegeneratedClasses::get_original_object(ik); 49 } 50 51 if (!ik->is_initialized() && !ik->is_being_initialized()) { 52 return false; 53 } 54 55 // About "static field that may hold a different value" errors: 56 // 57 // Automatic selection for aot-inited classes 58 // ========================================== 59 // 60 // When CDSConfig::is_initing_classes_at_dump_time is enabled, 61 // AOTArtifactFinder::find_artifacts() finds the classes of all 62 // heap objects that are reachable from HeapShared::_run_time_special_subgraph, 63 // and mark these classes as aot-inited. This preserves the initialized 64 // mirrors of these classes, and their <clinit> methods are NOT executed 65 // at runtime. See aotArtifactFinder.hpp for more info. 66 // 67 // For example, with -XX:+AOTInvokeDynamicLinking, _run_time_special_subgraph 68 // will contain some DirectMethodHandle objects. As a result, the DirectMethodHandle 69 // class is automatically marked as aot-inited. 70 // 71 // When a class is aot-inited, its static fields are already set up 72 // by executing the <clinit> method at AOT assembly time. Later on 73 // in the production run, when the class would normally be 74 // initialized, the VM performs guarding and synchronization as if 75 // it were going to run the <clinit> again, but instead it simply 76 // observes that that class was aot-inited. The VM assumes that, if 77 // it were to run <clinit> again, it would get a semantically 78 // equivalent set of final field values, so it just adopts the 79 // existing field values (from AOT assembly) and skips the call to 80 // <clinit>. There may at that point be fixups performed by ad hoc 81 // code, if the VM recognizes a request in the library. 82 // 83 // It is true that this is not generally correct for all possible 84 // Java code. A <clinit> method might have a side effect beyond 85 // initializing the static fields. It might send an email somewhere 86 // noting the current time of day. In that case, such an email 87 // would have been sent during the AOT assembly phase, and the email 88 // would NOT be sent again during production. This is clearly NOT 89 // what a user would want, if this were a general purpose facility. 90 // But in fact it is only for certain well-behaved classes, which 91 // are known NOT to have such side effects. We know this because 92 // the optimization (of skipping <clinit> for aot-init classes) is 93 // only applied to classes fully defined by the JDK. 94 // 95 // (A day may come when we figure out how to gracefully extend this 96 // optimization to untrusted third parties, but it is not this day.) 97 // 98 // Manual selection 99 // ================ 100 // 101 // There are important cases where one aot-init class has a side 102 // effect on another aot-class, a side effect which is not captured 103 // in any static field value in either class. The simplest example 104 // is class A forces the initialization of class B. In that case, 105 // we need to aot-init either both classes or neither. From looking 106 // at the JDK state after AOT assembly is done, it is hard to tell 107 // that A "touched" B and B might escape our notice. Another common 108 // example is A copying a field value from B. We don't know where A 109 // got the value, but it would be wrong to re-initialize B at 110 // startup, while keeping the snapshot of the old B value in A. In 111 // general, if we aot-init A, we need to aot-init every class B that 112 // somehow contributed to A's initial state, and every class C that 113 // was somehow side-effected by A's initialization. We say that the 114 // aot-init of A is "init-coupled" to those of B and C. 115 // 116 // So there are init-coupled classes that cannot be automatically discovered. For 117 // example, DirectMethodHandle::IMPL_NAMES points to MethodHandles::IMPL_NAMES, 118 // but the MethodHandles class is not automatically marked because there are 119 // no archived instances of the MethodHandles type. 120 // 121 // If we aot-initialize DirectMethodHandle, but allow MethodHandles to be 122 // initialized at runtime, MethodHandles::IMPL_NAMES will get a different 123 // value than DirectMethodHandle::IMPL_NAMES. This *may or may not* be a problem, 124 // but to ensure compatibility, we should try to preserve the identity equality 125 // of these two fields. 126 // 127 // To do that, we add MethodHandles to the indy_specs[] table below. 128 // 129 // Luckily we do not need to be all-knowing in order to choose which 130 // items to add to that table. We have tools to help detect couplings. 131 // 132 // Automatic validation 133 // ==================== 134 // 135 // CDSHeapVerifier is used to detect potential problems with identity equality. 136 // 137 // A class B is assumed to be init-coupled to some aot-init class if 138 // B has a field which points to a live object X in the AOT heap. 139 // The live object X was created by some other class A which somehow 140 // used B's reference to X, perhaps with the help of an intermediate 141 // class Z. Or, B pulled the reference to X from some other class 142 // Y, and B obtained that reference from Y (or an intermediate Z). 143 // It is not certain how X got into the heap, nor whether B 144 // contributed it, but it is a good heuristic that B is init-coupled 145 // to X's class or some other aot-init class. In any case, B should 146 // be made an aot-init class as well, unless a manual inspection 147 // shows that would be a problem. If there is a problem, then the 148 // JDK code for B and/or X probably needs refactoring. If there is 149 // no problem, we add B to the list. Typically the same scan will 150 // find any other accomplices Y, Z, etc. One failure would be a 151 // class Q whose only initialization action is to scribble a special 152 // value into B, from which the value X is derived and then makes 153 // its way into the heap. In that case, the heuristic does not 154 // identify Q. It is (currently) a human responsibility, of JDK 155 // engineers, not to write such dirty JDK code, or to repair it if 156 // it crops up. Eventually we may have tools, or even a user mode 157 // with design rules and checks, that will vet our code base more 158 // automatically. 159 // 160 // To see how the tool detects the problem with MethodHandles::IMPL_NAMES: 161 // 162 // - Comment out all the lines in indy_specs[] except the {nullptr} line. 163 // - Rebuild the JDK 164 // 165 // Then run the following: 166 // java -XX:AOTMode=record -XX:AOTConfiguration=jc.aotconfig com.sun.tools.javac.Main 167 // java -XX:AOTMode=create -Xlog:aot -XX:AOTCache=jc.aot -XX:AOTConfiguration=jc.aotconfig 168 // 169 // You will see an error like this: 170 // 171 // Archive heap points to a static field that may hold a different value at runtime: 172 // Field: java/lang/invoke/MethodHandles::IMPL_NAMES 173 // Value: java.lang.invoke.MemberName$Factory 174 // {0x000000060e906ae8} - klass: 'java/lang/invoke/MemberName$Factory' - flags: 175 // 176 // - ---- fields (total size 2 words): 177 // --- trace begin --- 178 // [ 0] {0x000000060e8deeb0} java.lang.Class (java.lang.invoke.DirectMethodHandle::IMPL_NAMES) 179 // [ 1] {0x000000060e906ae8} java.lang.invoke.MemberName$Factory 180 // --- trace end --- 181 // 182 // Trouble-shooting 183 // ================ 184 // 185 // If you see a "static field that may hold a different value" error, it's probably 186 // because you've made some changes in the JDK core libraries (most likely 187 // java.lang.invoke). 188 // 189 // - Did you add a new static field to a class that could be referenced by 190 // cached object instances of MethodType, MethodHandle, etc? You may need 191 // to add that class to indy_specs[]. 192 // - Did you modify the <clinit> of the classes in java.lang.invoke such that 193 // a static field now points to an object that should not be cached (e.g., 194 // a native resource such as a file descriptior, or a Thread)? 195 // 196 // Note that these potential problems only occur when one class gets 197 // the aot-init treatment, AND another class is init-coupled to it, 198 // AND the coupling is not detected. Currently there are a number 199 // classes that get the aot-init treatment, in java.lang.invoke 200 // because of invokedynamic. They are few enough for now to be 201 // manually tracked. There may be more in the future. 202 203 { 204 if (ik == vmClasses::Object_klass()) { 205 // everybody's favorite super 206 return true; 207 } 208 } 209 210 if (CDSConfig::is_dumping_method_handles()) { 211 // The minimal list of @AOTSafeClassInitializer was created with the help of CDSHeapVerifier. 212 // Also, some $Holder classes are needed. E.g., Invokers.<clinit> explicitly 213 // initializes Invokers$Holder. Since Invokers.<clinit> won't be executed 214 // at runtime, we need to make sure Invokers$Holder is also aot-inited. 215 if (ik->has_aot_safe_initializer()) { 216 return true; 217 } 218 } 219 220 #ifdef ASSERT 221 if (ik == _aot_init_class) { 222 return true; 223 } 224 #endif 225 226 return false; 227 } 228 229 void AOTClassInitializer::call_runtime_setup(JavaThread* current, InstanceKlass* ik) { 230 assert(ik->has_aot_initialized_mirror(), "sanity"); 231 if (ik->is_runtime_setup_required()) { 232 if (log_is_enabled(Info, aot, init)) { 233 ResourceMark rm; 234 log_info(aot, init)("Calling %s::runtimeSetup()", ik->external_name()); 235 } 236 JavaValue result(T_VOID); 237 JavaCalls::call_static(&result, ik, 238 vmSymbols::runtimeSetup(), 239 vmSymbols::void_method_signature(), current); 240 if (current->has_pending_exception()) { 241 // We cannot continue, as we might have cached instances of ik in the heap, but propagating the 242 // exception would cause ik to be in an error state. 243 AOTLinkedClassBulkLoader::exit_on_exception(current); 244 } 245 } 246 } 247 248 #ifdef ASSERT 249 void AOTClassInitializer::init_test_class(TRAPS) { 250 // -XX:AOTInitTestClass is used in regression tests for adding additional AOT-initialized classes 251 // and heap objects into the AOT cache. The tests must be carefully written to avoid including 252 // any classes that cannot be AOT-initialized. 253 // 254 // -XX:AOTInitTestClass is NOT a general mechanism for including user-defined objects into 255 // the AOT cache. Therefore, this option is NOT available in product JVM. 256 if (AOTInitTestClass != nullptr && CDSConfig::is_initing_classes_at_dump_time()) { 257 log_info(aot)("Debug build only: force initialization of AOTInitTestClass %s", AOTInitTestClass); 258 TempNewSymbol class_name = SymbolTable::new_symbol(AOTInitTestClass); 259 Handle app_loader(THREAD, SystemDictionary::java_system_loader()); 260 Klass* k = SystemDictionary::resolve_or_null(class_name, app_loader, CHECK); 261 if (k == nullptr) { 262 vm_exit_during_initialization("AOTInitTestClass not found", AOTInitTestClass); 263 } 264 if (!k->is_instance_klass()) { 265 vm_exit_during_initialization("Invalid name for AOTInitTestClass", AOTInitTestClass); 266 } 267 268 _aot_init_class = InstanceKlass::cast(k); 269 _aot_init_class->initialize(CHECK); 270 } 271 } 272 273 bool AOTClassInitializer::has_test_class() { 274 return _aot_init_class != nullptr; 275 } 276 #endif