1 /*
  2  * Copyright (c) 2020, 2026, 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/aotClassFilter.hpp"
 26 #include "cds/aotCompressedPointers.hpp"
 27 #include "cds/aotMetaspace.hpp"
 28 #include "cds/archiveBuilder.hpp"
 29 #include "cds/cdsConfig.hpp"
 30 #include "cds/lambdaFormInvokers.inline.hpp"
 31 #include "cds/regeneratedClasses.hpp"
 32 #include "classfile/classFileStream.hpp"
 33 #include "classfile/classLoadInfo.hpp"
 34 #include "classfile/javaClasses.inline.hpp"
 35 #include "classfile/klassFactory.hpp"
 36 #include "classfile/symbolTable.hpp"
 37 #include "classfile/systemDictionary.hpp"
 38 #include "classfile/systemDictionaryShared.hpp"
 39 #include "classfile/vmClasses.hpp"
 40 #include "classfile/vmSymbols.hpp"
 41 #include "logging/log.hpp"
 42 #include "memory/oopFactory.hpp"
 43 #include "memory/resourceArea.hpp"
 44 #include "oops/instanceKlass.hpp"
 45 #include "oops/klass.inline.hpp"
 46 #include "oops/objArrayKlass.hpp"
 47 #include "oops/objArrayOop.hpp"
 48 #include "oops/oop.inline.hpp"
 49 #include "oops/oopHandle.inline.hpp"
 50 #include "oops/typeArrayOop.inline.hpp"
 51 #include "runtime/handles.inline.hpp"
 52 #include "runtime/javaCalls.hpp"
 53 #include "runtime/mutexLocker.hpp"
 54 
 55 GrowableArrayCHeap<char*, mtClassShared>* LambdaFormInvokers::_lambdaform_lines = nullptr;
 56 Array<AOTCompressedPointers::narrowPtr>*  LambdaFormInvokers::_static_archive_invokers = nullptr;
 57 static bool _stop_appending = false;
 58 
 59 #define NUM_FILTER 4
 60 static const char* filter[NUM_FILTER] = {"java.lang.invoke.Invokers$Holder",
 61                                          "java.lang.invoke.DirectMethodHandle$Holder",
 62                                          "java.lang.invoke.DelegatingMethodHandle$Holder",
 63                                          "java.lang.invoke.LambdaForm$Holder"};
 64 
 65 static bool should_be_archived(char* line) {
 66   for (int k = 0; k < NUM_FILTER; k++) {
 67     if (strstr(line, filter[k]) != nullptr) {
 68       return true;
 69     }
 70   }
 71   return false;
 72 }
 73 #undef NUM_FILTER
 74 
 75 void LambdaFormInvokers::append(char* line) {
 76   // This function can be called by concurrent Java threads, even after
 77   // LambdaFormInvokers::regenerate_holder_classes() has been called.
 78   MutexLocker ml(Thread::current(), LambdaFormInvokers_lock);
 79   if (_stop_appending) {
 80     return;
 81   }
 82   if (_lambdaform_lines == nullptr) {
 83     _lambdaform_lines = new GrowableArrayCHeap<char*, mtClassShared>(150);
 84   }
 85   _lambdaform_lines->append(line);
 86 }
 87 
 88 
 89 // convenient output
 90 class PrintLambdaFormMessage {
 91  public:
 92   PrintLambdaFormMessage() {
 93     log_info(aot)("Regenerate MethodHandle Holder classes...");
 94   }
 95   ~PrintLambdaFormMessage() {
 96     log_info(aot)("Regenerate MethodHandle Holder classes...done");
 97   }
 98 };
 99 
100 class LambdaFormInvokersClassFilterMark : public AOTClassFilter::FilterMark {
101 public:
102   bool is_aot_tooling_class(InstanceKlass* ik) {
103     if (ik->name()->index_of_at(0, "$Species_", 9) > 0) {
104       // Classes like java.lang.invoke.BoundMethodHandle$Species_L should be included in AOT cache
105       return false;
106     }
107     if (LambdaFormInvokers::may_be_regenerated_class(ik->name())) {
108       // Regenerated holder classes should be included in AOT cache.
109       return false;
110     }
111     // Treat all other classes loaded during LambdaFormInvokers::regenerate_holder_classes() as
112     // "AOT tooling classes".
113     return true;
114   }
115 };
116 
117 void LambdaFormInvokers::regenerate_holder_classes(TRAPS) {
118   if (!CDSConfig::is_dumping_regenerated_lambdaform_invokers()) {
119     return;
120   }
121 
122   ResourceMark rm(THREAD);
123 
124   // Filter out AOT tooling classes like java.lang.invoke.GenerateJLIClassesHelper, etc.
125   LambdaFormInvokersClassFilterMark filter_mark;
126 
127   Symbol* cds_name  = vmSymbols::jdk_internal_misc_CDS();
128   Klass*  cds_klass = SystemDictionary::resolve_or_null(cds_name, THREAD);
129   guarantee(cds_klass != nullptr, "jdk/internal/misc/CDS must exist!");
130 
131   assert(CDSConfig::current_thread_is_dumper(), "not supposed to be called from other threads");
132   {
133     // Stop other threads from recording into _lambdaform_lines.
134     MutexLocker ml(Thread::current(), LambdaFormInvokers_lock);
135     _stop_appending = true;
136   }
137 
138   PrintLambdaFormMessage plm;
139   if (_lambdaform_lines == nullptr || _lambdaform_lines->length() == 0) {
140     log_info(aot)("Nothing to regenerate for lambda form holder classes");
141     return;
142   }
143 
144   HandleMark hm(THREAD);
145   int len = _lambdaform_lines->length();
146   objArrayHandle list_lines = oopFactory::new_objArray_handle(vmClasses::String_klass(), len, CHECK);
147   for (int i = 0; i < len; i++) {
148     Handle h_line = java_lang_String::create_from_str(_lambdaform_lines->at(i), CHECK);
149     list_lines->obj_at_put(i, h_line());
150   }
151 
152   // Object[] CDS.generateLambdaFormHolderClasses(String[] lines)
153   // the returned Object[] layout:
154   //   name, byte[], name, byte[] ....
155   Symbol* method = vmSymbols::generateLambdaFormHolderClasses();
156   Symbol* signrs = vmSymbols::generateLambdaFormHolderClasses_signature();
157 
158   JavaValue result(T_OBJECT);
159   JavaCalls::call_static(&result, cds_klass, method, signrs, list_lines, THREAD);
160 
161   if (HAS_PENDING_EXCEPTION) {
162     if (!PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
163       log_error(aot)("%s: %s", PENDING_EXCEPTION->klass()->external_name(),
164                      java_lang_String::as_utf8_string(java_lang_Throwable::message(PENDING_EXCEPTION)));
165       if (CDSConfig::is_dumping_static_archive()) {
166         log_error(aot)("Failed to generate LambdaForm holder classes. Is your classlist out of date?");
167       } else {
168         log_error(aot)("Failed to generate LambdaForm holder classes. Was the base archive generated with an outdated classlist?");
169       }
170       CLEAR_PENDING_EXCEPTION;
171     }
172     return;
173   }
174 
175   objArrayHandle h_array(THREAD, (objArrayOop)result.get_oop());
176   int sz = h_array->length();
177   assert(sz % 2 == 0 && sz >= 2, "Must be even size of length");
178   for (int i = 0; i < sz; i+= 2) {
179     Handle h_name(THREAD, h_array->obj_at(i));
180     typeArrayHandle h_bytes(THREAD, (typeArrayOop)h_array->obj_at(i+1));
181     assert(h_name != nullptr, "Class name is null");
182     assert(h_bytes != nullptr, "Class bytes is null");
183 
184     char *class_name = java_lang_String::as_utf8_string(h_name());
185     if (strstr(class_name, "java/lang/invoke/BoundMethodHandle$Species_") != nullptr) {
186       // The species classes are already loaded into the system dictionary
187       // during the execution of CDS.generateLambdaFormHolderClasses(). No
188       // need to regenerate.
189       TempNewSymbol class_name_sym = SymbolTable::new_symbol(class_name);
190       Klass* klass = SystemDictionary::resolve_or_null(class_name_sym, THREAD);
191       assert(klass != nullptr, "must already be loaded");
192       if (!klass->in_aot_cache() && klass->shared_classpath_index() < 0) {
193         // Fake it, so that it will be included into the archive.
194         klass->set_shared_classpath_index(0);
195         // Set the "generated" bit, so it won't interfere with JVMTI.
196         // See SystemDictionaryShared::find_builtin_class().
197         klass->set_is_aot_generated_class();
198       }
199     } else {
200       int len = h_bytes->length();
201       // make a copy of class bytes so GC will not affect us.
202       char *buf = NEW_RESOURCE_ARRAY(char, len);
203       memcpy(buf, (char*)h_bytes->byte_at_addr(0), len);
204       ClassFileStream st((u1*)buf, len, "jrt:/java.base");
205       regenerate_class(class_name, st, CHECK);
206     }
207   }
208 }
209 
210 void LambdaFormInvokers::regenerate_class(char* class_name, ClassFileStream& st, TRAPS) {
211   TempNewSymbol class_name_sym = SymbolTable::new_symbol(class_name);
212   Klass* klass = SystemDictionary::resolve_or_null(class_name_sym, THREAD);
213   assert(klass != nullptr, "must exist");
214   assert(klass->is_instance_klass(), "Should be");
215 
216   ClassLoaderData* cld = ClassLoaderData::the_null_class_loader_data();
217   Handle protection_domain;
218   ClassLoadInfo cl_info(protection_domain);
219 
220   InstanceKlass* result = KlassFactory::create_from_stream(&st,
221                                                    class_name_sym,
222                                                    cld,
223                                                    cl_info,
224                                                    CHECK);
225 
226   assert(result->java_mirror() != nullptr, "must be");
227   RegeneratedClasses::add_class(InstanceKlass::cast(klass), result);
228 
229   result->add_to_hierarchy(THREAD);
230 
231   // new class not linked yet.
232   AOTMetaspace::try_link_class(THREAD, result);
233   assert(!HAS_PENDING_EXCEPTION, "Invariant");
234 
235   result->set_is_aot_generated_class();
236   if (!klass->in_aot_cache()) {
237     log_info(aot, lambda)("regenerate_class excluding klass %s %s", class_name, klass->name()->as_C_string());
238     SystemDictionaryShared::set_excluded(InstanceKlass::cast(klass)); // exclude the existing class from dump
239   }
240   log_info(aot, lambda)("Regenerated class %s, old: " INTPTR_FORMAT " new: " INTPTR_FORMAT,
241                  class_name, p2i(klass), p2i(result));
242 }
243 
244 void LambdaFormInvokers::dump_static_archive_invokers() {
245   assert(SafepointSynchronize::is_at_safepoint(), "no concurrent update to _lambdaform_lines");
246   if (_lambdaform_lines != nullptr && _lambdaform_lines->length() > 0) {
247     int count = 0;
248     int len   = _lambdaform_lines->length();
249     for (int i = 0; i < len; i++) {
250       char* str = _lambdaform_lines->at(i);
251       if (should_be_archived(str)) {
252         count++;
253       }
254     }
255     if (count > 0) {
256       _static_archive_invokers = ArchiveBuilder::new_ro_array<narrowPtr>(count);
257       int index = 0;
258       for (int i = 0; i < len; i++) {
259         char* str = _lambdaform_lines->at(i);
260         if (should_be_archived(str)) {
261           size_t str_len = strlen(str) + 1;  // including terminating zero
262           Array<char>* line = ArchiveBuilder::new_ro_array<char>((int)str_len);
263           strncpy(line->adr_at(0), str, str_len);
264 
265           _static_archive_invokers->at_put(index, AOTCompressedPointers::encode_not_null(line));
266           index++;
267         }
268       }
269       assert(index == count, "Should match");
270     }
271     log_debug(aot)("Total LF lines stored into %s: %d", CDSConfig::type_of_archive_being_written(), count);
272   }
273 }
274 
275 void LambdaFormInvokers::read_static_archive_invokers() {
276   if (_static_archive_invokers != nullptr) {
277     for (int i = 0; i < _static_archive_invokers->length(); i++) {
278       narrowPtr encoded = _static_archive_invokers->at(i);
279       Array<char>* line = AOTCompressedPointers::decode_not_null<Array<char>*>(encoded);
280       char* str = line->adr_at(0);
281       append(str);
282     }
283     log_debug(aot)("Total LF lines read from %s: %d", CDSConfig::type_of_archive_being_loaded(), _static_archive_invokers->length());
284   }
285 }
286 
287 void LambdaFormInvokers::serialize(SerializeClosure* soc) {
288   soc->do_ptr(&_static_archive_invokers);
289   if (soc->reading() && CDSConfig::is_dumping_final_static_archive()) {
290     if (!CDSConfig::is_dumping_aot_linked_classes()) {
291       // See CDSConfig::is_dumping_regenerated_lambdaform_invokers() -- a dynamic archive can
292       // regenerate lambda form invokers only if the base archive does not contain aot-linked classes.
293       // If so, we copy the contents of _static_archive_invokers (from the preimage) into
294       //_lambdaform_lines, which will be written as _static_archive_invokers into final static archive.
295       LambdaFormInvokers::read_static_archive_invokers();
296     }
297     _static_archive_invokers = nullptr;
298   }
299 }