1 /*
  2  * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "cds/cdsConfig.hpp"
 27 #include "cds/heapShared.hpp"
 28 #include "classfile/resolutionErrors.hpp"
 29 #include "classfile/systemDictionary.hpp"
 30 #include "classfile/systemDictionaryShared.hpp"
 31 #include "classfile/vmClasses.hpp"
 32 #include "code/codeCache.hpp"
 33 #include "interpreter/bytecodeStream.hpp"
 34 #include "interpreter/bytecodes.hpp"
 35 #include "interpreter/interpreter.hpp"
 36 #include "interpreter/linkResolver.hpp"
 37 #include "interpreter/rewriter.hpp"
 38 #include "logging/log.hpp"
 39 #include "logging/logStream.hpp"
 40 #include "memory/metadataFactory.hpp"
 41 #include "memory/metaspaceClosure.hpp"
 42 #include "memory/resourceArea.hpp"
 43 #include "oops/access.inline.hpp"
 44 #include "oops/compressedOops.hpp"
 45 #include "oops/constantPool.inline.hpp"
 46 #include "oops/cpCache.inline.hpp"
 47 #include "oops/objArrayOop.inline.hpp"
 48 #include "oops/oop.inline.hpp"
 49 #include "oops/resolvedFieldEntry.hpp"
 50 #include "oops/resolvedIndyEntry.hpp"
 51 #include "oops/resolvedMethodEntry.hpp"
 52 #include "prims/methodHandles.hpp"
 53 #include "runtime/arguments.hpp"
 54 #include "runtime/atomic.hpp"
 55 #include "runtime/handles.inline.hpp"
 56 #include "runtime/mutexLocker.hpp"
 57 #include "runtime/vm_version.hpp"
 58 #include "utilities/macros.hpp"
 59 
 60 // Implementation of ConstantPoolCache
 61 
 62 template <class T>
 63 static Array<T>* initialize_resolved_entries_array(ClassLoaderData* loader_data, GrowableArray<T> entries, TRAPS) {
 64   Array<T>* resolved_entries;
 65   if (entries.length() != 0) {
 66     resolved_entries = MetadataFactory::new_array<T>(loader_data, entries.length(), CHECK_NULL);
 67     for (int i = 0; i < entries.length(); i++) {
 68       resolved_entries->at_put(i, entries.at(i));
 69     }
 70     return resolved_entries;
 71   }
 72   return nullptr;
 73 }
 74 
 75 void ConstantPoolCache::set_direct_or_vtable_call(Bytecodes::Code invoke_code,
 76                                                        int method_index,
 77                                                        const methodHandle& method,
 78                                                        int vtable_index,
 79                                                        bool sender_is_interface) {
 80   bool is_vtable_call = (vtable_index >= 0);  // FIXME: split this method on this boolean
 81   assert(method->interpreter_entry() != nullptr, "should have been set at this point");
 82   assert(!method->is_obsolete(),  "attempt to write obsolete method to cpCache");
 83 
 84   int byte_no = -1;
 85   bool change_to_virtual = false;
 86   InstanceKlass* holder = nullptr;  // have to declare this outside the switch
 87   ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
 88   switch (invoke_code) {
 89     case Bytecodes::_invokeinterface:
 90       holder = method->method_holder();
 91       // check for private interface method invocations
 92       if (vtable_index == Method::nonvirtual_vtable_index && holder->is_interface() ) {
 93         assert(method->is_private(), "unexpected non-private method");
 94         assert(method->can_be_statically_bound(), "unexpected non-statically-bound method");
 95 
 96         method_entry->set_flags((                             1      << ResolvedMethodEntry::is_vfinal_shift) |
 97                                 ((method->is_final_method() ? 1 : 0) << ResolvedMethodEntry::is_final_shift));
 98         method_entry->fill_in((u1)as_TosState(method->result_type()), (u2)method()->size_of_parameters());
 99         assert(method_entry->is_vfinal(), "flags must be set");
100         method_entry->set_method(method());
101         byte_no = 2;
102         method_entry->set_klass(holder);
103         break;
104       }
105       else {
106         // We get here from InterpreterRuntime::resolve_invoke when an invokeinterface
107         // instruction links to a non-interface method (in Object). This can happen when
108         // an interface redeclares an Object method (like CharSequence declaring toString())
109         // or when invokeinterface is used explicitly.
110         // In that case, the method has no itable index and must be invoked as a virtual.
111         // Set a flag to keep track of this corner case.
112         assert(holder->is_interface() || holder == vmClasses::Object_klass(), "unexpected holder class");
113         assert(method->is_public(), "Calling non-public method in Object with invokeinterface");
114         change_to_virtual = true;
115 
116         // ...and fall through as if we were handling invokevirtual:
117       }
118     case Bytecodes::_invokevirtual:
119       {
120         if (!is_vtable_call) {
121           assert(method->can_be_statically_bound(), "");
122           method_entry->set_flags((                             1      << ResolvedMethodEntry::is_vfinal_shift) |
123                                   ((method->is_final_method() ? 1 : 0) << ResolvedMethodEntry::is_final_shift)  |
124                                   ((change_to_virtual         ? 1 : 0) << ResolvedMethodEntry::is_forced_virtual_shift));
125           method_entry->fill_in((u1)as_TosState(method->result_type()), (u2)method()->size_of_parameters());
126           assert(method_entry->is_vfinal(), "flags must be set");
127           method_entry->set_method(method());
128         } else {
129           assert(!method->can_be_statically_bound(), "");
130           assert(vtable_index >= 0, "valid index");
131           assert(!method->is_final_method(), "sanity");
132           method_entry->set_flags((change_to_virtual ? 1 : 0) << ResolvedMethodEntry::is_forced_virtual_shift);
133           method_entry->fill_in((u1)as_TosState(method->result_type()), (u2)method()->size_of_parameters());
134           assert(!method_entry->is_vfinal(), "flags must not be set");
135           method_entry->set_table_index(vtable_index);
136         }
137         byte_no = 2;
138         break;
139       }
140 
141     case Bytecodes::_invokespecial:
142     case Bytecodes::_invokestatic: {
143       assert(!is_vtable_call, "");
144       // Note:  Read and preserve the value of the is_vfinal flag on any
145       // invokevirtual bytecode shared with this constant pool cache entry.
146       // It is cheap and safe to consult is_vfinal() at all times.
147       // Once is_vfinal is set, it must stay that way, lest we get a dangling oop.
148       bool vfinal = method_entry->is_vfinal();
149       method_entry->set_flags(((method->is_final_method() ? 1 : 0) << ResolvedMethodEntry::is_final_shift));
150       assert(vfinal == method_entry->is_vfinal(), "Vfinal flag must be preserved");
151       method_entry->fill_in((u1)as_TosState(method->result_type()), (u2)method()->size_of_parameters());
152       method_entry->set_method(method());
153       byte_no = 1;
154       break;
155     }
156     default:
157       ShouldNotReachHere();
158       break;
159   }
160 
161   // Note:  byte_no also appears in TemplateTable::resolve.
162   if (byte_no == 1) {
163     assert(invoke_code != Bytecodes::_invokevirtual &&
164            invoke_code != Bytecodes::_invokeinterface, "");
165     bool do_resolve = true;
166     // Don't mark invokespecial to method as resolved if sender is an interface.  The receiver
167     // has to be checked that it is a subclass of the current class every time this bytecode
168     // is executed.
169     if (invoke_code == Bytecodes::_invokespecial && sender_is_interface &&
170         method->name() != vmSymbols::object_initializer_name()) {
171       do_resolve = false;
172     }
173     if (invoke_code == Bytecodes::_invokestatic) {
174       assert(method->method_holder()->is_initialized() ||
175              method->method_holder()->is_init_thread(JavaThread::current()) ||
176              (CDSConfig::is_dumping_archive() && VM_Version::supports_fast_class_init_checks()),
177              "invalid class initialization state for invoke_static");
178 
179       if (!VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
180         // Don't mark invokestatic to method as resolved if the holder class has not yet completed
181         // initialization. An invokestatic must only proceed if the class is initialized, but if
182         // we resolve it before then that class initialization check is skipped.
183         //
184         // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
185         // template interpreter supports fast class initialization check for
186         // invokestatic which doesn't require call site re-resolution to
187         // enforce class initialization barrier.
188         do_resolve = false;
189       }
190     }
191     if (do_resolve) {
192       method_entry->set_bytecode1(invoke_code);
193     }
194   } else if (byte_no == 2)  {
195     if (change_to_virtual) {
196       assert(invoke_code == Bytecodes::_invokeinterface, "");
197       // NOTE: THIS IS A HACK - BE VERY CAREFUL!!!
198       //
199       // Workaround for the case where we encounter an invokeinterface, but we
200       // should really have an _invokevirtual since the resolved method is a
201       // virtual method in java.lang.Object. This is a corner case in the spec
202       // but is presumably legal. javac does not generate this code.
203       //
204       // We do not set bytecode_1() to _invokeinterface, because that is the
205       // bytecode # used by the interpreter to see if it is resolved.  In this
206       // case, the method gets reresolved with caller for each interface call
207       // because the actual selected method may not be public.
208       //
209       // We set bytecode_2() to _invokevirtual.
210       // See also interpreterRuntime.cpp. (8/25/2000)
211     } else {
212       assert(invoke_code == Bytecodes::_invokevirtual ||
213              (invoke_code == Bytecodes::_invokeinterface &&
214               ((method->is_private() ||
215                 (method->is_final() && method->method_holder() == vmClasses::Object_klass())))),
216              "unexpected invocation mode");
217       if (invoke_code == Bytecodes::_invokeinterface &&
218           (method->is_private() || method->is_final())) {
219         // We set bytecode_1() to _invokeinterface, because that is the
220         // bytecode # used by the interpreter to see if it is resolved.
221         // We set bytecode_2() to _invokevirtual.
222         method_entry->set_bytecode1(invoke_code);
223       }
224     }
225     // set up for invokevirtual, even if linking for invokeinterface also:
226     method_entry->set_bytecode2(Bytecodes::_invokevirtual);
227   } else {
228     ShouldNotReachHere();
229   }
230 }
231 
232 void ConstantPoolCache::set_direct_call(Bytecodes::Code invoke_code, int method_index, const methodHandle& method,
233                                         bool sender_is_interface) {
234   int index = Method::nonvirtual_vtable_index;
235   // index < 0; FIXME: inline and customize set_direct_or_vtable_call
236   set_direct_or_vtable_call(invoke_code, method_index, method, index, sender_is_interface);
237 }
238 
239 void ConstantPoolCache::set_vtable_call(Bytecodes::Code invoke_code, int method_index, const methodHandle& method, int index) {
240   // either the method is a miranda or its holder should accept the given index
241   assert(method->method_holder()->is_interface() || method->method_holder()->verify_vtable_index(index), "");
242   // index >= 0; FIXME: inline and customize set_direct_or_vtable_call
243   set_direct_or_vtable_call(invoke_code, method_index, method, index, false);
244 }
245 
246 void ConstantPoolCache::set_itable_call(Bytecodes::Code invoke_code,
247                                         int method_index,
248                                         Klass* referenced_klass,
249                                         const methodHandle& method, int index) {
250   assert(method->method_holder()->verify_itable_index(index), "");
251   assert(invoke_code == Bytecodes::_invokeinterface, "");
252   InstanceKlass* interf = method->method_holder();
253   assert(interf->is_interface(), "must be an interface");
254   assert(!method->is_final_method(), "interfaces do not have final methods; cannot link to one here");
255   ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
256   method_entry->set_klass(static_cast<InstanceKlass*>(referenced_klass));
257   method_entry->set_method(method());
258   method_entry->fill_in((u1)as_TosState(method->result_type()), (u2)method()->size_of_parameters());
259   method_entry->set_bytecode1(Bytecodes::_invokeinterface);
260 }
261 
262 ResolvedMethodEntry* ConstantPoolCache::set_method_handle(int method_index, const CallInfo &call_info) {
263   // NOTE: This method entry can be the subject of data races.
264   // There are three words to update: flags, refs[appendix_index], method (in that order).
265   // Writers must store all other values before method.
266   // Readers must test the method first for non-null before reading other fields.
267   // Competing writers must acquire exclusive access via a lock.
268   // A losing writer waits on the lock until the winner writes the method and leaves
269   // the lock, so that when the losing writer returns, he can use the linked
270   // cache entry.
271   // Lock fields to write
272   Bytecodes::Code invoke_code = Bytecodes::_invokehandle;
273   MutexLocker ml(constant_pool()->pool_holder()->init_monitor());
274   ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
275 
276   if (method_entry->is_resolved(invoke_code)) {
277     return method_entry;
278   }
279 
280   Method* adapter            = call_info.resolved_method();
281   const Handle appendix      = call_info.resolved_appendix();
282   const bool has_appendix    = appendix.not_null();
283 
284   // Write the flags.
285   // MHs are always sig-poly and have a local signature.
286   method_entry->fill_in((u1)as_TosState(adapter->result_type()), (u2)adapter->size_of_parameters());
287   method_entry->set_flags(((has_appendix    ? 1 : 0) << ResolvedMethodEntry::has_appendix_shift        ) |
288                           (                   1      << ResolvedMethodEntry::has_local_signature_shift ) |
289                           (                   1      << ResolvedMethodEntry::is_final_shift            ));
290 
291   // Method handle invokes use both a method and a resolved references index.
292   // refs[appendix_index], if not null, contains a value passed as a trailing argument to the adapter.
293   // In the general case, this could be the call site's MethodType,
294   // for use with java.lang.Invokers.checkExactType, or else a CallSite object.
295   // method_entry->method() contains the adapter method which manages the actual call.
296   // In the general case, this is a compiled LambdaForm.
297   // (The Java code is free to optimize these calls by binding other
298   // sorts of methods and appendices to call sites.)
299   // JVM-level linking is via the method, as if for invokespecial, and signatures are erased.
300   // The appendix argument (if any) is added to the signature, and is counted in the parameter_size bits.
301   // Even with the appendix, the method will never take more than 255 parameter slots.
302   //
303   // This means that given a call site like (List)mh.invoke("foo"),
304   // the method has signature '(Ljl/Object;Ljl/invoke/MethodType;)Ljl/Object;',
305   // not '(Ljava/lang/String;)Ljava/util/List;'.
306   // The fact that String and List are involved is encoded in the MethodType in refs[appendix_index].
307   // This allows us to create fewer Methods, while keeping type safety.
308   //
309 
310   // Store appendix, if any.
311   if (has_appendix) {
312     const int appendix_index = method_entry->resolved_references_index();
313     objArrayOop resolved_references = constant_pool()->resolved_references();
314     assert(appendix_index >= 0 && appendix_index < resolved_references->length(), "oob");
315     assert(resolved_references->obj_at(appendix_index) == nullptr, "init just once");
316     resolved_references->obj_at_put(appendix_index, appendix());
317   }
318 
319   method_entry->set_method(adapter); // This must be the last one to set (see NOTE above)!
320 
321   // The interpreter assembly code does not check byte_2,
322   // but it is used by is_resolved, method_if_resolved, etc.
323   method_entry->set_bytecode1(invoke_code);
324 
325   assert(has_appendix == method_entry->has_appendix(), "proper storage of appendix flag");
326   assert(method_entry->has_local_signature(), "proper storage of signature flag");
327   return method_entry;
328 }
329 
330 Method* ConstantPoolCache::method_if_resolved(int method_index) const {
331   // Decode the action of set_method and set_interface_call
332   ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
333 
334   Bytecodes::Code invoke_code = (Bytecodes::Code)method_entry->bytecode1();
335   switch (invoke_code) {
336     case Bytecodes::_invokeinterface:
337     case Bytecodes::_invokestatic:
338     case Bytecodes::_invokespecial:
339       assert(!method_entry->has_appendix(), "");
340       // fall through
341     case Bytecodes::_invokehandle:
342       return method_entry->method();
343     case Bytecodes::_invokedynamic:
344       ShouldNotReachHere();
345     default:
346       assert(invoke_code == (Bytecodes::Code)0, "unexpected bytecode");
347       break;
348   }
349 
350   invoke_code = (Bytecodes::Code)method_entry->bytecode2();
351   if (invoke_code == Bytecodes::_invokevirtual) {
352     if (method_entry->is_vfinal()) {
353       return method_entry->method();
354     } else {
355       int holder_index = constant_pool()->uncached_klass_ref_index_at(method_entry->constant_pool_index());
356       if (constant_pool()->tag_at(holder_index).is_klass()) {
357         Klass* klass = constant_pool()->resolved_klass_at(holder_index);
358         return klass->method_at_vtable(method_entry->table_index());
359       }
360     }
361   }
362   return nullptr;
363 #if 0
364  else {
365     assert(is_field_entry(), "must be a field entry");
366     st->print_cr(" - F1:  [   " PTR_FORMAT "]", (intptr_t)_f1);
367     st->print_cr(" - F2:  [   " PTR_FORMAT "]", (intptr_t)_f2);
368     st->print_cr(" - flag values: [%02x|0|1|0|0|0|%01x|%01x|0|0|%04x]",
369                  flag_state(), is_final(), is_volatile(), field_index());
370     st->print_cr(" - tos: %s\n - final: %d\n - volatile: %d\n - field index: %04x",
371                  type2name(as_BasicType(flag_state())), is_final(), is_volatile(), field_index());
372   }
373   st->print_cr("                 -------------");
374 #endif
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 void ConstantPoolCache::deallocate_contents(ClassLoaderData* data) {
401   assert(!is_shared(), "shared caches are not deallocated");
402   data->remove_handle(_resolved_references);
403   set_resolved_references(OopHandle());
404   MetadataFactory::free_array<u2>(data, _reference_map);
405   set_reference_map(nullptr);
406 #if INCLUDE_CDS
407   if (_resolved_indy_entries != nullptr) {
408     MetadataFactory::free_array<ResolvedIndyEntry>(data, _resolved_indy_entries);
409     _resolved_indy_entries = nullptr;
410   }
411   if (_resolved_field_entries != nullptr) {
412     MetadataFactory::free_array<ResolvedFieldEntry>(data, _resolved_field_entries);
413     _resolved_field_entries = nullptr;
414   }
415   if (_resolved_method_entries != nullptr) {
416     MetadataFactory::free_array<ResolvedMethodEntry>(data, _resolved_method_entries);
417     _resolved_method_entries = nullptr;
418   }
419 #endif
420 }
421 
422 #if INCLUDE_CDS_JAVA_HEAP
423 oop ConstantPoolCache::archived_references() {
424   if (_archived_references_index < 0) {
425     return nullptr;
426   }
427   return HeapShared::get_root(_archived_references_index);
428 }
429 
430 void ConstantPoolCache::clear_archived_references() {
431   if (_archived_references_index >= 0) {
432     HeapShared::clear_root(_archived_references_index);
433     _archived_references_index = -1;
434   }
435 }
436 
437 void ConstantPoolCache::set_archived_references(int root_index) {
438   assert(CDSConfig::is_dumping_heap(), "sanity");
439   _archived_references_index = root_index;
440 }
441 #endif
442 
443 #if INCLUDE_JVMTI
444 static void log_adjust(const char* entry_type, Method* old_method, Method* new_method, bool* trace_name_printed) {
445   ResourceMark rm;
446 
447   if (!(*trace_name_printed)) {
448     log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
449     *trace_name_printed = true;
450   }
451   log_trace(redefine, class, update, constantpool)
452     ("cpc %s entry update: %s", entry_type, new_method->external_name());
453 }
454 
455 // RedefineClasses() API support:
456 // If any entry of this ConstantPoolCache points to any of
457 // old_methods, replace it with the corresponding new_method.
458 void ConstantPoolCache::adjust_method_entries(bool * trace_name_printed) {
459   if (_resolved_indy_entries != nullptr) {
460     for (int j = 0; j < _resolved_indy_entries->length(); j++) {
461       Method* old_method = resolved_indy_entry_at(j)->method();
462       if (old_method == nullptr || !old_method->is_old()) {
463         continue;
464       }
465       Method* new_method = old_method->get_new_method();
466       resolved_indy_entry_at(j)->adjust_method_entry(new_method);
467       log_adjust("indy", old_method, new_method, trace_name_printed);
468     }
469   }
470   if (_resolved_method_entries != nullptr) {
471     for (int i = 0; i < _resolved_method_entries->length(); i++) {
472       ResolvedMethodEntry* method_entry = resolved_method_entry_at(i);
473       // get interesting method entry
474       Method* old_method = method_entry->method();
475       if (old_method == nullptr || !old_method->is_old()) {
476         continue; // skip uninteresting entries
477       }
478       if (old_method->is_deleted()) {
479         // clean up entries with deleted methods
480         method_entry->reset_entry();
481         continue;
482       }
483       Method* new_method = old_method->get_new_method();
484       method_entry->adjust_method_entry(new_method);
485       log_adjust("non-indy", old_method, new_method, trace_name_printed);
486     }
487   }
488 }
489 
490 // the constant pool cache should never contain old or obsolete methods
491 bool ConstantPoolCache::check_no_old_or_obsolete_entries() {
492   ResourceMark rm;
493   if (_resolved_indy_entries != nullptr) {
494     for (int i = 0; i < _resolved_indy_entries->length(); i++) {
495       Method* m = resolved_indy_entry_at(i)->method();
496       if (m != nullptr && !resolved_indy_entry_at(i)->check_no_old_or_obsolete_entry()) {
497         log_trace(redefine, class, update, constantpool)
498           ("cpcache check found old method entry: class: %s, old: %d, obsolete: %d, method: %s",
499            constant_pool()->pool_holder()->external_name(), m->is_old(), m->is_obsolete(), m->external_name());
500         return false;
501       }
502     }
503   }
504   if (_resolved_method_entries != nullptr) {
505     for (int i = 0; i < _resolved_method_entries->length(); i++) {
506       ResolvedMethodEntry* method_entry = resolved_method_entry_at(i);
507       Method* m = method_entry->method();
508       if (m != nullptr && !method_entry->check_no_old_or_obsolete_entry()) {
509         log_trace(redefine, class, update, constantpool)
510           ("cpcache check found old method entry: class: %s, old: %d, obsolete: %d, method: %s",
511            constant_pool()->pool_holder()->external_name(), m->is_old(), m->is_obsolete(), m->external_name());
512         return false;
513       }
514     }
515   }
516   return true;
517 }
518 
519 void ConstantPoolCache::dump_cache() {
520   print_on(tty);
521 }
522 #endif // INCLUDE_JVMTI
523 
524 void ConstantPoolCache::metaspace_pointers_do(MetaspaceClosure* it) {
525   log_trace(cds)("Iter(ConstantPoolCache): %p", this);
526   it->push(&_constant_pool);
527   it->push(&_reference_map);
528   if (_resolved_indy_entries != nullptr) {
529     it->push(&_resolved_indy_entries, MetaspaceClosure::_writable);
530   }
531   if (_resolved_field_entries != nullptr) {
532     it->push(&_resolved_field_entries, MetaspaceClosure::_writable);
533   }
534   if (_resolved_method_entries != nullptr) {
535     it->push(&_resolved_method_entries, MetaspaceClosure::_writable);
536   }
537 }
538 
539 bool ConstantPoolCache::save_and_throw_indy_exc(
540   const constantPoolHandle& cpool, int cpool_index, int index, constantTag tag, TRAPS) {
541 
542   assert(HAS_PENDING_EXCEPTION, "No exception got thrown!");
543   assert(PENDING_EXCEPTION->is_a(vmClasses::LinkageError_klass()),
544          "No LinkageError exception");
545 
546   MutexLocker ml(THREAD, cpool->pool_holder()->init_monitor());
547 
548   // if the indy_info is resolved or the indy_resolution_failed flag is set then another
549   // thread either succeeded in resolving the method or got a LinkageError
550   // exception, before this thread was able to record its failure.  So, clear
551   // this thread's exception and return false so caller can use the earlier
552   // thread's result.
553   if (resolved_indy_entry_at(index)->is_resolved() || resolved_indy_entry_at(index)->resolution_failed()) {
554     CLEAR_PENDING_EXCEPTION;
555     return false;
556   }
557   ResourceMark rm(THREAD);
558   Symbol* error = PENDING_EXCEPTION->klass()->name();
559   const char* message = java_lang_Throwable::message_as_utf8(PENDING_EXCEPTION);
560 
561   int encoded_index = ResolutionErrorTable::encode_indy_index(index);
562   SystemDictionary::add_resolution_error(cpool, encoded_index, error, message);
563   resolved_indy_entry_at(index)->set_resolution_failed();
564   return true;
565 }
566 
567 oop ConstantPoolCache::set_dynamic_call(const CallInfo &call_info, int index) {
568   ResourceMark rm;
569   MutexLocker ml(constant_pool()->pool_holder()->init_monitor());
570   assert(index >= 0, "Indy index must be positive at this point");
571 
572   if (resolved_indy_entry_at(index)->method() != nullptr) {
573     return constant_pool()->resolved_reference_from_indy(index);
574   }
575 
576   if (resolved_indy_entry_at(index)->resolution_failed()) {
577     // Before we got here, another thread got a LinkageError exception during
578     // resolution.  Ignore our success and throw their exception.
579     guarantee(index >= 0, "Invalid indy index");
580     int encoded_index = ResolutionErrorTable::encode_indy_index(index);
581     JavaThread* THREAD = JavaThread::current(); // For exception macros.
582     constantPoolHandle cp(THREAD, constant_pool());
583     ConstantPool::throw_resolution_error(cp, encoded_index, THREAD);
584     return nullptr;
585   }
586 
587   Method* adapter            = call_info.resolved_method();
588   const Handle appendix      = call_info.resolved_appendix();
589   const bool has_appendix    = appendix.not_null();
590 
591   LogStream* log_stream = nullptr;
592   LogStreamHandle(Debug, methodhandles, indy) lsh_indy;
593   if (lsh_indy.is_enabled()) {
594     ResourceMark rm;
595     log_stream = &lsh_indy;
596     log_stream->print_cr("set_method_handle bc=%d appendix=" PTR_FORMAT "%s method=" PTR_FORMAT " (local signature) ",
597                          0xba,
598                          p2i(appendix()),
599                          (has_appendix ? "" : " (unused)"),
600                          p2i(adapter));
601     adapter->print_on(log_stream);
602     if (has_appendix)  appendix()->print_on(log_stream);
603   }
604 
605   if (has_appendix) {
606     const int appendix_index = resolved_indy_entry_at(index)->resolved_references_index();
607     objArrayOop resolved_references = constant_pool()->resolved_references();
608     assert(appendix_index >= 0 && appendix_index < resolved_references->length(), "oob");
609     assert(resolved_references->obj_at(appendix_index) == nullptr, "init just once");
610     resolved_references->obj_at_put(appendix_index, appendix());
611   }
612 
613   // Populate entry with resolved information
614   assert(resolved_indy_entries() != nullptr, "Invokedynamic array is empty, cannot fill with resolved information");
615   resolved_indy_entry_at(index)->fill_in(adapter, adapter->size_of_parameters(), as_TosState(adapter->result_type()), has_appendix);
616 
617   if (log_stream != nullptr) {
618     resolved_indy_entry_at(index)->print_on(log_stream);
619   }
620   return appendix();
621 }
622 
623 oop ConstantPoolCache::appendix_if_resolved(int method_index) const {
624   ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
625   return appendix_if_resolved(method_entry);
626 }
627 
628 oop ConstantPoolCache::appendix_if_resolved(ResolvedMethodEntry* method_entry) const {
629   if (!method_entry->has_appendix())
630     return nullptr;
631   const int ref_index = method_entry->resolved_references_index();
632   return constant_pool()->resolved_reference_at(ref_index);
633 }
634 
635 // Printing
636 
637 void ConstantPoolCache::print_on(outputStream* st) const {
638   st->print_cr("%s", internal_name());
639   // print constant pool cache entries
640   print_resolved_field_entries(st);
641   print_resolved_method_entries(st);
642   print_resolved_indy_entries(st);
643 }
644 
645 void ConstantPoolCache::print_resolved_field_entries(outputStream* st) const {
646   for (int field_index = 0; field_index < resolved_field_entries_length(); field_index++) {
647     resolved_field_entry_at(field_index)->print_on(st);
648   }
649 }
650 
651 void ConstantPoolCache::print_resolved_method_entries(outputStream* st) const {
652   for (int method_index = 0; method_index < resolved_method_entries_length(); method_index++) {
653     ResolvedMethodEntry* method_entry = resolved_method_entry_at(method_index);
654     method_entry->print_on(st);
655     if (method_entry->has_appendix()) {
656       st->print("  appendix: ");
657       constant_pool()->resolved_reference_from_method(method_index)->print_on(st);
658     }
659   }
660 }
661 
662 void ConstantPoolCache::print_resolved_indy_entries(outputStream* st) const {
663   for (int indy_index = 0; indy_index < resolved_indy_entries_length(); indy_index++) {
664     ResolvedIndyEntry* indy_entry = resolved_indy_entry_at(indy_index);
665     indy_entry->print_on(st);
666     if (indy_entry->has_appendix()) {
667       st->print("  appendix: ");
668       constant_pool()->resolved_reference_from_indy(indy_index)->print_on(st);
669     }
670   }
671 }