1 /*
  2  * Copyright (c) 1998, 2021, 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/heapShared.hpp"
 27 #include "classfile/resolutionErrors.hpp"
 28 #include "classfile/systemDictionary.hpp"
 29 #include "classfile/vmClasses.hpp"
 30 #include "interpreter/bytecodeStream.hpp"
 31 #include "interpreter/bytecodes.hpp"
 32 #include "interpreter/interpreter.hpp"
 33 #include "interpreter/linkResolver.hpp"
 34 #include "interpreter/rewriter.hpp"
 35 #include "logging/log.hpp"
 36 #include "logging/logStream.hpp"
 37 #include "memory/metadataFactory.hpp"
 38 #include "memory/metaspaceClosure.hpp"
 39 #include "memory/resourceArea.hpp"
 40 #include "oops/access.inline.hpp"
 41 #include "oops/compressedOops.hpp"
 42 #include "oops/constantPool.inline.hpp"
 43 #include "oops/cpCache.inline.hpp"
 44 #include "oops/objArrayOop.inline.hpp"
 45 #include "oops/oop.inline.hpp"
 46 #include "prims/methodHandles.hpp"
 47 #include "runtime/arguments.hpp"
 48 #include "runtime/atomic.hpp"
 49 #include "runtime/handles.inline.hpp"
 50 #include "runtime/vm_version.hpp"
 51 #include "utilities/macros.hpp"
 52 
 53 // Implementation of ConstantPoolCacheEntry
 54 
 55 void ConstantPoolCacheEntry::initialize_entry(int index) {
 56   assert(0 < index && index < 0x10000, "sanity check");
 57   _indices = index;
 58   _f1 = NULL;
 59   _f2 = _flags = 0;
 60   assert(constant_pool_index() == index, "");
 61 }
 62 
 63 void ConstantPoolCacheEntry::verify_just_initialized(bool f2_used) {
 64   assert((_indices & (~cp_index_mask)) == 0, "sanity");
 65   assert(_f1 == NULL, "sanity");
 66   assert(_flags == 0, "sanity");
 67   if (!f2_used) {
 68     assert(_f2 == 0, "sanity");
 69   }
 70 }
 71 
 72 void ConstantPoolCacheEntry::reinitialize(bool f2_used) {
 73   _indices &= cp_index_mask;
 74   _f1 = NULL;
 75   _flags = 0;
 76   if (!f2_used) {
 77     _f2 = 0;
 78   }
 79 }
 80 
 81 int ConstantPoolCacheEntry::make_flags(TosState state,
 82                                        int option_bits,
 83                                        int field_index_or_method_params) {
 84   assert(state < number_of_states, "Invalid state in make_flags");
 85   int f = ((int)state << tos_state_shift) | option_bits | field_index_or_method_params;
 86   // Preserve existing flag bit values
 87   // The low bits are a field offset, or else the method parameter size.
 88 #ifdef ASSERT
 89   TosState old_state = flag_state();
 90   assert(old_state == (TosState)0 || old_state == state,
 91          "inconsistent cpCache flags state");
 92 #endif
 93   return (_flags | f) ;
 94 }
 95 
 96 void ConstantPoolCacheEntry::set_bytecode_1(Bytecodes::Code code) {
 97 #ifdef ASSERT
 98   // Read once.
 99   volatile Bytecodes::Code c = bytecode_1();
100   assert(c == 0 || c == code || code == 0, "update must be consistent");
101 #endif
102   // Need to flush pending stores here before bytecode is written.
103   Atomic::release_store(&_indices, _indices | ((u_char)code << bytecode_1_shift));
104 }
105 
106 void ConstantPoolCacheEntry::set_bytecode_2(Bytecodes::Code code) {
107 #ifdef ASSERT
108   // Read once.
109   volatile Bytecodes::Code c = bytecode_2();
110   assert(c == 0 || c == code || code == 0, "update must be consistent");
111 #endif
112   // Need to flush pending stores here before bytecode is written.
113   Atomic::release_store(&_indices, _indices | ((u_char)code << bytecode_2_shift));
114 }
115 
116 // Sets f1, ordering with previous writes.
117 void ConstantPoolCacheEntry::release_set_f1(Metadata* f1) {
118   assert(f1 != NULL, "");
119   Atomic::release_store(&_f1, f1);
120 }
121 
122 void ConstantPoolCacheEntry::set_indy_resolution_failed() {
123   Atomic::release_store(&_flags, _flags | (1 << indy_resolution_failed_shift));
124 }
125 
126 // Note that concurrent update of both bytecodes can leave one of them
127 // reset to zero.  This is harmless; the interpreter will simply re-resolve
128 // the damaged entry.  More seriously, the memory synchronization is needed
129 // to flush other fields (f1, f2) completely to memory before the bytecodes
130 // are updated, lest other processors see a non-zero bytecode but zero f1/f2.
131 void ConstantPoolCacheEntry::set_field(Bytecodes::Code get_code,
132                                        Bytecodes::Code put_code,
133                                        Klass* field_holder,
134                                        int field_index,
135                                        int field_offset,
136                                        TosState field_type,
137                                        bool is_final,
138                                        bool is_volatile,
139                                        bool is_inlined,
140                                        bool is_null_free_inline_type) {
141   set_f1(field_holder);
142   set_f2(field_offset);
143   assert((field_index & field_index_mask) == field_index,
144          "field index does not fit in low flag bits");
145   assert(!is_inlined || is_null_free_inline_type, "Sanity check");
146   set_field_flags(field_type,
147                   ((is_volatile ? 1 : 0) << is_volatile_shift) |
148                   ((is_final    ? 1 : 0) << is_final_shift) |
149                   ((is_inlined  ? 1 : 0) << is_inlined_shift) |
150                   ((is_null_free_inline_type ? 1 : 0) << is_null_free_inline_type_shift),
151                   field_index);
152   set_bytecode_1(get_code);
153   set_bytecode_2(put_code);
154   NOT_PRODUCT(verify(tty));
155 }
156 
157 void ConstantPoolCacheEntry::set_parameter_size(int value) {
158   // This routine is called only in corner cases where the CPCE is not yet initialized.
159   // See AbstractInterpreter::deopt_continue_after_entry.
160   assert(_flags == 0 || parameter_size() == 0 || parameter_size() == value,
161          "size must not change: parameter_size=%d, value=%d", parameter_size(), value);
162   // Setting the parameter size by itself is only safe if the
163   // current value of _flags is 0, otherwise another thread may have
164   // updated it and we don't want to overwrite that value.  Don't
165   // bother trying to update it once it's nonzero but always make
166   // sure that the final parameter size agrees with what was passed.
167   if (_flags == 0) {
168     intx newflags = (value & parameter_size_mask);
169     Atomic::cmpxchg(&_flags, (intx)0, newflags);
170   }
171   guarantee(parameter_size() == value,
172             "size must not change: parameter_size=%d, value=%d", parameter_size(), value);
173 }
174 
175 void ConstantPoolCacheEntry::set_direct_or_vtable_call(Bytecodes::Code invoke_code,
176                                                        const methodHandle& method,
177                                                        int vtable_index,
178                                                        bool sender_is_interface) {
179   bool is_vtable_call = (vtable_index >= 0);  // FIXME: split this method on this boolean
180   assert(method->interpreter_entry() != NULL, "should have been set at this point");
181   assert(!method->is_obsolete(),  "attempt to write obsolete method to cpCache");
182 
183   int byte_no = -1;
184   bool change_to_virtual = false;
185   InstanceKlass* holder = NULL;  // have to declare this outside the switch
186   switch (invoke_code) {
187     case Bytecodes::_invokeinterface:
188       holder = method->method_holder();
189       // check for private interface method invocations
190       if (vtable_index == Method::nonvirtual_vtable_index && holder->is_interface() ) {
191         assert(method->is_private(), "unexpected non-private method");
192         assert(method->can_be_statically_bound(), "unexpected non-statically-bound method");
193         // set_f2_as_vfinal_method checks if is_vfinal flag is true.
194         set_method_flags(as_TosState(method->result_type()),
195                          (                             1      << is_vfinal_shift) |
196                          ((method->is_final_method() ? 1 : 0) << is_final_shift),
197                          method()->size_of_parameters());
198         set_f2_as_vfinal_method(method());
199         byte_no = 2;
200         set_f1(holder); // interface klass*
201         break;
202       }
203       else {
204         // We get here from InterpreterRuntime::resolve_invoke when an invokeinterface
205         // instruction links to a non-interface method (in Object). This can happen when
206         // an interface redeclares an Object method (like CharSequence declaring toString())
207         // or when invokeinterface is used explicitly.
208         // In that case, the method has no itable index and must be invoked as a virtual.
209         // Set a flag to keep track of this corner case.
210         assert(holder->is_interface() || holder == vmClasses::Object_klass(), "unexpected holder class");
211         assert(method->is_public(), "Calling non-public method in Object with invokeinterface");
212         change_to_virtual = true;
213 
214         // ...and fall through as if we were handling invokevirtual:
215       }
216     case Bytecodes::_invokevirtual:
217       {
218         if (!is_vtable_call) {
219           assert(method->can_be_statically_bound(), "");
220           // set_f2_as_vfinal_method checks if is_vfinal flag is true.
221           set_method_flags(as_TosState(method->result_type()),
222                            (                             1      << is_vfinal_shift) |
223                            ((method->is_final_method() ? 1 : 0) << is_final_shift)  |
224                            ((change_to_virtual         ? 1 : 0) << is_forced_virtual_shift),
225                            method()->size_of_parameters());
226           set_f2_as_vfinal_method(method());
227         } else {
228           assert(!method->can_be_statically_bound(), "");
229           assert(vtable_index >= 0, "valid index");
230           assert(!method->is_final_method(), "sanity");
231           set_method_flags(as_TosState(method->result_type()),
232                            ((change_to_virtual ? 1 : 0) << is_forced_virtual_shift),
233                            method()->size_of_parameters());
234           set_f2(vtable_index);
235         }
236         byte_no = 2;
237         break;
238       }
239 
240     case Bytecodes::_invokespecial:
241     case Bytecodes::_invokestatic:
242       assert(!is_vtable_call, "");
243       // Note:  Read and preserve the value of the is_vfinal flag on any
244       // invokevirtual bytecode shared with this constant pool cache entry.
245       // It is cheap and safe to consult is_vfinal() at all times.
246       // Once is_vfinal is set, it must stay that way, lest we get a dangling oop.
247       set_method_flags(as_TosState(method->result_type()),
248                        ((is_vfinal()               ? 1 : 0) << is_vfinal_shift) |
249                        ((method->is_final_method() ? 1 : 0) << is_final_shift),
250                        method()->size_of_parameters());
251       set_f1(method());
252       byte_no = 1;
253       break;
254     default:
255       ShouldNotReachHere();
256       break;
257   }
258 
259   // Note:  byte_no also appears in TemplateTable::resolve.
260   if (byte_no == 1) {
261     assert(invoke_code != Bytecodes::_invokevirtual &&
262            invoke_code != Bytecodes::_invokeinterface, "");
263     bool do_resolve = true;
264     // Don't mark invokespecial to method as resolved if sender is an interface.  The receiver
265     // has to be checked that it is a subclass of the current class every time this bytecode
266     // is executed.
267     if (invoke_code == Bytecodes::_invokespecial && sender_is_interface &&
268         method->name() != vmSymbols::object_initializer_name()) {
269       do_resolve = false;
270     }
271     if (invoke_code == Bytecodes::_invokestatic) {
272       assert(method->method_holder()->is_initialized() ||
273              method->method_holder()->is_reentrant_initialization(Thread::current()),
274              "invalid class initialization state for invoke_static");
275 
276       if (!VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
277         // Don't mark invokestatic to method as resolved if the holder class has not yet completed
278         // initialization. An invokestatic must only proceed if the class is initialized, but if
279         // we resolve it before then that class initialization check is skipped.
280         //
281         // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
282         // template interpreter supports fast class initialization check for
283         // invokestatic which doesn't require call site re-resolution to
284         // enforce class initialization barrier.
285         do_resolve = false;
286       }
287     }
288     if (do_resolve) {
289       set_bytecode_1(invoke_code);
290     }
291   } else if (byte_no == 2)  {
292     if (change_to_virtual) {
293       assert(invoke_code == Bytecodes::_invokeinterface, "");
294       // NOTE: THIS IS A HACK - BE VERY CAREFUL!!!
295       //
296       // Workaround for the case where we encounter an invokeinterface, but we
297       // should really have an _invokevirtual since the resolved method is a
298       // virtual method in java.lang.Object. This is a corner case in the spec
299       // but is presumably legal. javac does not generate this code.
300       //
301       // We do not set bytecode_1() to _invokeinterface, because that is the
302       // bytecode # used by the interpreter to see if it is resolved.  In this
303       // case, the method gets reresolved with caller for each interface call
304       // because the actual selected method may not be public.
305       //
306       // We set bytecode_2() to _invokevirtual.
307       // See also interpreterRuntime.cpp. (8/25/2000)
308       invoke_code = Bytecodes::_invokevirtual;
309     } else {
310       assert(invoke_code == Bytecodes::_invokevirtual ||
311              (invoke_code == Bytecodes::_invokeinterface &&
312               ((method->is_private() ||
313                 (method->is_final() && method->method_holder() == vmClasses::Object_klass())))),
314              "unexpected invocation mode");
315       if (invoke_code == Bytecodes::_invokeinterface &&
316           (method->is_private() || method->is_final())) {
317         // We set bytecode_1() to _invokeinterface, because that is the
318         // bytecode # used by the interpreter to see if it is resolved.
319         // We set bytecode_2() to _invokevirtual.
320         set_bytecode_1(invoke_code);
321       }
322     }
323     // set up for invokevirtual, even if linking for invokeinterface also:
324     set_bytecode_2(invoke_code);
325   } else {
326     ShouldNotReachHere();
327   }
328   NOT_PRODUCT(verify(tty));
329 }
330 
331 void ConstantPoolCacheEntry::set_direct_call(Bytecodes::Code invoke_code, const methodHandle& method,
332                                              bool sender_is_interface) {
333   int index = Method::nonvirtual_vtable_index;
334   // index < 0; FIXME: inline and customize set_direct_or_vtable_call
335   set_direct_or_vtable_call(invoke_code, method, index, sender_is_interface);
336 }
337 
338 void ConstantPoolCacheEntry::set_vtable_call(Bytecodes::Code invoke_code, const methodHandle& method, int index) {
339   // either the method is a miranda or its holder should accept the given index
340   assert(method->method_holder()->is_interface() || method->method_holder()->verify_vtable_index(index), "");
341   // index >= 0; FIXME: inline and customize set_direct_or_vtable_call
342   set_direct_or_vtable_call(invoke_code, method, index, false);
343 }
344 
345 void ConstantPoolCacheEntry::set_itable_call(Bytecodes::Code invoke_code,
346                                              Klass* referenced_klass,
347                                              const methodHandle& method, int index) {
348   assert(method->method_holder()->verify_itable_index(index), "");
349   assert(invoke_code == Bytecodes::_invokeinterface, "");
350   InstanceKlass* interf = method->method_holder();
351   assert(interf->is_interface(), "must be an interface");
352   assert(!method->is_final_method(), "interfaces do not have final methods; cannot link to one here");
353   set_f1(referenced_klass);
354   set_f2((intx)method());
355   set_method_flags(as_TosState(method->result_type()),
356                    0,  // no option bits
357                    method()->size_of_parameters());
358   set_bytecode_1(Bytecodes::_invokeinterface);
359 }
360 
361 
362 void ConstantPoolCacheEntry::set_method_handle(const constantPoolHandle& cpool, const CallInfo &call_info) {
363   set_method_handle_common(cpool, Bytecodes::_invokehandle, call_info);
364 }
365 
366 void ConstantPoolCacheEntry::set_dynamic_call(const constantPoolHandle& cpool, const CallInfo &call_info) {
367   set_method_handle_common(cpool, Bytecodes::_invokedynamic, call_info);
368 }
369 
370 void ConstantPoolCacheEntry::set_method_handle_common(const constantPoolHandle& cpool,
371                                                       Bytecodes::Code invoke_code,
372                                                       const CallInfo &call_info) {
373   // NOTE: This CPCE can be the subject of data races.
374   // There are three words to update: flags, refs[f2], f1 (in that order).
375   // Writers must store all other values before f1.
376   // Readers must test f1 first for non-null before reading other fields.
377   // Competing writers must acquire exclusive access via a lock.
378   // A losing writer waits on the lock until the winner writes f1 and leaves
379   // the lock, so that when the losing writer returns, he can use the linked
380   // cache entry.
381 
382   JavaThread* current = JavaThread::current();
383   objArrayHandle resolved_references(current, cpool->resolved_references());
384   // Use the resolved_references() lock for this cpCache entry.
385   // resolved_references are created for all classes with Invokedynamic, MethodHandle
386   // or MethodType constant pool cache entries.
387   assert(resolved_references() != NULL,
388          "a resolved_references array should have been created for this class");
389   ObjectLocker ol(resolved_references, current);
390   if (!is_f1_null()) {
391     return;
392   }
393 
394   if (indy_resolution_failed()) {
395     // Before we got here, another thread got a LinkageError exception during
396     // resolution.  Ignore our success and throw their exception.
397     ConstantPoolCache* cpCache = cpool->cache();
398     int index = -1;
399     for (int i = 0; i < cpCache->length(); i++) {
400       if (cpCache->entry_at(i) == this) {
401         index = i;
402         break;
403       }
404     }
405     guarantee(index >= 0, "Didn't find cpCache entry!");
406     int encoded_index = ResolutionErrorTable::encode_cpcache_index(
407                           ConstantPool::encode_invokedynamic_index(index));
408     JavaThread* THREAD = JavaThread::current(); // For exception macros.
409     ConstantPool::throw_resolution_error(cpool, encoded_index, THREAD);
410     return;
411   }
412 
413   Method* adapter            = call_info.resolved_method();
414   const Handle appendix      = call_info.resolved_appendix();
415   const bool has_appendix    = appendix.not_null();
416 
417   // Write the flags.
418   // MHs and indy are always sig-poly and have a local signature.
419   set_method_flags(as_TosState(adapter->result_type()),
420                    ((has_appendix    ? 1 : 0) << has_appendix_shift        ) |
421                    (                   1      << has_local_signature_shift ) |
422                    (                   1      << is_final_shift            ),
423                    adapter->size_of_parameters());
424 
425   LogStream* log_stream = NULL;
426   LogStreamHandle(Debug, methodhandles, indy) lsh_indy;
427   if (lsh_indy.is_enabled()) {
428     ResourceMark rm;
429     log_stream = &lsh_indy;
430     log_stream->print_cr("set_method_handle bc=%d appendix=" PTR_FORMAT "%s method=" PTR_FORMAT " (local signature) ",
431                          invoke_code,
432                          p2i(appendix()),
433                          (has_appendix ? "" : " (unused)"),
434                          p2i(adapter));
435     adapter->print_on(log_stream);
436     if (has_appendix)  appendix()->print_on(log_stream);
437   }
438 
439   // Method handle invokes and invokedynamic sites use both cp cache words.
440   // refs[f2], if not null, contains a value passed as a trailing argument to the adapter.
441   // In the general case, this could be the call site's MethodType,
442   // for use with java.lang.Invokers.checkExactType, or else a CallSite object.
443   // f1 contains the adapter method which manages the actual call.
444   // In the general case, this is a compiled LambdaForm.
445   // (The Java code is free to optimize these calls by binding other
446   // sorts of methods and appendices to call sites.)
447   // JVM-level linking is via f1, as if for invokespecial, and signatures are erased.
448   // The appendix argument (if any) is added to the signature, and is counted in the parameter_size bits.
449   // Even with the appendix, the method will never take more than 255 parameter slots.
450   //
451   // This means that given a call site like (List)mh.invoke("foo"),
452   // the f1 method has signature '(Ljl/Object;Ljl/invoke/MethodType;)Ljl/Object;',
453   // not '(Ljava/lang/String;)Ljava/util/List;'.
454   // The fact that String and List are involved is encoded in the MethodType in refs[f2].
455   // This allows us to create fewer Methods, while keeping type safety.
456   //
457 
458   // Store appendix, if any.
459   if (has_appendix) {
460     const int appendix_index = f2_as_index();
461     assert(appendix_index >= 0 && appendix_index < resolved_references->length(), "oob");
462     assert(resolved_references->obj_at(appendix_index) == NULL, "init just once");
463     resolved_references->obj_at_put(appendix_index, appendix());
464   }
465 
466   release_set_f1(adapter);  // This must be the last one to set (see NOTE above)!
467 
468   // The interpreter assembly code does not check byte_2,
469   // but it is used by is_resolved, method_if_resolved, etc.
470   set_bytecode_1(invoke_code);
471   NOT_PRODUCT(verify(tty));
472 
473   if (log_stream != NULL) {
474     this->print(log_stream, 0);
475   }
476 
477   assert(has_appendix == this->has_appendix(), "proper storage of appendix flag");
478   assert(this->has_local_signature(), "proper storage of signature flag");
479 }
480 
481 bool ConstantPoolCacheEntry::save_and_throw_indy_exc(
482   const constantPoolHandle& cpool, int cpool_index, int index, constantTag tag, TRAPS) {
483 
484   assert(HAS_PENDING_EXCEPTION, "No exception got thrown!");
485   assert(PENDING_EXCEPTION->is_a(vmClasses::LinkageError_klass()),
486          "No LinkageError exception");
487 
488   // Use the resolved_references() lock for this cpCache entry.
489   // resolved_references are created for all classes with Invokedynamic, MethodHandle
490   // or MethodType constant pool cache entries.
491   JavaThread* current = THREAD;
492   objArrayHandle resolved_references(current, cpool->resolved_references());
493   assert(resolved_references() != NULL,
494          "a resolved_references array should have been created for this class");
495   ObjectLocker ol(resolved_references, current);
496 
497   // if f1 is not null or the indy_resolution_failed flag is set then another
498   // thread either succeeded in resolving the method or got a LinkageError
499   // exception, before this thread was able to record its failure.  So, clear
500   // this thread's exception and return false so caller can use the earlier
501   // thread's result.
502   if (!is_f1_null() || indy_resolution_failed()) {
503     CLEAR_PENDING_EXCEPTION;
504     return false;
505   }
506 
507   Symbol* error = PENDING_EXCEPTION->klass()->name();
508   Symbol* message = java_lang_Throwable::detail_message(PENDING_EXCEPTION);
509 
510   SystemDictionary::add_resolution_error(cpool, index, error, message);
511   set_indy_resolution_failed();
512   return true;
513 }
514 
515 Method* ConstantPoolCacheEntry::method_if_resolved(const constantPoolHandle& cpool) {
516   // Decode the action of set_method and set_interface_call
517   Bytecodes::Code invoke_code = bytecode_1();
518   if (invoke_code != (Bytecodes::Code)0) {
519     Metadata* f1 = f1_ord();
520     if (f1 != NULL) {
521       switch (invoke_code) {
522       case Bytecodes::_invokeinterface:
523         assert(f1->is_klass(), "");
524         return f2_as_interface_method();
525       case Bytecodes::_invokestatic:
526       case Bytecodes::_invokespecial:
527         assert(!has_appendix(), "");
528       case Bytecodes::_invokehandle:
529       case Bytecodes::_invokedynamic:
530         assert(f1->is_method(), "");
531         return (Method*)f1;
532       default:
533         break;
534       }
535     }
536   }
537   invoke_code = bytecode_2();
538   if (invoke_code != (Bytecodes::Code)0) {
539     switch (invoke_code) {
540     case Bytecodes::_invokevirtual:
541       if (is_vfinal()) {
542         // invokevirtual
543         Method* m = f2_as_vfinal_method();
544         assert(m->is_method(), "");
545         return m;
546       } else {
547         int holder_index = cpool->uncached_klass_ref_index_at(constant_pool_index());
548         if (cpool->tag_at(holder_index).is_klass()) {
549           Klass* klass = cpool->resolved_klass_at(holder_index);
550           return klass->method_at_vtable(f2_as_index());
551         }
552       }
553       break;
554     default:
555       break;
556     }
557   }
558   return NULL;
559 }
560 
561 
562 oop ConstantPoolCacheEntry::appendix_if_resolved(const constantPoolHandle& cpool) {
563   if (!has_appendix())
564     return NULL;
565   const int ref_index = f2_as_index();
566   objArrayOop resolved_references = cpool->resolved_references();
567   return resolved_references->obj_at(ref_index);
568 }
569 
570 
571 #if INCLUDE_JVMTI
572 
573 void log_adjust(const char* entry_type, Method* old_method, Method* new_method, bool* trace_name_printed) {
574   ResourceMark rm;
575 
576   if (!(*trace_name_printed)) {
577     log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
578     *trace_name_printed = true;
579   }
580   log_trace(redefine, class, update, constantpool)
581     ("cpc %s entry update: %s", entry_type, new_method->external_name());
582 }
583 
584 // RedefineClasses() API support:
585 // If this ConstantPoolCacheEntry refers to old_method then update it
586 // to refer to new_method.
587 void ConstantPoolCacheEntry::adjust_method_entry(Method* old_method,
588        Method* new_method, bool * trace_name_printed) {
589 
590   if (is_vfinal()) {
591     // virtual and final so _f2 contains method ptr instead of vtable index
592     if (f2_as_vfinal_method() == old_method) {
593       // match old_method so need an update
594       // NOTE: can't use set_f2_as_vfinal_method as it asserts on different values
595       _f2 = (intptr_t)new_method;
596       log_adjust("vfinal", old_method, new_method, trace_name_printed);
597     }
598     return;
599   }
600 
601   assert (_f1 != NULL, "should not call with uninteresting entry");
602 
603   if (!(_f1->is_method())) {
604     // _f1 is a Klass* for an interface, _f2 is the method
605     if (f2_as_interface_method() == old_method) {
606       _f2 = (intptr_t)new_method;
607       log_adjust("interface", old_method, new_method, trace_name_printed);
608     }
609   } else if (_f1 == old_method) {
610     _f1 = new_method;
611     log_adjust("special, static or dynamic", old_method, new_method, trace_name_printed);
612   }
613 }
614 
615 // a constant pool cache entry should never contain old or obsolete methods
616 bool ConstantPoolCacheEntry::check_no_old_or_obsolete_entries() {
617   Method* m = get_interesting_method_entry();
618   // return false if m refers to a non-deleted old or obsolete method
619   if (m != NULL) {
620     assert(m->is_valid() && m->is_method(), "m is a valid method");
621     return !m->is_old() && !m->is_obsolete(); // old is always set for old and obsolete
622   } else {
623     return true;
624   }
625 }
626 
627 Method* ConstantPoolCacheEntry::get_interesting_method_entry() {
628   if (!is_method_entry()) {
629     // not a method entry so not interesting by default
630     return NULL;
631   }
632   Method* m = NULL;
633   if (is_vfinal()) {
634     // virtual and final so _f2 contains method ptr instead of vtable index
635     m = f2_as_vfinal_method();
636   } else if (is_f1_null()) {
637     // NULL _f1 means this is a virtual entry so also not interesting
638     return NULL;
639   } else {
640     if (!(_f1->is_method())) {
641       // _f1 is a Klass* for an interface
642       m = f2_as_interface_method();
643     } else {
644       m = f1_as_method();
645     }
646   }
647   assert(m != NULL && m->is_method(), "sanity check");
648   if (m == NULL || !m->is_method()) {
649     return NULL;
650   }
651   return m;
652 }
653 #endif // INCLUDE_JVMTI
654 
655 void ConstantPoolCacheEntry::print(outputStream* st, int index) const {
656   // print separator
657   if (index == 0) st->print_cr("                 -------------");
658   // print entry
659   st->print("%3d  (" PTR_FORMAT ")  ", index, (intptr_t)this);
660   st->print_cr("[%02x|%02x|%5d]", bytecode_2(), bytecode_1(),
661                constant_pool_index());
662   st->print_cr("                 [   " PTR_FORMAT "]", (intptr_t)_f1);
663   st->print_cr("                 [   " PTR_FORMAT "]", (intptr_t)_f2);
664   st->print_cr("                 [   " PTR_FORMAT "]", (intptr_t)_flags);
665   st->print_cr("                 -------------");
666 }
667 
668 void ConstantPoolCacheEntry::verify(outputStream* st) const {
669   // not implemented yet
670 }
671 
672 // Implementation of ConstantPoolCache
673 
674 ConstantPoolCache* ConstantPoolCache::allocate(ClassLoaderData* loader_data,
675                                      const intStack& index_map,
676                                      const intStack& invokedynamic_index_map,
677                                      const intStack& invokedynamic_map, TRAPS) {
678 
679   const int length = index_map.length() + invokedynamic_index_map.length();
680   int size = ConstantPoolCache::size(length);
681 
682   return new (loader_data, size, MetaspaceObj::ConstantPoolCacheType, THREAD)
683     ConstantPoolCache(length, index_map, invokedynamic_index_map, invokedynamic_map);
684 }
685 
686 void ConstantPoolCache::initialize(const intArray& inverse_index_map,
687                                    const intArray& invokedynamic_inverse_index_map,
688                                    const intArray& invokedynamic_references_map) {
689   for (int i = 0; i < inverse_index_map.length(); i++) {
690     ConstantPoolCacheEntry* e = entry_at(i);
691     int original_index = inverse_index_map.at(i);
692     e->initialize_entry(original_index);
693     assert(entry_at(i) == e, "sanity");
694   }
695 
696   // Append invokedynamic entries at the end
697   int invokedynamic_offset = inverse_index_map.length();
698   for (int i = 0; i < invokedynamic_inverse_index_map.length(); i++) {
699     int offset = i + invokedynamic_offset;
700     ConstantPoolCacheEntry* e = entry_at(offset);
701     int original_index = invokedynamic_inverse_index_map.at(i);
702     e->initialize_entry(original_index);
703     assert(entry_at(offset) == e, "sanity");
704   }
705 
706   for (int ref = 0; ref < invokedynamic_references_map.length(); ref++) {
707     const int cpci = invokedynamic_references_map.at(ref);
708     if (cpci >= 0) {
709       entry_at(cpci)->initialize_resolved_reference_index(ref);
710     }
711   }
712 }
713 
714 void ConstantPoolCache::verify_just_initialized() {
715   DEBUG_ONLY(walk_entries_for_initialization(/*check_only = */ true));
716 }
717 
718 void ConstantPoolCache::remove_unshareable_info() {
719   walk_entries_for_initialization(/*check_only = */ false);
720 }
721 
722 void ConstantPoolCache::walk_entries_for_initialization(bool check_only) {
723   Arguments::assert_is_dumping_archive();
724   // When dumping the archive, we want to clean up the ConstantPoolCache
725   // to remove any effect of linking due to the execution of Java code --
726   // each ConstantPoolCacheEntry will have the same contents as if
727   // ConstantPoolCache::initialize has just returned:
728   //
729   // - We keep the ConstantPoolCache::constant_pool_index() bits for all entries.
730   // - We keep the "f2" field for entries used by invokedynamic and invokehandle
731   // - All other bits in the entries are cleared to zero.
732   ResourceMark rm;
733 
734   InstanceKlass* ik = constant_pool()->pool_holder();
735   bool* f2_used = NEW_RESOURCE_ARRAY(bool, length());
736   memset(f2_used, 0, sizeof(bool) * length());
737 
738   Thread* current = Thread::current();
739 
740   // Find all the slots that we need to preserve f2
741   for (int i = 0; i < ik->methods()->length(); i++) {
742     Method* m = ik->methods()->at(i);
743     RawBytecodeStream bcs(methodHandle(current, m));
744     while (!bcs.is_last_bytecode()) {
745       Bytecodes::Code opcode = bcs.raw_next();
746       switch (opcode) {
747       case Bytecodes::_invokedynamic: {
748           int index = Bytes::get_native_u4(bcs.bcp() + 1);
749           int cp_cache_index = constant_pool()->invokedynamic_cp_cache_index(index);
750           f2_used[cp_cache_index] = 1;
751         }
752         break;
753       case Bytecodes::_invokehandle: {
754           int cp_cache_index = Bytes::get_native_u2(bcs.bcp() + 1);
755           f2_used[cp_cache_index] = 1;
756         }
757         break;
758       default:
759         break;
760       }
761     }
762   }
763 
764   if (check_only) {
765     DEBUG_ONLY(
766       for (int i=0; i<length(); i++) {
767         entry_at(i)->verify_just_initialized(f2_used[i]);
768       })
769   } else {
770     for (int i=0; i<length(); i++) {
771       entry_at(i)->reinitialize(f2_used[i]);
772     }
773   }
774 }
775 
776 void ConstantPoolCache::deallocate_contents(ClassLoaderData* data) {
777   assert(!is_shared(), "shared caches are not deallocated");
778   data->remove_handle(_resolved_references);
779   set_resolved_references(OopHandle());
780   MetadataFactory::free_array<u2>(data, _reference_map);
781   set_reference_map(NULL);
782 }
783 
784 #if INCLUDE_CDS_JAVA_HEAP
785 oop ConstantPoolCache::archived_references() {
786   if (_archived_references_index < 0) {
787     return NULL;
788   }
789   return HeapShared::get_root(_archived_references_index);
790 }
791 
792 void ConstantPoolCache::clear_archived_references() {
793   if (_archived_references_index >= 0) {
794     HeapShared::clear_root(_archived_references_index);
795     _archived_references_index = -1;
796   }
797 }
798 
799 void ConstantPoolCache::set_archived_references(oop o) {
800   assert(DumpSharedSpaces, "called only during runtime");
801   _archived_references_index = HeapShared::append_root(o);
802 }
803 #endif
804 
805 #if INCLUDE_JVMTI
806 // RedefineClasses() API support:
807 // If any entry of this ConstantPoolCache points to any of
808 // old_methods, replace it with the corresponding new_method.
809 void ConstantPoolCache::adjust_method_entries(bool * trace_name_printed) {
810   for (int i = 0; i < length(); i++) {
811     ConstantPoolCacheEntry* entry = entry_at(i);
812     Method* old_method = entry->get_interesting_method_entry();
813     if (old_method == NULL || !old_method->is_old()) {
814       continue; // skip uninteresting entries
815     }
816     if (old_method->is_deleted()) {
817       // clean up entries with deleted methods
818       entry->initialize_entry(entry->constant_pool_index());
819       continue;
820     }
821     Method* new_method = old_method->get_new_method();
822     entry_at(i)->adjust_method_entry(old_method, new_method, trace_name_printed);
823   }
824 }
825 
826 // the constant pool cache should never contain old or obsolete methods
827 bool ConstantPoolCache::check_no_old_or_obsolete_entries() {
828   ResourceMark rm;
829   for (int i = 1; i < length(); i++) {
830     Method* m = entry_at(i)->get_interesting_method_entry();
831     if (m != NULL && !entry_at(i)->check_no_old_or_obsolete_entries()) {
832       log_trace(redefine, class, update, constantpool)
833         ("cpcache check found old method entry: class: %s, old: %d, obsolete: %d, method: %s",
834          constant_pool()->pool_holder()->external_name(), m->is_old(), m->is_obsolete(), m->external_name());
835       return false;
836     }
837   }
838   return true;
839 }
840 
841 void ConstantPoolCache::dump_cache() {
842   for (int i = 1; i < length(); i++) {
843     if (entry_at(i)->get_interesting_method_entry() != NULL) {
844       entry_at(i)->print(tty, i);
845     }
846   }
847 }
848 #endif // INCLUDE_JVMTI
849 
850 void ConstantPoolCache::metaspace_pointers_do(MetaspaceClosure* it) {
851   log_trace(cds)("Iter(ConstantPoolCache): %p", this);
852   it->push(&_constant_pool);
853   it->push(&_reference_map);
854 }
855 
856 // Printing
857 
858 void ConstantPoolCache::print_on(outputStream* st) const {
859   st->print_cr("%s", internal_name());
860   // print constant pool cache entries
861   for (int i = 0; i < length(); i++) entry_at(i)->print(st, i);
862 }
863 
864 void ConstantPoolCache::print_value_on(outputStream* st) const {
865   st->print("cache [%d]", length());
866   print_address_on(st);
867   st->print(" for ");
868   constant_pool()->print_value_on(st);
869 }
870 
871 
872 // Verification
873 
874 void ConstantPoolCache::verify_on(outputStream* st) {
875   // print constant pool cache entries
876   for (int i = 0; i < length(); i++) entry_at(i)->verify(st);
877 }