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