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/aotClassLinker.hpp"
 26 #include "cds/aotConstantPoolResolver.hpp"
 27 #include "cds/aotLinkedClassTable.hpp"
 28 #include "cds/archiveBuilder.hpp"
 29 #include "cds/archiveUtils.inline.hpp"
 30 #include "cds/cdsConfig.hpp"
 31 #include "cds/heapShared.hpp"
 32 #include "cds/lambdaFormInvokers.inline.hpp"
 33 #include "classfile/classLoader.hpp"
 34 #include "classfile/dictionary.hpp"
 35 #include "classfile/systemDictionary.hpp"
 36 #include "classfile/systemDictionaryShared.hpp"
 37 #include "classfile/vmClasses.hpp"
 38 #include "memory/resourceArea.hpp"
 39 #include "oops/constantPool.inline.hpp"
 40 #include "oops/instanceKlass.hpp"
 41 #include "oops/klass.inline.hpp"
 42 #include "runtime/handles.inline.hpp"
 43 
 44 AOTClassLinker::ClassesTable* AOTClassLinker::_vm_classes = nullptr;
 45 AOTClassLinker::ClassesTable* AOTClassLinker::_candidates = nullptr;
 46 GrowableArrayCHeap<InstanceKlass*, mtClassShared>* AOTClassLinker::_sorted_candidates = nullptr;
 47 
 48 #ifdef ASSERT
 49 bool AOTClassLinker::is_initialized() {
 50   assert(CDSConfig::is_dumping_archive(), "AOTClassLinker is for CDS dumping only");
 51   return _vm_classes != nullptr;
 52 }
 53 #endif
 54 
 55 void AOTClassLinker::initialize() {
 56   assert(!is_initialized(), "sanity");
 57 
 58   _vm_classes = new (mtClass)ClassesTable();
 59   _candidates = new (mtClass)ClassesTable();
 60   _sorted_candidates = new GrowableArrayCHeap<InstanceKlass*, mtClassShared>(1000);
 61 
 62   for (auto id : EnumRange<vmClassID>{}) {
 63     add_vm_class(vmClasses::klass_at(id));
 64   }
 65 
 66   assert(is_initialized(), "sanity");
 67 
 68   AOTConstantPoolResolver::initialize();
 69 }
 70 
 71 void AOTClassLinker::dispose() {
 72   assert(is_initialized(), "sanity");
 73 
 74   delete _vm_classes;
 75   delete _candidates;
 76   delete _sorted_candidates;
 77   _vm_classes = nullptr;
 78   _candidates = nullptr;
 79   _sorted_candidates = nullptr;
 80 
 81   assert(!is_initialized(), "sanity");
 82 
 83   AOTConstantPoolResolver::dispose();
 84 }
 85 
 86 bool AOTClassLinker::is_vm_class(InstanceKlass* ik) {
 87   assert(is_initialized(), "sanity");
 88   return (_vm_classes->get(ik) != nullptr);
 89 }
 90 
 91 void AOTClassLinker::add_vm_class(InstanceKlass* ik) {
 92   assert(is_initialized(), "sanity");
 93   bool created;
 94   _vm_classes->put_if_absent(ik, &created);
 95   if (created) {
 96     if (CDSConfig::is_dumping_aot_linked_classes()) {
 97       bool v = try_add_candidate(ik);
 98       assert(v, "must succeed for VM class");
 99     }
100     InstanceKlass* super = ik->java_super();
101     if (super != nullptr) {
102       add_vm_class(super);
103     }
104     Array<InstanceKlass*>* ifs = ik->local_interfaces();
105     for (int i = 0; i < ifs->length(); i++) {
106       add_vm_class(ifs->at(i));
107     }
108   }
109 }
110 
111 bool AOTClassLinker::is_candidate(InstanceKlass* ik) {
112   return (_candidates->get(ik) != nullptr);
113 }
114 
115 void AOTClassLinker::add_new_candidate(InstanceKlass* ik) {
116   assert(!is_candidate(ik), "caller need to check");
117   _candidates->put_when_absent(ik, true);
118   _sorted_candidates->append(ik);
119 
120   if (log_is_enabled(Info, cds, aot, link)) {
121     ResourceMark rm;
122     log_info(cds, aot, link)("%s %s %p", class_category_name(ik), ik->external_name(), ik);
123   }
124 }
125 
126 // ik is a candidate for aot-linking; see if it can really work
127 // that way, and return success or failure. Not only must ik itself
128 // look like a class that can be aot-linked but its supers must also be
129 // aot-linkable.
130 bool AOTClassLinker::try_add_candidate(InstanceKlass* ik) {
131   assert(is_initialized(), "sanity");
132   assert(CDSConfig::is_dumping_aot_linked_classes(), "sanity");
133 
134   if (!SystemDictionaryShared::is_builtin(ik)) {
135     // not loaded by a class loader which we know about
136     return false;
137   }
138 
139   if (is_candidate(ik)) { // already checked.
140     return true;
141   }
142 
143   if (ik->is_hidden()) {
144     assert(ik->shared_class_loader_type() != ClassLoader::OTHER, "must have been set");
145     if (!CDSConfig::is_dumping_invokedynamic()) {
146       return false;
147     }
148     if (HeapShared::is_lambda_proxy_klass(ik)) {
149       InstanceKlass* nest_host = ik->nest_host_not_null();
150       if (!try_add_candidate(nest_host)) {
151         ResourceMark rm;
152         log_warning(cds, aot, link)("%s cannot be aot-linked because it nest host is not aot-linked", ik->external_name());
153         return false;
154       }
155     }
156   }
157 
158   InstanceKlass* s = ik->java_super();
159   if (s != nullptr && !try_add_candidate(s)) {
160     return false;
161   }
162 
163   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
164   int num_interfaces = interfaces->length();
165   for (int index = 0; index < num_interfaces; index++) {
166     InstanceKlass* intf = interfaces->at(index);
167     if (!try_add_candidate(intf)) {
168       return false;
169     }
170   }
171 
172   // There are no loops in the class hierarchy, and this function is always called single-threaded, so
173   // we know ik has not been added yet.
174   assert(CDSConfig::current_thread_is_vm_or_dumper(), "that's why we don't need locks");
175   add_new_candidate(ik);
176 
177   return true;
178 }
179 
180 void AOTClassLinker::add_candidates() {
181   assert_at_safepoint();
182   if (CDSConfig::is_dumping_aot_linked_classes()) {
183     GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
184     for (GrowableArrayIterator<Klass*> it = klasses->begin(); it != klasses->end(); ++it) {
185       Klass* k = *it;
186       if (k->is_instance_klass()) {
187         try_add_candidate(InstanceKlass::cast(k));
188       }
189     }
190   }
191 }
192 
193 void AOTClassLinker::write_to_archive() {
194   assert(is_initialized(), "sanity");
195   assert_at_safepoint();
196 
197   if (CDSConfig::is_dumping_aot_linked_classes()) {
198     AOTLinkedClassTable* table = AOTLinkedClassTable::get(CDSConfig::is_dumping_static_archive());
199     table->set_boot(write_classes(nullptr, true));
200     table->set_boot2(write_classes(nullptr, false));
201     table->set_platform(write_classes(SystemDictionary::java_platform_loader(), false));
202     table->set_app(write_classes(SystemDictionary::java_system_loader(), false));
203   }
204 }
205 
206 Array<InstanceKlass*>* AOTClassLinker::write_classes(oop class_loader, bool is_javabase) {
207   ResourceMark rm;
208   GrowableArray<InstanceKlass*> list;
209 
210   for (int i = 0; i < _sorted_candidates->length(); i++) {
211     InstanceKlass* ik = _sorted_candidates->at(i);
212     if (ik->class_loader() != class_loader) {
213       continue;
214     }
215     if ((ik->module() == ModuleEntryTable::javabase_moduleEntry()) != is_javabase) {
216       continue;
217     }
218 
219     if (ik->is_shared() && CDSConfig::is_dumping_dynamic_archive()) {
220       if (CDSConfig::is_using_aot_linked_classes()) {
221         // This class was recorded as AOT-linked for the base archive,
222         // so there's no need to do so again for the dynamic archive.
223       } else {
224         list.append(ik);
225       }
226     } else {
227       list.append(ArchiveBuilder::current()->get_buffered_addr(ik));
228     }
229   }
230 
231   if (list.length() == 0) {
232     return nullptr;
233   } else {
234     const char* category = class_category_name(list.at(0));
235     log_info(cds, aot, link)("wrote %d class(es) for category %s", list.length(), category);
236     return ArchiveUtils::archive_array(&list);
237   }
238 }
239 
240 int AOTClassLinker::num_platform_initiated_classes() {
241   if (CDSConfig::is_dumping_aot_linked_classes()) {
242     // AOTLinkedClassBulkLoader will initiate loading of all public boot classes in the platform loader.
243     return count_public_classes(nullptr);
244   } else {
245     return 0;
246   }
247 }
248 
249 int AOTClassLinker::num_app_initiated_classes() {
250   if (CDSConfig::is_dumping_aot_linked_classes()) {
251     // AOTLinkedClassBulkLoader will initiate loading of all public boot/platform classes in the app loader.
252     return count_public_classes(nullptr) + count_public_classes(SystemDictionary::java_platform_loader());
253   } else {
254     return 0;
255   }
256 }
257 
258 int AOTClassLinker::count_public_classes(oop loader) {
259   int n = 0;
260   for (int i = 0; i < _sorted_candidates->length(); i++) {
261     InstanceKlass* ik = _sorted_candidates->at(i);
262     if (ik->is_public() && !ik->is_hidden() && ik->class_loader() == loader) {
263       n++;
264     }
265   }
266 
267   return n;
268 }
269 
270 // Used in logging: "boot1", "boot2", "plat", "app" and "unreg", or "array"
271 const char* AOTClassLinker::class_category_name(Klass* k) {
272   if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(k)) {
273     k = ArchiveBuilder::current()->get_source_addr(k);
274   }
275 
276   if (k->is_array_klass()) {
277     return "array";
278   } else {
279     oop loader = k->class_loader();
280     if (loader == nullptr) {
281       if (k->module() != nullptr &&
282           k->module()->name() != nullptr &&
283           k->module()->name()->equals("java.base")) {
284         return "boot1"; // boot classes in java.base are loaded in the 1st phase
285       } else {
286         return "boot2"; // boot classes outside of java.base are loaded in the 2nd phase phase
287       }
288     } else {
289       if (loader == SystemDictionary::java_platform_loader()) {
290         return "plat";
291       } else if (loader == SystemDictionary::java_system_loader()) {
292         return "app";
293       } else {
294         return "unreg";
295       }
296     }
297   }
298 }
299 
300 const char* AOTClassLinker::class_category_name(AOTLinkedClassCategory category) {
301   switch (category) {
302   case AOTLinkedClassCategory::BOOT1:
303     return "boot1";
304   case AOTLinkedClassCategory::BOOT2:
305     return "boot2";
306   case AOTLinkedClassCategory::PLATFORM:
307     return "plat";
308   case AOTLinkedClassCategory::APP:
309     return "app";
310   case AOTLinkedClassCategory::UNREGISTERED:
311   default:
312       return "unreg";
313   }
314 }