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