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