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