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