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::_getfield) ||
 93                 rfe->is_resolved(Bytecodes::_putfield)) {
 94               cp_indices.append(rfe->constant_pool_index());
 95               flags |= CP_RESOLVE_FIELD_AND_METHOD;
 96             }
 97           }
 98         }
 99 
100         Array<ResolvedMethodEntry>* method_entries = cp_cache->resolved_method_entries();
101         if (method_entries != nullptr) {
102           for (int i = 0; i < method_entries->length(); i++) {
103             ResolvedMethodEntry* rme = method_entries->adr_at(i);
104             if (rme->is_resolved(Bytecodes::_invokevirtual) ||
105                 rme->is_resolved(Bytecodes::_invokespecial) ||
106                 rme->is_resolved(Bytecodes::_invokeinterface) ||
107                 rme->is_resolved(Bytecodes::_invokestatic) ||
108                 rme->is_resolved(Bytecodes::_invokehandle)) {
109               cp_indices.append(rme->constant_pool_index());
110               flags |= CP_RESOLVE_FIELD_AND_METHOD;
111             }
112           }
113         }
114 
115         Array<ResolvedIndyEntry>* indy_entries = cp_cache->resolved_indy_entries();
116         if (indy_entries != nullptr) {
117           for (int i = 0; i < indy_entries->length(); i++) {
118             ResolvedIndyEntry* rie = indy_entries->adr_at(i);
119             int cp_index = rie->constant_pool_index();
120             if (rie->is_resolved()) {
121               cp_indices.append(cp_index);
122               flags |= CP_RESOLVE_INDY;
123             }
124           }
125         }
126       }
127     }
128 
129     if (cp_indices.length() > 0) {
130       tmp_cp_recipes.append(ArchiveUtils::archive_array(&cp_indices));
131     } else {
132       tmp_cp_recipes.append(nullptr);
133     }
134     tmp_flags.append(flags);
135   }
136 
137   _cp_recipes = ArchiveUtils::archive_array(&tmp_cp_recipes);
138   ArchivePtrMarker::mark_pointer(&_cp_recipes);
139 
140   _flags = ArchiveUtils::archive_array(&tmp_flags);
141   ArchivePtrMarker::mark_pointer(&_flags);
142 }
143 
144 void FinalImageRecipes::apply_recipes_for_constantpool(JavaThread* current) {
145   assert(CDSConfig::is_dumping_final_static_archive(), "must be");
146 
147   for (int i = 0; i < _all_klasses->length(); i++) {
148     Array<int>* cp_indices = _cp_recipes->at(i);
149     int flags = _flags->at(i);
150     if (cp_indices != nullptr) {
151       InstanceKlass* ik = InstanceKlass::cast(_all_klasses->at(i));
152       if (ik->is_loaded()) {
153         ResourceMark rm(current);
154         ConstantPool* cp = ik->constants();
155         GrowableArray<bool> preresolve_list(cp->length(), cp->length(), false);
156         for (int j = 0; j < cp_indices->length(); j++) {
157           preresolve_list.at_put(cp_indices->at(j), true);
158         }
159         if ((flags & CP_RESOLVE_CLASS) != 0) {
160           AOTConstantPoolResolver::preresolve_class_cp_entries(current, ik, &preresolve_list);
161         }
162         if ((flags & CP_RESOLVE_FIELD_AND_METHOD) != 0) {
163           AOTConstantPoolResolver::preresolve_field_and_method_cp_entries(current, ik, &preresolve_list);
164         }
165         if ((flags & CP_RESOLVE_INDY) != 0) {
166           AOTConstantPoolResolver::preresolve_indy_cp_entries(current, ik, &preresolve_list);
167         }
168       }
169     }
170   }
171 }
172 
173 void FinalImageRecipes::load_all_classes(TRAPS) {
174   assert(CDSConfig::is_dumping_final_static_archive(), "sanity");
175   Handle class_loader(THREAD, SystemDictionary::java_system_loader());
176   for (int i = 0; i < _all_klasses->length(); i++) {
177     Klass* k = _all_klasses->at(i);
178     int flags = _flags->at(i);
179     if (k->is_instance_klass()) {
180       InstanceKlass* ik = InstanceKlass::cast(k);
181       if (ik->defined_by_other_loaders()) {
182         SystemDictionaryShared::init_dumptime_info(ik);
183         SystemDictionaryShared::add_unregistered_class(THREAD, ik);
184         SystemDictionaryShared::copy_unregistered_class_size_and_crc32(ik);
185       } else if (!ik->is_hidden()) {
186         Klass* actual = SystemDictionary::resolve_or_fail(ik->name(), class_loader, true, CHECK);
187         if (actual != ik) {
188           ResourceMark rm(THREAD);
189           log_error(aot)("Unable to resolve class from CDS archive: %s", ik->external_name());
190           log_error(aot)("Expected: " INTPTR_FORMAT ", actual: " INTPTR_FORMAT, p2i(ik), p2i(actual));
191           log_error(aot)("Please check if your VM command-line is the same as in the training run");
192           AOTMetaspace::unrecoverable_writing_error();
193         }
194         assert(ik->is_loaded(), "must be");
195         ik->link_class(CHECK);
196 
197         if (ik->has_aot_safe_initializer() && (flags & WAS_INITED) != 0) {
198           assert(ik->class_loader() == nullptr, "supported only for boot classes for now");
199           ik->initialize(CHECK);
200         }
201       }
202     }
203   }
204 }
205 
206 void FinalImageRecipes::record_recipes() {
207   assert(CDSConfig::is_dumping_preimage_static_archive(), "must be");
208   _final_image_recipes = new FinalImageRecipes();
209   _final_image_recipes->record_all_classes();
210   _final_image_recipes->record_recipes_for_constantpool();
211 }
212 
213 void FinalImageRecipes::apply_recipes(TRAPS) {
214   assert(CDSConfig::is_dumping_final_static_archive(), "must be");
215   if (_final_image_recipes != nullptr) {
216     _final_image_recipes->apply_recipes_impl(THREAD);
217     if (HAS_PENDING_EXCEPTION) {
218       log_error(aot)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
219                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
220       log_error(aot)("Please check if your VM command-line is the same as in the training run");
221       AOTMetaspace::unrecoverable_writing_error("Unexpected exception, use -Xlog:aot,exceptions=trace for detail");
222     }
223   }
224 
225   // Set it to null as we don't need to write this table into the final image.
226   _final_image_recipes = nullptr;
227 }
228 
229 void FinalImageRecipes::apply_recipes_impl(TRAPS) {
230   load_all_classes(CHECK);
231   apply_recipes_for_constantpool(THREAD);
232 }
233 
234 void FinalImageRecipes::serialize(SerializeClosure* soc) {
235   soc->do_ptr((void**)&_final_image_recipes);
236 }