1 /*
  2  * Copyright (c) 2022, 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/aotClassLocation.hpp"
 27 #include "cds/aotConstantPoolResolver.hpp"
 28 #include "cds/aotLogging.hpp"
 29 #include "cds/archiveBuilder.hpp"
 30 #include "cds/archiveUtils.inline.hpp"
 31 #include "cds/cdsConfig.hpp"
 32 #include "cds/classListWriter.hpp"
 33 #include "cds/finalImageRecipes.hpp"
 34 #include "cds/heapShared.hpp"
 35 #include "cds/lambdaFormInvokers.inline.hpp"
 36 #include "classfile/classLoader.hpp"
 37 #include "classfile/dictionary.hpp"
 38 #include "classfile/symbolTable.hpp"
 39 #include "classfile/systemDictionary.hpp"
 40 #include "classfile/systemDictionaryShared.hpp"
 41 #include "classfile/vmClasses.hpp"
 42 #include "interpreter/bytecodeStream.hpp"
 43 #include "interpreter/interpreterRuntime.hpp"
 44 #include "memory/resourceArea.hpp"
 45 #include "oops/constantPool.inline.hpp"
 46 #include "oops/fieldStreams.inline.hpp"
 47 #include "oops/instanceKlass.hpp"
 48 #include "oops/klass.inline.hpp"
 49 #include "runtime/handles.inline.hpp"
 50 #include "runtime/javaCalls.hpp"
 51 #include "runtime/signature.hpp"
 52 
 53 // Returns true if we CAN PROVE that cp_index will always resolve to
 54 // the same information at both dump time and run time. This is a
 55 // necessary (but not sufficient) condition for pre-resolving cp_index
 56 // during CDS archive assembly.
 57 bool AOTConstantPoolResolver::is_resolution_deterministic(ConstantPool* cp, int cp_index) {
 58   assert(!is_in_archivebuilder_buffer(cp), "sanity");
 59 
 60   if (cp->tag_at(cp_index).is_klass()) {
 61     // We require cp_index to be already resolved. This is fine for now, are we
 62     // currently archive only CP entries that are already resolved.
 63     Klass* resolved_klass = cp->resolved_klass_at(cp_index);
 64     return resolved_klass != nullptr && is_class_resolution_deterministic(cp->pool_holder(), resolved_klass);
 65   } else if (cp->tag_at(cp_index).is_invoke_dynamic()) {
 66     return is_indy_resolution_deterministic(cp, cp_index);
 67   } else if (cp->tag_at(cp_index).is_field() ||
 68              cp->tag_at(cp_index).is_method() ||
 69              cp->tag_at(cp_index).is_interface_method()) {
 70     int klass_cp_index = cp->uncached_klass_ref_index_at(cp_index);
 71     if (!cp->tag_at(klass_cp_index).is_klass()) {
 72       // Not yet resolved
 73       return false;
 74     }
 75     Klass* k = cp->resolved_klass_at(klass_cp_index);
 76     if (!is_class_resolution_deterministic(cp->pool_holder(), k)) {
 77       return false;
 78     }
 79 
 80     if (!k->is_instance_klass()) {
 81       // TODO: support non instance klasses as well.
 82       return false;
 83     }
 84 
 85     // Here, We don't check if this entry can actually be resolved to a valid Field/Method.
 86     // This method should be called by the ConstantPool to check Fields/Methods that
 87     // have already been successfully resolved.
 88     return true;
 89   } else {
 90     return false;
 91   }
 92 }
 93 
 94 bool AOTConstantPoolResolver::is_class_resolution_deterministic(InstanceKlass* cp_holder, Klass* resolved_class) {
 95   assert(!is_in_archivebuilder_buffer(cp_holder), "sanity");
 96   assert(!is_in_archivebuilder_buffer(resolved_class), "sanity");
 97 
 98   if (resolved_class->is_instance_klass()) {
 99     InstanceKlass* ik = InstanceKlass::cast(resolved_class);
100 
101     if (!ik->in_aot_cache() && SystemDictionaryShared::is_excluded_class(ik)) {
102       return false;
103     }
104 
105     if (cp_holder->is_subtype_of(ik)) {
106       // All super types of ik will be resolved in ik->class_loader() before
107       // ik is defined in this loader, so it's safe to archive the resolved klass reference.
108       return true;
109     }
110 
111     if (CDSConfig::is_dumping_aot_linked_classes()) {
112       // Need to call try_add_candidate instead of is_candidate, as this may be called
113       // before AOTClassLinker::add_candidates().
114       if (AOTClassLinker::try_add_candidate(ik)) {
115         return true;
116       } else {
117         return false;
118       }
119     } else if (AOTClassLinker::is_vm_class(ik)) {
120       if (ik->class_loader() != cp_holder->class_loader()) {
121         // At runtime, cp_holder() may not be able to resolve to the same
122         // ik. For example, a different version of ik may be defined in
123         // cp->pool_holder()'s loader using MethodHandles.Lookup.defineClass().
124         return false;
125       } else {
126         return true;
127       }
128     } else {
129       return false;
130     }
131   } else if (resolved_class->is_objArray_klass()) {
132     Klass* elem = ObjArrayKlass::cast(resolved_class)->bottom_klass();
133     if (elem->is_instance_klass()) {
134       return is_class_resolution_deterministic(cp_holder, InstanceKlass::cast(elem));
135     } else if (elem->is_typeArray_klass()) {
136       return true;
137     } else {
138       return false;
139     }
140   } else if (resolved_class->is_typeArray_klass()) {
141     return true;
142   } else {
143     return false;
144   }
145 }
146 
147 void AOTConstantPoolResolver::preresolve_string_cp_entries(InstanceKlass* ik, TRAPS) {
148   if (!ik->is_linked()) {
149     // The cp->resolved_referenced() array is not ready yet, so we can't call resolve_string().
150     return;
151   }
152   constantPoolHandle cp(THREAD, ik->constants());
153   for (int cp_index = 1; cp_index < cp->length(); cp_index++) { // Index 0 is unused
154     switch (cp->tag_at(cp_index).value()) {
155     case JVM_CONSTANT_String:
156       resolve_string(cp, cp_index, CHECK); // may throw OOM when interning strings.
157       break;
158     }
159   }
160 
161   // Normally, we don't want to archive any CP entries that were not resolved
162   // in the training run. Otherwise the AOT/JIT may inline too much code that has not
163   // been executed.
164   //
165   // However, we want to aggressively resolve all klass/field/method constants for
166   // LambdaForm Invoker Holder classes, Lambda Proxy classes, and LambdaForm classes,
167   // so that the compiler can inline through them.
168   if (SystemDictionaryShared::is_builtin_loader(ik->class_loader_data())) {
169     bool eager_resolve = false;
170 
171     if (LambdaFormInvokers::may_be_regenerated_class(ik->name())) {
172       eager_resolve = true;
173     }
174     if (ik->is_hidden() && HeapShared::is_archivable_hidden_klass(ik)) {
175       eager_resolve = true;
176     }
177 
178     if (eager_resolve) {
179       preresolve_class_cp_entries(THREAD, ik, nullptr);
180       preresolve_field_and_method_cp_entries(THREAD, ik, nullptr);
181     }
182   }
183 }
184 
185 // This works only for the boot/platform/app loaders
186 Klass* AOTConstantPoolResolver::find_loaded_class(Thread* current, oop class_loader, Symbol* name) {
187   HandleMark hm(current);
188   Handle h_loader(current, class_loader);
189   Klass* k = SystemDictionary::find_instance_or_array_klass(current, name, h_loader);
190   if (k != nullptr) {
191     return k;
192   }
193   if (h_loader() == SystemDictionary::java_system_loader()) {
194     return find_loaded_class(current, SystemDictionary::java_platform_loader(), name);
195   } else if (h_loader() == SystemDictionary::java_platform_loader()) {
196     return find_loaded_class(current, nullptr, name);
197   } else {
198     assert(h_loader() == nullptr, "This function only works for boot/platform/app loaders %p %p %p",
199            cast_from_oop<address>(h_loader()),
200            cast_from_oop<address>(SystemDictionary::java_system_loader()),
201            cast_from_oop<address>(SystemDictionary::java_platform_loader()));
202   }
203 
204   return nullptr;
205 }
206 
207 Klass* AOTConstantPoolResolver::find_loaded_class(Thread* current, ConstantPool* cp, int class_cp_index) {
208   Symbol* name = cp->klass_name_at(class_cp_index);
209   return find_loaded_class(current, cp->pool_holder()->class_loader(), name);
210 }
211 
212 #if INCLUDE_CDS_JAVA_HEAP
213 void AOTConstantPoolResolver::resolve_string(constantPoolHandle cp, int cp_index, TRAPS) {
214   if (CDSConfig::is_dumping_heap()) {
215     int cache_index = cp->cp_to_object_index(cp_index);
216     ConstantPool::string_at_impl(cp, cp_index, cache_index, CHECK);
217   }
218 }
219 #endif
220 
221 void AOTConstantPoolResolver::preresolve_class_cp_entries(JavaThread* current, InstanceKlass* ik, GrowableArray<bool>* preresolve_list) {
222   if (!SystemDictionaryShared::is_builtin_loader(ik->class_loader_data())) {
223     return;
224   }
225 
226   JavaThread* THREAD = current;
227   constantPoolHandle cp(THREAD, ik->constants());
228   for (int cp_index = 1; cp_index < cp->length(); cp_index++) {
229     if (cp->tag_at(cp_index).value() == JVM_CONSTANT_UnresolvedClass) {
230       if (preresolve_list != nullptr && preresolve_list->at(cp_index) == false) {
231         // This class was not resolved during trial run. Don't attempt to resolve it. Otherwise
232         // the compiler may generate less efficient code.
233         continue;
234       }
235       if (find_loaded_class(current, cp(), cp_index) == nullptr) {
236         // Do not resolve any class that has not been loaded yet
237         continue;
238       }
239       Klass* resolved_klass = cp->klass_at(cp_index, THREAD);
240       if (HAS_PENDING_EXCEPTION) {
241         CLEAR_PENDING_EXCEPTION; // just ignore
242       } else {
243         log_trace(aot, resolve)("Resolved class  [%3d] %s -> %s", cp_index, ik->external_name(),
244                                 resolved_klass->external_name());
245       }
246     }
247   }
248 }
249 
250 void AOTConstantPoolResolver::preresolve_field_and_method_cp_entries(JavaThread* current, InstanceKlass* ik, GrowableArray<bool>* preresolve_list) {
251   JavaThread* THREAD = current;
252   constantPoolHandle cp(THREAD, ik->constants());
253   if (cp->cache() == nullptr) {
254     return;
255   }
256   for (int i = 0; i < ik->methods()->length(); i++) {
257     Method* m = ik->methods()->at(i);
258     BytecodeStream bcs(methodHandle(THREAD, m));
259     while (!bcs.is_last_bytecode()) {
260       bcs.next();
261       Bytecodes::Code raw_bc = bcs.raw_code();
262       switch (raw_bc) {
263       case Bytecodes::_getstatic:
264       case Bytecodes::_putstatic:
265         maybe_resolve_fmi_ref(ik, m, raw_bc, bcs.get_index_u2(), preresolve_list, THREAD);
266         if (HAS_PENDING_EXCEPTION) {
267           CLEAR_PENDING_EXCEPTION; // just ignore
268         }
269         break;
270       case Bytecodes::_getfield:
271       // no-fast bytecode
272       case Bytecodes::_nofast_getfield:
273       // fast bytecodes
274       case Bytecodes::_fast_agetfield:
275       case Bytecodes::_fast_bgetfield:
276       case Bytecodes::_fast_cgetfield:
277       case Bytecodes::_fast_dgetfield:
278       case Bytecodes::_fast_fgetfield:
279       case Bytecodes::_fast_igetfield:
280       case Bytecodes::_fast_lgetfield:
281       case Bytecodes::_fast_sgetfield:
282         raw_bc = Bytecodes::_getfield;
283         maybe_resolve_fmi_ref(ik, m, raw_bc, bcs.get_index_u2(), preresolve_list, THREAD);
284         if (HAS_PENDING_EXCEPTION) {
285           CLEAR_PENDING_EXCEPTION; // just ignore
286         }
287         break;
288 
289       case Bytecodes::_putfield:
290       // no-fast bytecode
291       case Bytecodes::_nofast_putfield:
292       // fast bytecodes
293       case Bytecodes::_fast_aputfield:
294       case Bytecodes::_fast_bputfield:
295       case Bytecodes::_fast_zputfield:
296       case Bytecodes::_fast_cputfield:
297       case Bytecodes::_fast_dputfield:
298       case Bytecodes::_fast_fputfield:
299       case Bytecodes::_fast_iputfield:
300       case Bytecodes::_fast_lputfield:
301       case Bytecodes::_fast_sputfield:
302         raw_bc = Bytecodes::_putfield;
303         maybe_resolve_fmi_ref(ik, m, raw_bc, bcs.get_index_u2(), preresolve_list, THREAD);
304         if (HAS_PENDING_EXCEPTION) {
305           CLEAR_PENDING_EXCEPTION; // just ignore
306         }
307         break;
308       case Bytecodes::_invokehandle:
309       case Bytecodes::_invokespecial:
310       case Bytecodes::_invokevirtual:
311       case Bytecodes::_invokeinterface:
312       case Bytecodes::_invokestatic:
313         maybe_resolve_fmi_ref(ik, m, raw_bc, bcs.get_index_u2(), preresolve_list, THREAD);
314         if (HAS_PENDING_EXCEPTION) {
315           CLEAR_PENDING_EXCEPTION; // just ignore
316         }
317         break;
318       default:
319         break;
320       }
321     }
322   }
323 }
324 
325 void AOTConstantPoolResolver::maybe_resolve_fmi_ref(InstanceKlass* ik, Method* m, Bytecodes::Code bc, int raw_index,
326                                            GrowableArray<bool>* preresolve_list, TRAPS) {
327   methodHandle mh(THREAD, m);
328   constantPoolHandle cp(THREAD, ik->constants());
329   HandleMark hm(THREAD);
330   int cp_index = cp->to_cp_index(raw_index, bc);
331 
332   if (cp->is_resolved(raw_index, bc)) {
333     return;
334   }
335 
336   if (preresolve_list != nullptr && preresolve_list->at(cp_index) == false) {
337     // This field wasn't resolved during the trial run. Don't attempt to resolve it. Otherwise
338     // the compiler may generate less efficient code.
339     return;
340   }
341 
342   int klass_cp_index = cp->uncached_klass_ref_index_at(cp_index);
343   if (find_loaded_class(THREAD, cp(), klass_cp_index) == nullptr) {
344     // Do not resolve any field/methods from a class that has not been loaded yet.
345     return;
346   }
347 
348   Klass* resolved_klass = cp->klass_ref_at(raw_index, bc, CHECK);
349   const char* is_static = "";
350 
351   switch (bc) {
352   case Bytecodes::_getstatic:
353   case Bytecodes::_putstatic:
354     if (!VM_Version::supports_fast_class_init_checks()) {
355       return; // Do not resolve since interpreter lacks fast clinit barriers support
356     }
357     InterpreterRuntime::resolve_get_put(bc, raw_index, mh, cp, ClassInitMode::dont_init, CHECK);
358     is_static = " *** static";
359     break;
360 
361   case Bytecodes::_getfield:
362   case Bytecodes::_putfield:
363     InterpreterRuntime::resolve_get_put(bc, raw_index, mh, cp, ClassInitMode::dont_init, CHECK);
364     break;
365 
366   case Bytecodes::_invokestatic:
367     if (!VM_Version::supports_fast_class_init_checks()) {
368       return; // Do not resolve since interpreter lacks fast clinit barriers support
369     }
370     InterpreterRuntime::cds_resolve_invoke(bc, raw_index, cp, CHECK);
371     is_static = " *** static";
372     break;
373 
374   case Bytecodes::_invokevirtual:
375   case Bytecodes::_invokespecial:
376   case Bytecodes::_invokeinterface:
377     InterpreterRuntime::cds_resolve_invoke(bc, raw_index, cp, CHECK);
378     break;
379 
380   case Bytecodes::_invokehandle:
381     InterpreterRuntime::cds_resolve_invokehandle(raw_index, cp, CHECK);
382     break;
383 
384   default:
385     ShouldNotReachHere();
386   }
387 
388   if (log_is_enabled(Trace, aot, resolve)) {
389     ResourceMark rm(THREAD);
390     bool resolved = cp->is_resolved(raw_index, bc);
391     Symbol* name = cp->name_ref_at(raw_index, bc);
392     Symbol* signature = cp->signature_ref_at(raw_index, bc);
393     log_trace(aot, resolve)("%s %s [%3d] %s -> %s.%s:%s%s",
394                             (resolved ? "Resolved" : "Failed to resolve"),
395                             Bytecodes::name(bc), cp_index, ik->external_name(),
396                             resolved_klass->external_name(),
397                             name->as_C_string(), signature->as_C_string(), is_static);
398   }
399 }
400 
401 void AOTConstantPoolResolver::preresolve_indy_cp_entries(JavaThread* current, InstanceKlass* ik, GrowableArray<bool>* preresolve_list) {
402   JavaThread* THREAD = current;
403   constantPoolHandle cp(THREAD, ik->constants());
404   if (!CDSConfig::is_dumping_invokedynamic() || cp->cache() == nullptr) {
405     return;
406   }
407 
408   assert(preresolve_list != nullptr, "preresolve_indy_cp_entries() should not be called for "
409          "regenerated LambdaForm Invoker classes, which should not have indys anyway.");
410 
411   Array<ResolvedIndyEntry>* indy_entries = cp->cache()->resolved_indy_entries();
412   for (int i = 0; i < indy_entries->length(); i++) {
413     ResolvedIndyEntry* rie = indy_entries->adr_at(i);
414     int cp_index = rie->constant_pool_index();
415     if (preresolve_list->at(cp_index) == true) {
416       if (!rie->is_resolved() && is_indy_resolution_deterministic(cp(), cp_index)) {
417         InterpreterRuntime::cds_resolve_invokedynamic(i, cp, THREAD);
418         if (HAS_PENDING_EXCEPTION) {
419           CLEAR_PENDING_EXCEPTION; // just ignore
420         }
421       }
422       if (log_is_enabled(Trace, aot, resolve)) {
423         ResourceMark rm(THREAD);
424         log_trace(aot, resolve)("%s indy   [%3d] %s",
425                                 rie->is_resolved() ? "Resolved" : "Failed to resolve",
426                                 cp_index, ik->external_name());
427       }
428     }
429   }
430 }
431 
432 // Check the MethodType signatures used by parameters to the indy BSMs. Make sure we don't
433 // use types that have been excluded, or else we might end up creating MethodTypes that cannot be stored
434 // in the AOT cache.
435 bool AOTConstantPoolResolver::check_methodtype_signature(ConstantPool* cp, Symbol* sig, Klass** return_type_ret) {
436   ResourceMark rm;
437   for (SignatureStream ss(sig); !ss.is_done(); ss.next()) {
438     if (ss.is_reference()) {
439       Symbol* type = ss.as_symbol();
440       Klass* k = find_loaded_class(Thread::current(), cp->pool_holder()->class_loader(), type);
441       if (k == nullptr) {
442         return false;
443       }
444 
445       if (SystemDictionaryShared::should_be_excluded(k)) {
446         if (log_is_enabled(Warning, aot, resolve)) {
447           ResourceMark rm;
448           log_warning(aot, resolve)("Cannot aot-resolve Lambda proxy because %s is excluded", k->external_name());
449         }
450         return false;
451       }
452 
453       if (ss.at_return_type() && return_type_ret != nullptr) {
454         *return_type_ret = k;
455       }
456     }
457   }
458   return true;
459 }
460 
461 bool AOTConstantPoolResolver::check_lambda_metafactory_signature(ConstantPool* cp, Symbol* sig) {
462   Klass* k;
463   if (!check_methodtype_signature(cp, sig, &k)) {
464     return false;
465   }
466 
467   // <k> is the interface type implemented by the lambda proxy
468   if (!k->is_interface()) {
469     // cp->pool_holder() doesn't look like a valid class generated by javac
470     return false;
471   }
472 
473 
474   // The linked lambda callsite has an instance of the interface implemented by this lambda. If this
475   // interface requires its <clinit> to be executed, then we must delay the execution to the production run
476   // as <clinit> can have side effects ==> exclude such cases.
477   InstanceKlass* intf = InstanceKlass::cast(k);
478   bool exclude = intf->interface_needs_clinit_execution_as_super();
479   if (log_is_enabled(Debug, aot, resolve)) {
480     ResourceMark rm;
481     log_debug(aot, resolve)("%s aot-resolve Lambda proxy of interface type %s",
482                             exclude ? "Cannot" : "Can", k->external_name());
483   }
484   return !exclude;
485 }
486 
487 bool AOTConstantPoolResolver::check_lambda_metafactory_methodtype_arg(ConstantPool* cp, int bsms_attribute_index, int arg_i) {
488   int mt_index = cp->bsm_attribute_entry(bsms_attribute_index)->argument_index(arg_i);
489   if (!cp->tag_at(mt_index).is_method_type()) {
490     // malformed class?
491     return false;
492   }
493 
494   Symbol* sig = cp->method_type_signature_at(mt_index);
495   if (log_is_enabled(Debug, aot, resolve)) {
496     ResourceMark rm;
497     log_debug(aot, resolve)("Checking MethodType for LambdaMetafactory BSM arg %d: %s", arg_i, sig->as_C_string());
498   }
499 
500   return check_methodtype_signature(cp, sig);
501 }
502 
503 bool AOTConstantPoolResolver::check_lambda_metafactory_methodhandle_arg(ConstantPool* cp, int bsms_attribute_index, int arg_i) {
504   int mh_index = cp->bsm_attribute_entry(bsms_attribute_index)->argument_index(arg_i);
505   if (!cp->tag_at(mh_index).is_method_handle()) {
506     // malformed class?
507     return false;
508   }
509 
510   Symbol* sig = cp->method_handle_signature_ref_at(mh_index);
511   if (log_is_enabled(Debug, aot, resolve)) {
512     ResourceMark rm;
513     log_debug(aot, resolve)("Checking MethodType of MethodHandle for LambdaMetafactory BSM arg %d: %s", arg_i, sig->as_C_string());
514   }
515   return check_methodtype_signature(cp, sig);
516 }
517 
518 bool AOTConstantPoolResolver::is_indy_resolution_deterministic(ConstantPool* cp, int cp_index) {
519   assert(cp->tag_at(cp_index).is_invoke_dynamic(), "sanity");
520   if (!CDSConfig::is_dumping_invokedynamic()) {
521     return false;
522   }
523 
524   InstanceKlass* pool_holder = cp->pool_holder();
525   if (!SystemDictionaryShared::is_builtin(pool_holder)) {
526     return false;
527   }
528 
529   int bsm = cp->bootstrap_method_ref_index_at(cp_index);
530   int bsm_ref = cp->method_handle_index_at(bsm);
531   Symbol* bsm_name = cp->uncached_name_ref_at(bsm_ref);
532   Symbol* bsm_signature = cp->uncached_signature_ref_at(bsm_ref);
533   Symbol* bsm_klass = cp->klass_name_at(cp->uncached_klass_ref_index_at(bsm_ref));
534 
535   // We currently support only StringConcatFactory::makeConcatWithConstants() and LambdaMetafactory::metafactory()
536   // We should mark the allowed BSMs in the JDK code using a private annotation.
537   // See notes on RFE JDK-8342481.
538 
539   if (bsm_klass->equals("java/lang/invoke/StringConcatFactory") &&
540       bsm_name->equals("makeConcatWithConstants") &&
541       bsm_signature->equals("(Ljava/lang/invoke/MethodHandles$Lookup;"
542                              "Ljava/lang/String;"
543                              "Ljava/lang/invoke/MethodType;"
544                              "Ljava/lang/String;"
545                              "[Ljava/lang/Object;"
546                             ")Ljava/lang/invoke/CallSite;")) {
547     Symbol* factory_type_sig = cp->uncached_signature_ref_at(cp_index);
548     if (log_is_enabled(Debug, aot, resolve)) {
549       ResourceMark rm;
550       log_debug(aot, resolve)("Checking StringConcatFactory callsite signature [%d]: %s", cp_index, factory_type_sig->as_C_string());
551     }
552 
553     Klass* k;
554     if (!check_methodtype_signature(cp, factory_type_sig, &k)) {
555       return false;
556     }
557     if (k != vmClasses::String_klass()) {
558       // bad class file?
559       return false;
560     }
561 
562     return true;
563   }
564 
565   if (bsm_klass->equals("java/lang/invoke/LambdaMetafactory") &&
566       bsm_name->equals("metafactory") &&
567       bsm_signature->equals("(Ljava/lang/invoke/MethodHandles$Lookup;"
568                              "Ljava/lang/String;"
569                              "Ljava/lang/invoke/MethodType;"
570                              "Ljava/lang/invoke/MethodType;"
571                              "Ljava/lang/invoke/MethodHandle;"
572                              "Ljava/lang/invoke/MethodType;"
573                             ")Ljava/lang/invoke/CallSite;")) {
574     /*
575      * An indy callsite is associated with the following MethodType and MethodHandles:
576      *
577      * https://github.com/openjdk/jdk/blob/580eb62dc097efeb51c76b095c1404106859b673/src/java.base/share/classes/java/lang/invoke/LambdaMetafactory.java#L293-L309
578      *
579      * MethodType factoryType         The expected signature of the {@code CallSite}.  The
580      *                                parameter types represent the types of capture variables;
581      *                                the return type is the interface to implement.   When
582      *                                used with {@code invokedynamic}, this is provided by
583      *                                the {@code NameAndType} of the {@code InvokeDynamic}
584      *
585      * MethodType interfaceMethodType Signature and return type of method to be
586      *                                implemented by the function object.
587      *
588      * MethodHandle implementation    A direct method handle describing the implementation
589      *                                method which should be called (with suitable adaptation
590      *                                of argument types and return types, and with captured
591      *                                arguments prepended to the invocation arguments) at
592      *                                invocation time.
593      *
594      * MethodType dynamicMethodType   The signature and return type that should
595      *                                be enforced dynamically at invocation time.
596      *                                In simple use cases this is the same as
597      *                                {@code interfaceMethodType}.
598      */
599     Symbol* factory_type_sig = cp->uncached_signature_ref_at(cp_index);
600     if (log_is_enabled(Debug, aot, resolve)) {
601       ResourceMark rm;
602       log_debug(aot, resolve)("Checking lambda callsite signature [%d]: %s", cp_index, factory_type_sig->as_C_string());
603     }
604 
605     if (!check_lambda_metafactory_signature(cp, factory_type_sig)) {
606       return false;
607     }
608 
609     int bsms_attribute_index = cp->bootstrap_methods_attribute_index(cp_index);
610     int arg_count = cp->bsm_attribute_entry(bsms_attribute_index)->argument_count();
611     if (arg_count != 3) {
612       // Malformed class?
613       return false;
614     }
615 
616     // interfaceMethodType
617     if (!check_lambda_metafactory_methodtype_arg(cp, bsms_attribute_index, 0)) {
618       return false;
619     }
620 
621     // implementation
622     if (!check_lambda_metafactory_methodhandle_arg(cp, bsms_attribute_index, 1)) {
623       return false;
624     }
625 
626     // dynamicMethodType
627     if (!check_lambda_metafactory_methodtype_arg(cp, bsms_attribute_index, 2)) {
628       return false;
629     }
630 
631     return true;
632   }
633 
634   return false;
635 }
636 #ifdef ASSERT
637 bool AOTConstantPoolResolver::is_in_archivebuilder_buffer(address p) {
638   if (!Thread::current()->is_VM_thread() || ArchiveBuilder::current() == nullptr) {
639     return false;
640   } else {
641     return ArchiveBuilder::current()->is_in_buffer_space(p);
642   }
643 }
644 #endif
645 
646 // Paranoid check -- if any field/method signature in <ik> is referencing a class that is known to be
647 // excluded, do not archive any reflection data in <ik>.
648 bool AOTConstantPoolResolver::check_signature_for_reflection_data(InstanceKlass* ik, Symbol* sig, bool is_method) {
649   precond(SafepointSynchronize::is_at_safepoint());
650   ResourceMark rm;
651   for (SignatureStream ss(sig, is_method); !ss.is_done(); ss.next()) {
652     if (ss.is_reference()) {
653       Symbol* klass_name = ss.as_symbol(/*probe_only=*/true);
654       if (klass_name == nullptr) {
655         // This symbol has never been created during the assembly phase, so it can't
656         // possibly be referencing an excluded class.
657         continue;
658       }
659       if (Signature::is_array(klass_name)) {
660         SignatureStream ss2(klass_name, false);
661         ss2.skip_array_prefix();
662         if (ss2.is_reference() && ss2.as_symbol(/*probe_only=*/true) == nullptr) {
663           // klass_name is an array klass that has not been loaded during the assembly phase, so it can't
664           // possibly be referencing an excluded class.
665           continue;
666         }
667       }
668       Klass* k = find_loaded_class(Thread::current(), ik->class_loader(), klass_name);
669       if (k == nullptr) {
670         // No class of this name has been loaded for this loader, so this name can't
671         // possibly be referencing an excluded class.
672         continue;
673       }
674       if (SystemDictionaryShared::should_be_excluded(k)) {
675         if (log_is_enabled(Warning, aot, resolve)) {
676           ResourceMark rm;
677           log_warning(aot, resolve)("Cannot archive reflection data in %s because it refers to excluded class %s",
678                                     ik->external_name(), k->external_name());
679         }
680         return false;
681       }
682     }
683   }
684   return true;
685 }
686 
687 bool AOTConstantPoolResolver::can_archive_reflection_data_declared_fields(InstanceKlass* ik) {
688   for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
689     if (!check_signature_for_reflection_data(ik, fs.signature(), /*is_method=*/false)) {
690       return false;
691     }
692   }
693 
694   return true;
695 }
696 
697 bool AOTConstantPoolResolver::can_archive_reflection_data_declared_methods(InstanceKlass* ik) {
698   Array<Method*>* methods = ik->methods();
699   for (int i = 0; i < methods->length(); i++) {
700     Method* m = methods->at(i);
701     if (!check_signature_for_reflection_data(ik, m->signature(), /*is_method=*/true)) {
702       return false;
703     }
704   }
705 
706   return true;
707 }
708 
709 // This is called by AOT assembly phase to see if java_lang_Class::reflection_data(k) can be
710 // archived.
711 bool AOTConstantPoolResolver::can_archive_reflection_data(InstanceKlass* ik) {
712   // At this point, we have resolved the reflection data of *all* classes
713   // recorded by FinalImageRecipes.
714   // When we are in the AOT safepoint, we will archive the reflection
715   // data of <ik> *only if* it doesn't reference any excluded classes.
716   precond(SafepointSynchronize::is_at_safepoint());
717 
718   if (!can_archive_reflection_data_declared_fields(ik)) {
719     return false;
720   }
721   if (!can_archive_reflection_data_declared_methods(ik)) {
722     return false;
723   }
724 
725   if (log_is_enabled(Info, aot, resolve)) {
726     ResourceMark rm;
727     log_info(aot, resolve)("Archived reflection data in %s", ik->external_name());
728   }
729 
730   return true;
731 }
732 
733 int AOTConstantPoolResolver::class_reflection_data_flags(InstanceKlass* ik, TRAPS) {
734   assert(java_lang_Class::has_reflection_data(ik->java_mirror()), "must be");
735 
736   HandleMark hm(THREAD);
737   JavaCallArguments args(Handle(THREAD, ik->java_mirror()));
738   JavaValue result(T_INT);
739   JavaCalls::call_special(&result,
740                           vmClasses::Class_klass(),
741                           vmSymbols::encodeReflectionData_name(),
742                           vmSymbols::void_int_signature(),
743                           &args, CHECK_0);
744   int flags = result.get_jint();
745   aot_log_info(aot)("Encode ReflectionData: %s (flags=0x%x)", ik->external_name(), flags);
746   return flags;
747 }
748 
749 void AOTConstantPoolResolver::generate_reflection_data(JavaThread* current, InstanceKlass* ik, int rd_flags) {
750   aot_log_info(aot)("Generate ReflectionData: %s (flags=" INT32_FORMAT_X ")", ik->external_name(), rd_flags);
751   JavaThread* THREAD = current; // for exception macros
752   JavaCallArguments args(Handle(THREAD, ik->java_mirror()));
753   args.push_int(rd_flags);
754   JavaValue result(T_OBJECT);
755   JavaCalls::call_special(&result,
756                           vmClasses::Class_klass(),
757                           vmSymbols::generateReflectionData_name(),
758                           vmSymbols::int_void_signature(),
759                           &args, THREAD);
760   if (HAS_PENDING_EXCEPTION) {
761     Handle exc_handle(THREAD, PENDING_EXCEPTION);
762     CLEAR_PENDING_EXCEPTION;
763 
764     log_warning(aot)("Exception during Class::generateReflectionData() call for %s", ik->external_name());
765     LogStreamHandle(Debug, aot) log;
766     if (log.is_enabled()) {
767       java_lang_Throwable::print_stack_trace(exc_handle, &log);
768     }
769   }
770 }
771 
772 Klass* AOTConstantPoolResolver::resolve_boot_class_or_fail(const char* class_name, TRAPS) {
773   Handle class_loader;
774   TempNewSymbol class_name_sym = SymbolTable::new_symbol(class_name);
775   return SystemDictionary::resolve_or_fail(class_name_sym, class_loader, true, THREAD);
776 }
777 
778 void AOTConstantPoolResolver::trace_dynamic_proxy_class(oop loader, const char* proxy_name, objArrayOop interfaces, int access_flags) {
779   if (interfaces->length() < 1) {
780     return;
781   }
782   if (ClassListWriter::is_enabled()) {
783     const char* loader_name = ArchiveUtils::builtin_loader_name_or_null(loader);
784     if (loader_name != nullptr) {
785       stringStream ss;
786       ss.print("%s %s %d %d", loader_name, proxy_name, access_flags, interfaces->length());
787       for (int i = 0; i < interfaces->length(); i++) {
788         oop mirror = interfaces->obj_at(i);
789         Klass* k = java_lang_Class::as_Klass(mirror);
790         ss.print(" %s", k->name()->as_C_string());
791       }
792       ClassListWriter w; // This locks ClassListFile_lock
793       w.stream()->print_cr("@dynamic-proxy %s", ss.freeze());
794     }
795   }
796   if (CDSConfig::is_dumping_preimage_static_archive()) {
797     FinalImageRecipes::add_dynamic_proxy_class(loader, proxy_name, interfaces, access_flags);
798   }
799 }
800 
801 void AOTConstantPoolResolver::init_dynamic_proxy_cache(TRAPS) {
802   static bool inited = false;
803   if (inited) {
804     return;
805   }
806   inited = true;
807 
808   Klass* klass = resolve_boot_class_or_fail("java/lang/reflect/Proxy", CHECK);
809   TempNewSymbol method = SymbolTable::new_symbol("initCacheForCDS");
810   TempNewSymbol signature = SymbolTable::new_symbol("(Ljava/lang/ClassLoader;Ljava/lang/ClassLoader;)V");
811 
812   JavaCallArguments args;
813   args.push_oop(Handle(THREAD, SystemDictionary::java_platform_loader()));
814   args.push_oop(Handle(THREAD, SystemDictionary::java_system_loader()));
815   JavaValue result(T_VOID);
816   JavaCalls::call_static(&result,
817                          klass,
818                          method,
819                          signature,
820                          &args, CHECK);
821 }
822 
823 
824 void AOTConstantPoolResolver::define_dynamic_proxy_class(Handle loader, Handle proxy_name, Handle interfaces, int access_flags, TRAPS) {
825   if (!CDSConfig::is_dumping_dynamic_proxies()) {
826     return;
827   }
828   init_dynamic_proxy_cache(CHECK);
829 
830   Klass* klass = resolve_boot_class_or_fail("java/lang/reflect/Proxy$ProxyBuilder", CHECK);
831   TempNewSymbol method = SymbolTable::new_symbol("defineProxyClassForCDS");
832   TempNewSymbol signature = SymbolTable::new_symbol("(Ljava/lang/ClassLoader;Ljava/lang/String;[Ljava/lang/Class;I)Ljava/lang/Class;");
833 
834   JavaCallArguments args;
835   args.push_oop(Handle(THREAD, loader()));
836   args.push_oop(Handle(THREAD, proxy_name()));
837   args.push_oop(Handle(THREAD, interfaces()));
838   args.push_int(access_flags);
839   JavaValue result(T_OBJECT);
840   JavaCalls::call_static(&result,
841                          klass,
842                          method,
843                          signature,
844                          &args, CHECK);
845 
846   // Assumptions:
847   // FMG is archived, which means -modulepath and -Xbootclasspath are both not specified.
848   // All named modules are loaded from the system modules files.
849   // TODO: test support for -Xbootclasspath after JDK-8322322. Some of the code below need to be changed.
850   // TODO: we just give dummy shared_classpath_index for the generated class so that it will be archived.
851   //       The index is not used at runtime (see SystemDictionaryShared::load_shared_class_for_builtin_loader, which
852   //       uses a null ProtectionDomain for this class)
853   oop mirror = result.get_oop();
854   assert(mirror != nullptr, "class must have been generated if not OOM");
855   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror));
856   if (ik->defined_by_boot_loader() || ik->defined_by_platform_loader()) {
857     assert(ik->module()->is_named(), "dynamic proxies defined in unnamed modules for boot/platform loaders not supported");
858     ik->set_shared_classpath_index(0);
859   } else {
860     assert(ik->defined_by_app_loader(), "must be");
861     ik->set_shared_classpath_index(AOTClassLocationConfig::dumptime()->app_cp_start_index());
862   }
863 
864   ArchiveBuilder::alloc_stats()->record_dynamic_proxy_class();
865   if (log_is_enabled(Info, cds, dynamic, proxy)) {
866     ResourceMark rm(THREAD);
867     stringStream ss;
868     const char* prefix = "";
869     ss.print("%s (%-7s, cp index = %d) implements ", ik->external_name(),
870              ArchiveUtils::builtin_loader_name(loader()), ik->shared_classpath_index());
871     objArrayOop intfs = (objArrayOop)interfaces();
872     for (int i = 0; i < intfs->length(); i++) {
873       oop intf_mirror = intfs->obj_at(i);
874       ss.print("%s%s", prefix, java_lang_Class::as_Klass(intf_mirror)->external_name());
875       prefix = ", ";
876     }
877 
878     log_info(cds, dynamic, proxy)("%s", ss.freeze());
879   }
880 }