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