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/aotConstantPoolResolver.hpp"
 26 #include "cds/archiveBuilder.hpp"
 27 #include "cds/archiveUtils.inline.hpp"
 28 #include "cds/cdsConfig.hpp"
 29 #include "cds/finalImageRecipes.hpp"
 30 #include "classfile/classLoader.hpp"
 31 #include "classfile/javaClasses.hpp"
 32 #include "classfile/systemDictionary.hpp"
 33 #include "classfile/systemDictionaryShared.hpp"
 34 #include "classfile/vmClasses.hpp"
 35 #include "memory/oopFactory.hpp"
 36 #include "memory/resourceArea.hpp"
 37 #include "oops/constantPool.inline.hpp"
 38 #include "runtime/handles.inline.hpp"
 39 #include "runtime/mutexLocker.hpp"
 40 
 41 static FinalImageRecipes* _final_image_recipes = nullptr;
 42 
 43 void* FinalImageRecipes::operator new(size_t size) throw() {
 44   return ArchiveBuilder::current()->ro_region_alloc(size);
 45 }
 46 
 47 void FinalImageRecipes::record_all_classes() {
 48   _all_klasses = ArchiveUtils::archive_array(ArchiveBuilder::current()->klasses());
 49   ArchivePtrMarker::mark_pointer(&_all_klasses);
 50 }
 51 
 52 void FinalImageRecipes::record_recipes_for_constantpool() {
 53   ResourceMark rm;
 54 
 55   // The recipes are recorded regardless of CDSConfig::is_dumping_{invokedynamic,dynamic_proxies,reflection_data}().
 56   // If some of these options are not enabled, the corresponding recipes will be
 57   // ignored during the final image assembly.
 58 
 59   GrowableArray<Array<int>*> tmp_cp_recipes;
 60   GrowableArray<int> tmp_flags;
 61 
 62   GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 63   for (int i = 0; i < klasses->length(); i++) {
 64     GrowableArray<int> cp_indices;
 65     int flags = 0;
 66 
 67     Klass* k = klasses->at(i);
 68     if (k->is_instance_klass()) {
 69       InstanceKlass* ik = InstanceKlass::cast(k);
 70       ConstantPool* cp = ik->constants();
 71       ConstantPoolCache* cp_cache = cp->cache();
 72 
 73       if (ik->is_initialized()) {
 74         flags |= WAS_INITED;
 75       }
 76 
 77       for (int cp_index = 1; cp_index < cp->length(); cp_index++) { // Index 0 is unused
 78         if (cp->tag_at(cp_index).value() == JVM_CONSTANT_Class) {
 79           Klass* k = cp->resolved_klass_at(cp_index);
 80           if (k->is_instance_klass()) {
 81             cp_indices.append(cp_index);
 82             flags |= CP_RESOLVE_CLASS;
 83           }
 84         }
 85       }
 86 
 87       if (cp_cache != nullptr) {
 88         Array<ResolvedFieldEntry>* field_entries = cp_cache->resolved_field_entries();
 89         if (field_entries != nullptr) {
 90           for (int i = 0; i < field_entries->length(); i++) {
 91             ResolvedFieldEntry* rfe = field_entries->adr_at(i);
 92             if (rfe->is_resolved(Bytecodes::_getstatic) ||
 93                 rfe->is_resolved(Bytecodes::_putstatic) ||
 94                 rfe->is_resolved(Bytecodes::_getfield) ||
 95                 rfe->is_resolved(Bytecodes::_putfield)) {
 96               cp_indices.append(rfe->constant_pool_index());
 97               flags |= CP_RESOLVE_FIELD_AND_METHOD;
 98             }
 99           }
100         }
101 
102         Array<ResolvedMethodEntry>* method_entries = cp_cache->resolved_method_entries();
103         if (method_entries != nullptr) {
104           for (int i = 0; i < method_entries->length(); i++) {
105             ResolvedMethodEntry* rme = method_entries->adr_at(i);
106             if (rme->is_resolved(Bytecodes::_invokevirtual) ||
107                 rme->is_resolved(Bytecodes::_invokespecial) ||
108                 rme->is_resolved(Bytecodes::_invokeinterface) ||
109                 rme->is_resolved(Bytecodes::_invokestatic) ||
110                 rme->is_resolved(Bytecodes::_invokehandle)) {
111               cp_indices.append(rme->constant_pool_index());
112               flags |= CP_RESOLVE_FIELD_AND_METHOD;
113             }
114           }
115         }
116 
117         Array<ResolvedIndyEntry>* indy_entries = cp_cache->resolved_indy_entries();
118         if (indy_entries != nullptr) {
119           for (int i = 0; i < indy_entries->length(); i++) {
120             ResolvedIndyEntry* rie = indy_entries->adr_at(i);
121             int cp_index = rie->constant_pool_index();
122             if (rie->is_resolved()) {
123               cp_indices.append(cp_index);
124               flags |= CP_RESOLVE_INDY;
125             }
126           }
127         }
128       }
129     }
130 
131     if (cp_indices.length() > 0) {
132       LogStreamHandle(Trace, aot, resolve) log;
133       if (log.is_enabled()) {
134         log.print("ConstantPool entries for %s to be pre-resolved:", k->external_name());
135         for (int i = 0; i < cp_indices.length(); i++) {
136           log.print(" %d", cp_indices.at(i));
137         }
138         log.print("\n");
139       }
140       tmp_cp_recipes.append(ArchiveUtils::archive_array(&cp_indices));
141     } else {
142       tmp_cp_recipes.append(nullptr);
143     }
144     tmp_flags.append(flags);
145   }
146 
147   _cp_recipes = ArchiveUtils::archive_array(&tmp_cp_recipes);
148   ArchivePtrMarker::mark_pointer(&_cp_recipes);
149 
150   _flags = ArchiveUtils::archive_array(&tmp_flags);
151   ArchivePtrMarker::mark_pointer(&_flags);
152 }
153 
154 void FinalImageRecipes::apply_recipes_for_constantpool(JavaThread* current) {
155   assert(CDSConfig::is_dumping_final_static_archive(), "must be");
156 
157   for (int i = 0; i < _all_klasses->length(); i++) {
158     Array<int>* cp_indices = _cp_recipes->at(i);
159     int flags = _flags->at(i);
160     if (cp_indices != nullptr) {
161       InstanceKlass* ik = InstanceKlass::cast(_all_klasses->at(i));
162       if (ik->is_loaded()) {
163         ResourceMark rm(current);
164         ConstantPool* cp = ik->constants();
165         GrowableArray<bool> preresolve_list(cp->length(), cp->length(), false);
166         for (int j = 0; j < cp_indices->length(); j++) {
167           preresolve_list.at_put(cp_indices->at(j), true);
168         }
169         if ((flags & CP_RESOLVE_CLASS) != 0) {
170           AOTConstantPoolResolver::preresolve_class_cp_entries(current, ik, &preresolve_list);
171         }
172         if ((flags & CP_RESOLVE_FIELD_AND_METHOD) != 0) {
173           AOTConstantPoolResolver::preresolve_field_and_method_cp_entries(current, ik, &preresolve_list);
174         }
175         if ((flags & CP_RESOLVE_INDY) != 0) {
176           AOTConstantPoolResolver::preresolve_indy_cp_entries(current, ik, &preresolve_list);
177         }
178       }
179     }
180   }
181 }
182 
183 void FinalImageRecipes::load_all_classes(TRAPS) {
184   assert(CDSConfig::is_dumping_final_static_archive(), "sanity");
185   Handle class_loader(THREAD, SystemDictionary::java_system_loader());
186   for (int i = 0; i < _all_klasses->length(); i++) {
187     Klass* k = _all_klasses->at(i);
188     int flags = _flags->at(i);
189     if (k->is_instance_klass()) {
190       InstanceKlass* ik = InstanceKlass::cast(k);
191       if (ik->defined_by_other_loaders()) {
192         SystemDictionaryShared::init_dumptime_info(ik);
193         SystemDictionaryShared::add_unregistered_class(THREAD, ik);
194         SystemDictionaryShared::copy_unregistered_class_size_and_crc32(ik);
195       } else if (!ik->is_hidden()) {
196         Klass* actual = SystemDictionary::resolve_or_fail(ik->name(), class_loader, true, CHECK);
197         if (actual != ik) {
198           ResourceMark rm(THREAD);
199           log_error(aot)("Unable to resolve class from CDS archive: %s", ik->external_name());
200           log_error(aot)("Expected: " INTPTR_FORMAT ", actual: " INTPTR_FORMAT, p2i(ik), p2i(actual));
201           log_error(aot)("Please check if your VM command-line is the same as in the training run");
202           AOTMetaspace::unrecoverable_writing_error();
203         }
204         assert(ik->is_loaded(), "must be");
205         ik->link_class(CHECK);
206 
207         if (ik->has_aot_safe_initializer() && (flags & WAS_INITED) != 0) {
208           assert(ik->class_loader() == nullptr, "supported only for boot classes for now");
209           ik->initialize(CHECK);
210         }
211       }
212     }
213   }
214 }
215 
216 void FinalImageRecipes::record_recipes() {
217   assert(CDSConfig::is_dumping_preimage_static_archive(), "must be");
218   _final_image_recipes = new FinalImageRecipes();
219   _final_image_recipes->record_all_classes();
220   _final_image_recipes->record_recipes_for_constantpool();
221 }
222 
223 void FinalImageRecipes::apply_recipes(TRAPS) {
224   assert(CDSConfig::is_dumping_final_static_archive(), "must be");
225   if (_final_image_recipes != nullptr) {
226     _final_image_recipes->apply_recipes_impl(THREAD);
227     if (HAS_PENDING_EXCEPTION) {
228       log_error(aot)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
229                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
230       log_error(aot)("Please check if your VM command-line is the same as in the training run");
231       AOTMetaspace::unrecoverable_writing_error("Unexpected exception, use -Xlog:aot,exceptions=trace for detail");
232     }
233   }
234 
235   // Set it to null as we don't need to write this table into the final image.
236   _final_image_recipes = nullptr;
237 }
238 
239 void FinalImageRecipes::apply_recipes_impl(TRAPS) {
240   load_all_classes(CHECK);
241   apply_recipes_for_constantpool(THREAD);
242 }
243 
244 void FinalImageRecipes::serialize(SerializeClosure* soc) {
245   soc->do_ptr((void**)&_final_image_recipes);
246 }