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