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