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 GrowableArray<InstanceKlass*>* FinalImageRecipes::_tmp_reflect_klasses = nullptr;
 42 GrowableArray<int>* FinalImageRecipes::_tmp_reflect_flags = nullptr;
 43 GrowableArray<FinalImageRecipes::TmpDynamicProxyClassInfo>* FinalImageRecipes::_tmp_dynamic_proxy_classes = nullptr;
 44 static FinalImageRecipes* _final_image_recipes = nullptr;
 45 
 46 void* FinalImageRecipes::operator new(size_t size) throw() {
 47   return ArchiveBuilder::current()->ro_region_alloc(size);
 48 }
 49 
 50 void FinalImageRecipes::record_all_classes() {
 51   _all_klasses = ArchiveUtils::archive_array(ArchiveBuilder::current()->klasses());
 52   ArchivePtrMarker::mark_pointer(&_all_klasses);
 53 }
 54 
 55 void FinalImageRecipes::record_recipes_for_constantpool() {
 56   ResourceMark rm;
 57 
 58   // The recipes are recorded regardless of CDSConfig::is_dumping_{invokedynamic,dynamic_proxies,reflection_data}().
 59   // If some of these options are not enabled, the corresponding recipes will be
 60   // ignored during the final image assembly.
 61 
 62   GrowableArray<Array<int>*> tmp_cp_recipes;
 63   GrowableArray<int> tmp_flags;
 64 
 65   GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 66   for (int i = 0; i < klasses->length(); i++) {
 67     GrowableArray<int> cp_indices;
 68     int flags = 0;
 69 
 70     Klass* k = klasses->at(i);
 71     if (k->is_instance_klass()) {
 72       InstanceKlass* ik = InstanceKlass::cast(k);
 73       ConstantPool* cp = ik->constants();
 74       ConstantPoolCache* cp_cache = cp->cache();
 75 
 76       if (ik->is_initialized()) {
 77         flags |= WAS_INITED;
 78       }
 79 
 80       for (int cp_index = 1; cp_index < cp->length(); cp_index++) { // Index 0 is unused
 81         if (cp->tag_at(cp_index).value() == JVM_CONSTANT_Class) {
 82           Klass* k = cp->resolved_klass_at(cp_index);
 83           if (k->is_instance_klass()) {
 84             cp_indices.append(cp_index);
 85             flags |= CP_RESOLVE_CLASS;
 86           }
 87         }
 88       }
 89 
 90       if (cp_cache != nullptr) {
 91         Array<ResolvedFieldEntry>* field_entries = cp_cache->resolved_field_entries();
 92         if (field_entries != nullptr) {
 93           for (int i = 0; i < field_entries->length(); i++) {
 94             ResolvedFieldEntry* rfe = field_entries->adr_at(i);
 95             if (rfe->is_resolved(Bytecodes::_getfield) ||
 96                 rfe->is_resolved(Bytecodes::_putfield)) {
 97               cp_indices.append(rfe->constant_pool_index());
 98               flags |= CP_RESOLVE_FIELD_AND_METHOD;
 99             }
100           }
101         }
102 
103         Array<ResolvedMethodEntry>* method_entries = cp_cache->resolved_method_entries();
104         if (method_entries != nullptr) {
105           for (int i = 0; i < method_entries->length(); i++) {
106             ResolvedMethodEntry* rme = method_entries->adr_at(i);
107             if (rme->is_resolved(Bytecodes::_invokevirtual) ||
108                 rme->is_resolved(Bytecodes::_invokespecial) ||
109                 rme->is_resolved(Bytecodes::_invokeinterface) ||
110                 rme->is_resolved(Bytecodes::_invokestatic) ||
111                 rme->is_resolved(Bytecodes::_invokehandle)) {
112               cp_indices.append(rme->constant_pool_index());
113               flags |= CP_RESOLVE_FIELD_AND_METHOD;
114             }
115           }
116         }
117 
118         Array<ResolvedIndyEntry>* indy_entries = cp_cache->resolved_indy_entries();
119         if (indy_entries != nullptr) {
120           for (int i = 0; i < indy_entries->length(); i++) {
121             ResolvedIndyEntry* rie = indy_entries->adr_at(i);
122             int cp_index = rie->constant_pool_index();
123             if (rie->is_resolved()) {
124               cp_indices.append(cp_index);
125               flags |= CP_RESOLVE_INDY;
126             }
127           }
128         }
129       }
130     }
131 
132     if (cp_indices.length() > 0) {
133       tmp_cp_recipes.append(ArchiveUtils::archive_array(&cp_indices));
134     } else {
135       tmp_cp_recipes.append(nullptr);
136     }
137     tmp_flags.append(flags);
138   }
139 
140   _cp_recipes = ArchiveUtils::archive_array(&tmp_cp_recipes);
141   ArchivePtrMarker::mark_pointer(&_cp_recipes);
142 
143   _flags = ArchiveUtils::archive_array(&tmp_flags);
144   ArchivePtrMarker::mark_pointer(&_flags);
145 }
146 
147 void FinalImageRecipes::apply_recipes_for_constantpool(JavaThread* current) {
148   assert(CDSConfig::is_dumping_final_static_archive(), "must be");
149 
150   for (int i = 0; i < _all_klasses->length(); i++) {
151     Array<int>* cp_indices = _cp_recipes->at(i);
152     int flags = _flags->at(i);
153     if (cp_indices != nullptr) {
154       InstanceKlass* ik = InstanceKlass::cast(_all_klasses->at(i));
155       if (ik->is_loaded()) {
156         ResourceMark rm(current);
157         ConstantPool* cp = ik->constants();
158         GrowableArray<bool> preresolve_list(cp->length(), cp->length(), false);
159         for (int j = 0; j < cp_indices->length(); j++) {
160           preresolve_list.at_put(cp_indices->at(j), true);
161         }
162         if ((flags & CP_RESOLVE_CLASS) != 0) {
163           AOTConstantPoolResolver::preresolve_class_cp_entries(current, ik, &preresolve_list);
164         }
165         if ((flags & CP_RESOLVE_FIELD_AND_METHOD) != 0) {
166           AOTConstantPoolResolver::preresolve_field_and_method_cp_entries(current, ik, &preresolve_list);
167         }
168         if ((flags & CP_RESOLVE_INDY) != 0) {
169           AOTConstantPoolResolver::preresolve_indy_cp_entries(current, ik, &preresolve_list);
170         }
171       }
172     }
173   }
174 }
175 
176 void FinalImageRecipes::record_recipes_for_reflection_data() {
177   int reflect_count = 0;
178   if (_tmp_reflect_klasses != nullptr) {
179     for (int i = _tmp_reflect_klasses->length() - 1; i >= 0; i--) {
180       InstanceKlass* ik = _tmp_reflect_klasses->at(i);
181       if (SystemDictionaryShared::is_excluded_class(ik)) {
182         _tmp_reflect_klasses->remove_at(i);
183         _tmp_reflect_flags->remove_at(i);
184       } else {
185         _tmp_reflect_klasses->at_put(i, ArchiveBuilder::current()->get_buffered_addr(ik));
186       }
187     }
188     if (_tmp_reflect_klasses->length() > 0) {
189       _reflect_klasses = ArchiveUtils::archive_array(_tmp_reflect_klasses);
190       _reflect_flags = ArchiveUtils::archive_array(_tmp_reflect_flags);
191 
192       ArchivePtrMarker::mark_pointer(&_reflect_klasses);
193       ArchivePtrMarker::mark_pointer(&_reflect_flags);
194       reflect_count = _tmp_reflect_klasses->length();
195     }
196   }
197   log_info(cds)("ReflectionData of %d classes will be archived in final CDS image", reflect_count);
198 }
199 
200 void FinalImageRecipes::record_recipes_for_dynamic_proxies() {
201   if (_tmp_dynamic_proxy_classes != nullptr) {
202     // Remove proxies for excluded classes
203     for (int i = _tmp_dynamic_proxy_classes->length() - 1; i >= 0; i--) {
204       TmpDynamicProxyClassInfo* tmp_info = _tmp_dynamic_proxy_classes->adr_at(i);
205       bool exclude = false;
206       for (int j = 0; j < tmp_info->_interfaces->length(); j++) {
207         if (SystemDictionaryShared::is_excluded_class(InstanceKlass::cast(tmp_info->_interfaces->at(j)))) {
208           exclude = true;
209           break;
210         }
211       }
212       if (exclude) {
213         _tmp_dynamic_proxy_classes->remove_at(i);
214       }
215     }
216     int len = _tmp_dynamic_proxy_classes->length();
217     _dynamic_proxy_classes = ArchiveBuilder::new_ro_array<DynamicProxyClassInfo>(len);
218     ArchivePtrMarker::mark_pointer(&_dynamic_proxy_classes);
219     for (int i = 0; i < len; i++) {
220       TmpDynamicProxyClassInfo* tmp_info = _tmp_dynamic_proxy_classes->adr_at(i);
221       DynamicProxyClassInfo* info = _dynamic_proxy_classes->adr_at(i);
222       info->_loader_type = tmp_info->_loader_type;
223       info->_access_flags = tmp_info->_access_flags;
224       info->_proxy_name = ArchiveBuilder::current()->ro_strdup(tmp_info->_proxy_name);
225 
226       ResourceMark rm;
227       GrowableArray<Klass*> buffered_interfaces;
228       for (int j = 0; j < tmp_info->_interfaces->length(); j++) {
229         InstanceKlass* intf = InstanceKlass::cast(tmp_info->_interfaces->at(j));
230         assert(!SystemDictionaryShared::is_excluded_class(intf), "sanity");
231         buffered_interfaces.append(ArchiveBuilder::current()->get_buffered_addr(intf));
232       }
233       info->_interfaces = ArchiveUtils::archive_array(&buffered_interfaces);
234 
235       ArchivePtrMarker::mark_pointer(&info->_proxy_name);
236       ArchivePtrMarker::mark_pointer(&info->_interfaces);
237       ArchiveBuilder::alloc_stats()->record_dynamic_proxy_class();
238     }
239   }
240 }
241 
242 void FinalImageRecipes::load_all_classes(TRAPS) {
243   assert(CDSConfig::is_dumping_final_static_archive(), "sanity");
244   Handle class_loader(THREAD, SystemDictionary::java_system_loader());
245   for (int i = 0; i < _all_klasses->length(); i++) {
246     Klass* k = _all_klasses->at(i);
247     int flags = _flags->at(i);
248     if (k->is_instance_klass()) {
249       InstanceKlass* ik = InstanceKlass::cast(k);
250       if (ik->defined_by_other_loaders()) {
251         SystemDictionaryShared::init_dumptime_info(ik);
252         SystemDictionaryShared::add_unregistered_class(THREAD, ik);
253         SystemDictionaryShared::copy_unregistered_class_size_and_crc32(ik);
254       } else if (!ik->is_hidden()) {
255         Klass* actual = SystemDictionary::resolve_or_fail(ik->name(), class_loader, true, CHECK);
256         if (actual != ik) {
257           ResourceMark rm(THREAD);
258           log_error(aot)("Unable to resolve class from CDS archive: %s", ik->external_name());
259           log_error(aot)("Expected: " INTPTR_FORMAT ", actual: " INTPTR_FORMAT, p2i(ik), p2i(actual));
260           log_error(aot)("Please check if your VM command-line is the same as in the training run");
261           AOTMetaspace::unrecoverable_writing_error();
262         }
263         assert(ik->is_loaded(), "must be");
264         ik->link_class(CHECK);
265 
266         if (ik->has_aot_safe_initializer() && (flags & WAS_INITED) != 0) {
267           assert(ik->class_loader() == nullptr, "supported only for boot classes for now");
268           ik->initialize(CHECK);
269         }
270       }
271     }
272   }
273 }
274 
275 void FinalImageRecipes::apply_recipes_for_reflection_data(JavaThread* current) {
276   assert(CDSConfig::is_dumping_final_static_archive(), "must be");
277 
278   if (CDSConfig::is_dumping_reflection_data() && _reflect_klasses != nullptr) {
279     assert(_reflect_flags != nullptr, "must be");
280     for (int i = 0; i < _reflect_klasses->length(); i++) {
281       InstanceKlass* ik = _reflect_klasses->at(i);
282       int rd_flags = _reflect_flags->at(i);
283       AOTConstantPoolResolver::generate_reflection_data(current, ik, rd_flags);
284     }
285   }
286 }
287 
288 void FinalImageRecipes::add_reflection_data_flags(InstanceKlass* ik, TRAPS) {
289   assert(CDSConfig::is_dumping_preimage_static_archive(), "must be");
290   if (ik->is_linked() &&
291       SystemDictionaryShared::is_builtin_loader(ik->class_loader_data()) && !ik->is_hidden() &&
292       java_lang_Class::has_reflection_data(ik->java_mirror())) {
293     int rd_flags = AOTConstantPoolResolver::class_reflection_data_flags(ik, CHECK);
294 
295     MutexLocker mu(FinalImageRecipes_lock, Mutex::_no_safepoint_check_flag);
296     if (_tmp_reflect_klasses == nullptr) {
297       _tmp_reflect_klasses = new (mtClassShared) GrowableArray<InstanceKlass*>(100, mtClassShared);
298       _tmp_reflect_flags = new (mtClassShared) GrowableArray<int>(100, mtClassShared);
299     }
300     _tmp_reflect_klasses->append(ik);
301     _tmp_reflect_flags->append(rd_flags);
302   }
303 }
304 
305 void FinalImageRecipes::add_dynamic_proxy_class(oop loader, const char* proxy_name, objArrayOop interfaces, int access_flags) {
306   int loader_type;
307   if (loader == nullptr) {
308     loader_type = ClassLoader::BOOT_LOADER;
309   } else if (loader == SystemDictionary::java_platform_loader()) {
310     loader_type = ClassLoader::PLATFORM_LOADER;
311   } else if (loader == SystemDictionary::java_system_loader()) {
312     loader_type = ClassLoader::APP_LOADER;
313   } else {
314     return;
315   }
316 
317   MutexLocker mu(FinalImageRecipes_lock, Mutex::_no_safepoint_check_flag);
318   if (_tmp_dynamic_proxy_classes == nullptr) {
319     _tmp_dynamic_proxy_classes = new (mtClassShared) GrowableArray<TmpDynamicProxyClassInfo>(32, mtClassShared);
320   }
321 
322   log_info(cds, dynamic, proxy)("Adding proxy name %s", proxy_name);
323 
324   TmpDynamicProxyClassInfo info;
325   info._loader_type = loader_type;
326   info._access_flags = access_flags;
327   info._proxy_name = os::strdup(proxy_name);
328   info._interfaces = new (mtClassShared) GrowableArray<Klass*>(interfaces->length(), mtClassShared);
329   for (int i = 0; i < interfaces->length(); i++) {
330     Klass* intf = java_lang_Class::as_Klass(interfaces->obj_at(i));
331     info._interfaces->append(InstanceKlass::cast(intf));
332 
333     if (log_is_enabled(Info, cds, dynamic, proxy)) {
334       ResourceMark rm;
335       log_info(cds, dynamic, proxy)("interface[%d] = %s", i, intf->external_name());
336     }
337   }
338   _tmp_dynamic_proxy_classes->append(info);
339 }
340 
341 void FinalImageRecipes::apply_recipes_for_dynamic_proxies(TRAPS) {
342   if (CDSConfig::is_dumping_dynamic_proxies() && _dynamic_proxy_classes != nullptr) {
343     for (int proxy_index = 0; proxy_index < _dynamic_proxy_classes->length(); proxy_index++) {
344       DynamicProxyClassInfo* info = _dynamic_proxy_classes->adr_at(proxy_index);
345 
346       Handle loader(THREAD, ArchiveUtils::builtin_loader_from_type(info->_loader_type));
347       oop proxy_name_oop = java_lang_String::create_oop_from_str(info->_proxy_name, CHECK);
348       Handle proxy_name(THREAD, proxy_name_oop);
349 
350       int num_intfs = info->_interfaces->length();
351       objArrayOop interfaces_oop = oopFactory::new_objArray(vmClasses::Class_klass(), num_intfs, CHECK);
352       objArrayHandle interfaces(THREAD, interfaces_oop);
353       for (int intf_index = 0; intf_index < num_intfs; intf_index++) {
354         Klass* k = info->_interfaces->at(intf_index);
355         assert(k->java_mirror() != nullptr, "must be loaded");
356         interfaces()->obj_at_put(intf_index, k->java_mirror());
357       }
358 
359       AOTConstantPoolResolver::define_dynamic_proxy_class(loader, proxy_name, interfaces, info->_access_flags, CHECK);
360     }
361   }
362 }
363 
364 void FinalImageRecipes::record_recipes() {
365   assert(CDSConfig::is_dumping_preimage_static_archive(), "must be");
366   _final_image_recipes = new FinalImageRecipes();
367   _final_image_recipes->record_all_classes();
368   _final_image_recipes->record_recipes_for_constantpool();
369   _final_image_recipes->record_recipes_for_reflection_data();
370   _final_image_recipes->record_recipes_for_dynamic_proxies();
371 }
372 
373 void FinalImageRecipes::apply_recipes(TRAPS) {
374   assert(CDSConfig::is_dumping_final_static_archive(), "must be");
375   if (_final_image_recipes != nullptr) {
376     _final_image_recipes->apply_recipes_impl(THREAD);
377     if (HAS_PENDING_EXCEPTION) {
378       log_error(aot)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
379                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
380       log_error(aot)("Please check if your VM command-line is the same as in the training run");
381       AOTMetaspace::unrecoverable_writing_error("Unexpected exception, use -Xlog:aot,exceptions=trace for detail");
382     }
383   }
384 
385   // Set it to null as we don't need to write this table into the final image.
386   _final_image_recipes = nullptr;
387 }
388 
389 void FinalImageRecipes::apply_recipes_impl(TRAPS) {
390   load_all_classes(CHECK);
391   apply_recipes_for_constantpool(THREAD);
392   apply_recipes_for_reflection_data(CHECK);
393   apply_recipes_for_dynamic_proxies(CHECK);
394 }
395 
396 void FinalImageRecipes::serialize(SerializeClosure* soc) {
397   soc->do_ptr((void**)&_final_image_recipes);
398 }