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/cdsConfig.hpp"
 29 #include "classfile/systemDictionary.hpp"
 30 #include "classfile/systemDictionaryShared.hpp"
 31 #include "classfile/vmClasses.hpp"
 32 #include "interpreter/bytecodeStream.hpp"
 33 #include "interpreter/interpreterRuntime.hpp"
 34 #include "memory/resourceArea.hpp"
 35 #include "oops/constantPool.inline.hpp"
 36 #include "oops/instanceKlass.hpp"
 37 #include "oops/klass.inline.hpp"
 38 #include "runtime/handles.inline.hpp"
 39 
 40 // Returns true if we CAN PROVE that cp_index will always resolve to
 41 // the same information at both dump time and run time. This is a
 42 // necessary (but not sufficient) condition for pre-resolving cp_index
 43 // during CDS archive assembly.
 44 bool AOTConstantPoolResolver::is_resolution_deterministic(ConstantPool* cp, int cp_index) {
 45   assert(!is_in_archivebuilder_buffer(cp), "sanity");
 46 
 47   if (cp->tag_at(cp_index).is_klass()) {
 48     // We require cp_index to be already resolved. This is fine for now, are we
 49     // currently archive only CP entries that are already resolved.
 50     Klass* resolved_klass = cp->resolved_klass_at(cp_index);
 51     return resolved_klass != nullptr && is_class_resolution_deterministic(cp->pool_holder(), resolved_klass);
 52   } else if (cp->tag_at(cp_index).is_invoke_dynamic()) {
 53     return is_indy_resolution_deterministic(cp, cp_index);
 54   } else if (cp->tag_at(cp_index).is_field() ||
 55              cp->tag_at(cp_index).is_method() ||
 56              cp->tag_at(cp_index).is_interface_method()) {
 57     int klass_cp_index = cp->uncached_klass_ref_index_at(cp_index);
 58     if (!cp->tag_at(klass_cp_index).is_klass()) {
 59       // Not yet resolved
 60       return false;
 61     }
 62     Klass* k = cp->resolved_klass_at(klass_cp_index);
 63     if (!is_class_resolution_deterministic(cp->pool_holder(), k)) {
 64       return false;
 65     }
 66 
 67     if (!k->is_instance_klass()) {
 68       // TODO: support non instance klasses as well.
 69       return false;
 70     }
 71 
 72     // Here, We don't check if this entry can actually be resolved to a valid Field/Method.
 73     // This method should be called by the ConstantPool to check Fields/Methods that
 74     // have already been successfully resolved.
 75     return true;
 76   } else {
 77     return false;
 78   }
 79 }
 80 
 81 bool AOTConstantPoolResolver::is_class_resolution_deterministic(InstanceKlass* cp_holder, Klass* resolved_class) {
 82   assert(!is_in_archivebuilder_buffer(cp_holder), "sanity");
 83   assert(!is_in_archivebuilder_buffer(resolved_class), "sanity");
 84 
 85   if (resolved_class->is_instance_klass()) {
 86     InstanceKlass* ik = InstanceKlass::cast(resolved_class);
 87 
 88     if (!ik->is_shared() && SystemDictionaryShared::is_excluded_class(ik)) {
 89       return false;
 90     }
 91 
 92     if (cp_holder->is_subtype_of(ik)) {
 93       // All super types of ik will be resolved in ik->class_loader() before
 94       // ik is defined in this loader, so it's safe to archive the resolved klass reference.
 95       return true;
 96     }
 97 
 98     if (CDSConfig::is_dumping_aot_linked_classes()) {
 99       // Need to call try_add_candidate instead of is_candidate, as this may be called
100       // before AOTClassLinker::add_candidates().
101       if (AOTClassLinker::try_add_candidate(ik)) {
102         return true;
103       } else {
104         return false;
105       }
106     } else if (AOTClassLinker::is_vm_class(ik)) {
107       if (ik->class_loader() != cp_holder->class_loader()) {
108         // At runtime, cp_holder() may not be able to resolve to the same
109         // ik. For example, a different version of ik may be defined in
110         // cp->pool_holder()'s loader using MethodHandles.Lookup.defineClass().
111         return false;
112       } else {
113         return true;
114       }
115     } else {
116       return false;
117     }
118   } else if (resolved_class->is_objArray_klass()) {
119     Klass* elem = ObjArrayKlass::cast(resolved_class)->bottom_klass();
120     if (elem->is_instance_klass()) {
121       return is_class_resolution_deterministic(cp_holder, InstanceKlass::cast(elem));
122     } else if (elem->is_typeArray_klass()) {
123       return true;
124     } else {
125       return false;
126     }
127   } else if (resolved_class->is_typeArray_klass()) {
128     return true;
129   } else {
130     return false;
131   }
132 }
133 
134 void AOTConstantPoolResolver::preresolve_string_cp_entries(InstanceKlass* ik, TRAPS) {
135   if (!ik->is_linked()) {
136     // The cp->resolved_referenced() array is not ready yet, so we can't call resolve_string().
137     return;
138   }
139   constantPoolHandle cp(THREAD, ik->constants());
140   for (int cp_index = 1; cp_index < cp->length(); cp_index++) { // Index 0 is unused
141     switch (cp->tag_at(cp_index).value()) {
142     case JVM_CONSTANT_String:
143       resolve_string(cp, cp_index, CHECK); // may throw OOM when interning strings.
144       break;
145     }
146   }
147 }
148 
149 // This works only for the boot/platform/app loaders
150 Klass* AOTConstantPoolResolver::find_loaded_class(Thread* current, oop class_loader, Symbol* name) {
151   HandleMark hm(current);
152   Handle h_loader(current, class_loader);
153   Klass* k = SystemDictionary::find_instance_or_array_klass(current, name, h_loader);
154   if (k != nullptr) {
155     return k;
156   }
157   if (h_loader() == SystemDictionary::java_system_loader()) {
158     return find_loaded_class(current, SystemDictionary::java_platform_loader(), name);
159   } else if (h_loader() == SystemDictionary::java_platform_loader()) {
160     return find_loaded_class(current, nullptr, name);
161   } else {
162     assert(h_loader() == nullptr, "This function only works for boot/platform/app loaders %p %p %p",
163            cast_from_oop<address>(h_loader()),
164            cast_from_oop<address>(SystemDictionary::java_system_loader()),
165            cast_from_oop<address>(SystemDictionary::java_platform_loader()));
166   }
167 
168   return nullptr;
169 }
170 
171 Klass* AOTConstantPoolResolver::find_loaded_class(Thread* current, ConstantPool* cp, int class_cp_index) {
172   Symbol* name = cp->klass_name_at(class_cp_index);
173   return find_loaded_class(current, cp->pool_holder()->class_loader(), name);
174 }
175 
176 #if INCLUDE_CDS_JAVA_HEAP
177 void AOTConstantPoolResolver::resolve_string(constantPoolHandle cp, int cp_index, TRAPS) {
178   if (CDSConfig::is_dumping_heap()) {
179     int cache_index = cp->cp_to_object_index(cp_index);
180     ConstantPool::string_at_impl(cp, cp_index, cache_index, CHECK);
181   }
182 }
183 #endif
184 
185 void AOTConstantPoolResolver::preresolve_class_cp_entries(JavaThread* current, InstanceKlass* ik, GrowableArray<bool>* preresolve_list) {
186   if (!SystemDictionaryShared::is_builtin_loader(ik->class_loader_data())) {
187     return;
188   }
189 
190   JavaThread* THREAD = current;
191   constantPoolHandle cp(THREAD, ik->constants());
192   for (int cp_index = 1; cp_index < cp->length(); cp_index++) {
193     if (cp->tag_at(cp_index).value() == JVM_CONSTANT_UnresolvedClass) {
194       if (preresolve_list != nullptr && preresolve_list->at(cp_index) == false) {
195         // This class was not resolved during trial run. Don't attempt to resolve it. Otherwise
196         // the compiler may generate less efficient code.
197         continue;
198       }
199       if (find_loaded_class(current, cp(), cp_index) == nullptr) {
200         // Do not resolve any class that has not been loaded yet
201         continue;
202       }
203       Klass* resolved_klass = cp->klass_at(cp_index, THREAD);
204       if (HAS_PENDING_EXCEPTION) {
205         CLEAR_PENDING_EXCEPTION; // just ignore
206       } else {
207         log_trace(cds, resolve)("Resolved class  [%3d] %s -> %s", cp_index, ik->external_name(),
208                                 resolved_klass->external_name());
209       }
210     }
211   }
212 }
213 
214 void AOTConstantPoolResolver::preresolve_field_and_method_cp_entries(JavaThread* current, InstanceKlass* ik, GrowableArray<bool>* preresolve_list) {
215   JavaThread* THREAD = current;
216   constantPoolHandle cp(THREAD, ik->constants());
217   if (cp->cache() == nullptr) {
218     return;
219   }
220   for (int i = 0; i < ik->methods()->length(); i++) {
221     Method* m = ik->methods()->at(i);
222     BytecodeStream bcs(methodHandle(THREAD, m));
223     while (!bcs.is_last_bytecode()) {
224       bcs.next();
225       Bytecodes::Code raw_bc = bcs.raw_code();
226       switch (raw_bc) {
227       case Bytecodes::_getfield:
228       case Bytecodes::_putfield:
229         maybe_resolve_fmi_ref(ik, m, raw_bc, bcs.get_index_u2(), preresolve_list, THREAD);
230         if (HAS_PENDING_EXCEPTION) {
231           CLEAR_PENDING_EXCEPTION; // just ignore
232         }
233         break;
234       case Bytecodes::_invokehandle:
235       case Bytecodes::_invokespecial:
236       case Bytecodes::_invokevirtual:
237       case Bytecodes::_invokeinterface:
238         maybe_resolve_fmi_ref(ik, m, raw_bc, bcs.get_index_u2(), preresolve_list, THREAD);
239         if (HAS_PENDING_EXCEPTION) {
240           CLEAR_PENDING_EXCEPTION; // just ignore
241         }
242         break;
243       default:
244         break;
245       }
246     }
247   }
248 }
249 
250 void AOTConstantPoolResolver::maybe_resolve_fmi_ref(InstanceKlass* ik, Method* m, Bytecodes::Code bc, int raw_index,
251                                            GrowableArray<bool>* preresolve_list, TRAPS) {
252   methodHandle mh(THREAD, m);
253   constantPoolHandle cp(THREAD, ik->constants());
254   HandleMark hm(THREAD);
255   int cp_index = cp->to_cp_index(raw_index, bc);
256 
257   if (cp->is_resolved(raw_index, bc)) {
258     return;
259   }
260 
261   if (preresolve_list != nullptr && preresolve_list->at(cp_index) == false) {
262     // This field wasn't resolved during the trial run. Don't attempt to resolve it. Otherwise
263     // the compiler may generate less efficient code.
264     return;
265   }
266 
267   int klass_cp_index = cp->uncached_klass_ref_index_at(cp_index);
268   if (find_loaded_class(THREAD, cp(), klass_cp_index) == nullptr) {
269     // Do not resolve any field/methods from a class that has not been loaded yet.
270     return;
271   }
272 
273   Klass* resolved_klass = cp->klass_ref_at(raw_index, bc, CHECK);
274 
275   switch (bc) {
276   case Bytecodes::_getfield:
277   case Bytecodes::_putfield:
278     InterpreterRuntime::resolve_get_put(bc, raw_index, mh, cp, StaticMode::dont_initialize_klass, CHECK);
279     break;
280 
281   case Bytecodes::_invokevirtual:
282   case Bytecodes::_invokespecial:
283   case Bytecodes::_invokeinterface:
284     InterpreterRuntime::cds_resolve_invoke(bc, raw_index, cp, CHECK);
285     break;
286 
287   case Bytecodes::_invokehandle:
288     InterpreterRuntime::cds_resolve_invokehandle(raw_index, cp, CHECK);
289     break;
290 
291   default:
292     ShouldNotReachHere();
293   }
294 
295   if (log_is_enabled(Trace, cds, resolve)) {
296     ResourceMark rm(THREAD);
297     bool resolved = cp->is_resolved(raw_index, bc);
298     Symbol* name = cp->name_ref_at(raw_index, bc);
299     Symbol* signature = cp->signature_ref_at(raw_index, bc);
300     log_trace(cds, resolve)("%s %s [%3d] %s -> %s.%s:%s",
301                             (resolved ? "Resolved" : "Failed to resolve"),
302                             Bytecodes::name(bc), cp_index, ik->external_name(),
303                             resolved_klass->external_name(),
304                             name->as_C_string(), signature->as_C_string());
305   }
306 }
307 
308 void AOTConstantPoolResolver::preresolve_indy_cp_entries(JavaThread* current, InstanceKlass* ik, GrowableArray<bool>* preresolve_list) {
309   JavaThread* THREAD = current;
310   constantPoolHandle cp(THREAD, ik->constants());
311   if (!CDSConfig::is_dumping_invokedynamic() || cp->cache() == nullptr) {
312     return;
313   }
314 
315   assert(preresolve_list != nullptr, "preresolve_indy_cp_entries() should not be called for "
316          "regenerated LambdaForm Invoker classes, which should not have indys anyway.");
317 
318   Array<ResolvedIndyEntry>* indy_entries = cp->cache()->resolved_indy_entries();
319   for (int i = 0; i < indy_entries->length(); i++) {
320     ResolvedIndyEntry* rie = indy_entries->adr_at(i);
321     int cp_index = rie->constant_pool_index();
322     if (preresolve_list->at(cp_index) == true) {
323       if (!rie->is_resolved() && is_indy_resolution_deterministic(cp(), cp_index)) {
324         InterpreterRuntime::cds_resolve_invokedynamic(i, cp, THREAD);
325         if (HAS_PENDING_EXCEPTION) {
326           CLEAR_PENDING_EXCEPTION; // just ignore
327         }
328       }
329       if (log_is_enabled(Trace, cds, resolve)) {
330         ResourceMark rm(THREAD);
331         log_trace(cds, resolve)("%s indy   [%3d] %s",
332                                 rie->is_resolved() ? "Resolved" : "Failed to resolve",
333                                 cp_index, ik->external_name());
334       }
335     }
336   }
337 }
338 
339 // Check the MethodType signatures used by parameters to the indy BSMs. Make sure we don't
340 // use types that have been excluded, or else we might end up creating MethodTypes that cannot be stored
341 // in the AOT cache.
342 bool AOTConstantPoolResolver::check_methodtype_signature(ConstantPool* cp, Symbol* sig, Klass** return_type_ret) {
343   ResourceMark rm;
344   for (SignatureStream ss(sig); !ss.is_done(); ss.next()) {
345     if (ss.is_reference()) {
346       Symbol* type = ss.as_symbol();
347       Klass* k = find_loaded_class(Thread::current(), cp->pool_holder()->class_loader(), type);
348       if (k == nullptr) {
349         return false;
350       }
351 
352       if (SystemDictionaryShared::should_be_excluded(k)) {
353         if (log_is_enabled(Warning, cds, resolve)) {
354           ResourceMark rm;
355           log_warning(cds, resolve)("Cannot aot-resolve Lambda proxy because %s is excluded", k->external_name());
356         }
357         return false;
358       }
359 
360       if (ss.at_return_type() && return_type_ret != nullptr) {
361         *return_type_ret = k;
362       }
363     }
364   }
365   return true;
366 }
367 
368 bool AOTConstantPoolResolver::check_lambda_metafactory_signature(ConstantPool* cp, Symbol* sig) {
369   Klass* k;
370   if (!check_methodtype_signature(cp, sig, &k)) {
371     return false;
372   }
373 
374   // <k> is the interface type implemented by the lambda proxy
375   if (!k->is_interface()) {
376     // cp->pool_holder() doesn't look like a valid class generated by javac
377     return false;
378   }
379 
380 
381   // The linked lambda callsite has an instance of the interface implemented by this lambda. If this
382   // interface requires its <clinit> to be executed, then we must delay the execution to the production run
383   // as <clinit> can have side effects ==> exclude such cases.
384   InstanceKlass* intf = InstanceKlass::cast(k);
385   bool exclude = intf->interface_needs_clinit_execution_as_super();
386   if (log_is_enabled(Debug, cds, resolve)) {
387     ResourceMark rm;
388     log_debug(cds, resolve)("%s aot-resolve Lambda proxy of interface type %s",
389                             exclude ? "Cannot" : "Can", k->external_name());
390   }
391   return !exclude;
392 }
393 
394 bool AOTConstantPoolResolver::check_lambda_metafactory_methodtype_arg(ConstantPool* cp, int bsms_attribute_index, int arg_i) {
395   int mt_index = cp->operand_argument_index_at(bsms_attribute_index, arg_i);
396   if (!cp->tag_at(mt_index).is_method_type()) {
397     // malformed class?
398     return false;
399   }
400 
401   Symbol* sig = cp->method_type_signature_at(mt_index);
402   if (log_is_enabled(Debug, cds, resolve)) {
403     ResourceMark rm;
404     log_debug(cds, resolve)("Checking MethodType for LambdaMetafactory BSM arg %d: %s", arg_i, sig->as_C_string());
405   }
406 
407   return check_methodtype_signature(cp, sig);
408 }
409 
410 bool AOTConstantPoolResolver::check_lambda_metafactory_methodhandle_arg(ConstantPool* cp, int bsms_attribute_index, int arg_i) {
411   int mh_index = cp->operand_argument_index_at(bsms_attribute_index, arg_i);
412   if (!cp->tag_at(mh_index).is_method_handle()) {
413     // malformed class?
414     return false;
415   }
416 
417   Symbol* sig = cp->method_handle_signature_ref_at(mh_index);
418   if (log_is_enabled(Debug, cds, resolve)) {
419     ResourceMark rm;
420     log_debug(cds, resolve)("Checking MethodType of MethodHandle for LambdaMetafactory BSM arg %d: %s", arg_i, sig->as_C_string());
421   }
422   return check_methodtype_signature(cp, sig);
423 }
424 
425 bool AOTConstantPoolResolver::is_indy_resolution_deterministic(ConstantPool* cp, int cp_index) {
426   assert(cp->tag_at(cp_index).is_invoke_dynamic(), "sanity");
427   if (!CDSConfig::is_dumping_invokedynamic()) {
428     return false;
429   }
430 
431   InstanceKlass* pool_holder = cp->pool_holder();
432   if (!SystemDictionaryShared::is_builtin(pool_holder)) {
433     return false;
434   }
435 
436   int bsm = cp->bootstrap_method_ref_index_at(cp_index);
437   int bsm_ref = cp->method_handle_index_at(bsm);
438   Symbol* bsm_name = cp->uncached_name_ref_at(bsm_ref);
439   Symbol* bsm_signature = cp->uncached_signature_ref_at(bsm_ref);
440   Symbol* bsm_klass = cp->klass_name_at(cp->uncached_klass_ref_index_at(bsm_ref));
441 
442   // We currently support only StringConcatFactory::makeConcatWithConstants() and LambdaMetafactory::metafactory()
443   // We should mark the allowed BSMs in the JDK code using a private annotation.
444   // See notes on RFE JDK-8342481.
445 
446   if (bsm_klass->equals("java/lang/invoke/StringConcatFactory") &&
447       bsm_name->equals("makeConcatWithConstants") &&
448       bsm_signature->equals("(Ljava/lang/invoke/MethodHandles$Lookup;"
449                              "Ljava/lang/String;"
450                              "Ljava/lang/invoke/MethodType;"
451                              "Ljava/lang/String;"
452                              "[Ljava/lang/Object;"
453                             ")Ljava/lang/invoke/CallSite;")) {
454     Symbol* factory_type_sig = cp->uncached_signature_ref_at(cp_index);
455     if (log_is_enabled(Debug, cds, resolve)) {
456       ResourceMark rm;
457       log_debug(cds, resolve)("Checking StringConcatFactory callsite signature [%d]: %s", cp_index, factory_type_sig->as_C_string());
458     }
459 
460     Klass* k;
461     if (!check_methodtype_signature(cp, factory_type_sig, &k)) {
462       return false;
463     }
464     if (k != vmClasses::String_klass()) {
465       // bad class file?
466       return false;
467     }
468 
469     return true;
470   }
471 
472   if (bsm_klass->equals("java/lang/invoke/LambdaMetafactory") &&
473       bsm_name->equals("metafactory") &&
474       bsm_signature->equals("(Ljava/lang/invoke/MethodHandles$Lookup;"
475                              "Ljava/lang/String;"
476                              "Ljava/lang/invoke/MethodType;"
477                              "Ljava/lang/invoke/MethodType;"
478                              "Ljava/lang/invoke/MethodHandle;"
479                              "Ljava/lang/invoke/MethodType;"
480                             ")Ljava/lang/invoke/CallSite;")) {
481     /*
482      * An indy callsite is associated with the following MethodType and MethodHandles:
483      *
484      * https://github.com/openjdk/jdk/blob/580eb62dc097efeb51c76b095c1404106859b673/src/java.base/share/classes/java/lang/invoke/LambdaMetafactory.java#L293-L309
485      *
486      * MethodType factoryType         The expected signature of the {@code CallSite}.  The
487      *                                parameter types represent the types of capture variables;
488      *                                the return type is the interface to implement.   When
489      *                                used with {@code invokedynamic}, this is provided by
490      *                                the {@code NameAndType} of the {@code InvokeDynamic}
491      *
492      * MethodType interfaceMethodType Signature and return type of method to be
493      *                                implemented by the function object.
494      *
495      * MethodHandle implementation    A direct method handle describing the implementation
496      *                                method which should be called (with suitable adaptation
497      *                                of argument types and return types, and with captured
498      *                                arguments prepended to the invocation arguments) at
499      *                                invocation time.
500      *
501      * MethodType dynamicMethodType   The signature and return type that should
502      *                                be enforced dynamically at invocation time.
503      *                                In simple use cases this is the same as
504      *                                {@code interfaceMethodType}.
505      */
506     Symbol* factory_type_sig = cp->uncached_signature_ref_at(cp_index);
507     if (log_is_enabled(Debug, cds, resolve)) {
508       ResourceMark rm;
509       log_debug(cds, resolve)("Checking lambda callsite signature [%d]: %s", cp_index, factory_type_sig->as_C_string());
510     }
511 
512     if (!check_lambda_metafactory_signature(cp, factory_type_sig)) {
513       return false;
514     }
515 
516     int bsms_attribute_index = cp->bootstrap_methods_attribute_index(cp_index);
517     int arg_count = cp->operand_argument_count_at(bsms_attribute_index);
518     if (arg_count != 3) {
519       // Malformed class?
520       return false;
521     }
522 
523     // interfaceMethodType
524     if (!check_lambda_metafactory_methodtype_arg(cp, bsms_attribute_index, 0)) {
525       return false;
526     }
527 
528     // implementation
529     if (!check_lambda_metafactory_methodhandle_arg(cp, bsms_attribute_index, 1)) {
530       return false;
531     }
532 
533     // dynamicMethodType
534     if (!check_lambda_metafactory_methodtype_arg(cp, bsms_attribute_index, 2)) {
535       return false;
536     }
537 
538     return true;
539   }
540 
541   return false;
542 }
543 #ifdef ASSERT
544 bool AOTConstantPoolResolver::is_in_archivebuilder_buffer(address p) {
545   if (!Thread::current()->is_VM_thread() || ArchiveBuilder::current() == nullptr) {
546     return false;
547   } else {
548     return ArchiveBuilder::current()->is_in_buffer_space(p);
549   }
550 }
551 #endif