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