1 /*
   2  * Copyright (c) 1997, 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/archiveUtils.hpp"
  27 #include "classfile/defaultMethods.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "classfile/vmClasses.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "compiler/compilationPolicy.hpp"
  33 #include "compiler/compileBroker.hpp"
  34 #include "gc/shared/collectedHeap.inline.hpp"
  35 #include "interpreter/bootstrapInfo.hpp"
  36 #include "interpreter/bytecode.hpp"
  37 #include "interpreter/interpreterRuntime.hpp"
  38 #include "interpreter/linkResolver.hpp"
  39 #include "jvm.h"
  40 #include "logging/log.hpp"
  41 #include "logging/logStream.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "oops/constantPool.inline.hpp"
  44 #include "oops/cpCache.inline.hpp"
  45 #include "oops/instanceKlass.inline.hpp"
  46 #include "oops/klass.inline.hpp"
  47 #include "oops/method.inline.hpp"
  48 #include "oops/objArrayKlass.hpp"
  49 #include "oops/objArrayOop.hpp"
  50 #include "oops/oop.inline.hpp"
  51 #include "oops/resolvedIndyEntry.hpp"
  52 #include "oops/symbolHandle.hpp"
  53 #include "prims/jvmtiExport.hpp"
  54 #include "prims/methodHandles.hpp"
  55 #include "runtime/fieldDescriptor.inline.hpp"
  56 #include "runtime/frame.inline.hpp"
  57 #include "runtime/handles.inline.hpp"
  58 #include "runtime/javaThread.hpp"
  59 #include "runtime/reflection.hpp"
  60 #include "runtime/safepointVerifiers.hpp"
  61 #include "runtime/sharedRuntime.hpp"
  62 #include "runtime/signature.hpp"
  63 #include "runtime/vmThread.hpp"
  64 #include "utilities/macros.hpp"
  65 #if INCLUDE_JFR
  66 #include "jfr/jfr.hpp"
  67 #endif
  68 
  69 //------------------------------------------------------------------------------------------------------------------------
  70 // Implementation of CallInfo
  71 
  72 
  73 void CallInfo::set_static(Klass* resolved_klass, const methodHandle& resolved_method, TRAPS) {
  74   int vtable_index = Method::nonvirtual_vtable_index;
  75   set_common(resolved_klass, resolved_method, resolved_method, CallInfo::direct_call, vtable_index, CHECK);
  76 }
  77 
  78 
  79 void CallInfo::set_interface(Klass* resolved_klass,
  80                              const methodHandle& resolved_method,
  81                              const methodHandle& selected_method,
  82                              int itable_index, TRAPS) {
  83   // This is only called for interface methods. If the resolved_method
  84   // comes from java/lang/Object, it can be the subject of a virtual call, so
  85   // we should pick the vtable index from the resolved method.
  86   // In that case, the caller must call set_virtual instead of set_interface.
  87   assert(resolved_method->method_holder()->is_interface(), "");
  88   assert(itable_index == resolved_method()->itable_index(), "");
  89   set_common(resolved_klass, resolved_method, selected_method, CallInfo::itable_call, itable_index, CHECK);
  90 }
  91 
  92 void CallInfo::set_virtual(Klass* resolved_klass,
  93                            const methodHandle& resolved_method,
  94                            const methodHandle& selected_method,
  95                            int vtable_index, TRAPS) {
  96   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index, "valid index");
  97   assert(vtable_index < 0 || !resolved_method->has_vtable_index() || vtable_index == resolved_method->vtable_index(), "");
  98   CallKind kind = (vtable_index >= 0 && !resolved_method->can_be_statically_bound() ? CallInfo::vtable_call : CallInfo::direct_call);
  99   set_common(resolved_klass, resolved_method, selected_method, kind, vtable_index, CHECK);
 100   assert(!resolved_method->is_compiled_lambda_form(), "these must be handled via an invokehandle call");
 101 }
 102 
 103 void CallInfo::set_handle(Klass* resolved_klass,
 104                           const methodHandle& resolved_method,
 105                           Handle resolved_appendix, TRAPS) {
 106   guarantee(resolved_method.not_null(), "resolved method is null");
 107   assert(resolved_method->intrinsic_id() == vmIntrinsics::_invokeBasic ||
 108          resolved_method->is_compiled_lambda_form(),
 109          "linkMethod must return one of these");
 110   int vtable_index = Method::nonvirtual_vtable_index;
 111   assert(!resolved_method->has_vtable_index(), "");
 112   set_common(resolved_klass, resolved_method, resolved_method, CallInfo::direct_call, vtable_index, CHECK);
 113   _resolved_appendix = resolved_appendix;
 114 }
 115 
 116 // Redefinition safepoint may have updated the method. Make sure the new version of the method is returned.
 117 // Callers are responsible for not safepointing and storing this method somewhere safe where redefinition
 118 // can replace it if runs again.  Safe places are constant pool cache and code cache metadata.
 119 // The old method is safe in CallInfo since its a methodHandle (it won't get deleted), and accessed with these
 120 // accessors.
 121 Method* CallInfo::resolved_method() const {
 122   if (JvmtiExport::can_hotswap_or_post_breakpoint() && _resolved_method->is_old()) {
 123     return _resolved_method->get_new_method();
 124   } else {
 125     return _resolved_method();
 126   }
 127 }
 128 
 129 Method* CallInfo::selected_method() const {
 130   if (JvmtiExport::can_hotswap_or_post_breakpoint() && _selected_method->is_old()) {
 131     return _selected_method->get_new_method();
 132   } else {
 133     return _selected_method();
 134   }
 135 }
 136 
 137 void CallInfo::set_common(Klass* resolved_klass,
 138                           const methodHandle& resolved_method,
 139                           const methodHandle& selected_method,
 140                           CallKind kind,
 141                           int index,
 142                           TRAPS) {
 143   assert(resolved_method->signature() == selected_method->signature(), "signatures must correspond");
 144   _resolved_klass  = resolved_klass;
 145   _resolved_method = resolved_method;
 146   _selected_method = selected_method;
 147   _call_kind       = kind;
 148   _call_index      = index;
 149   _resolved_appendix = Handle();
 150   DEBUG_ONLY(verify());  // verify before making side effects
 151 
 152   CompilationPolicy::compile_if_required(selected_method, THREAD);
 153 }
 154 
 155 // utility query for unreflecting a method
 156 CallInfo::CallInfo(Method* resolved_method, Klass* resolved_klass, TRAPS) {
 157   Klass* resolved_method_holder = resolved_method->method_holder();
 158   if (resolved_klass == nullptr) { // 2nd argument defaults to holder of 1st
 159     resolved_klass = resolved_method_holder;
 160   }
 161   _resolved_klass  = resolved_klass;
 162   _resolved_method = methodHandle(THREAD, resolved_method);
 163   _selected_method = methodHandle(THREAD, resolved_method);
 164   // classify:
 165   CallKind kind = CallInfo::unknown_kind;
 166   int index = resolved_method->vtable_index();
 167   if (resolved_method->can_be_statically_bound()) {
 168     kind = CallInfo::direct_call;
 169   } else if (!resolved_method_holder->is_interface()) {
 170     // Could be an Object method inherited into an interface, but still a vtable call.
 171     kind = CallInfo::vtable_call;
 172   } else if (!resolved_klass->is_interface()) {
 173     // A default or miranda method.  Compute the vtable index.
 174     index = LinkResolver::vtable_index_of_interface_method(resolved_klass, _resolved_method);
 175     assert(index >= 0 , "we should have valid vtable index at this point");
 176 
 177     kind = CallInfo::vtable_call;
 178   } else if (resolved_method->has_vtable_index()) {
 179     // Can occur if an interface redeclares a method of Object.
 180 
 181 #ifdef ASSERT
 182     // Ensure that this is really the case.
 183     Klass* object_klass = vmClasses::Object_klass();
 184     Method * object_resolved_method = object_klass->vtable().method_at(index);
 185     assert(object_resolved_method->name() == resolved_method->name(),
 186       "Object and interface method names should match at vtable index %d, %s != %s",
 187       index, object_resolved_method->name()->as_C_string(), resolved_method->name()->as_C_string());
 188     assert(object_resolved_method->signature() == resolved_method->signature(),
 189       "Object and interface method signatures should match at vtable index %d, %s != %s",
 190       index, object_resolved_method->signature()->as_C_string(), resolved_method->signature()->as_C_string());
 191 #endif // ASSERT
 192 
 193     kind = CallInfo::vtable_call;
 194   } else {
 195     // A regular interface call.
 196     kind = CallInfo::itable_call;
 197     index = resolved_method->itable_index();
 198   }
 199   assert(index == Method::nonvirtual_vtable_index || index >= 0, "bad index %d", index);
 200   _call_kind  = kind;
 201   _call_index = index;
 202   _resolved_appendix = Handle();
 203   // Find or create a ResolvedMethod instance for this Method*
 204   set_resolved_method_name(CHECK);
 205 
 206   DEBUG_ONLY(verify());
 207 }
 208 
 209 void CallInfo::set_resolved_method_name(TRAPS) {
 210   assert(_resolved_method() != nullptr, "Should already have a Method*");
 211   oop rmethod_name = java_lang_invoke_ResolvedMethodName::find_resolved_method(_resolved_method, CHECK);
 212   _resolved_method_name = Handle(THREAD, rmethod_name);
 213 }
 214 
 215 #ifdef ASSERT
 216 void CallInfo::verify() {
 217   switch (call_kind()) {  // the meaning and allowed value of index depends on kind
 218   case CallInfo::direct_call:
 219     if (_call_index == Method::nonvirtual_vtable_index)  break;
 220     // else fall through to check vtable index:
 221   case CallInfo::vtable_call:
 222     assert(resolved_klass()->verify_vtable_index(_call_index), "");
 223     break;
 224   case CallInfo::itable_call:
 225     assert(resolved_method()->method_holder()->verify_itable_index(_call_index), "");
 226     break;
 227   case CallInfo::unknown_kind:
 228     assert(call_kind() != CallInfo::unknown_kind, "CallInfo must be set");
 229     break;
 230   default:
 231     fatal("Unexpected call kind %d", call_kind());
 232   }
 233 }
 234 #endif // ASSERT
 235 
 236 #ifndef PRODUCT
 237 void CallInfo::print() {
 238   ResourceMark rm;
 239   const char* kindstr;
 240   switch (_call_kind) {
 241   case direct_call: kindstr = "direct";  break;
 242   case vtable_call: kindstr = "vtable";  break;
 243   case itable_call: kindstr = "itable";  break;
 244   default         : kindstr = "unknown"; break;
 245   }
 246   tty->print_cr("Call %s@%d %s", kindstr, _call_index,
 247                 _resolved_method.is_null() ? "(none)" : _resolved_method->name_and_sig_as_C_string());
 248 }
 249 #endif
 250 
 251 //------------------------------------------------------------------------------------------------------------------------
 252 // Implementation of LinkInfo
 253 
 254 LinkInfo::LinkInfo(const constantPoolHandle& pool, int index, const methodHandle& current_method, Bytecodes::Code code, TRAPS) {
 255    // resolve klass
 256   _resolved_klass = pool->klass_ref_at(index, code, CHECK);
 257 
 258   // Get name, signature, and static klass
 259   _name          = pool->name_ref_at(index, code);
 260   _signature     = pool->signature_ref_at(index, code);
 261   _tag           = pool->tag_ref_at(index, code);
 262   _current_klass = pool->pool_holder();
 263   _current_method = current_method;
 264 
 265   // Coming from the constant pool always checks access
 266   _check_access  = true;
 267   _check_loader_constraints = true;
 268 }
 269 
 270 LinkInfo::LinkInfo(const constantPoolHandle& pool, int index, Bytecodes::Code code, TRAPS) {
 271    // resolve klass
 272   _resolved_klass = pool->klass_ref_at(index, code, CHECK);
 273 
 274   // Get name, signature, and static klass
 275   _name          = pool->name_ref_at(index, code);
 276   _signature     = pool->signature_ref_at(index, code);
 277   _tag           = pool->tag_ref_at(index, code);
 278   _current_klass = pool->pool_holder();
 279   _current_method = methodHandle();
 280 
 281   // Coming from the constant pool always checks access
 282   _check_access  = true;
 283   _check_loader_constraints = true;
 284 }
 285 
 286 #ifndef PRODUCT
 287 void LinkInfo::print() {
 288   ResourceMark rm;
 289   tty->print_cr("Link resolved_klass=%s name=%s signature=%s current_klass=%s check_access=%s check_loader_constraints=%s",
 290                 _resolved_klass->name()->as_C_string(),
 291                 _name->as_C_string(),
 292                 _signature->as_C_string(),
 293                 _current_klass == nullptr ? "(none)" : _current_klass->name()->as_C_string(),
 294                 _check_access ? "true" : "false",
 295                 _check_loader_constraints ? "true" : "false");
 296 
 297 }
 298 #endif // PRODUCT
 299 //------------------------------------------------------------------------------------------------------------------------
 300 // Klass resolution
 301 
 302 void LinkResolver::check_klass_accessibility(Klass* ref_klass, Klass* sel_klass, TRAPS) {
 303   Klass* base_klass = sel_klass;
 304   if (sel_klass->is_objArray_klass()) {
 305     base_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass();
 306   }
 307   // The element type could be a typeArray - we only need the access
 308   // check if it is a reference to another class.
 309   if (!base_klass->is_instance_klass()) {
 310     return;  // no relevant check to do
 311   }
 312 
 313   Reflection::VerifyClassAccessResults vca_result =
 314     Reflection::verify_class_access(ref_klass, InstanceKlass::cast(base_klass), true);
 315   if (vca_result != Reflection::ACCESS_OK) {
 316     ResourceMark rm(THREAD);
 317     char* msg = Reflection::verify_class_access_msg(ref_klass,
 318                                                     InstanceKlass::cast(base_klass),
 319                                                     vca_result);
 320     bool same_module = (base_klass->module() == ref_klass->module());
 321     if (msg == nullptr) {
 322       Exceptions::fthrow(
 323         THREAD_AND_LOCATION,
 324         vmSymbols::java_lang_IllegalAccessError(),
 325         "failed to access class %s from class %s (%s%s%s)",
 326         base_klass->external_name(),
 327         ref_klass->external_name(),
 328         (same_module) ? base_klass->joint_in_module_of_loader(ref_klass) : base_klass->class_in_module_of_loader(),
 329         (same_module) ? "" : "; ",
 330         (same_module) ? "" : ref_klass->class_in_module_of_loader());
 331     } else {
 332       // Use module specific message returned by verify_class_access_msg().
 333       Exceptions::fthrow(
 334         THREAD_AND_LOCATION,
 335         vmSymbols::java_lang_IllegalAccessError(),
 336         "%s", msg);
 337     }
 338   }
 339 }
 340 
 341 //------------------------------------------------------------------------------------------------------------------------
 342 // Method resolution
 343 //
 344 // According to JVM spec. $5.4.3c & $5.4.3d
 345 
 346 // Look up method in klasses, including static methods
 347 // Then look up local default methods
 348 Method* LinkResolver::lookup_method_in_klasses(const LinkInfo& link_info,
 349                                                bool checkpolymorphism,
 350                                                bool in_imethod_resolve) {
 351   NoSafepointVerifier nsv;  // Method* returned may not be reclaimed
 352 
 353   Klass* klass = link_info.resolved_klass();
 354   Symbol* name = link_info.name();
 355   Symbol* signature = link_info.signature();
 356 
 357   // Ignore overpasses so statics can be found during resolution
 358   Method* result = klass->uncached_lookup_method(name, signature, Klass::OverpassLookupMode::skip);
 359 
 360   if (klass->is_array_klass()) {
 361     // Only consider klass and super klass for arrays
 362     return result;
 363   }
 364 
 365   InstanceKlass* ik = InstanceKlass::cast(klass);
 366 
 367   // JDK 8, JVMS 5.4.3.4: Interface method resolution should
 368   // ignore static and non-public methods of java.lang.Object,
 369   // like clone and finalize.
 370   if (in_imethod_resolve &&
 371       result != nullptr &&
 372       ik->is_interface() &&
 373       (result->is_static() || !result->is_public()) &&
 374       result->method_holder() == vmClasses::Object_klass()) {
 375     result = nullptr;
 376   }
 377 
 378   // Before considering default methods, check for an overpass in the
 379   // current class if a method has not been found.
 380   if (result == nullptr) {
 381     result = ik->find_method(name, signature);
 382   }
 383 
 384   if (result == nullptr) {
 385     Array<Method*>* default_methods = ik->default_methods();
 386     if (default_methods != nullptr) {
 387       result = InstanceKlass::find_method(default_methods, name, signature);
 388     }
 389   }
 390 
 391   if (checkpolymorphism && result != nullptr) {
 392     vmIntrinsics::ID iid = result->intrinsic_id();
 393     if (MethodHandles::is_signature_polymorphic(iid)) {
 394       // Do not link directly to these.  The VM must produce a synthetic one using lookup_polymorphic_method.
 395       return nullptr;
 396     }
 397   }
 398   return result;
 399 }
 400 
 401 // returns first instance method
 402 // Looks up method in classes, then looks up local default methods
 403 Method* LinkResolver::lookup_instance_method_in_klasses(Klass* klass,
 404                                                         Symbol* name,
 405                                                         Symbol* signature,
 406                                                         Klass::PrivateLookupMode private_mode) {
 407   Method* result = klass->uncached_lookup_method(name, signature, Klass::OverpassLookupMode::find, private_mode);
 408 
 409   while (result != nullptr && result->is_static() && result->method_holder()->super() != nullptr) {
 410     Klass* super_klass = result->method_holder()->super();
 411     result = super_klass->uncached_lookup_method(name, signature, Klass::OverpassLookupMode::find, private_mode);
 412   }
 413 
 414   if (klass->is_array_klass()) {
 415     // Only consider klass and super klass for arrays
 416     return result;
 417   }
 418 
 419   if (result == nullptr) {
 420     Array<Method*>* default_methods = InstanceKlass::cast(klass)->default_methods();
 421     if (default_methods != nullptr) {
 422       result = InstanceKlass::find_method(default_methods, name, signature);
 423       assert(result == nullptr || !result->is_static(), "static defaults not allowed");
 424     }
 425   }
 426   return result;
 427 }
 428 
 429 int LinkResolver::vtable_index_of_interface_method(Klass* klass, const methodHandle& resolved_method) {
 430   InstanceKlass* ik = InstanceKlass::cast(klass);
 431   return ik->vtable_index_of_interface_method(resolved_method());
 432 }
 433 
 434 Method* LinkResolver::lookup_method_in_interfaces(const LinkInfo& cp_info) {
 435   InstanceKlass *ik = InstanceKlass::cast(cp_info.resolved_klass());
 436 
 437   // Specify 'true' in order to skip default methods when searching the
 438   // interfaces.  Function lookup_method_in_klasses() already looked for
 439   // the method in the default methods table.
 440   return ik->lookup_method_in_all_interfaces(cp_info.name(), cp_info.signature(), Klass::DefaultsLookupMode::skip);
 441 }
 442 
 443 Method* LinkResolver::lookup_polymorphic_method(const LinkInfo& link_info,
 444                                                 Handle *appendix_result_or_null,
 445                                                 TRAPS) {
 446   ResourceMark rm(THREAD);
 447   Klass* klass = link_info.resolved_klass();
 448   Symbol* name = link_info.name();
 449   Symbol* full_signature = link_info.signature();
 450   LogTarget(Info, methodhandles) lt_mh;
 451 
 452   vmIntrinsics::ID iid = MethodHandles::signature_polymorphic_name_id(name);
 453   log_info(methodhandles)("lookup_polymorphic_method iid=%s %s.%s%s",
 454                           vmIntrinsics::name_at(iid), klass->external_name(),
 455                           name->as_C_string(), full_signature->as_C_string());
 456   if ((klass == vmClasses::MethodHandle_klass() ||
 457        klass == vmClasses::VarHandle_klass()) &&
 458       iid != vmIntrinsics::_none) {
 459     if (MethodHandles::is_signature_polymorphic_intrinsic(iid)) {
 460       // Most of these do not need an up-call to Java to resolve, so can be done anywhere.
 461       // Do not erase last argument type (MemberName) if it is a static linkTo method.
 462       bool keep_last_arg = MethodHandles::is_signature_polymorphic_static(iid);
 463       TempNewSymbol basic_signature =
 464         MethodHandles::lookup_basic_type_signature(full_signature, keep_last_arg);
 465       log_info(methodhandles)("lookup_polymorphic_method %s %s => basic %s",
 466                               name->as_C_string(),
 467                               full_signature->as_C_string(),
 468                               basic_signature->as_C_string());
 469       Method* result = SystemDictionary::find_method_handle_intrinsic(iid,
 470                                                               basic_signature,
 471                                                               CHECK_NULL);
 472       if (result != nullptr) {
 473         assert(result->is_method_handle_intrinsic(), "MH.invokeBasic or MH.linkTo* intrinsic");
 474         assert(result->intrinsic_id() != vmIntrinsics::_invokeGeneric, "wrong place to find this");
 475         assert(basic_signature == result->signature(), "predict the result signature");
 476         if (lt_mh.is_enabled()) {
 477           LogStream ls(lt_mh);
 478           ls.print("lookup_polymorphic_method => intrinsic ");
 479           result->print_on(&ls);
 480         }
 481       }
 482       return result;
 483     } else if (iid == vmIntrinsics::_invokeGeneric
 484                && THREAD->can_call_java()
 485                && appendix_result_or_null != nullptr) {
 486       // This is a method with type-checking semantics.
 487       // We will ask Java code to spin an adapter method for it.
 488       if (!MethodHandles::enabled()) {
 489         // Make sure the Java part of the runtime has been booted up.
 490         Klass* natives = vmClasses::MethodHandleNatives_klass();
 491         if (natives == nullptr || InstanceKlass::cast(natives)->is_not_initialized()) {
 492           SystemDictionary::resolve_or_fail(vmSymbols::java_lang_invoke_MethodHandleNatives(),
 493                                             Handle(),
 494                                             Handle(),
 495                                             true,
 496                                             CHECK_NULL);
 497         }
 498       }
 499 
 500       Handle appendix;
 501       Method* result = SystemDictionary::find_method_handle_invoker(klass,
 502                                                                     name,
 503                                                                     full_signature,
 504                                                                     link_info.current_klass(),
 505                                                                     &appendix,
 506                                                                     CHECK_NULL);
 507       if (lt_mh.is_enabled()) {
 508         LogStream ls(lt_mh);
 509         ls.print("lookup_polymorphic_method => (via Java) ");
 510         result->print_on(&ls);
 511         ls.print("  lookup_polymorphic_method => appendix = ");
 512         appendix.is_null() ? ls.print_cr("(none)") : appendix->print_on(&ls);
 513       }
 514       if (result != nullptr) {
 515 #ifdef ASSERT
 516         ResourceMark rm(THREAD);
 517 
 518         TempNewSymbol basic_signature =
 519           MethodHandles::lookup_basic_type_signature(full_signature);
 520         int actual_size_of_params = result->size_of_parameters();
 521         int expected_size_of_params = ArgumentSizeComputer(basic_signature).size();
 522         // +1 for MethodHandle.this, +1 for trailing MethodType
 523         if (!MethodHandles::is_signature_polymorphic_static(iid))  expected_size_of_params += 1;
 524         if (appendix.not_null())                                   expected_size_of_params += 1;
 525         if (actual_size_of_params != expected_size_of_params) {
 526           tty->print_cr("*** basic_signature=%s", basic_signature->as_C_string());
 527           tty->print_cr("*** result for %s: ", vmIntrinsics::name_at(iid));
 528           result->print();
 529         }
 530         assert(actual_size_of_params == expected_size_of_params,
 531                "%d != %d", actual_size_of_params, expected_size_of_params);
 532 #endif //ASSERT
 533 
 534         assert(appendix_result_or_null != nullptr, "");
 535         (*appendix_result_or_null) = appendix;
 536       }
 537       return result;
 538     }
 539   }
 540   return nullptr;
 541 }
 542 
 543 static void print_nest_host_error_on(stringStream* ss, Klass* ref_klass, Klass* sel_klass) {
 544   assert(ref_klass->is_instance_klass(), "must be");
 545   assert(sel_klass->is_instance_klass(), "must be");
 546   InstanceKlass* ref_ik = InstanceKlass::cast(ref_klass);
 547   InstanceKlass* sel_ik = InstanceKlass::cast(sel_klass);
 548   const char* nest_host_error_1 = ref_ik->nest_host_error();
 549   const char* nest_host_error_2 = sel_ik->nest_host_error();
 550   if (nest_host_error_1 != nullptr || nest_host_error_2 != nullptr) {
 551     ss->print(", (%s%s%s)",
 552               (nest_host_error_1 != nullptr) ? nest_host_error_1 : "",
 553               (nest_host_error_1 != nullptr && nest_host_error_2 != nullptr) ? ", " : "",
 554               (nest_host_error_2 != nullptr) ? nest_host_error_2 : "");
 555   }
 556 }
 557 
 558 void LinkResolver::check_method_accessability(Klass* ref_klass,
 559                                               Klass* resolved_klass,
 560                                               Klass* sel_klass,
 561                                               const methodHandle& sel_method,
 562                                               TRAPS) {
 563 
 564   AccessFlags flags = sel_method->access_flags();
 565 
 566   // Special case:  arrays always override "clone". JVMS 2.15.
 567   // If the resolved klass is an array class, and the declaring class
 568   // is java.lang.Object and the method is "clone", set the flags
 569   // to public.
 570   //
 571   // We'll check for the method name first, as that's most likely
 572   // to be false (so we'll short-circuit out of these tests).
 573   if (sel_method->name() == vmSymbols::clone_name() &&
 574       sel_klass == vmClasses::Object_klass() &&
 575       resolved_klass->is_array_klass()) {
 576     // We need to change "protected" to "public".
 577     assert(flags.is_protected(), "clone not protected?");
 578     jint new_flags = flags.as_int();
 579     new_flags = new_flags & (~JVM_ACC_PROTECTED);
 580     new_flags = new_flags | JVM_ACC_PUBLIC;
 581     flags.set_flags(new_flags);
 582   }
 583 //  assert(extra_arg_result_or_null != nullptr, "must be able to return extra argument");
 584 
 585   bool can_access = Reflection::verify_member_access(ref_klass,
 586                                                      resolved_klass,
 587                                                      sel_klass,
 588                                                      flags,
 589                                                      true, false, CHECK);
 590   // Any existing exceptions that may have been thrown
 591   // have been allowed to propagate.
 592   if (!can_access) {
 593     ResourceMark rm(THREAD);
 594     stringStream ss;
 595     bool same_module = (sel_klass->module() == ref_klass->module());
 596     ss.print("class %s tried to access %s%s%smethod '%s' (%s%s%s)",
 597              ref_klass->external_name(),
 598              sel_method->is_abstract()  ? "abstract "  : "",
 599              sel_method->is_protected() ? "protected " : "",
 600              sel_method->is_private()   ? "private "   : "",
 601              sel_method->external_name(),
 602              (same_module) ? ref_klass->joint_in_module_of_loader(sel_klass) : ref_klass->class_in_module_of_loader(),
 603              (same_module) ? "" : "; ",
 604              (same_module) ? "" : sel_klass->class_in_module_of_loader()
 605              );
 606 
 607     // For private access see if there was a problem with nest host
 608     // resolution, and if so report that as part of the message.
 609     if (sel_method->is_private()) {
 610       print_nest_host_error_on(&ss, ref_klass, sel_klass);
 611     }
 612 
 613     Exceptions::fthrow(THREAD_AND_LOCATION,
 614                        vmSymbols::java_lang_IllegalAccessError(),
 615                        "%s",
 616                        ss.as_string()
 617                        );
 618     return;
 619   }
 620 }
 621 
 622 void LinkResolver::resolve_continuation_enter(CallInfo& callinfo, TRAPS) {
 623   Klass* resolved_klass = vmClasses::Continuation_klass();
 624   Symbol* method_name = vmSymbols::enter_name();
 625   Symbol* method_signature = vmSymbols::continuationEnter_signature();
 626   Klass*  current_klass = resolved_klass;
 627   LinkInfo link_info(resolved_klass, method_name, method_signature, current_klass);
 628   Method* resolved_method = resolve_method(link_info, Bytecodes::_invokestatic, CHECK);
 629   callinfo.set_static(resolved_klass, methodHandle(THREAD, resolved_method), CHECK);
 630 }
 631 
 632 Method* LinkResolver::resolve_method_statically(Bytecodes::Code code,
 633                                                 const constantPoolHandle& pool, int index, TRAPS) {
 634   // This method is used only
 635   // (1) in C2 from InlineTree::ok_to_inline (via ciMethod::check_call),
 636   // and
 637   // (2) in Bytecode_invoke::static_target
 638   // It appears to fail when applied to an invokeinterface call site.
 639   // FIXME: Remove this method and ciMethod::check_call; refactor to use the other LinkResolver entry points.
 640   // resolve klass
 641   if (code == Bytecodes::_invokedynamic) {
 642     Klass* resolved_klass = vmClasses::MethodHandle_klass();
 643     Symbol* method_name = vmSymbols::invoke_name();
 644     Symbol* method_signature = pool->signature_ref_at(index, code);
 645     Klass*  current_klass = pool->pool_holder();
 646     LinkInfo link_info(resolved_klass, method_name, method_signature, current_klass);
 647     return resolve_method(link_info, code, THREAD);
 648   }
 649 
 650   LinkInfo link_info(pool, index, methodHandle(), code, CHECK_NULL);
 651   Klass* resolved_klass = link_info.resolved_klass();
 652 
 653   if (pool->has_preresolution()
 654       || ((resolved_klass == vmClasses::MethodHandle_klass() || resolved_klass == vmClasses::VarHandle_klass()) &&
 655           MethodHandles::is_signature_polymorphic_name(resolved_klass, link_info.name()))) {
 656     Method* result = ConstantPool::method_at_if_loaded(pool, index);
 657     if (result != nullptr) {
 658       return result;
 659     }
 660   }
 661 
 662   if (code == Bytecodes::_invokeinterface) {
 663     return resolve_interface_method(link_info, code, THREAD);
 664   } else if (code == Bytecodes::_invokevirtual) {
 665     return resolve_method(link_info, code, THREAD);
 666   } else if (!resolved_klass->is_interface()) {
 667     return resolve_method(link_info, code, THREAD);
 668   } else {
 669     return resolve_interface_method(link_info, code, THREAD);
 670   }
 671 }
 672 
 673 // Check and print a loader constraint violation message for method or interface method
 674 void LinkResolver::check_method_loader_constraints(const LinkInfo& link_info,
 675                                                    const methodHandle& resolved_method,
 676                                                    const char* method_type, TRAPS) {
 677   Handle current_loader(THREAD, link_info.current_klass()->class_loader());
 678   Handle resolved_loader(THREAD, resolved_method->method_holder()->class_loader());
 679 
 680   ResourceMark rm(THREAD);
 681   Symbol* failed_type_symbol =
 682     SystemDictionary::check_signature_loaders(link_info.signature(),
 683                                               /*klass_being_linked*/ nullptr, // We are not linking class
 684                                               current_loader,
 685                                               resolved_loader, true);
 686   if (failed_type_symbol != nullptr) {
 687     Klass* current_class = link_info.current_klass();
 688     ClassLoaderData* current_loader_data = current_class->class_loader_data();
 689     assert(current_loader_data != nullptr, "current class has no class loader data");
 690     Klass* resolved_method_class = resolved_method->method_holder();
 691     ClassLoaderData* target_loader_data = resolved_method_class->class_loader_data();
 692     assert(target_loader_data != nullptr, "resolved method's class has no class loader data");
 693 
 694     stringStream ss;
 695     ss.print("loader constraint violation: when resolving %s '", method_type);
 696     Method::print_external_name(&ss, link_info.resolved_klass(), link_info.name(), link_info.signature());
 697     ss.print("' the class loader %s of the current class, %s,"
 698              " and the class loader %s for the method's defining class, %s, have"
 699              " different Class objects for the type %s used in the signature (%s; %s)",
 700              current_loader_data->loader_name_and_id(),
 701              current_class->name()->as_C_string(),
 702              target_loader_data->loader_name_and_id(),
 703              resolved_method_class->name()->as_C_string(),
 704              failed_type_symbol->as_C_string(),
 705              current_class->class_in_module_of_loader(false, true),
 706              resolved_method_class->class_in_module_of_loader(false, true));
 707     THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());
 708   }
 709 }
 710 
 711 void LinkResolver::check_field_loader_constraints(Symbol* field, Symbol* sig,
 712                                                   Klass* current_klass,
 713                                                   Klass* sel_klass, TRAPS) {
 714   Handle ref_loader(THREAD, current_klass->class_loader());
 715   Handle sel_loader(THREAD, sel_klass->class_loader());
 716 
 717   ResourceMark rm(THREAD);  // needed for check_signature_loaders
 718   Symbol* failed_type_symbol =
 719     SystemDictionary::check_signature_loaders(sig,
 720                                               /*klass_being_linked*/ nullptr, // We are not linking class
 721                                               ref_loader, sel_loader,
 722                                               false);
 723   if (failed_type_symbol != nullptr) {
 724     stringStream ss;
 725     const char* failed_type_name = failed_type_symbol->as_klass_external_name();
 726 
 727     ss.print("loader constraint violation: when resolving field \"%s\" of type %s, "
 728              "the class loader %s of the current class, %s, "
 729              "and the class loader %s for the field's defining %s, %s, "
 730              "have different Class objects for type %s (%s; %s)",
 731              field->as_C_string(),
 732              failed_type_name,
 733              current_klass->class_loader_data()->loader_name_and_id(),
 734              current_klass->external_name(),
 735              sel_klass->class_loader_data()->loader_name_and_id(),
 736              sel_klass->external_kind(),
 737              sel_klass->external_name(),
 738              failed_type_name,
 739              current_klass->class_in_module_of_loader(false, true),
 740              sel_klass->class_in_module_of_loader(false, true));
 741     THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());
 742   }
 743 }
 744 
 745 Method* LinkResolver::resolve_method(const LinkInfo& link_info,
 746                                      Bytecodes::Code code, TRAPS) {
 747 
 748   Handle nested_exception;
 749   Klass* resolved_klass = link_info.resolved_klass();
 750 
 751   // 1. For invokevirtual, cannot call an interface method
 752   if (code == Bytecodes::_invokevirtual && resolved_klass->is_interface()) {
 753     ResourceMark rm(THREAD);
 754     char buf[200];
 755     jio_snprintf(buf, sizeof(buf), "Found interface %s, but class was expected",
 756         resolved_klass->external_name());
 757     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
 758   }
 759 
 760   // 2. check constant pool tag for called method - must be JVM_CONSTANT_Methodref
 761   if (!link_info.tag().is_invalid() && !link_info.tag().is_method()) {
 762     ResourceMark rm(THREAD);
 763     stringStream ss;
 764     ss.print("Method '");
 765     Method::print_external_name(&ss, link_info.resolved_klass(), link_info.name(), link_info.signature());
 766     ss.print("' must be Methodref constant");
 767     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
 768   }
 769 
 770   // 3. lookup method in resolved klass and its super klasses
 771   methodHandle resolved_method(THREAD, lookup_method_in_klasses(link_info, true, false));
 772 
 773   // 4. lookup method in all the interfaces implemented by the resolved klass
 774   if (resolved_method.is_null() && !resolved_klass->is_array_klass()) { // not found in the class hierarchy
 775     resolved_method = methodHandle(THREAD, lookup_method_in_interfaces(link_info));
 776 
 777     if (resolved_method.is_null()) {
 778       // JSR 292:  see if this is an implicitly generated method MethodHandle.linkToVirtual(*...), etc
 779       Method* method = lookup_polymorphic_method(link_info, (Handle*)nullptr, THREAD);
 780       resolved_method = methodHandle(THREAD, method);
 781       if (HAS_PENDING_EXCEPTION) {
 782         nested_exception = Handle(THREAD, PENDING_EXCEPTION);
 783         CLEAR_PENDING_EXCEPTION;
 784       }
 785     }
 786   }
 787 
 788   // 5. method lookup failed
 789   if (resolved_method.is_null()) {
 790     ResourceMark rm(THREAD);
 791     stringStream ss;
 792     ss.print("'");
 793     Method::print_external_name(&ss, resolved_klass, link_info.name(), link_info.signature());
 794     ss.print("'");
 795     THROW_MSG_CAUSE_(vmSymbols::java_lang_NoSuchMethodError(),
 796                      ss.as_string(), nested_exception, nullptr);
 797   }
 798 
 799   // 6. access checks, access checking may be turned off when calling from within the VM.
 800   Klass* current_klass = link_info.current_klass();
 801   if (link_info.check_access()) {
 802     assert(current_klass != nullptr , "current_klass should not be null");
 803 
 804     // check if method can be accessed by the referring class
 805     check_method_accessability(current_klass,
 806                                resolved_klass,
 807                                resolved_method->method_holder(),
 808                                resolved_method,
 809                                CHECK_NULL);
 810   }
 811   if (link_info.check_loader_constraints()) {
 812     // check loader constraints
 813     check_method_loader_constraints(link_info, resolved_method, "method", CHECK_NULL);
 814   }
 815 
 816   return resolved_method();
 817 }
 818 
 819 static void trace_method_resolution(const char* prefix,
 820                                     Klass* klass,
 821                                     Klass* resolved_klass,
 822                                     Method* method,
 823                                     bool logitables,
 824                                     int index = -1) {
 825 #ifndef PRODUCT
 826   ResourceMark rm;
 827   Log(itables) logi;
 828   LogStream lsi(logi.trace());
 829   Log(vtables) logv;
 830   LogStream lsv(logv.trace());
 831   outputStream* st;
 832   if (logitables) {
 833     st = &lsi;
 834   } else {
 835     st = &lsv;
 836   }
 837   st->print("%s%s, compile-time-class:%s, method:%s, method_holder:%s, access_flags: ",
 838             prefix,
 839             (klass == nullptr ? "<null>" : klass->internal_name()),
 840             resolved_klass->internal_name(),
 841             Method::name_and_sig_as_C_string(resolved_klass,
 842                                              method->name(),
 843                                              method->signature()),
 844             method->method_holder()->internal_name());
 845   method->print_linkage_flags(st);
 846   if (index != -1) {
 847     st->print("vtable_index:%d", index);
 848   }
 849   st->cr();
 850 #endif // PRODUCT
 851 }
 852 
 853 // Do linktime resolution of a method in the interface within the context of the specified bytecode.
 854 Method* LinkResolver::resolve_interface_method(const LinkInfo& link_info, Bytecodes::Code code, TRAPS) {
 855 
 856   Klass* resolved_klass = link_info.resolved_klass();
 857 
 858   // check if klass is interface
 859   if (!resolved_klass->is_interface()) {
 860     ResourceMark rm(THREAD);
 861     char buf[200];
 862     jio_snprintf(buf, sizeof(buf), "Found class %s, but interface was expected", resolved_klass->external_name());
 863     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
 864   }
 865 
 866   // check constant pool tag for called method - must be JVM_CONSTANT_InterfaceMethodref
 867   if (!link_info.tag().is_invalid() && !link_info.tag().is_interface_method()) {
 868     ResourceMark rm(THREAD);
 869     stringStream ss;
 870     ss.print("Method '");
 871     Method::print_external_name(&ss, link_info.resolved_klass(), link_info.name(), link_info.signature());
 872     ss.print("' must be InterfaceMethodref constant");
 873     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
 874   }
 875 
 876   // lookup method in this interface or its super, java.lang.Object
 877   // JDK8: also look for static methods
 878   methodHandle resolved_method(THREAD, lookup_method_in_klasses(link_info, false, true));
 879 
 880   if (resolved_method.is_null() && !resolved_klass->is_array_klass()) {
 881     // lookup method in all the super-interfaces
 882     resolved_method = methodHandle(THREAD, lookup_method_in_interfaces(link_info));
 883   }
 884 
 885   if (resolved_method.is_null()) {
 886     // no method found
 887     ResourceMark rm(THREAD);
 888     stringStream ss;
 889     ss.print("'");
 890     Method::print_external_name(&ss, resolved_klass, link_info.name(), link_info.signature());
 891     ss.print("'");
 892     THROW_MSG_NULL(vmSymbols::java_lang_NoSuchMethodError(), ss.as_string());
 893   }
 894 
 895   if (link_info.check_access()) {
 896     // JDK8 adds non-public interface methods, and accessability check requirement
 897     Klass* current_klass = link_info.current_klass();
 898 
 899     assert(current_klass != nullptr , "current_klass should not be null");
 900 
 901     // check if method can be accessed by the referring class
 902     check_method_accessability(current_klass,
 903                                resolved_klass,
 904                                resolved_method->method_holder(),
 905                                resolved_method,
 906                                CHECK_NULL);
 907   }
 908   if (link_info.check_loader_constraints()) {
 909     check_method_loader_constraints(link_info, resolved_method, "interface method", CHECK_NULL);
 910   }
 911 
 912   if (code != Bytecodes::_invokestatic && resolved_method->is_static()) {
 913     ResourceMark rm(THREAD);
 914     stringStream ss;
 915     ss.print("Expected instance not static method '");
 916     Method::print_external_name(&ss, resolved_klass,
 917                                 resolved_method->name(), resolved_method->signature());
 918     ss.print("'");
 919     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
 920   }
 921 
 922   if (log_develop_is_enabled(Trace, itables)) {
 923     char buf[200];
 924     jio_snprintf(buf, sizeof(buf), "%s resolved interface method: caller-class:",
 925                  Bytecodes::name(code));
 926     trace_method_resolution(buf, link_info.current_klass(), resolved_klass, resolved_method(), true);
 927   }
 928 
 929   return resolved_method();
 930 }
 931 
 932 //------------------------------------------------------------------------------------------------------------------------
 933 // Field resolution
 934 
 935 void LinkResolver::check_field_accessability(Klass* ref_klass,
 936                                              Klass* resolved_klass,
 937                                              Klass* sel_klass,
 938                                              const fieldDescriptor& fd,
 939                                              TRAPS) {
 940   bool can_access = Reflection::verify_member_access(ref_klass,
 941                                                      resolved_klass,
 942                                                      sel_klass,
 943                                                      fd.access_flags(),
 944                                                      true, false, CHECK);
 945   // Any existing exceptions that may have been thrown, for example LinkageErrors
 946   // from nest-host resolution, have been allowed to propagate.
 947   if (!can_access) {
 948     bool same_module = (sel_klass->module() == ref_klass->module());
 949     ResourceMark rm(THREAD);
 950     stringStream ss;
 951     ss.print("class %s tried to access %s%sfield %s.%s (%s%s%s)",
 952              ref_klass->external_name(),
 953              fd.is_protected() ? "protected " : "",
 954              fd.is_private()   ? "private "   : "",
 955              sel_klass->external_name(),
 956              fd.name()->as_C_string(),
 957              (same_module) ? ref_klass->joint_in_module_of_loader(sel_klass) : ref_klass->class_in_module_of_loader(),
 958              (same_module) ? "" : "; ",
 959              (same_module) ? "" : sel_klass->class_in_module_of_loader()
 960              );
 961     // For private access see if there was a problem with nest host
 962     // resolution, and if so report that as part of the message.
 963     if (fd.is_private()) {
 964       print_nest_host_error_on(&ss, ref_klass, sel_klass);
 965     }
 966     Exceptions::fthrow(THREAD_AND_LOCATION,
 967                        vmSymbols::java_lang_IllegalAccessError(),
 968                        "%s",
 969                        ss.as_string()
 970                        );
 971     return;
 972   }
 973 }
 974 
 975 void LinkResolver::resolve_field_access(fieldDescriptor& fd, const constantPoolHandle& pool, int index, const methodHandle& method, Bytecodes::Code byte, TRAPS) {
 976   LinkInfo link_info(pool, index, method, byte, CHECK);
 977   resolve_field(fd, link_info, byte, true, CHECK);
 978 }
 979 
 980 void LinkResolver::resolve_field(fieldDescriptor& fd,
 981                                  const LinkInfo& link_info,
 982                                  Bytecodes::Code byte, bool initialize_class,
 983                                  TRAPS) {
 984   assert(byte == Bytecodes::_getstatic || byte == Bytecodes::_putstatic ||
 985          byte == Bytecodes::_getfield  || byte == Bytecodes::_putfield  ||
 986          byte == Bytecodes::_nofast_getfield  || byte == Bytecodes::_nofast_putfield  ||
 987          (byte == Bytecodes::_nop && !link_info.check_access()), "bad field access bytecode");
 988 
 989   bool is_static = (byte == Bytecodes::_getstatic || byte == Bytecodes::_putstatic);
 990   bool is_put    = (byte == Bytecodes::_putfield  || byte == Bytecodes::_putstatic || byte == Bytecodes::_nofast_putfield);
 991   // Check if there's a resolved klass containing the field
 992   Klass* resolved_klass = link_info.resolved_klass();
 993   Symbol* field = link_info.name();
 994   Symbol* sig = link_info.signature();
 995 
 996   // Resolve instance field
 997   Klass* sel_klass = resolved_klass->find_field(field, sig, &fd);
 998   // check if field exists; i.e., if a klass containing the field def has been selected
 999   if (sel_klass == nullptr) {
1000     ResourceMark rm(THREAD);
1001     stringStream ss;
1002     ss.print("Class %s does not have member field '", resolved_klass->external_name());
1003     sig->print_as_field_external_type(&ss);
1004     ss.print(" %s'", field->as_C_string());
1005     THROW_MSG(vmSymbols::java_lang_NoSuchFieldError(), ss.as_string());
1006   }
1007 
1008   // Access checking may be turned off when calling from within the VM.
1009   Klass* current_klass = link_info.current_klass();
1010   if (link_info.check_access()) {
1011 
1012     // check access
1013     check_field_accessability(current_klass, resolved_klass, sel_klass, fd, CHECK);
1014 
1015     // check for errors
1016     if (is_static != fd.is_static()) {
1017       ResourceMark rm(THREAD);
1018       char msg[200];
1019       jio_snprintf(msg, sizeof(msg), "Expected %s field %s.%s", is_static ? "static" : "non-static", resolved_klass->external_name(), fd.name()->as_C_string());
1020       THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), msg);
1021     }
1022 
1023     // A final field can be modified only
1024     // (1) by methods declared in the class declaring the field and
1025     // (2) by the <clinit> method (in case of a static field)
1026     //     or by the <init> method (in case of an instance field).
1027     if (is_put && fd.access_flags().is_final()) {
1028 
1029       if (sel_klass != current_klass) {
1030         ResourceMark rm(THREAD);
1031         stringStream ss;
1032         ss.print("Update to %s final field %s.%s attempted from a different class (%s) than the field's declaring class",
1033                  is_static ? "static" : "non-static", resolved_klass->external_name(), fd.name()->as_C_string(),
1034                 current_klass->external_name());
1035         THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), ss.as_string());
1036       }
1037 
1038       if (fd.constants()->pool_holder()->major_version() >= 53) {
1039         Method* m = link_info.current_method();
1040         assert(m != nullptr, "information about the current method must be available for 'put' bytecodes");
1041         bool is_initialized_static_final_update = (byte == Bytecodes::_putstatic &&
1042                                                    fd.is_static() &&
1043                                                    !m->is_static_initializer());
1044         bool is_initialized_instance_final_update = ((byte == Bytecodes::_putfield || byte == Bytecodes::_nofast_putfield) &&
1045                                                      !fd.is_static() &&
1046                                                      !m->is_object_initializer());
1047 
1048         if (is_initialized_static_final_update || is_initialized_instance_final_update) {
1049           ResourceMark rm(THREAD);
1050           stringStream ss;
1051           ss.print("Update to %s final field %s.%s attempted from a different method (%s) than the initializer method %s ",
1052                    is_static ? "static" : "non-static", resolved_klass->external_name(), fd.name()->as_C_string(),
1053                    m->name()->as_C_string(),
1054                    is_static ? "<clinit>" : "<init>");
1055           THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), ss.as_string());
1056         }
1057       }
1058     }
1059 
1060     // initialize resolved_klass if necessary
1061     // note 1: the klass which declared the field must be initialized (i.e, sel_klass)
1062     //         according to the newest JVM spec (5.5, p.170) - was bug (gri 7/28/99)
1063     //
1064     // note 2: we don't want to force initialization if we are just checking
1065     //         if the field access is legal; e.g., during compilation
1066     if (is_static && initialize_class) {
1067       sel_klass->initialize(CHECK);
1068     }
1069   }
1070 
1071   if (link_info.check_loader_constraints() && (sel_klass != current_klass) && (current_klass != nullptr)) {
1072     check_field_loader_constraints(field, sig, current_klass, sel_klass, CHECK);
1073   }
1074 
1075   // return information. note that the klass is set to the actual klass containing the
1076   // field, otherwise access of static fields in superclasses will not work.
1077 }
1078 
1079 
1080 //------------------------------------------------------------------------------------------------------------------------
1081 // Invoke resolution
1082 //
1083 // Naming conventions:
1084 //
1085 // resolved_method    the specified method (i.e., static receiver specified via constant pool index)
1086 // sel_method         the selected method  (selected via run-time lookup; e.g., based on dynamic receiver class)
1087 // resolved_klass     the specified klass  (i.e., specified via constant pool index)
1088 // recv_klass         the receiver klass
1089 
1090 
1091 void LinkResolver::resolve_static_call(CallInfo& result,
1092                                        const LinkInfo& link_info,
1093                                        bool initialize_class, TRAPS) {
1094   Method* resolved_method = linktime_resolve_static_method(link_info, CHECK);
1095 
1096   // The resolved class can change as a result of this resolution.
1097   Klass* resolved_klass = resolved_method->method_holder();
1098 
1099   // Initialize klass (this should only happen if everything is ok)
1100   if (initialize_class && resolved_klass->should_be_initialized()) {
1101     resolved_klass->initialize(CHECK);
1102     // Use updated LinkInfo to reresolve with resolved method holder
1103     LinkInfo new_info(resolved_klass, link_info.name(), link_info.signature(),
1104                       link_info.current_klass(),
1105                       link_info.check_access() ? LinkInfo::AccessCheck::required : LinkInfo::AccessCheck::skip,
1106                       link_info.check_loader_constraints() ? LinkInfo::LoaderConstraintCheck::required : LinkInfo::LoaderConstraintCheck::skip);
1107     resolved_method = linktime_resolve_static_method(new_info, CHECK);
1108   }
1109 
1110   // setup result
1111   result.set_static(resolved_klass, methodHandle(THREAD, resolved_method), CHECK);
1112   JFR_ONLY(Jfr::on_resolution(result, CHECK);)
1113 }
1114 
1115 // throws linktime exceptions
1116 Method* LinkResolver::linktime_resolve_static_method(const LinkInfo& link_info, TRAPS) {
1117 
1118   Klass* resolved_klass = link_info.resolved_klass();
1119   Method* resolved_method;
1120   if (!resolved_klass->is_interface()) {
1121     resolved_method = resolve_method(link_info, Bytecodes::_invokestatic, CHECK_NULL);
1122   } else {
1123     resolved_method = resolve_interface_method(link_info, Bytecodes::_invokestatic, CHECK_NULL);
1124   }
1125   assert(resolved_method->name() != vmSymbols::class_initializer_name(), "should have been checked in verifier");
1126 
1127   // check if static
1128   if (!resolved_method->is_static()) {
1129     ResourceMark rm(THREAD);
1130     stringStream ss;
1131     ss.print("Expected static method '");
1132     resolved_method->print_external_name(&ss);
1133     ss.print("'");
1134     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1135   }
1136   return resolved_method;
1137 }
1138 
1139 
1140 void LinkResolver::resolve_special_call(CallInfo& result,
1141                                         Handle recv,
1142                                         const LinkInfo& link_info,
1143                                         TRAPS) {
1144   Method* resolved_method = linktime_resolve_special_method(link_info, CHECK);
1145   runtime_resolve_special_method(result, link_info, methodHandle(THREAD, resolved_method), recv, CHECK);
1146 }
1147 
1148 // throws linktime exceptions
1149 Method* LinkResolver::linktime_resolve_special_method(const LinkInfo& link_info, TRAPS) {
1150 
1151   // Invokespecial is called for multiple special reasons:
1152   // <init>
1153   // local private method invocation, for classes and interfaces
1154   // superclass.method, which can also resolve to a default method
1155   // and the selected method is recalculated relative to the direct superclass
1156   // superinterface.method, which explicitly does not check shadowing
1157   Klass* resolved_klass = link_info.resolved_klass();
1158   Method* resolved_method = nullptr;
1159 
1160   if (!resolved_klass->is_interface()) {
1161     resolved_method = resolve_method(link_info, Bytecodes::_invokespecial, CHECK_NULL);
1162   } else {
1163     resolved_method = resolve_interface_method(link_info, Bytecodes::_invokespecial, CHECK_NULL);
1164   }
1165 
1166   // check if method name is <init>, that it is found in same klass as static type
1167   if (resolved_method->name() == vmSymbols::object_initializer_name() &&
1168       resolved_method->method_holder() != resolved_klass) {
1169     ResourceMark rm(THREAD);
1170     stringStream ss;
1171     ss.print("%s: method '", resolved_klass->external_name());
1172     resolved_method->signature()->print_as_signature_external_return_type(&ss);
1173     ss.print(" %s(", resolved_method->name()->as_C_string());
1174     resolved_method->signature()->print_as_signature_external_parameters(&ss);
1175     ss.print(")' not found");
1176     Exceptions::fthrow(
1177       THREAD_AND_LOCATION,
1178       vmSymbols::java_lang_NoSuchMethodError(),
1179       "%s", ss.as_string());
1180     return nullptr;
1181   }
1182 
1183   // ensure that invokespecial's interface method reference is in
1184   // a direct superinterface, not an indirect superinterface
1185   Klass* current_klass = link_info.current_klass();
1186   if (current_klass != nullptr && resolved_klass->is_interface()) {
1187     InstanceKlass* klass_to_check = InstanceKlass::cast(current_klass);
1188     // Disable verification for the dynamically-generated reflection bytecodes
1189     // for serialization constructor accessor.
1190     bool is_reflect = klass_to_check->is_subclass_of(
1191                         vmClasses::reflect_SerializationConstructorAccessorImpl_klass());
1192 
1193     if (!is_reflect &&
1194         !klass_to_check->is_same_or_direct_interface(resolved_klass)) {
1195       ResourceMark rm(THREAD);
1196       stringStream ss;
1197       ss.print("Interface method reference: '");
1198       resolved_method->print_external_name(&ss);
1199       ss.print("', is in an indirect superinterface of %s",
1200                current_klass->external_name());
1201       THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1202     }
1203   }
1204 
1205   // check if not static
1206   if (resolved_method->is_static()) {
1207     ResourceMark rm(THREAD);
1208     stringStream ss;
1209     ss.print("Expecting non-static method '");
1210     resolved_method->print_external_name(&ss);
1211     ss.print("'");
1212     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1213   }
1214 
1215   if (log_develop_is_enabled(Trace, itables)) {
1216     trace_method_resolution("invokespecial resolved method: caller-class:",
1217                             current_klass, resolved_klass, resolved_method, true);
1218   }
1219 
1220   return resolved_method;
1221 }
1222 
1223 // throws runtime exceptions
1224 void LinkResolver::runtime_resolve_special_method(CallInfo& result,
1225                                                   const LinkInfo& link_info,
1226                                                   const methodHandle& resolved_method,
1227                                                   Handle recv, TRAPS) {
1228 
1229   Klass* resolved_klass = link_info.resolved_klass();
1230 
1231   // resolved method is selected method unless we have an old-style lookup
1232   // for a superclass method
1233   // Invokespecial for a superinterface, resolved method is selected method,
1234   // no checks for shadowing
1235   methodHandle sel_method(THREAD, resolved_method());
1236 
1237   if (link_info.check_access() &&
1238       // check if the method is not <init>
1239       resolved_method->name() != vmSymbols::object_initializer_name()) {
1240 
1241     Klass* current_klass = link_info.current_klass();
1242 
1243     // Check if the class of the resolved_klass is a superclass
1244     // (not supertype in order to exclude interface classes) of the current class.
1245     // This check is not performed for super.invoke for interface methods
1246     // in super interfaces.
1247     if (current_klass->is_subclass_of(resolved_klass) &&
1248         current_klass != resolved_klass) {
1249       // Lookup super method
1250       Klass* super_klass = current_klass->super();
1251       Method* instance_method = lookup_instance_method_in_klasses(super_klass,
1252                                                      resolved_method->name(),
1253                                                      resolved_method->signature(),
1254                                                      Klass::PrivateLookupMode::find);
1255       sel_method = methodHandle(THREAD, instance_method);
1256 
1257       // check if found
1258       if (sel_method.is_null()) {
1259         ResourceMark rm(THREAD);
1260         stringStream ss;
1261         ss.print("'");
1262         resolved_method->print_external_name(&ss);
1263         ss.print("'");
1264         THROW_MSG(vmSymbols::java_lang_AbstractMethodError(), ss.as_string());
1265       // check loader constraints if found a different method
1266       } else if (link_info.check_loader_constraints() && sel_method() != resolved_method()) {
1267         check_method_loader_constraints(link_info, sel_method, "method", CHECK);
1268       }
1269     }
1270 
1271     // Check that the class of objectref (the receiver) is the current class or interface,
1272     // or a subtype of the current class or interface (the sender), otherwise invokespecial
1273     // throws IllegalAccessError.
1274     // The verifier checks that the sender is a subtype of the class in the I/MR operand.
1275     // The verifier also checks that the receiver is a subtype of the sender, if the sender is
1276     // a class.  If the sender is an interface, the check has to be performed at runtime.
1277     InstanceKlass* sender = InstanceKlass::cast(current_klass);
1278     if (sender->is_interface() && recv.not_null()) {
1279       Klass* receiver_klass = recv->klass();
1280       if (!receiver_klass->is_subtype_of(sender)) {
1281         ResourceMark rm(THREAD);
1282         char buf[500];
1283         jio_snprintf(buf, sizeof(buf),
1284                      "Receiver class %s must be the current class or a subtype of interface %s",
1285                      receiver_klass->external_name(),
1286                      sender->external_name());
1287         THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), buf);
1288       }
1289     }
1290   }
1291 
1292   // check if not static
1293   if (sel_method->is_static()) {
1294     ResourceMark rm(THREAD);
1295     stringStream ss;
1296     ss.print("Expecting non-static method '");
1297     resolved_method->print_external_name(&ss);
1298     ss.print("'");
1299     THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1300   }
1301 
1302   // check if abstract
1303   if (sel_method->is_abstract()) {
1304     ResourceMark rm(THREAD);
1305     stringStream ss;
1306     ss.print("'");
1307     Method::print_external_name(&ss, resolved_klass, sel_method->name(), sel_method->signature());
1308     ss.print("'");
1309     THROW_MSG(vmSymbols::java_lang_AbstractMethodError(), ss.as_string());
1310   }
1311 
1312   if (log_develop_is_enabled(Trace, itables)) {
1313     trace_method_resolution("invokespecial selected method: resolved-class:",
1314                             resolved_klass, resolved_klass, sel_method(), true);
1315   }
1316 
1317   // setup result
1318   result.set_static(resolved_klass, sel_method, CHECK);
1319   JFR_ONLY(Jfr::on_resolution(result, CHECK);)
1320 }
1321 
1322 void LinkResolver::resolve_virtual_call(CallInfo& result, Handle recv, Klass* receiver_klass,
1323                                         const LinkInfo& link_info,
1324                                         bool check_null_and_abstract, TRAPS) {
1325   Method* resolved_method = linktime_resolve_virtual_method(link_info, CHECK);
1326   runtime_resolve_virtual_method(result, methodHandle(THREAD, resolved_method),
1327                                  link_info.resolved_klass(),
1328                                  recv, receiver_klass,
1329                                  check_null_and_abstract, CHECK);
1330 }
1331 
1332 // throws linktime exceptions
1333 Method* LinkResolver::linktime_resolve_virtual_method(const LinkInfo& link_info,
1334                                                            TRAPS) {
1335   // normal method resolution
1336   Method* resolved_method = resolve_method(link_info, Bytecodes::_invokevirtual, CHECK_NULL);
1337 
1338   assert(resolved_method->name() != vmSymbols::object_initializer_name(), "should have been checked in verifier");
1339   assert(resolved_method->name() != vmSymbols::class_initializer_name (), "should have been checked in verifier");
1340 
1341   // check if private interface method
1342   Klass* resolved_klass = link_info.resolved_klass();
1343   Klass* current_klass = link_info.current_klass();
1344 
1345   // This is impossible, if resolve_klass is an interface, we've thrown icce in resolve_method
1346   if (resolved_klass->is_interface() && resolved_method->is_private()) {
1347     ResourceMark rm(THREAD);
1348     stringStream ss;
1349     ss.print("private interface method requires invokespecial, not invokevirtual: method '");
1350     resolved_method->print_external_name(&ss);
1351     ss.print("', caller-class: %s",
1352              (current_klass == nullptr ? "<null>" : current_klass->internal_name()));
1353     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1354   }
1355 
1356   // check if not static
1357   if (resolved_method->is_static()) {
1358     ResourceMark rm(THREAD);
1359     stringStream ss;
1360     ss.print("Expecting non-static method '");
1361     resolved_method->print_external_name(&ss);
1362     ss.print("'");
1363     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1364   }
1365 
1366   if (log_develop_is_enabled(Trace, vtables)) {
1367     trace_method_resolution("invokevirtual resolved method: caller-class:",
1368                             current_klass, resolved_klass, resolved_method, false);
1369   }
1370 
1371   return resolved_method;
1372 }
1373 
1374 // throws runtime exceptions
1375 void LinkResolver::runtime_resolve_virtual_method(CallInfo& result,
1376                                                   const methodHandle& resolved_method,
1377                                                   Klass* resolved_klass,
1378                                                   Handle recv,
1379                                                   Klass* recv_klass,
1380                                                   bool check_null_and_abstract,
1381                                                   TRAPS) {
1382 
1383   // setup default return values
1384   int vtable_index = Method::invalid_vtable_index;
1385   methodHandle selected_method;
1386 
1387   // runtime method resolution
1388   if (check_null_and_abstract && recv.is_null()) { // check if receiver exists
1389     THROW(vmSymbols::java_lang_NullPointerException());
1390   }
1391 
1392   // Virtual methods cannot be resolved before its klass has been linked, for otherwise the Method*'s
1393   // has not been rewritten, and the vtable initialized. Make sure to do this after the nullcheck, since
1394   // a missing receiver might result in a bogus lookup.
1395   assert(resolved_method->method_holder()->is_linked(), "must be linked");
1396 
1397   // do lookup based on receiver klass using the vtable index
1398   if (resolved_method->method_holder()->is_interface()) { // default or miranda method
1399     vtable_index = vtable_index_of_interface_method(resolved_klass, resolved_method);
1400     assert(vtable_index >= 0 , "we should have valid vtable index at this point");
1401 
1402     selected_method = methodHandle(THREAD, recv_klass->method_at_vtable(vtable_index));
1403   } else {
1404     // at this point we are sure that resolved_method is virtual and not
1405     // a default or miranda method; therefore, it must have a valid vtable index.
1406     assert(!resolved_method->has_itable_index(), "");
1407     vtable_index = resolved_method->vtable_index();
1408     // We could get a negative vtable_index of nonvirtual_vtable_index for private
1409     // methods, or for final methods. Private methods never appear in the vtable
1410     // and never override other methods. As an optimization, final methods are
1411     // never put in the vtable, unless they override an existing method.
1412     // So if we do get nonvirtual_vtable_index, it means the selected method is the
1413     // resolved method, and it can never be changed by an override.
1414     if (vtable_index == Method::nonvirtual_vtable_index) {
1415       assert(resolved_method->can_be_statically_bound(), "cannot override this method");
1416       selected_method = resolved_method;
1417     } else {
1418       selected_method = methodHandle(THREAD, recv_klass->method_at_vtable(vtable_index));
1419     }
1420   }
1421 
1422   // check if method exists
1423   if (selected_method.is_null()) {
1424     throw_abstract_method_error(resolved_method, recv_klass, CHECK);
1425   }
1426 
1427   // check if abstract
1428   if (check_null_and_abstract && selected_method->is_abstract()) {
1429     // Pass arguments for generating a verbose error message.
1430     throw_abstract_method_error(resolved_method, selected_method, recv_klass, CHECK);
1431   }
1432 
1433   if (log_develop_is_enabled(Trace, vtables)) {
1434     trace_method_resolution("invokevirtual selected method: receiver-class:",
1435                             recv_klass, resolved_klass, selected_method(),
1436                             false, vtable_index);
1437   }
1438   // setup result
1439   result.set_virtual(resolved_klass, resolved_method, selected_method, vtable_index, CHECK);
1440   JFR_ONLY(Jfr::on_resolution(result, CHECK);)
1441 }
1442 
1443 void LinkResolver::resolve_interface_call(CallInfo& result, Handle recv, Klass* recv_klass,
1444                                           const LinkInfo& link_info,
1445                                           bool check_null_and_abstract, TRAPS) {
1446   // throws linktime exceptions
1447   Method* resolved_method = linktime_resolve_interface_method(link_info, CHECK);
1448   methodHandle mh(THREAD, resolved_method);
1449   runtime_resolve_interface_method(result, mh, link_info.resolved_klass(),
1450                                    recv, recv_klass, check_null_and_abstract, CHECK);
1451 }
1452 
1453 Method* LinkResolver::linktime_resolve_interface_method(const LinkInfo& link_info,
1454                                                              TRAPS) {
1455   // normal interface method resolution
1456   Method* resolved_method = resolve_interface_method(link_info, Bytecodes::_invokeinterface, CHECK_NULL);
1457   assert(resolved_method->name() != vmSymbols::object_initializer_name(), "should have been checked in verifier");
1458   assert(resolved_method->name() != vmSymbols::class_initializer_name (), "should have been checked in verifier");
1459 
1460   return resolved_method;
1461 }
1462 
1463 // throws runtime exceptions
1464 void LinkResolver::runtime_resolve_interface_method(CallInfo& result,
1465                                                     const methodHandle& resolved_method,
1466                                                     Klass* resolved_klass,
1467                                                     Handle recv,
1468                                                     Klass* recv_klass,
1469                                                     bool check_null_and_abstract, TRAPS) {
1470 
1471   // check if receiver exists
1472   if (check_null_and_abstract && recv.is_null()) {
1473     THROW(vmSymbols::java_lang_NullPointerException());
1474   }
1475 
1476   // check if receiver klass implements the resolved interface
1477   if (!recv_klass->is_subtype_of(resolved_klass)) {
1478     ResourceMark rm(THREAD);
1479     char buf[200];
1480     jio_snprintf(buf, sizeof(buf), "Class %s does not implement the requested interface %s",
1481                  recv_klass->external_name(),
1482                  resolved_klass->external_name());
1483     THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
1484   }
1485 
1486   methodHandle selected_method = resolved_method;
1487 
1488   // resolve the method in the receiver class, unless it is private
1489   if (!resolved_method()->is_private()) {
1490     // do lookup based on receiver klass
1491     // This search must match the linktime preparation search for itable initialization
1492     // to correctly enforce loader constraints for interface method inheritance.
1493     // Private methods are skipped as the resolved method was not private.
1494     Method* method = lookup_instance_method_in_klasses(recv_klass,
1495                                                        resolved_method->name(),
1496                                                        resolved_method->signature(),
1497                                                        Klass::PrivateLookupMode::skip);
1498     selected_method = methodHandle(THREAD, method);
1499 
1500     if (selected_method.is_null() && !check_null_and_abstract) {
1501       // In theory this is a harmless placeholder value, but
1502       // in practice leaving in null affects the nsk default method tests.
1503       // This needs further study.
1504       selected_method = resolved_method;
1505     }
1506     // check if method exists
1507     if (selected_method.is_null()) {
1508       // Pass arguments for generating a verbose error message.
1509       throw_abstract_method_error(resolved_method, recv_klass, CHECK);
1510     }
1511     // check access
1512     // Throw Illegal Access Error if selected_method is not public.
1513     if (!selected_method->is_public()) {
1514       ResourceMark rm(THREAD);
1515       stringStream ss;
1516       ss.print("'");
1517       Method::print_external_name(&ss, recv_klass, selected_method->name(), selected_method->signature());
1518       ss.print("'");
1519       THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), ss.as_string());
1520     }
1521     // check if abstract
1522     if (check_null_and_abstract && selected_method->is_abstract()) {
1523       throw_abstract_method_error(resolved_method, selected_method, recv_klass, CHECK);
1524     }
1525   }
1526 
1527   if (log_develop_is_enabled(Trace, itables)) {
1528     trace_method_resolution("invokeinterface selected method: receiver-class:",
1529                             recv_klass, resolved_klass, selected_method(), true);
1530   }
1531   // setup result
1532   if (resolved_method->has_vtable_index()) {
1533     int vtable_index = resolved_method->vtable_index();
1534     log_develop_trace(itables)("  -- vtable index: %d", vtable_index);
1535     assert(vtable_index == selected_method->vtable_index(), "sanity check");
1536     result.set_virtual(resolved_klass, resolved_method, selected_method, vtable_index, CHECK);
1537   } else if (resolved_method->has_itable_index()) {
1538     int itable_index = resolved_method()->itable_index();
1539     log_develop_trace(itables)("  -- itable index: %d", itable_index);
1540     result.set_interface(resolved_klass, resolved_method, selected_method, itable_index, CHECK);
1541   } else {
1542     int index = resolved_method->vtable_index();
1543     log_develop_trace(itables)("  -- non itable/vtable index: %d", index);
1544     assert(index == Method::nonvirtual_vtable_index, "Oops hit another case!");
1545     assert(resolved_method()->is_private() ||
1546            (resolved_method()->is_final() && resolved_method->method_holder() == vmClasses::Object_klass()),
1547            "Should only have non-virtual invokeinterface for private or final-Object methods!");
1548     assert(resolved_method()->can_be_statically_bound(), "Should only have non-virtual invokeinterface for statically bound methods!");
1549     // This sets up the nonvirtual form of "virtual" call (as needed for final and private methods)
1550     result.set_virtual(resolved_klass, resolved_method, resolved_method, index, CHECK);
1551   }
1552   JFR_ONLY(Jfr::on_resolution(result, CHECK);)
1553 }
1554 
1555 
1556 Method* LinkResolver::linktime_resolve_interface_method_or_null(
1557                                                  const LinkInfo& link_info) {
1558   EXCEPTION_MARK;
1559   Method* method_result = linktime_resolve_interface_method(link_info, THREAD);
1560   if (HAS_PENDING_EXCEPTION) {
1561     CLEAR_PENDING_EXCEPTION;
1562     return nullptr;
1563   } else {
1564     return method_result;
1565   }
1566 }
1567 
1568 Method* LinkResolver::linktime_resolve_virtual_method_or_null(
1569                                                  const LinkInfo& link_info) {
1570   EXCEPTION_MARK;
1571   Method* method_result = linktime_resolve_virtual_method(link_info, THREAD);
1572   if (HAS_PENDING_EXCEPTION) {
1573     CLEAR_PENDING_EXCEPTION;
1574     return nullptr;
1575   } else {
1576     return method_result;
1577   }
1578 }
1579 
1580 Method* LinkResolver::resolve_virtual_call_or_null(
1581                                                  Klass* receiver_klass,
1582                                                  const LinkInfo& link_info) {
1583   EXCEPTION_MARK;
1584   CallInfo info;
1585   resolve_virtual_call(info, Handle(), receiver_klass, link_info, false, THREAD);
1586   if (HAS_PENDING_EXCEPTION) {
1587     CLEAR_PENDING_EXCEPTION;
1588     return nullptr;
1589   }
1590   return info.selected_method();
1591 }
1592 
1593 Method* LinkResolver::resolve_interface_call_or_null(
1594                                                  Klass* receiver_klass,
1595                                                  const LinkInfo& link_info) {
1596   EXCEPTION_MARK;
1597   CallInfo info;
1598   resolve_interface_call(info, Handle(), receiver_klass, link_info, false, THREAD);
1599   if (HAS_PENDING_EXCEPTION) {
1600     CLEAR_PENDING_EXCEPTION;
1601     return nullptr;
1602   }
1603   return info.selected_method();
1604 }
1605 
1606 int LinkResolver::resolve_virtual_vtable_index(Klass* receiver_klass,
1607                                                const LinkInfo& link_info) {
1608   EXCEPTION_MARK;
1609   CallInfo info;
1610   resolve_virtual_call(info, Handle(), receiver_klass, link_info,
1611                        /*check_null_or_abstract*/false, THREAD);
1612   if (HAS_PENDING_EXCEPTION) {
1613     CLEAR_PENDING_EXCEPTION;
1614     return Method::invalid_vtable_index;
1615   }
1616   return info.vtable_index();
1617 }
1618 
1619 Method* LinkResolver::resolve_static_call_or_null(const LinkInfo& link_info) {
1620   EXCEPTION_MARK;
1621   CallInfo info;
1622   resolve_static_call(info, link_info, /*initialize_class*/false, THREAD);
1623   if (HAS_PENDING_EXCEPTION) {
1624     CLEAR_PENDING_EXCEPTION;
1625     return nullptr;
1626   }
1627   return info.selected_method();
1628 }
1629 
1630 Method* LinkResolver::resolve_special_call_or_null(const LinkInfo& link_info) {
1631   EXCEPTION_MARK;
1632   CallInfo info;
1633   resolve_special_call(info, Handle(), link_info, THREAD);
1634   if (HAS_PENDING_EXCEPTION) {
1635     CLEAR_PENDING_EXCEPTION;
1636     return nullptr;
1637   }
1638   return info.selected_method();
1639 }
1640 
1641 
1642 
1643 //------------------------------------------------------------------------------------------------------------------------
1644 // ConstantPool entries
1645 
1646 void LinkResolver::resolve_invoke(CallInfo& result, Handle recv, const constantPoolHandle& pool, int index, Bytecodes::Code byte, TRAPS) {
1647   switch (byte) {
1648     case Bytecodes::_invokestatic   : resolve_invokestatic   (result,       pool, index, CHECK); break;
1649     case Bytecodes::_invokespecial  : resolve_invokespecial  (result, recv, pool, index, CHECK); break;
1650     case Bytecodes::_invokevirtual  : resolve_invokevirtual  (result, recv, pool, index, CHECK); break;
1651     case Bytecodes::_invokehandle   : resolve_invokehandle   (result,       pool, index, CHECK); break;
1652     case Bytecodes::_invokedynamic  : resolve_invokedynamic  (result,       pool, index, CHECK); break;
1653     case Bytecodes::_invokeinterface: resolve_invokeinterface(result, recv, pool, index, CHECK); break;
1654     default                         :                                                            break;
1655   }
1656   return;
1657 }
1658 
1659 void LinkResolver::resolve_invoke(CallInfo& result, Handle& recv,
1660                              const methodHandle& attached_method,
1661                              Bytecodes::Code byte, TRAPS) {
1662   Klass* defc = attached_method->method_holder();
1663   Symbol* name = attached_method->name();
1664   Symbol* type = attached_method->signature();
1665   LinkInfo link_info(defc, name, type);
1666   switch(byte) {
1667     case Bytecodes::_invokevirtual:
1668       resolve_virtual_call(result, recv, recv->klass(), link_info,
1669                            /*check_null_and_abstract=*/true, CHECK);
1670       break;
1671     case Bytecodes::_invokeinterface:
1672       resolve_interface_call(result, recv, recv->klass(), link_info,
1673                              /*check_null_and_abstract=*/true, CHECK);
1674       break;
1675     case Bytecodes::_invokestatic:
1676       resolve_static_call(result, link_info, /*initialize_class=*/false, CHECK);
1677       break;
1678     case Bytecodes::_invokespecial:
1679       resolve_special_call(result, recv, link_info, CHECK);
1680       break;
1681     default:
1682       fatal("bad call: %s", Bytecodes::name(byte));
1683       break;
1684   }
1685 }
1686 
1687 void LinkResolver::resolve_invokestatic(CallInfo& result, const constantPoolHandle& pool, int index, TRAPS) {
1688   LinkInfo link_info(pool, index, Bytecodes::_invokestatic, CHECK);
1689   resolve_static_call(result, link_info, /*initialize_class*/true, CHECK);
1690 }
1691 
1692 
1693 void LinkResolver::resolve_invokespecial(CallInfo& result, Handle recv,
1694                                          const constantPoolHandle& pool, int index, TRAPS) {
1695   LinkInfo link_info(pool, index, Bytecodes::_invokespecial, CHECK);
1696   resolve_special_call(result, recv, link_info, CHECK);
1697 }
1698 
1699 
1700 void LinkResolver::resolve_invokevirtual(CallInfo& result, Handle recv,
1701                                           const constantPoolHandle& pool, int index,
1702                                           TRAPS) {
1703 
1704   LinkInfo link_info(pool, index, Bytecodes::_invokevirtual, CHECK);
1705   Klass* recvrKlass = recv.is_null() ? (Klass*)nullptr : recv->klass();
1706   resolve_virtual_call(result, recv, recvrKlass, link_info, /*check_null_or_abstract*/true, CHECK);
1707 }
1708 
1709 
1710 void LinkResolver::resolve_invokeinterface(CallInfo& result, Handle recv, const constantPoolHandle& pool, int index, TRAPS) {
1711   LinkInfo link_info(pool, index, Bytecodes::_invokeinterface, CHECK);
1712   Klass* recvrKlass = recv.is_null() ? (Klass*)nullptr : recv->klass();
1713   resolve_interface_call(result, recv, recvrKlass, link_info, true, CHECK);
1714 }
1715 
1716 bool LinkResolver::resolve_previously_linked_invokehandle(CallInfo& result, const LinkInfo& link_info, const constantPoolHandle& pool, int index, TRAPS) {
1717   ResolvedMethodEntry* method_entry = pool->cache()->resolved_method_entry_at(index);
1718   if (method_entry->method() != nullptr) {
1719     Klass* resolved_klass = link_info.resolved_klass();
1720     methodHandle method(THREAD, method_entry->method());
1721     Handle     appendix(THREAD, pool->cache()->appendix_if_resolved(method_entry));
1722     result.set_handle(resolved_klass, method, appendix, CHECK_false);
1723     JFR_ONLY(Jfr::on_resolution(result, CHECK_false);)
1724     return true;
1725   } else {
1726     return false;
1727   }
1728 }
1729 
1730 void LinkResolver::resolve_invokehandle(CallInfo& result, const constantPoolHandle& pool, int index, TRAPS) {
1731   LinkInfo link_info(pool, index, Bytecodes::_invokehandle, CHECK);
1732   if (log_is_enabled(Info, methodhandles)) {
1733     ResourceMark rm(THREAD);
1734     log_info(methodhandles)("resolve_invokehandle %s %s", link_info.name()->as_C_string(),
1735                             link_info.signature()->as_C_string());
1736   }
1737   { // Check if the call site has been bound already, and short circuit:
1738     bool is_done = resolve_previously_linked_invokehandle(result, link_info, pool, index, CHECK);
1739     if (is_done) return;
1740   }
1741   resolve_handle_call(result, link_info, CHECK);
1742 }
1743 
1744 void LinkResolver::resolve_handle_call(CallInfo& result,
1745                                        const LinkInfo& link_info,
1746                                        TRAPS) {
1747   // JSR 292:  this must be an implicitly generated method MethodHandle.invokeExact(*...) or similar
1748   Klass* resolved_klass = link_info.resolved_klass();
1749   assert(resolved_klass == vmClasses::MethodHandle_klass() ||
1750          resolved_klass == vmClasses::VarHandle_klass(), "");
1751   assert(MethodHandles::is_signature_polymorphic_name(link_info.name()), "");
1752   Handle resolved_appendix;
1753   Method* m = lookup_polymorphic_method(link_info, &resolved_appendix, CHECK);
1754   methodHandle resolved_method(THREAD, m);
1755 
1756   if (link_info.check_access()) {
1757     Symbol* name = link_info.name();
1758     vmIntrinsics::ID iid = MethodHandles::signature_polymorphic_name_id(name);
1759     if (MethodHandles::is_signature_polymorphic_intrinsic(iid)) {
1760       // Check if method can be accessed by the referring class.
1761       // MH.linkTo* invocations are not rewritten to invokehandle.
1762       assert(iid == vmIntrinsicID::_invokeBasic, "%s", vmIntrinsics::name_at(iid));
1763 
1764       Klass* current_klass = link_info.current_klass();
1765       assert(current_klass != nullptr , "current_klass should not be null");
1766       check_method_accessability(current_klass,
1767                                  resolved_klass,
1768                                  resolved_method->method_holder(),
1769                                  resolved_method,
1770                                  CHECK);
1771     } else {
1772       // Java code is free to arbitrarily link signature-polymorphic invokers.
1773       assert(iid == vmIntrinsics::_invokeGeneric, "not an invoker: %s", vmIntrinsics::name_at(iid));
1774       assert(MethodHandles::is_signature_polymorphic_public_name(resolved_klass, name), "not public");
1775     }
1776   }
1777   result.set_handle(resolved_klass, resolved_method, resolved_appendix, CHECK);
1778   JFR_ONLY(Jfr::on_resolution(result, CHECK);)
1779 }
1780 
1781 void LinkResolver::resolve_invokedynamic(CallInfo& result, const constantPoolHandle& pool, int indy_index, TRAPS) {
1782   int pool_index = pool->resolved_indy_entry_at(indy_index)->constant_pool_index();
1783 
1784   // Resolve the bootstrap specifier (BSM + optional arguments).
1785   BootstrapInfo bootstrap_specifier(pool, pool_index, indy_index);
1786 
1787   // Check if CallSite has been bound already or failed already, and short circuit:
1788   {
1789     bool is_done = bootstrap_specifier.resolve_previously_linked_invokedynamic(result, CHECK);
1790     if (is_done) return;
1791   }
1792 
1793   // The initial step in Call Site Specifier Resolution is to resolve the symbolic
1794   // reference to a method handle which will be the bootstrap method for a dynamic
1795   // call site.  If resolution for the java.lang.invoke.MethodHandle for the bootstrap
1796   // method fails, then a MethodHandleInError is stored at the corresponding bootstrap
1797   // method's CP index for the CONSTANT_MethodHandle_info.
1798   // Any subsequent invokedynamic instruction which shares
1799   // this bootstrap method will encounter the resolution of MethodHandleInError.
1800 
1801   resolve_dynamic_call(result, bootstrap_specifier, CHECK);
1802 
1803   LogTarget(Debug, methodhandles, indy) lt_indy;
1804   if (lt_indy.is_enabled()) {
1805     LogStream ls(lt_indy);
1806     bootstrap_specifier.print_msg_on(&ls, "resolve_invokedynamic");
1807   }
1808 
1809   // The returned linkage result is provisional up to the moment
1810   // the interpreter or runtime performs a serialized check of
1811   // the relevant ResolvedIndyEntry::method field.  This is done by the caller
1812   // of this method, via CPC::set_dynamic_call, which uses
1813   // a lock to do the final serialization of updates
1814   // to ResolvedIndyEntry state, including method.
1815 
1816   // Log dynamic info to CDS classlist.
1817   ArchiveUtils::log_to_classlist(&bootstrap_specifier, CHECK);
1818 }
1819 
1820 void LinkResolver::resolve_dynamic_call(CallInfo& result,
1821                                         BootstrapInfo& bootstrap_specifier,
1822                                         TRAPS) {
1823   // JSR 292:  this must resolve to an implicitly generated method
1824   // such as MH.linkToCallSite(*...) or some other call-site shape.
1825   // The appendix argument is likely to be a freshly-created CallSite.
1826   // It may also be a MethodHandle from an unwrapped ConstantCallSite,
1827   // or any other reference.  The resolved_method as well as the appendix
1828   // are both recorded together via CallInfo::set_handle.
1829   SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);
1830   Exceptions::wrap_dynamic_exception(/* is_indy */ true, THREAD);
1831 
1832   if (HAS_PENDING_EXCEPTION) {
1833     if (!PENDING_EXCEPTION->is_a(vmClasses::LinkageError_klass())) {
1834       // Let any random low-level IE or SOE or OOME just bleed through.
1835       // Basically we pretend that the bootstrap method was never called,
1836       // if it fails this way:  We neither record a successful linkage,
1837       // nor do we memorize a LE for posterity.
1838       return;
1839     }
1840     // JVMS 5.4.3 says: If an attempt by the Java Virtual Machine to resolve
1841     // a symbolic reference fails because an error is thrown that is an
1842     // instance of LinkageError (or a subclass), then subsequent attempts to
1843     // resolve the reference always fail with the same error that was thrown
1844     // as a result of the initial resolution attempt.
1845     bool recorded_res_status = bootstrap_specifier.save_and_throw_indy_exc(CHECK);
1846     if (!recorded_res_status) {
1847       // Another thread got here just before we did.  So, either use the method
1848       // that it resolved or throw the LinkageError exception that it threw.
1849       bool is_done = bootstrap_specifier.resolve_previously_linked_invokedynamic(result, CHECK);
1850       if (is_done) return;
1851     }
1852     assert(bootstrap_specifier.pool()->resolved_indy_entry_at(bootstrap_specifier.indy_index())->resolution_failed(),
1853           "Resolution should have failed");
1854   }
1855 
1856   bootstrap_specifier.resolve_newly_linked_invokedynamic(result, CHECK);
1857   // Exceptions::wrap_dynamic_exception not used because
1858   // set_handle doesn't throw linkage errors
1859   JFR_ONLY(Jfr::on_resolution(result, CHECK);)
1860 }
1861 
1862 // Selected method is abstract.
1863 void LinkResolver::throw_abstract_method_error(const methodHandle& resolved_method,
1864                                                const methodHandle& selected_method,
1865                                                Klass *recv_klass, TRAPS) {
1866   Klass *resolved_klass = resolved_method->method_holder();
1867   ResourceMark rm(THREAD);
1868   stringStream ss;
1869 
1870   if (recv_klass != nullptr) {
1871     ss.print("Receiver class %s does not define or inherit an "
1872              "implementation of the",
1873              recv_klass->external_name());
1874   } else {
1875     ss.print("Missing implementation of");
1876   }
1877 
1878   assert(resolved_method.not_null(), "Sanity");
1879   ss.print(" resolved method '%s%s",
1880            resolved_method->is_abstract() ? "abstract " : "",
1881            resolved_method->is_private()  ? "private "  : "");
1882   resolved_method->signature()->print_as_signature_external_return_type(&ss);
1883   ss.print(" %s(", resolved_method->name()->as_C_string());
1884   resolved_method->signature()->print_as_signature_external_parameters(&ss);
1885   ss.print(")' of %s %s.",
1886            resolved_klass->external_kind(),
1887            resolved_klass->external_name());
1888 
1889   if (selected_method.not_null() && !(resolved_method == selected_method)) {
1890     ss.print(" Selected method is '%s%s",
1891              selected_method->is_abstract() ? "abstract " : "",
1892              selected_method->is_private()  ? "private "  : "");
1893     selected_method->print_external_name(&ss);
1894     ss.print("'.");
1895   }
1896 
1897   THROW_MSG(vmSymbols::java_lang_AbstractMethodError(), ss.as_string());
1898 }