1 /*
2 * Copyright (c) 1998, 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/aotConstantPoolResolver.hpp"
26 #include "cds/archiveBuilder.hpp"
27 #include "cds/cdsConfig.hpp"
28 #include "cds/heapShared.hpp"
29 #include "classfile/resolutionErrors.hpp"
30 #include "classfile/systemDictionary.hpp"
31 #include "classfile/systemDictionaryShared.hpp"
32 #include "classfile/vmClasses.hpp"
33 #include "code/codeCache.hpp"
34 #include "interpreter/bytecodes.hpp"
35 #include "interpreter/bytecodeStream.hpp"
36 #include "interpreter/interpreter.hpp"
37 #include "interpreter/linkResolver.hpp"
38 #include "interpreter/rewriter.hpp"
39 #include "logging/log.hpp"
40 #include "logging/logStream.hpp"
41 #include "memory/metadataFactory.hpp"
42 #include "memory/metaspaceClosure.hpp"
43 #include "memory/resourceArea.hpp"
44 #include "oops/access.inline.hpp"
45 #include "oops/compressedOops.hpp"
46 #include "oops/constantPool.inline.hpp"
47 #include "oops/cpCache.inline.hpp"
48 #include "oops/method.inline.hpp"
49 #include "oops/objArrayOop.inline.hpp"
50 #include "oops/oop.inline.hpp"
51 #include "oops/resolvedFieldEntry.hpp"
52 #include "oops/resolvedIndyEntry.hpp"
53 #include "oops/resolvedMethodEntry.hpp"
54 #include "prims/methodHandles.hpp"
55 #include "runtime/arguments.hpp"
56 #include "runtime/atomicAccess.hpp"
57 #include "runtime/handles.inline.hpp"
58 #include "runtime/mutexLocker.hpp"
59 #include "runtime/synchronizer.hpp"
60 #include "runtime/vm_version.hpp"
61 #include "utilities/macros.hpp"
62
63 // Implementation of ConstantPoolCache
64
65 template <class T>
66 static Array<T>* initialize_resolved_entries_array(ClassLoaderData* loader_data, GrowableArray<T> entries, TRAPS) {
67 Array<T>* resolved_entries;
68 if (entries.length() != 0) {
69 resolved_entries = MetadataFactory::new_array<T>(loader_data, entries.length(), CHECK_NULL);
70 for (int i = 0; i < entries.length(); i++) {
71 resolved_entries->at_put(i, entries.at(i));
72 }
73 return resolved_entries;
74 }
75 return nullptr;
76 }
77
78 void ConstantPoolCache::set_direct_or_vtable_call(Bytecodes::Code invoke_code,
79 int method_index,
80 const methodHandle& method,
81 int vtable_index,
82 bool sender_is_interface) {
83 bool is_vtable_call = (vtable_index >= 0); // FIXME: split this method on this boolean
84 assert(method->interpreter_entry() != nullptr, "should have been set at this point");
85 assert(!method->is_obsolete(), "attempt to write obsolete method to cpCache");
86
87 int byte_no = -1;
88 bool change_to_virtual = false;
89 InstanceKlass* holder = nullptr; // have to declare this outside the switch
90 ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
91 switch (invoke_code) {
92 case Bytecodes::_invokeinterface:
93 holder = method->method_holder();
94 // check for private interface method invocations
95 if (vtable_index == Method::nonvirtual_vtable_index && holder->is_interface() ) {
96 assert(method->is_private(), "unexpected non-private method");
97 assert(method->can_be_statically_bound(), "unexpected non-statically-bound method");
98
99 method_entry->set_flags(( 1 << ResolvedMethodEntry::is_vfinal_shift) |
100 ((method->is_final_method() ? 1 : 0) << ResolvedMethodEntry::is_final_shift));
101 method_entry->fill_in((u1)as_TosState(method->result_type()), (u2)method()->size_of_parameters());
102 assert(method_entry->is_vfinal(), "flags must be set");
103 method_entry->set_method(method());
104 byte_no = 2;
105 method_entry->set_klass(holder);
106 break;
107 }
108 else {
109 // We get here from InterpreterRuntime::resolve_invoke when an invokeinterface
110 // instruction links to a non-interface method (in Object). This can happen when
111 // an interface redeclares an Object method (like CharSequence declaring toString())
112 // or when invokeinterface is used explicitly.
113 // In that case, the method has no itable index and must be invoked as a virtual.
114 // Set a flag to keep track of this corner case.
115 assert(holder->is_interface() || holder == vmClasses::Object_klass(), "unexpected holder class");
116 assert(method->is_public(), "Calling non-public method in Object with invokeinterface");
117 change_to_virtual = true;
118
119 // ...and fall through as if we were handling invokevirtual:
120 }
121 case Bytecodes::_invokevirtual:
122 {
123 if (!is_vtable_call) {
124 assert(method->can_be_statically_bound(), "");
125 method_entry->set_flags(( 1 << ResolvedMethodEntry::is_vfinal_shift) |
126 ((method->is_final_method() ? 1 : 0) << ResolvedMethodEntry::is_final_shift) |
127 ((change_to_virtual ? 1 : 0) << ResolvedMethodEntry::is_forced_virtual_shift));
128 method_entry->fill_in((u1)as_TosState(method->result_type()), (u2)method()->size_of_parameters());
129 assert(method_entry->is_vfinal(), "flags must be set");
130 method_entry->set_method(method());
131 } else {
132 assert(!method->can_be_statically_bound(), "");
133 assert(vtable_index >= 0, "valid index");
134 assert(!method->is_final_method(), "sanity");
135 method_entry->set_flags((change_to_virtual ? 1 : 0) << ResolvedMethodEntry::is_forced_virtual_shift);
136 method_entry->fill_in((u1)as_TosState(method->result_type()), (u2)method()->size_of_parameters());
137 assert(!method_entry->is_vfinal(), "flags must not be set");
138 method_entry->set_table_index(vtable_index);
139 }
140 byte_no = 2;
141 break;
142 }
143
144 case Bytecodes::_invokespecial:
145 case Bytecodes::_invokestatic: {
146 assert(!is_vtable_call, "");
147 // Note: Read and preserve the value of the is_vfinal flag on any
148 // invokevirtual bytecode shared with this constant pool cache entry.
149 // It is cheap and safe to consult is_vfinal() at all times.
150 // Once is_vfinal is set, it must stay that way, lest we get a dangling oop.
151 bool vfinal = method_entry->is_vfinal();
152 method_entry->set_flags(((method->is_final_method() ? 1 : 0) << ResolvedMethodEntry::is_final_shift));
153 assert(vfinal == method_entry->is_vfinal(), "Vfinal flag must be preserved");
154 method_entry->fill_in((u1)as_TosState(method->result_type()), (u2)method()->size_of_parameters());
155 method_entry->set_method(method());
156 byte_no = 1;
157 break;
158 }
159 default:
160 ShouldNotReachHere();
161 break;
162 }
163
164 // Note: byte_no also appears in TemplateTable::resolve.
165 if (byte_no == 1) {
166 assert(invoke_code != Bytecodes::_invokevirtual &&
167 invoke_code != Bytecodes::_invokeinterface, "");
168 bool do_resolve = true;
169 // Don't mark invokespecial to method as resolved if sender is an interface. The receiver
170 // has to be checked that it is a subclass of the current class every time this bytecode
171 // is executed.
172 if (invoke_code == Bytecodes::_invokespecial && sender_is_interface &&
173 method->name() != vmSymbols::object_initializer_name()) {
174 do_resolve = false;
175 }
176 if (invoke_code == Bytecodes::_invokestatic) {
177 assert(method->method_holder()->is_initialized() ||
178 method->method_holder()->is_reentrant_initialization(JavaThread::current()) ||
179 (CDSConfig::is_dumping_archive() && VM_Version::supports_fast_class_init_checks()),
180 "invalid class initialization state for invoke_static");
181
182 if (!VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
183 // Don't mark invokestatic to method as resolved if the holder class has not yet completed
184 // initialization. An invokestatic must only proceed if the class is initialized, but if
185 // we resolve it before then that class initialization check is skipped.
186 //
187 // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
188 // template interpreter supports fast class initialization check for
189 // invokestatic which doesn't require call site re-resolution to
190 // enforce class initialization barrier.
191 do_resolve = false;
192 }
193 }
194 if (do_resolve) {
195 method_entry->set_bytecode1(invoke_code);
196 }
197 } else if (byte_no == 2) {
198 if (change_to_virtual) {
199 assert(invoke_code == Bytecodes::_invokeinterface, "");
200 // NOTE: THIS IS A HACK - BE VERY CAREFUL!!!
201 //
202 // Workaround for the case where we encounter an invokeinterface, but we
203 // should really have an _invokevirtual since the resolved method is a
204 // virtual method in java.lang.Object. This is a corner case in the spec
205 // but is presumably legal. javac does not generate this code.
206 //
207 // We do not set bytecode_1() to _invokeinterface, because that is the
208 // bytecode # used by the interpreter to see if it is resolved. In this
209 // case, the method gets reresolved with caller for each interface call
210 // because the actual selected method may not be public.
211 //
212 // We set bytecode_2() to _invokevirtual.
213 // See also interpreterRuntime.cpp. (8/25/2000)
214 invoke_code = Bytecodes::_invokevirtual;
215 } else {
216 assert(invoke_code == Bytecodes::_invokevirtual ||
217 (invoke_code == Bytecodes::_invokeinterface &&
218 ((method->is_private() ||
219 (method->is_final() && method->method_holder() == vmClasses::Object_klass())))),
220 "unexpected invocation mode");
221 if (invoke_code == Bytecodes::_invokeinterface &&
222 (method->is_private() || method->is_final())) {
223 // We set bytecode_1() to _invokeinterface, because that is the
224 // bytecode # used by the interpreter to see if it is resolved.
225 // We set bytecode_2() to _invokevirtual.
226 method_entry->set_bytecode1(invoke_code);
227 }
228 }
229 // set up for invokevirtual, even if linking for invokeinterface also:
230 method_entry->set_bytecode2(invoke_code);
231 } else {
232 ShouldNotReachHere();
233 }
234 }
235
236 void ConstantPoolCache::set_direct_call(Bytecodes::Code invoke_code, int method_index, const methodHandle& method,
237 bool sender_is_interface) {
238 int index = Method::nonvirtual_vtable_index;
239 // index < 0; FIXME: inline and customize set_direct_or_vtable_call
240 set_direct_or_vtable_call(invoke_code, method_index, method, index, sender_is_interface);
241 }
242
243 void ConstantPoolCache::set_vtable_call(Bytecodes::Code invoke_code, int method_index, const methodHandle& method, int index) {
244 // either the method is a miranda or its holder should accept the given index
245 assert(method->method_holder()->is_interface() || method->method_holder()->verify_vtable_index(index), "");
246 // index >= 0; FIXME: inline and customize set_direct_or_vtable_call
247 set_direct_or_vtable_call(invoke_code, method_index, method, index, false);
248 }
249
250 void ConstantPoolCache::set_itable_call(Bytecodes::Code invoke_code,
251 int method_index,
252 Klass* referenced_klass,
253 const methodHandle& method, int index) {
254 assert(method->method_holder()->verify_itable_index(index), "");
255 assert(invoke_code == Bytecodes::_invokeinterface, "");
256 InstanceKlass* interf = method->method_holder();
257 assert(interf->is_interface(), "must be an interface");
258 assert(!method->is_final_method(), "interfaces do not have final methods; cannot link to one here");
259 ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
260 method_entry->set_klass(static_cast<InstanceKlass*>(referenced_klass));
261 method_entry->set_method(method());
262 method_entry->fill_in((u1)as_TosState(method->result_type()), (u2)method()->size_of_parameters());
263 method_entry->set_bytecode1(Bytecodes::_invokeinterface);
264 }
265
266 ResolvedMethodEntry* ConstantPoolCache::set_method_handle(int method_index, const CallInfo &call_info) {
267 // NOTE: This method entry can be the subject of data races.
268 // There are three words to update: flags, refs[appendix_index], method (in that order).
269 // Writers must store all other values before method.
270 // Readers must test the method first for non-null before reading other fields.
271 // Competing writers must acquire exclusive access via a lock.
272 // A losing writer waits on the lock until the winner writes the method and leaves
273 // the lock, so that when the losing writer returns, he can use the linked
274 // cache entry.
275
276 // Lock fields to write
277 Bytecodes::Code invoke_code = Bytecodes::_invokehandle;
278
279 JavaThread* current = JavaThread::current();
280 refArrayHandle resolved_references(current, constant_pool()->resolved_references());
281 // Use the resolved_references() lock for this cpCache entry.
282 // resolved_references are created for all classes with Invokedynamic, MethodHandle
283 // or MethodType constant pool cache entries.
284 assert(resolved_references() != nullptr,
285 "a resolved_references array should have been created for this class");
286 ObjectLocker ol(resolved_references, current);
287
288 ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
289 if (method_entry->is_resolved(invoke_code)) {
290 return method_entry;
291 }
292
293 Method* adapter = call_info.resolved_method();
294 const Handle appendix = call_info.resolved_appendix();
295 const bool has_appendix = appendix.not_null();
296
297 // Write the flags.
298 // MHs are always sig-poly and have a local signature.
299 method_entry->fill_in((u1)as_TosState(adapter->result_type()), (u2)adapter->size_of_parameters());
300 method_entry->set_flags(((has_appendix ? 1 : 0) << ResolvedMethodEntry::has_appendix_shift ) |
301 ( 1 << ResolvedMethodEntry::has_local_signature_shift ) |
302 ( 1 << ResolvedMethodEntry::is_final_shift ));
303
304 // Method handle invokes use both a method and a resolved references index.
305 // refs[appendix_index], if not null, contains a value passed as a trailing argument to the adapter.
306 // In the general case, this could be the call site's MethodType,
307 // for use with java.lang.Invokers.checkExactType, or else a CallSite object.
308 // method_entry->method() contains the adapter method which manages the actual call.
309 // In the general case, this is a compiled LambdaForm.
310 // (The Java code is free to optimize these calls by binding other
311 // sorts of methods and appendices to call sites.)
312 // JVM-level linking is via the method, as if for invokespecial, and signatures are erased.
313 // The appendix argument (if any) is added to the signature, and is counted in the parameter_size bits.
314 // Even with the appendix, the method will never take more than 255 parameter slots.
315 //
316 // This means that given a call site like (List)mh.invoke("foo"),
317 // the method has signature '(Ljl/Object;Ljl/invoke/MethodType;)Ljl/Object;',
318 // not '(Ljava/lang/String;)Ljava/util/List;'.
319 // The fact that String and List are involved is encoded in the MethodType in refs[appendix_index].
320 // This allows us to create fewer Methods, while keeping type safety.
321 //
322
323 // Store appendix, if any.
324 if (has_appendix) {
325 const int appendix_index = method_entry->resolved_references_index();
326 assert(appendix_index >= 0 && appendix_index < resolved_references->length(), "oob");
327 assert(resolved_references->obj_at(appendix_index) == nullptr, "init just once");
328 resolved_references->obj_at_put(appendix_index, appendix());
329 }
330
331 method_entry->set_method(adapter); // This must be the last one to set (see NOTE above)!
332
333 // The interpreter assembly code does not check byte_2,
334 // but it is used by is_resolved, method_if_resolved, etc.
335 method_entry->set_bytecode1(invoke_code);
336
337 assert(has_appendix == method_entry->has_appendix(), "proper storage of appendix flag");
338 assert(method_entry->has_local_signature(), "proper storage of signature flag");
339 return method_entry;
340 }
341
342 Method* ConstantPoolCache::method_if_resolved(int method_index) const {
343 // Decode the action of set_method and set_interface_call
344 ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
345
346 Bytecodes::Code invoke_code = (Bytecodes::Code)method_entry->bytecode1();
347 switch (invoke_code) {
348 case Bytecodes::_invokeinterface:
349 case Bytecodes::_invokestatic:
350 case Bytecodes::_invokespecial:
351 assert(!method_entry->has_appendix(), "");
352 // fall through
353 case Bytecodes::_invokehandle:
354 return method_entry->method();
355 case Bytecodes::_invokedynamic:
356 ShouldNotReachHere();
357 default:
358 assert(invoke_code == (Bytecodes::Code)0, "unexpected bytecode");
359 break;
360 }
361
362 invoke_code = (Bytecodes::Code)method_entry->bytecode2();
363 if (invoke_code == Bytecodes::_invokevirtual) {
364 if (method_entry->is_vfinal()) {
365 return method_entry->method();
366 } else {
367 int holder_index = constant_pool()->uncached_klass_ref_index_at(method_entry->constant_pool_index());
368 if (constant_pool()->tag_at(holder_index).is_klass()) {
369 Klass* klass = constant_pool()->resolved_klass_at(holder_index);
370 return klass->method_at_vtable(method_entry->table_index());
371 }
372 }
373 }
374 return nullptr;
375 }
376
377 ConstantPoolCache* ConstantPoolCache::allocate(ClassLoaderData* loader_data,
378 const intStack& invokedynamic_map,
379 const GrowableArray<ResolvedIndyEntry> indy_entries,
380 const GrowableArray<ResolvedFieldEntry> field_entries,
381 const GrowableArray<ResolvedMethodEntry> method_entries,
382 TRAPS) {
383
384 int size = ConstantPoolCache::size();
385
386 // Initialize resolved entry arrays with available data
387 Array<ResolvedFieldEntry>* resolved_field_entries = initialize_resolved_entries_array(loader_data, field_entries, CHECK_NULL);
388 Array<ResolvedIndyEntry>* resolved_indy_entries = initialize_resolved_entries_array(loader_data, indy_entries, CHECK_NULL);
389 Array<ResolvedMethodEntry>* resolved_method_entries = initialize_resolved_entries_array(loader_data, method_entries, CHECK_NULL);
390
391 return new (loader_data, size, MetaspaceObj::ConstantPoolCacheType, THREAD)
392 ConstantPoolCache(invokedynamic_map, resolved_indy_entries, resolved_field_entries, resolved_method_entries);
393 }
394
395 // Record the GC marking cycle when redefined vs. when found in the loom stack chunks.
396 void ConstantPoolCache::record_gc_epoch() {
397 _gc_epoch = CodeCache::gc_epoch();
398 }
399
400 #if INCLUDE_CDS
401 void ConstantPoolCache::remove_unshareable_info() {
402 assert(CDSConfig::is_dumping_archive(), "sanity");
403
404 if (_resolved_indy_entries != nullptr) {
405 remove_resolved_indy_entries_if_non_deterministic();
406 }
407 if (_resolved_field_entries != nullptr) {
408 remove_resolved_field_entries_if_non_deterministic();
409 }
410 if (_resolved_method_entries != nullptr) {
411 remove_resolved_method_entries_if_non_deterministic();
412 }
413
414 #if INCLUDE_CDS_JAVA_HEAP
415 _archived_references_index = -1;
416 if (CDSConfig::is_dumping_heap()) {
417 ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(constant_pool());
418 oop rr = HeapShared::scratch_resolved_references(src_cp);
419 if (rr != nullptr) {
420 _archived_references_index = HeapShared::append_root(rr);
421 }
422 }
423 #endif
424 }
425
426 void ConstantPoolCache::remove_resolved_field_entries_if_non_deterministic() {
427 ConstantPool* cp = constant_pool();
428 ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(cp);
429 for (int i = 0; i < _resolved_field_entries->length(); i++) {
430 ResolvedFieldEntry* rfi = _resolved_field_entries->adr_at(i);
431 int cp_index = rfi->constant_pool_index();
432 bool archived = false;
433 bool resolved = false;
434
435 if (rfi->is_resolved(Bytecodes::_getfield) || rfi->is_resolved(Bytecodes::_putfield) ||
436 ((rfi->is_resolved(Bytecodes::_getstatic) || rfi->is_resolved(Bytecodes::_putstatic)) && VM_Version::supports_fast_class_init_checks())) {
437 resolved = true;
438 }
439
440 if (resolved && !CDSConfig::is_dumping_preimage_static_archive()
441 && AOTConstantPoolResolver::is_resolution_deterministic(src_cp, cp_index)) {
442 rfi->mark_and_relocate();
443 archived = true;
444 } else {
445 rfi->remove_unshareable_info();
446 }
447 LogStreamHandle(Trace, aot, resolve) log;
448 if (log.is_enabled()) {
449 ResourceMark rm;
450 int klass_cp_index = cp->uncached_klass_ref_index_at(cp_index);
451 Symbol* klass_name = cp->klass_name_at(klass_cp_index);
452 Symbol* name = cp->uncached_name_ref_at(cp_index);
453 Symbol* signature = cp->uncached_signature_ref_at(cp_index);
454 if (resolved) {
455 log.print("%s field CP entry [%3d]: %s => %s.%s:%s%s%s",
456 (archived ? "archived" : "reverted"),
457 cp_index,
458 cp->pool_holder()->name()->as_C_string(),
459 klass_name->as_C_string(), name->as_C_string(), signature->as_C_string(),
460 rfi->is_resolved(Bytecodes::_getstatic) || rfi->is_resolved(Bytecodes::_putstatic) ? " *** static" : "",
461 (archived ? "" : " (resolution is not deterministic)"));
462 }
463 }
464 ArchiveBuilder::alloc_stats()->record_field_cp_entry(archived, resolved && !archived);
465 }
466 }
467
468 void ConstantPoolCache::remove_resolved_method_entries_if_non_deterministic() {
469 ConstantPool* cp = constant_pool();
470 ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(cp);
471 for (int i = 0; i < _resolved_method_entries->length(); i++) {
472 ResolvedMethodEntry* rme = _resolved_method_entries->adr_at(i);
473 int cp_index = rme->constant_pool_index();
474 bool archived = false;
475 bool resolved = rme->is_resolved(Bytecodes::_invokevirtual) ||
476 rme->is_resolved(Bytecodes::_invokespecial) ||
477 rme->is_resolved(Bytecodes::_invokeinterface) ||
478 rme->is_resolved(Bytecodes::_invokehandle) ||
479 (rme->is_resolved(Bytecodes::_invokestatic) && VM_Version::supports_fast_class_init_checks());
480
481 const char* rejection_reason = nullptr;
482 if (resolved && !CDSConfig::is_dumping_preimage_static_archive()
483 && can_archive_resolved_method(src_cp, rme, rejection_reason)) {
484 rme->mark_and_relocate(src_cp);
485 archived = true;
486 } else {
487 rme->remove_unshareable_info();
488 }
489 LogTarget(Trace, aot, resolve) lt;
490 if (lt.is_enabled()) {
491 ResourceMark rm;
492 int klass_cp_index = cp->uncached_klass_ref_index_at(cp_index);
493 Symbol* klass_name = cp->klass_name_at(klass_cp_index);
494 Symbol* name = cp->uncached_name_ref_at(cp_index);
495 Symbol* signature = cp->uncached_signature_ref_at(cp_index);
496 LogStream ls(lt);
497 if (resolved) {
498 ls.print("%s%s method CP entry [%3d]: %s %s.%s:%s",
499 (archived ? "archived" : "reverted"),
500 (rme->is_resolved(Bytecodes::_invokeinterface) ? " interface" : ""),
501 cp_index,
502 cp->pool_holder()->name()->as_C_string(),
503 klass_name->as_C_string(), name->as_C_string(), signature->as_C_string());
504 if (rejection_reason != nullptr) {
505 ls.print(" %s", rejection_reason);
506 }
507 }
508 if (archived) {
509 Klass* resolved_klass = cp->resolved_klass_at(klass_cp_index);
510 ls.print(" => %s%s",
511 resolved_klass->name()->as_C_string(),
512 (rme->is_resolved(Bytecodes::_invokestatic) ? " *** static" : ""));
513 }
514 ls.cr();
515 }
516 ArchiveBuilder::alloc_stats()->record_method_cp_entry(archived, resolved && !archived);
517 }
518 }
519
520 void ConstantPoolCache::remove_resolved_indy_entries_if_non_deterministic() {
521 ConstantPool* cp = constant_pool();
522 ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(cp);
523 for (int i = 0; i < _resolved_indy_entries->length(); i++) {
524 ResolvedIndyEntry* rei = _resolved_indy_entries->adr_at(i);
525 int cp_index = rei->constant_pool_index();
526 bool archived = false;
527 bool resolved = rei->is_resolved();
528 if (resolved && !CDSConfig::is_dumping_preimage_static_archive()
529 && AOTConstantPoolResolver::is_resolution_deterministic(src_cp, cp_index)) {
530 rei->mark_and_relocate();
531 archived = true;
532 } else {
533 rei->remove_unshareable_info();
534 }
535 LogStreamHandle(Trace, aot, resolve) log;
536 if (log.is_enabled()) {
537 ResourceMark rm;
538 int bsm = cp->bootstrap_method_ref_index_at(cp_index);
539 int bsm_ref = cp->method_handle_index_at(bsm);
540 Symbol* bsm_name = cp->uncached_name_ref_at(bsm_ref);
541 Symbol* bsm_signature = cp->uncached_signature_ref_at(bsm_ref);
542 Symbol* bsm_klass = cp->klass_name_at(cp->uncached_klass_ref_index_at(bsm_ref));
543 if (resolved) {
544 log.print("%s indy CP entry [%3d]: %s (%d)",
545 (archived ? "archived" : "reverted"),
546 cp_index, cp->pool_holder()->name()->as_C_string(), i);
547 log.print(" %s %s.%s:%s%s", (archived ? "=>" : " "), bsm_klass->as_C_string(),
548 bsm_name->as_C_string(), bsm_signature->as_C_string(),
549 (archived ? "" : " (resolution is not deterministic)"));
550 }
551 }
552 ArchiveBuilder::alloc_stats()->record_indy_cp_entry(archived, resolved && !archived);
553 }
554 }
555
556 bool ConstantPoolCache::can_archive_resolved_method(ConstantPool* src_cp, ResolvedMethodEntry* method_entry, const char*& rejection_reason) {
557 InstanceKlass* pool_holder = constant_pool()->pool_holder();
558 if (pool_holder->defined_by_other_loaders()) {
559 // Archiving resolved cp entries for classes from non-builtin loaders
560 // is not yet supported.
561 rejection_reason = "(pool holder comes from a non-builtin loader)";
562 return false;
563 }
564
565 if (CDSConfig::is_dumping_dynamic_archive()) {
566 // InstanceKlass::methods() has been resorted. We need to
567 // update the vtable_index in method_entry (not implemented)
568 rejection_reason = "(InstanceKlass::methods() has been resorted)";
569 return false;
570 }
571
572 int cp_index = method_entry->constant_pool_index();
573
574 if (!method_entry->is_resolved(Bytecodes::_invokevirtual)) {
575 if (method_entry->method() == nullptr) {
576 rejection_reason = "(method entry is not resolved)";
577 return false;
578 }
579 if (method_entry->method()->is_continuation_native_intrinsic()) {
580 rejection_reason = "(corresponding stub is generated on demand during method resolution)";
581 return false; // FIXME: corresponding stub is generated on demand during method resolution (see LinkResolver::resolve_static_call).
582 }
583 if (method_entry->is_resolved(Bytecodes::_invokehandle)) {
584 if (!CDSConfig::is_dumping_method_handles()) {
585 rejection_reason = "(not dumping method handles)";
586 return false;
587 }
588
589 Symbol* sig = constant_pool()->uncached_signature_ref_at(cp_index);
590 Klass* k;
591 if (!AOTConstantPoolResolver::check_methodtype_signature(constant_pool(), sig, &k, true)) {
592 // invokehandles that were resolved in the training run should have been filtered in
593 // AOTConstantPoolResolver::maybe_resolve_fmi_ref so we shouldn't come to here.
594 //
595 // If we come here it's because the AOT assembly phase has executed an invokehandle
596 // that uses an excluded type like jdk.jfr.Event. This should not happen because the
597 // AOT assembly phase should execute only a very limited set of Java code.
598 ResourceMark rm;
599 fatal("AOT assembly phase must not resolve any invokehandles whose signatures include an excluded type");
600 }
601 }
602 if (method_entry->method()->is_method_handle_intrinsic() && !CDSConfig::is_dumping_method_handles()) {
603 rejection_reason = "(not dumping intrinsic method handles)";
604 return false;
605 }
606 }
607
608 assert(src_cp->tag_at(cp_index).is_method() || src_cp->tag_at(cp_index).is_interface_method(), "sanity");
609
610 if (!AOTConstantPoolResolver::is_resolution_deterministic(src_cp, cp_index)) {
611 rejection_reason = "(resolution is not deterministic)";
612 return false;
613 }
614 return true;
615 }
616 #endif // INCLUDE_CDS
617
618 void ConstantPoolCache::deallocate_contents(ClassLoaderData* data) {
619 assert(!in_aot_cache(), "objects in aot metaspace are not deallocated");
620 data->remove_handle(_resolved_references);
621 set_resolved_references(OopHandle());
622 MetadataFactory::free_array<u2>(data, _reference_map);
623 set_reference_map(nullptr);
624 #if INCLUDE_CDS
625 if (_resolved_indy_entries != nullptr) {
626 MetadataFactory::free_array<ResolvedIndyEntry>(data, _resolved_indy_entries);
627 _resolved_indy_entries = nullptr;
628 }
629 if (_resolved_field_entries != nullptr) {
630 MetadataFactory::free_array<ResolvedFieldEntry>(data, _resolved_field_entries);
631 _resolved_field_entries = nullptr;
632 }
633 if (_resolved_method_entries != nullptr) {
634 MetadataFactory::free_array<ResolvedMethodEntry>(data, _resolved_method_entries);
635 _resolved_method_entries = nullptr;
636 }
637 #endif
638 }
639
640 #if INCLUDE_CDS_JAVA_HEAP
641 oop ConstantPoolCache::archived_references() {
642 if (_archived_references_index < 0) {
643 return nullptr;
644 }
645 return HeapShared::get_root(_archived_references_index);
646 }
647
648 void ConstantPoolCache::clear_archived_references() {
649 if (_archived_references_index >= 0) {
650 HeapShared::clear_root(_archived_references_index);
651 _archived_references_index = -1;
652 }
653 }
654 #endif
655
656 #if INCLUDE_JVMTI
657 static void log_adjust(const char* entry_type, Method* old_method, Method* new_method, bool* trace_name_printed) {
658 ResourceMark rm;
659
660 if (!(*trace_name_printed)) {
661 log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
662 *trace_name_printed = true;
663 }
664 log_trace(redefine, class, update, constantpool)
665 ("cpc %s entry update: %s", entry_type, new_method->external_name());
666 }
667
668 // RedefineClasses() API support:
669 // If any entry of this ConstantPoolCache points to any of
670 // old_methods, replace it with the corresponding new_method.
671 void ConstantPoolCache::adjust_method_entries(bool * trace_name_printed) {
672 if (_resolved_indy_entries != nullptr) {
673 for (int j = 0; j < _resolved_indy_entries->length(); j++) {
674 Method* old_method = resolved_indy_entry_at(j)->method();
675 if (old_method == nullptr || !old_method->is_old()) {
676 continue;
677 }
678 assert(!old_method->is_deleted(), "cannot delete these methods");
679 Method* new_method = old_method->get_new_method();
680 resolved_indy_entry_at(j)->adjust_method_entry(new_method);
681 log_adjust("indy", old_method, new_method, trace_name_printed);
682 }
683 }
684 if (_resolved_method_entries != nullptr) {
685 for (int i = 0; i < _resolved_method_entries->length(); i++) {
686 ResolvedMethodEntry* method_entry = resolved_method_entry_at(i);
687 // get interesting method entry
688 Method* old_method = method_entry->method();
689 if (old_method == nullptr || !old_method->is_old()) {
690 continue; // skip uninteresting entries
691 }
692 if (old_method->is_deleted()) {
693 // clean up entries with deleted methods
694 method_entry->reset_entry();
695 continue;
696 }
697 Method* new_method = old_method->get_new_method();
698 method_entry->adjust_method_entry(new_method);
699 log_adjust("non-indy", old_method, new_method, trace_name_printed);
700 }
701 }
702 }
703
704 // the constant pool cache should never contain old or obsolete methods
705 bool ConstantPoolCache::check_no_old_or_obsolete_entries() {
706 ResourceMark rm;
707 if (_resolved_indy_entries != nullptr) {
708 for (int i = 0; i < _resolved_indy_entries->length(); i++) {
709 Method* m = resolved_indy_entry_at(i)->method();
710 if (m != nullptr && !resolved_indy_entry_at(i)->check_no_old_or_obsolete_entry()) {
711 log_trace(redefine, class, update, constantpool)
712 ("cpcache check found old method entry: class: %s, old: %d, obsolete: %d, method: %s",
713 constant_pool()->pool_holder()->external_name(), m->is_old(), m->is_obsolete(), m->external_name());
714 return false;
715 }
716 }
717 }
718 if (_resolved_method_entries != nullptr) {
719 for (int i = 0; i < _resolved_method_entries->length(); i++) {
720 ResolvedMethodEntry* method_entry = resolved_method_entry_at(i);
721 Method* m = method_entry->method();
722 if (m != nullptr && !method_entry->check_no_old_or_obsolete_entry()) {
723 log_trace(redefine, class, update, constantpool)
724 ("cpcache check found old method entry: class: %s, old: %d, obsolete: %d, method: %s",
725 constant_pool()->pool_holder()->external_name(), m->is_old(), m->is_obsolete(), m->external_name());
726 return false;
727 }
728 }
729 }
730 return true;
731 }
732
733 void ConstantPoolCache::dump_cache() {
734 print_on(tty);
735 }
736 #endif // INCLUDE_JVMTI
737
738 void ConstantPoolCache::metaspace_pointers_do(MetaspaceClosure* it) {
739 log_trace(aot)("Iter(ConstantPoolCache): %p", this);
740 it->push(&_constant_pool);
741 it->push(&_reference_map);
742 if (_resolved_indy_entries != nullptr) {
743 it->push(&_resolved_indy_entries, MetaspaceClosure::_writable);
744 }
745 if (_resolved_field_entries != nullptr) {
746 it->push(&_resolved_field_entries, MetaspaceClosure::_writable);
747 }
748 if (_resolved_method_entries != nullptr) {
749 it->push(&_resolved_method_entries, MetaspaceClosure::_writable);
750 }
751 }
752
753 bool ConstantPoolCache::save_and_throw_indy_exc(
754 const constantPoolHandle& cpool, int cpool_index, int index, constantTag tag, TRAPS) {
755
756 assert(HAS_PENDING_EXCEPTION, "No exception got thrown!");
757 assert(PENDING_EXCEPTION->is_a(vmClasses::LinkageError_klass()),
758 "No LinkageError exception");
759
760 // Use the resolved_references() lock for this cpCache entry.
761 // resolved_references are created for all classes with Invokedynamic, MethodHandle
762 // or MethodType constant pool cache entries.
763 JavaThread* current = THREAD;
764 objArrayHandle resolved_references(current, cpool->resolved_references());
765 assert(resolved_references() != nullptr,
766 "a resolved_references array should have been created for this class");
767 ObjectLocker ol(resolved_references, current);
768
769 // if the indy_info is resolved or the indy_resolution_failed flag is set then another
770 // thread either succeeded in resolving the method or got a LinkageError
771 // exception, before this thread was able to record its failure. So, clear
772 // this thread's exception and return false so caller can use the earlier
773 // thread's result.
774 if (resolved_indy_entry_at(index)->is_resolved() || resolved_indy_entry_at(index)->resolution_failed()) {
775 CLEAR_PENDING_EXCEPTION;
776 return false;
777 }
778 ResourceMark rm(THREAD);
779 Symbol* error = PENDING_EXCEPTION->klass()->name();
780 const char* message = java_lang_Throwable::message_as_utf8(PENDING_EXCEPTION);
781
782 int encoded_index = ResolutionErrorTable::encode_indy_index(index);
783 SystemDictionary::add_resolution_error(cpool, encoded_index, error, message);
784 resolved_indy_entry_at(index)->set_resolution_failed();
785 return true;
786 }
787
788 oop ConstantPoolCache::set_dynamic_call(const CallInfo &call_info, int index) {
789 ResourceMark rm;
790
791 // Use the resolved_references() lock for this cpCache entry.
792 // resolved_references are created for all classes with Invokedynamic, MethodHandle
793 // or MethodType constant pool cache entries.
794 JavaThread* current = JavaThread::current();
795 constantPoolHandle cp(current, constant_pool());
796
797 refArrayHandle resolved_references(current, cp->resolved_references());
798 assert(resolved_references() != nullptr,
799 "a resolved_references array should have been created for this class");
800 ObjectLocker ol(resolved_references, current);
801 assert(index >= 0, "Indy index must be positive at this point");
802
803 if (resolved_indy_entry_at(index)->method() != nullptr) {
804 return cp->resolved_reference_from_indy(index);
805 }
806
807 if (resolved_indy_entry_at(index)->resolution_failed()) {
808 // Before we got here, another thread got a LinkageError exception during
809 // resolution. Ignore our success and throw their exception.
810 guarantee(index >= 0, "Invalid indy index");
811 int encoded_index = ResolutionErrorTable::encode_indy_index(index);
812 ConstantPool::throw_resolution_error(cp, encoded_index, current);
813 return nullptr;
814 }
815
816 Method* adapter = call_info.resolved_method();
817 const Handle appendix = call_info.resolved_appendix();
818 const bool has_appendix = appendix.not_null();
819
820 LogStream* log_stream = nullptr;
821 LogStreamHandle(Debug, methodhandles, indy) lsh_indy;
822 if (lsh_indy.is_enabled()) {
823 ResourceMark rm;
824 log_stream = &lsh_indy;
825 log_stream->print_cr("set_method_handle bc=%d appendix=" PTR_FORMAT "%s method=" PTR_FORMAT " (local signature) ",
826 0xba,
827 p2i(appendix()),
828 (has_appendix ? "" : " (unused)"),
829 p2i(adapter));
830 adapter->print_on(log_stream);
831 if (has_appendix) appendix()->print_on(log_stream);
832 }
833
834 if (has_appendix) {
835 const int appendix_index = resolved_indy_entry_at(index)->resolved_references_index();
836 assert(appendix_index >= 0 && appendix_index < resolved_references->length(), "oob");
837 assert(resolved_references->obj_at(appendix_index) == nullptr, "init just once");
838 resolved_references->obj_at_put(appendix_index, appendix());
839 }
840
841 // Populate entry with resolved information
842 assert(resolved_indy_entries() != nullptr, "Invokedynamic array is empty, cannot fill with resolved information");
843 resolved_indy_entry_at(index)->fill_in(adapter, adapter->size_of_parameters(), as_TosState(adapter->result_type()), has_appendix);
844
845 if (log_stream != nullptr) {
846 resolved_indy_entry_at(index)->print_on(log_stream);
847 }
848 return appendix();
849 }
850
851 oop ConstantPoolCache::appendix_if_resolved(int method_index) const {
852 ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
853 return appendix_if_resolved(method_entry);
854 }
855
856 oop ConstantPoolCache::appendix_if_resolved(ResolvedMethodEntry* method_entry) const {
857 if (!method_entry->has_appendix())
858 return nullptr;
859 const int ref_index = method_entry->resolved_references_index();
860 return constant_pool()->resolved_reference_at(ref_index);
861 }
862
863 // Printing
864
865 void ConstantPoolCache::print_on(outputStream* st) const {
866 st->print_cr("%s", internal_name());
867 // print constant pool cache entries
868 if (_resolved_field_entries != nullptr) {
869 print_resolved_field_entries(st);
870 }
871 if (_resolved_method_entries != nullptr) {
872 print_resolved_method_entries(st);
873 }
874 if (_resolved_indy_entries != nullptr) {
875 print_resolved_indy_entries(st);
876 }
877 }
878
879 void ConstantPoolCache::print_resolved_field_entries(outputStream* st) const {
880 for (int field_index = 0; field_index < resolved_field_entries_length(); field_index++) {
881 resolved_field_entry_at(field_index)->print_on(st);
882 }
883 }
884
885 void ConstantPoolCache::print_resolved_method_entries(outputStream* st) const {
886 for (int method_index = 0; method_index < resolved_method_entries_length(); method_index++) {
887 ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
888 method_entry->print_on(st);
889 if (method_entry->has_appendix()) {
890 st->print(" appendix: ");
891 constant_pool()->resolved_reference_from_method(method_index)->print_on(st);
892 }
893 }
894 }
895
896 void ConstantPoolCache::print_resolved_indy_entries(outputStream* st) const {
897 for (int indy_index = 0; indy_index < resolved_indy_entries_length(); indy_index++) {
898 ResolvedIndyEntry* indy_entry = resolved_indy_entry_at(indy_index);
899 indy_entry->print_on(st);
900 if (indy_entry->has_appendix()) {
901 st->print(" appendix: ");
902 constant_pool()->resolved_reference_from_indy(indy_index)->print_on(st);
903 }
904 }
905 }