1 /*
   2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "cds/archiveUtils.hpp"
  28 #include "classfile/defaultMethods.hpp"
  29 #include "classfile/javaClasses.hpp"
  30 #include "classfile/resolutionErrors.hpp"
  31 #include "classfile/symbolTable.hpp"
  32 #include "classfile/systemDictionary.hpp"
  33 #include "classfile/vmClasses.hpp"
  34 #include "classfile/vmSymbols.hpp"
  35 #include "compiler/compilationPolicy.hpp"
  36 #include "compiler/compileBroker.hpp"
  37 #include "gc/shared/collectedHeap.inline.hpp"
  38 #include "interpreter/bootstrapInfo.hpp"
  39 #include "interpreter/bytecode.hpp"
  40 #include "interpreter/interpreterRuntime.hpp"
  41 #include "interpreter/linkResolver.hpp"
  42 #include "logging/log.hpp"
  43 #include "logging/logStream.hpp"
  44 #include "memory/resourceArea.hpp"
  45 #include "oops/constantPool.hpp"
  46 #include "oops/cpCache.inline.hpp"
  47 #include "oops/instanceKlass.inline.hpp"
  48 #include "oops/klass.inline.hpp"
  49 #include "oops/method.hpp"
  50 #include "oops/objArrayKlass.hpp"
  51 #include "oops/objArrayOop.hpp"
  52 #include "oops/oop.inline.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/reflection.hpp"
  58 #include "runtime/safepointVerifiers.hpp"
  59 #include "runtime/signature.hpp"
  60 #include "runtime/thread.inline.hpp"
  61 #include "runtime/vmThread.hpp"
  62 
  63 //------------------------------------------------------------------------------------------------------------------------
  64 // Implementation of CallInfo
  65 
  66 
  67 void CallInfo::set_static(Klass* resolved_klass, const methodHandle& resolved_method, TRAPS) {
  68   int vtable_index = Method::nonvirtual_vtable_index;
  69   set_common(resolved_klass, resolved_method, resolved_method, CallInfo::direct_call, vtable_index, CHECK);
  70 }
  71 
  72 
  73 void CallInfo::set_interface(Klass* resolved_klass,
  74                              const methodHandle& resolved_method,
  75                              const methodHandle& selected_method,
  76                              int itable_index, TRAPS) {
  77   // This is only called for interface methods. If the resolved_method
  78   // comes from java/lang/Object, it can be the subject of a virtual call, so
  79   // we should pick the vtable index from the resolved method.
  80   // In that case, the caller must call set_virtual instead of set_interface.
  81   assert(resolved_method->method_holder()->is_interface(), "");
  82   assert(itable_index == resolved_method()->itable_index(), "");
  83   set_common(resolved_klass, resolved_method, selected_method, CallInfo::itable_call, itable_index, CHECK);
  84 }
  85 
  86 void CallInfo::set_virtual(Klass* resolved_klass,
  87                            const methodHandle& resolved_method,
  88                            const methodHandle& selected_method,
  89                            int vtable_index, TRAPS) {
  90   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index, "valid index");
  91   assert(vtable_index < 0 || !resolved_method->has_vtable_index() || vtable_index == resolved_method->vtable_index(), "");
  92   CallKind kind = (vtable_index >= 0 && !resolved_method->can_be_statically_bound() ? CallInfo::vtable_call : CallInfo::direct_call);
  93   set_common(resolved_klass, resolved_method, selected_method, kind, vtable_index, CHECK);
  94   assert(!resolved_method->is_compiled_lambda_form(), "these must be handled via an invokehandle call");
  95 }
  96 
  97 void CallInfo::set_handle(const methodHandle& resolved_method,
  98                           Handle resolved_appendix, TRAPS) {
  99   set_handle(vmClasses::MethodHandle_klass(), resolved_method, resolved_appendix, CHECK);
 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 == NULL) { // 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() != NULL, "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, TRAPS) {
 233    // resolve klass
 234   _resolved_klass = pool->klass_ref_at(index, CHECK);
 235 
 236   // Get name, signature, and static klass
 237   _name          = pool->name_ref_at(index);
 238   _signature     = pool->signature_ref_at(index);
 239   _tag           = pool->tag_ref_at(index);
 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, TRAPS) {
 249    // resolve klass
 250   _resolved_klass = pool->klass_ref_at(index, CHECK);
 251 
 252   // Get name, signature, and static klass
 253   _name          = pool->name_ref_at(index);
 254   _signature     = pool->signature_ref_at(index);
 255   _tag           = pool->tag_ref_at(index);
 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 == NULL ? "(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 == NULL) {
 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 != NULL &&
 350       ik->is_interface() &&
 351       (result->is_static() || !result->is_public()) &&
 352       result->method_holder() == vmClasses::Object_klass()) {
 353     result = NULL;
 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 == NULL) {
 359     result = ik->find_method(name, signature);
 360   }
 361 
 362   if (result == NULL) {
 363     Array<Method*>* default_methods = ik->default_methods();
 364     if (default_methods != NULL) {
 365       result = InstanceKlass::find_method(default_methods, name, signature);
 366     }
 367   }
 368 
 369   if (checkpolymorphism && result != NULL) {
 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 NULL;
 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 != NULL && result->is_static() && result->method_holder()->super() != NULL) {
 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 == NULL) {
 398     Array<Method*>* default_methods = InstanceKlass::cast(klass)->default_methods();
 399     if (default_methods != NULL) {
 400       result = InstanceKlass::find_method(default_methods, name, signature);
 401       assert(result == NULL || !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 != NULL) {
 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 != NULL) {
 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 == NULL || 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       Handle method_type;
 480       Method* result = SystemDictionary::find_method_handle_invoker(
 481                                                             klass,
 482                                                             name,
 483                                                             full_signature,
 484                                                             link_info.current_klass(),
 485                                                             &appendix,
 486                                                             CHECK_NULL);
 487       if (lt_mh.is_enabled()) {
 488         LogStream ls(lt_mh);
 489         ls.print("lookup_polymorphic_method => (via Java) ");
 490         result->print_on(&ls);
 491         ls.print("  lookup_polymorphic_method => appendix = ");
 492         appendix.is_null() ? ls.print_cr("(none)") : appendix->print_on(&ls);
 493       }
 494       if (result != NULL) {
 495 #ifdef ASSERT
 496         ResourceMark rm(THREAD);
 497 
 498         TempNewSymbol basic_signature =
 499           MethodHandles::lookup_basic_type_signature(full_signature);
 500         int actual_size_of_params = result->size_of_parameters();
 501         int expected_size_of_params = ArgumentSizeComputer(basic_signature).size();
 502         // +1 for MethodHandle.this, +1 for trailing MethodType
 503         if (!MethodHandles::is_signature_polymorphic_static(iid))  expected_size_of_params += 1;
 504         if (appendix.not_null())                                   expected_size_of_params += 1;
 505         if (actual_size_of_params != expected_size_of_params) {
 506           tty->print_cr("*** basic_signature=%s", basic_signature->as_C_string());
 507           tty->print_cr("*** result for %s: ", vmIntrinsics::name_at(iid));
 508           result->print();
 509         }
 510         assert(actual_size_of_params == expected_size_of_params,
 511                "%d != %d", actual_size_of_params, expected_size_of_params);
 512 #endif //ASSERT
 513 
 514         assert(appendix_result_or_null != NULL, "");
 515         (*appendix_result_or_null) = appendix;
 516       }
 517       return result;
 518     }
 519   }
 520   return NULL;
 521 }
 522 
 523 static void print_nest_host_error_on(stringStream* ss, Klass* ref_klass, Klass* sel_klass) {
 524   assert(ref_klass->is_instance_klass(), "must be");
 525   assert(sel_klass->is_instance_klass(), "must be");
 526   InstanceKlass* ref_ik = InstanceKlass::cast(ref_klass);
 527   InstanceKlass* sel_ik = InstanceKlass::cast(sel_klass);
 528   const char* nest_host_error_1 = ref_ik->nest_host_error();
 529   const char* nest_host_error_2 = sel_ik->nest_host_error();
 530   if (nest_host_error_1 != NULL || nest_host_error_2 != NULL) {
 531     ss->print(", (%s%s%s)",
 532               (nest_host_error_1 != NULL) ? nest_host_error_1 : "",
 533               (nest_host_error_1 != NULL && nest_host_error_2 != NULL) ? ", " : "",
 534               (nest_host_error_2 != NULL) ? nest_host_error_2 : "");
 535   }
 536 }
 537 
 538 void LinkResolver::check_method_accessability(Klass* ref_klass,
 539                                               Klass* resolved_klass,
 540                                               Klass* sel_klass,
 541                                               const methodHandle& sel_method,
 542                                               TRAPS) {
 543 
 544   AccessFlags flags = sel_method->access_flags();
 545 
 546   // Special case:  arrays always override "clone". JVMS 2.15.
 547   // If the resolved klass is an array class, and the declaring class
 548   // is java.lang.Object and the method is "clone", set the flags
 549   // to public.
 550   //
 551   // We'll check for the method name first, as that's most likely
 552   // to be false (so we'll short-circuit out of these tests).
 553   if (sel_method->name() == vmSymbols::clone_name() &&
 554       sel_klass == vmClasses::Object_klass() &&
 555       resolved_klass->is_array_klass()) {
 556     // We need to change "protected" to "public".
 557     assert(flags.is_protected(), "clone not protected?");
 558     jint new_flags = flags.as_int();
 559     new_flags = new_flags & (~JVM_ACC_PROTECTED);
 560     new_flags = new_flags | JVM_ACC_PUBLIC;
 561     flags.set_flags(new_flags);
 562   }
 563 //  assert(extra_arg_result_or_null != NULL, "must be able to return extra argument");
 564 
 565   bool can_access = Reflection::verify_member_access(ref_klass,
 566                                                      resolved_klass,
 567                                                      sel_klass,
 568                                                      flags,
 569                                                      true, false, CHECK);
 570   // Any existing exceptions that may have been thrown
 571   // have been allowed to propagate.
 572   if (!can_access) {
 573     ResourceMark rm(THREAD);
 574     stringStream ss;
 575     bool same_module = (sel_klass->module() == ref_klass->module());
 576     ss.print("class %s tried to access %s%s%smethod '%s' (%s%s%s)",
 577              ref_klass->external_name(),
 578              sel_method->is_abstract()  ? "abstract "  : "",
 579              sel_method->is_protected() ? "protected " : "",
 580              sel_method->is_private()   ? "private "   : "",
 581              sel_method->external_name(),
 582              (same_module) ? ref_klass->joint_in_module_of_loader(sel_klass) : ref_klass->class_in_module_of_loader(),
 583              (same_module) ? "" : "; ",
 584              (same_module) ? "" : sel_klass->class_in_module_of_loader()
 585              );
 586 
 587     // For private access see if there was a problem with nest host
 588     // resolution, and if so report that as part of the message.
 589     if (sel_method->is_private()) {
 590       print_nest_host_error_on(&ss, ref_klass, sel_klass);
 591     }
 592 
 593     Exceptions::fthrow(THREAD_AND_LOCATION,
 594                        vmSymbols::java_lang_IllegalAccessError(),
 595                        "%s",
 596                        ss.as_string()
 597                        );
 598     return;
 599   }
 600 }
 601 
 602 Method* LinkResolver::resolve_method_statically(Bytecodes::Code code,
 603                                                 const constantPoolHandle& pool, int index, TRAPS) {
 604   // This method is used only
 605   // (1) in C2 from InlineTree::ok_to_inline (via ciMethod::check_call),
 606   // and
 607   // (2) in Bytecode_invoke::static_target
 608   // It appears to fail when applied to an invokeinterface call site.
 609   // FIXME: Remove this method and ciMethod::check_call; refactor to use the other LinkResolver entry points.
 610   // resolve klass
 611   if (code == Bytecodes::_invokedynamic) {
 612     Klass* resolved_klass = vmClasses::MethodHandle_klass();
 613     Symbol* method_name = vmSymbols::invoke_name();
 614     Symbol* method_signature = pool->signature_ref_at(index);
 615     Klass*  current_klass = pool->pool_holder();
 616     LinkInfo link_info(resolved_klass, method_name, method_signature, current_klass);
 617     return resolve_method(link_info, code, THREAD);
 618   }
 619 
 620   LinkInfo link_info(pool, index, methodHandle(), CHECK_NULL);
 621   Klass* resolved_klass = link_info.resolved_klass();
 622 
 623   if (pool->has_preresolution()
 624       || (resolved_klass == vmClasses::MethodHandle_klass() &&
 625           MethodHandles::is_signature_polymorphic_name(resolved_klass, link_info.name()))) {
 626     Method* result = ConstantPool::method_at_if_loaded(pool, index);
 627     if (result != NULL) {
 628       return result;
 629     }
 630   }
 631 
 632   if (code == Bytecodes::_invokeinterface) {
 633     return resolve_interface_method(link_info, code, THREAD);
 634   } else if (code == Bytecodes::_invokevirtual) {
 635     return resolve_method(link_info, code, THREAD);
 636   } else if (!resolved_klass->is_interface()) {
 637     return resolve_method(link_info, code, THREAD);
 638   } else {
 639     return resolve_interface_method(link_info, code, THREAD);
 640   }
 641 }
 642 
 643 // Check and print a loader constraint violation message for method or interface method
 644 void LinkResolver::check_method_loader_constraints(const LinkInfo& link_info,
 645                                                    const methodHandle& resolved_method,
 646                                                    const char* method_type, TRAPS) {
 647   Handle current_loader(THREAD, link_info.current_klass()->class_loader());
 648   Handle resolved_loader(THREAD, resolved_method->method_holder()->class_loader());
 649 
 650   ResourceMark rm(THREAD);
 651   Symbol* failed_type_symbol =
 652     SystemDictionary::check_signature_loaders(link_info.signature(),
 653                                               /*klass_being_linked*/ NULL, // We are not linking class
 654                                               current_loader,
 655                                               resolved_loader, true);
 656   if (failed_type_symbol != NULL) {
 657     Klass* current_class = link_info.current_klass();
 658     ClassLoaderData* current_loader_data = current_class->class_loader_data();
 659     assert(current_loader_data != NULL, "current class has no class loader data");
 660     Klass* resolved_method_class = resolved_method->method_holder();
 661     ClassLoaderData* target_loader_data = resolved_method_class->class_loader_data();
 662     assert(target_loader_data != NULL, "resolved method's class has no class loader data");
 663 
 664     stringStream ss;
 665     ss.print("loader constraint violation: when resolving %s '", method_type);
 666     Method::print_external_name(&ss, link_info.resolved_klass(), link_info.name(), link_info.signature());
 667     ss.print("' the class loader %s of the current class, %s,"
 668              " and the class loader %s for the method's defining class, %s, have"
 669              " different Class objects for the type %s used in the signature (%s; %s)",
 670              current_loader_data->loader_name_and_id(),
 671              current_class->name()->as_C_string(),
 672              target_loader_data->loader_name_and_id(),
 673              resolved_method_class->name()->as_C_string(),
 674              failed_type_symbol->as_C_string(),
 675              current_class->class_in_module_of_loader(false, true),
 676              resolved_method_class->class_in_module_of_loader(false, true));
 677     THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());
 678   }
 679 }
 680 
 681 void LinkResolver::check_field_loader_constraints(Symbol* field, Symbol* sig,
 682                                                   Klass* current_klass,
 683                                                   Klass* sel_klass, TRAPS) {
 684   Handle ref_loader(THREAD, current_klass->class_loader());
 685   Handle sel_loader(THREAD, sel_klass->class_loader());
 686 
 687   ResourceMark rm(THREAD);  // needed for check_signature_loaders
 688   Symbol* failed_type_symbol =
 689     SystemDictionary::check_signature_loaders(sig,
 690                                               /*klass_being_linked*/ NULL, // We are not linking class
 691                                               ref_loader, sel_loader,
 692                                               false);
 693   if (failed_type_symbol != NULL) {
 694     stringStream ss;
 695     const char* failed_type_name = failed_type_symbol->as_klass_external_name();
 696 
 697     ss.print("loader constraint violation: when resolving field \"%s\" of type %s, "
 698              "the class loader %s of the current class, %s, "
 699              "and the class loader %s for the field's defining %s, %s, "
 700              "have different Class objects for type %s (%s; %s)",
 701              field->as_C_string(),
 702              failed_type_name,
 703              current_klass->class_loader_data()->loader_name_and_id(),
 704              current_klass->external_name(),
 705              sel_klass->class_loader_data()->loader_name_and_id(),
 706              sel_klass->external_kind(),
 707              sel_klass->external_name(),
 708              failed_type_name,
 709              current_klass->class_in_module_of_loader(false, true),
 710              sel_klass->class_in_module_of_loader(false, true));
 711     THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());
 712   }
 713 }
 714 
 715 Method* LinkResolver::resolve_method(const LinkInfo& link_info,
 716                                      Bytecodes::Code code, TRAPS) {
 717 
 718   Handle nested_exception;
 719   Klass* resolved_klass = link_info.resolved_klass();
 720 
 721   // 1. For invokevirtual, cannot call an interface method
 722   if (code == Bytecodes::_invokevirtual && resolved_klass->is_interface()) {
 723     ResourceMark rm(THREAD);
 724     char buf[200];
 725     jio_snprintf(buf, sizeof(buf), "Found interface %s, but class was expected",
 726         resolved_klass->external_name());
 727     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
 728   }
 729 
 730   // 2. check constant pool tag for called method - must be JVM_CONSTANT_Methodref
 731   if (!link_info.tag().is_invalid() && !link_info.tag().is_method()) {
 732     ResourceMark rm(THREAD);
 733     stringStream ss;
 734     ss.print("Method '");
 735     Method::print_external_name(&ss, link_info.resolved_klass(), link_info.name(), link_info.signature());
 736     ss.print("' must be Methodref constant");
 737     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
 738   }
 739 
 740   // 3. lookup method in resolved klass and its super klasses
 741   methodHandle resolved_method(THREAD, lookup_method_in_klasses(link_info, true, false));
 742 
 743   // 4. lookup method in all the interfaces implemented by the resolved klass
 744   if (resolved_method.is_null() && !resolved_klass->is_array_klass()) { // not found in the class hierarchy
 745     resolved_method = methodHandle(THREAD, lookup_method_in_interfaces(link_info));
 746 
 747     if (resolved_method.is_null()) {
 748       // JSR 292:  see if this is an implicitly generated method MethodHandle.linkToVirtual(*...), etc
 749       Method* method = lookup_polymorphic_method(link_info, (Handle*)NULL, THREAD);
 750       resolved_method = methodHandle(THREAD, method);
 751       if (HAS_PENDING_EXCEPTION) {
 752         nested_exception = Handle(THREAD, PENDING_EXCEPTION);
 753         CLEAR_PENDING_EXCEPTION;
 754       }
 755     }
 756   }
 757 
 758   // 5. method lookup failed
 759   if (resolved_method.is_null()) {
 760     ResourceMark rm(THREAD);
 761     stringStream ss;
 762     ss.print("'");
 763     Method::print_external_name(&ss, resolved_klass, link_info.name(), link_info.signature());
 764     ss.print("'");
 765     THROW_MSG_CAUSE_(vmSymbols::java_lang_NoSuchMethodError(),
 766                      ss.as_string(), nested_exception, NULL);
 767   }
 768 
 769   // 6. access checks, access checking may be turned off when calling from within the VM.
 770   Klass* current_klass = link_info.current_klass();
 771   if (link_info.check_access()) {
 772     assert(current_klass != NULL , "current_klass should not be null");
 773 
 774     // check if method can be accessed by the referring class
 775     check_method_accessability(current_klass,
 776                                resolved_klass,
 777                                resolved_method->method_holder(),
 778                                resolved_method,
 779                                CHECK_NULL);
 780   }
 781   if (link_info.check_loader_constraints()) {
 782     // check loader constraints
 783     check_method_loader_constraints(link_info, resolved_method, "method", CHECK_NULL);
 784   }
 785 
 786   return resolved_method();
 787 }
 788 
 789 static void trace_method_resolution(const char* prefix,
 790                                     Klass* klass,
 791                                     Klass* resolved_klass,
 792                                     Method* method,
 793                                     bool logitables,
 794                                     int index = -1) {
 795 #ifndef PRODUCT
 796   ResourceMark rm;
 797   Log(itables) logi;
 798   LogStream lsi(logi.trace());
 799   Log(vtables) logv;
 800   LogStream lsv(logv.trace());
 801   outputStream* st;
 802   if (logitables) {
 803     st = &lsi;
 804   } else {
 805     st = &lsv;
 806   }
 807   st->print("%s%s, compile-time-class:%s, method:%s, method_holder:%s, access_flags: ",
 808             prefix,
 809             (klass == NULL ? "<NULL>" : klass->internal_name()),
 810             (resolved_klass == NULL ? "<NULL>" : resolved_klass->internal_name()),
 811             Method::name_and_sig_as_C_string(resolved_klass,
 812                                              method->name(),
 813                                              method->signature()),
 814             method->method_holder()->internal_name());
 815   method->print_linkage_flags(st);
 816   if (index != -1) {
 817     st->print("vtable_index:%d", index);
 818   }
 819   st->cr();
 820 #endif // PRODUCT
 821 }
 822 
 823 // Do linktime resolution of a method in the interface within the context of the specied bytecode.
 824 Method* LinkResolver::resolve_interface_method(const LinkInfo& link_info, Bytecodes::Code code, TRAPS) {
 825 
 826   Klass* resolved_klass = link_info.resolved_klass();
 827 
 828   // check if klass is interface
 829   if (!resolved_klass->is_interface()) {
 830     ResourceMark rm(THREAD);
 831     char buf[200];
 832     jio_snprintf(buf, sizeof(buf), "Found class %s, but interface was expected", resolved_klass->external_name());
 833     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
 834   }
 835 
 836   // check constant pool tag for called method - must be JVM_CONSTANT_InterfaceMethodref
 837   if (!link_info.tag().is_invalid() && !link_info.tag().is_interface_method()) {
 838     ResourceMark rm(THREAD);
 839     stringStream ss;
 840     ss.print("Method '");
 841     Method::print_external_name(&ss, link_info.resolved_klass(), link_info.name(), link_info.signature());
 842     ss.print("' must be InterfaceMethodref constant");
 843     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
 844   }
 845 
 846   // lookup method in this interface or its super, java.lang.Object
 847   // JDK8: also look for static methods
 848   methodHandle resolved_method(THREAD, lookup_method_in_klasses(link_info, false, true));
 849 
 850   if (resolved_method.is_null() && !resolved_klass->is_array_klass()) {
 851     // lookup method in all the super-interfaces
 852     resolved_method = methodHandle(THREAD, lookup_method_in_interfaces(link_info));
 853   }
 854 
 855   if (resolved_method.is_null()) {
 856     // no method found
 857     ResourceMark rm(THREAD);
 858     stringStream ss;
 859     ss.print("'");
 860     Method::print_external_name(&ss, resolved_klass, link_info.name(), link_info.signature());
 861     ss.print("'");
 862     THROW_MSG_NULL(vmSymbols::java_lang_NoSuchMethodError(), ss.as_string());
 863   }
 864 
 865   if (link_info.check_access()) {
 866     // JDK8 adds non-public interface methods, and accessability check requirement
 867     Klass* current_klass = link_info.current_klass();
 868 
 869     assert(current_klass != NULL , "current_klass should not be null");
 870 
 871     // check if method can be accessed by the referring class
 872     check_method_accessability(current_klass,
 873                                resolved_klass,
 874                                resolved_method->method_holder(),
 875                                resolved_method,
 876                                CHECK_NULL);
 877   }
 878   if (link_info.check_loader_constraints()) {
 879     check_method_loader_constraints(link_info, resolved_method, "interface method", CHECK_NULL);
 880   }
 881 
 882   if (code != Bytecodes::_invokestatic && resolved_method->is_static()) {
 883     ResourceMark rm(THREAD);
 884     stringStream ss;
 885     ss.print("Expected instance not static method '");
 886     Method::print_external_name(&ss, resolved_klass,
 887                                 resolved_method->name(), resolved_method->signature());
 888     ss.print("'");
 889     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
 890   }
 891 
 892   if (log_develop_is_enabled(Trace, itables)) {
 893     char buf[200];
 894     jio_snprintf(buf, sizeof(buf), "%s resolved interface method: caller-class:",
 895                  Bytecodes::name(code));
 896     trace_method_resolution(buf, link_info.current_klass(), resolved_klass, resolved_method(), true);
 897   }
 898 
 899   return resolved_method();
 900 }
 901 
 902 //------------------------------------------------------------------------------------------------------------------------
 903 // Field resolution
 904 
 905 void LinkResolver::check_field_accessability(Klass* ref_klass,
 906                                              Klass* resolved_klass,
 907                                              Klass* sel_klass,
 908                                              const fieldDescriptor& fd,
 909                                              TRAPS) {
 910   bool can_access = Reflection::verify_member_access(ref_klass,
 911                                                      resolved_klass,
 912                                                      sel_klass,
 913                                                      fd.access_flags(),
 914                                                      true, false, CHECK);
 915   // Any existing exceptions that may have been thrown, for example LinkageErrors
 916   // from nest-host resolution, have been allowed to propagate.
 917   if (!can_access) {
 918     bool same_module = (sel_klass->module() == ref_klass->module());
 919     ResourceMark rm(THREAD);
 920     stringStream ss;
 921     ss.print("class %s tried to access %s%sfield %s.%s (%s%s%s)",
 922              ref_klass->external_name(),
 923              fd.is_protected() ? "protected " : "",
 924              fd.is_private()   ? "private "   : "",
 925              sel_klass->external_name(),
 926              fd.name()->as_C_string(),
 927              (same_module) ? ref_klass->joint_in_module_of_loader(sel_klass) : ref_klass->class_in_module_of_loader(),
 928              (same_module) ? "" : "; ",
 929              (same_module) ? "" : sel_klass->class_in_module_of_loader()
 930              );
 931     // For private access see if there was a problem with nest host
 932     // resolution, and if so report that as part of the message.
 933     if (fd.is_private()) {
 934       print_nest_host_error_on(&ss, ref_klass, sel_klass);
 935     }
 936     Exceptions::fthrow(THREAD_AND_LOCATION,
 937                        vmSymbols::java_lang_IllegalAccessError(),
 938                        "%s",
 939                        ss.as_string()
 940                        );
 941     return;
 942   }
 943 }
 944 
 945 void LinkResolver::resolve_field_access(fieldDescriptor& fd, const constantPoolHandle& pool, int index, const methodHandle& method, Bytecodes::Code byte, TRAPS) {
 946   LinkInfo link_info(pool, index, method, CHECK);
 947   resolve_field(fd, link_info, byte, true, CHECK);
 948 }
 949 
 950 void LinkResolver::resolve_field(fieldDescriptor& fd,
 951                                  const LinkInfo& link_info,
 952                                  Bytecodes::Code byte, bool initialize_class,
 953                                  TRAPS) {
 954   assert(byte == Bytecodes::_getstatic || byte == Bytecodes::_putstatic ||
 955          byte == Bytecodes::_getfield  || byte == Bytecodes::_putfield  ||
 956          byte == Bytecodes::_nofast_getfield  || byte == Bytecodes::_nofast_putfield  ||
 957          (byte == Bytecodes::_nop && !link_info.check_access()), "bad field access bytecode");
 958 
 959   bool is_static = (byte == Bytecodes::_getstatic || byte == Bytecodes::_putstatic);
 960   bool is_put    = (byte == Bytecodes::_putfield  || byte == Bytecodes::_putstatic || byte == Bytecodes::_nofast_putfield);
 961   // Check if there's a resolved klass containing the field
 962   Klass* resolved_klass = link_info.resolved_klass();
 963   Symbol* field = link_info.name();
 964   Symbol* sig = link_info.signature();
 965 
 966   if (resolved_klass == NULL) {
 967     ResourceMark rm(THREAD);
 968     THROW_MSG(vmSymbols::java_lang_NoSuchFieldError(), field->as_C_string());
 969   }
 970 
 971   // Resolve instance field
 972   Klass* sel_klass = resolved_klass->find_field(field, sig, &fd);
 973   // check if field exists; i.e., if a klass containing the field def has been selected
 974   if (sel_klass == NULL) {
 975     ResourceMark rm(THREAD);
 976     THROW_MSG(vmSymbols::java_lang_NoSuchFieldError(), field->as_C_string());
 977   }
 978 
 979   // Access checking may be turned off when calling from within the VM.
 980   Klass* current_klass = link_info.current_klass();
 981   if (link_info.check_access()) {
 982 
 983     // check access
 984     check_field_accessability(current_klass, resolved_klass, sel_klass, fd, CHECK);
 985 
 986     // check for errors
 987     if (is_static != fd.is_static()) {
 988       ResourceMark rm(THREAD);
 989       char msg[200];
 990       jio_snprintf(msg, sizeof(msg), "Expected %s field %s.%s", is_static ? "static" : "non-static", resolved_klass->external_name(), fd.name()->as_C_string());
 991       THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), msg);
 992     }
 993 
 994     // A final field can be modified only
 995     // (1) by methods declared in the class declaring the field and
 996     // (2) by the <clinit> method (in case of a static field)
 997     //     or by the <init> method (in case of an instance field).
 998     if (is_put && fd.access_flags().is_final()) {
 999 
1000       if (sel_klass != current_klass) {
1001         ResourceMark rm(THREAD);
1002         stringStream ss;
1003         ss.print("Update to %s final field %s.%s attempted from a different class (%s) than the field's declaring class",
1004                  is_static ? "static" : "non-static", resolved_klass->external_name(), fd.name()->as_C_string(),
1005                 current_klass->external_name());
1006         THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), ss.as_string());
1007       }
1008 
1009       if (fd.constants()->pool_holder()->major_version() >= 53) {
1010         Method* m = link_info.current_method();
1011         assert(m != NULL, "information about the current method must be available for 'put' bytecodes");
1012         bool is_initialized_static_final_update = (byte == Bytecodes::_putstatic &&
1013                                                    fd.is_static() &&
1014                                                    !m->is_static_initializer());
1015         bool is_initialized_instance_final_update = ((byte == Bytecodes::_putfield || byte == Bytecodes::_nofast_putfield) &&
1016                                                      !fd.is_static() &&
1017                                                      !m->is_object_initializer());
1018 
1019         if (is_initialized_static_final_update || is_initialized_instance_final_update) {
1020           ResourceMark rm(THREAD);
1021           stringStream ss;
1022           ss.print("Update to %s final field %s.%s attempted from a different method (%s) than the initializer method %s ",
1023                    is_static ? "static" : "non-static", resolved_klass->external_name(), fd.name()->as_C_string(),
1024                    m->name()->as_C_string(),
1025                    is_static ? "<clinit>" : "<init>");
1026           THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), ss.as_string());
1027         }
1028       }
1029     }
1030 
1031     // initialize resolved_klass if necessary
1032     // note 1: the klass which declared the field must be initialized (i.e, sel_klass)
1033     //         according to the newest JVM spec (5.5, p.170) - was bug (gri 7/28/99)
1034     //
1035     // note 2: we don't want to force initialization if we are just checking
1036     //         if the field access is legal; e.g., during compilation
1037     if (is_static && initialize_class) {
1038       sel_klass->initialize(CHECK);
1039     }
1040   }
1041 
1042   if (link_info.check_loader_constraints() && (sel_klass != current_klass) && (current_klass != NULL)) {
1043     check_field_loader_constraints(field, sig, current_klass, sel_klass, CHECK);
1044   }
1045 
1046   // return information. note that the klass is set to the actual klass containing the
1047   // field, otherwise access of static fields in superclasses will not work.
1048 }
1049 
1050 
1051 //------------------------------------------------------------------------------------------------------------------------
1052 // Invoke resolution
1053 //
1054 // Naming conventions:
1055 //
1056 // resolved_method    the specified method (i.e., static receiver specified via constant pool index)
1057 // sel_method         the selected method  (selected via run-time lookup; e.g., based on dynamic receiver class)
1058 // resolved_klass     the specified klass  (i.e., specified via constant pool index)
1059 // recv_klass         the receiver klass
1060 
1061 
1062 void LinkResolver::resolve_static_call(CallInfo& result,
1063                                        const LinkInfo& link_info,
1064                                        bool initialize_class, TRAPS) {
1065   Method* resolved_method = linktime_resolve_static_method(link_info, CHECK);
1066 
1067   // The resolved class can change as a result of this resolution.
1068   Klass* resolved_klass = resolved_method->method_holder();
1069 
1070   // Initialize klass (this should only happen if everything is ok)
1071   if (initialize_class && resolved_klass->should_be_initialized()) {
1072     resolved_klass->initialize(CHECK);
1073     // Use updated LinkInfo to reresolve with resolved method holder
1074     LinkInfo new_info(resolved_klass, link_info.name(), link_info.signature(),
1075                       link_info.current_klass(),
1076                       link_info.check_access() ? LinkInfo::AccessCheck::required : LinkInfo::AccessCheck::skip,
1077                       link_info.check_loader_constraints() ? LinkInfo::LoaderConstraintCheck::required : LinkInfo::LoaderConstraintCheck::skip);
1078     resolved_method = linktime_resolve_static_method(new_info, CHECK);
1079   }
1080 
1081   // setup result
1082   result.set_static(resolved_klass, methodHandle(THREAD, resolved_method), CHECK);
1083 }
1084 
1085 // throws linktime exceptions
1086 Method* LinkResolver::linktime_resolve_static_method(const LinkInfo& link_info, TRAPS) {
1087 
1088   Klass* resolved_klass = link_info.resolved_klass();
1089   Method* resolved_method;
1090   if (!resolved_klass->is_interface()) {
1091     resolved_method = resolve_method(link_info, Bytecodes::_invokestatic, CHECK_NULL);
1092   } else {
1093     resolved_method = resolve_interface_method(link_info, Bytecodes::_invokestatic, CHECK_NULL);
1094   }
1095   assert(resolved_method->name() != vmSymbols::class_initializer_name(), "should have been checked in verifier");
1096 
1097   // check if static
1098   if (!resolved_method->is_static()) {
1099     ResourceMark rm(THREAD);
1100     stringStream ss;
1101     ss.print("Expected static method '");
1102     resolved_method->print_external_name(&ss);
1103     ss.print("'");
1104     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1105   }
1106   return resolved_method;
1107 }
1108 
1109 
1110 void LinkResolver::resolve_special_call(CallInfo& result,
1111                                         Handle recv,
1112                                         const LinkInfo& link_info,
1113                                         TRAPS) {
1114   Method* resolved_method = linktime_resolve_special_method(link_info, CHECK);
1115   runtime_resolve_special_method(result, link_info, methodHandle(THREAD, resolved_method), recv, CHECK);
1116 }
1117 
1118 // throws linktime exceptions
1119 Method* LinkResolver::linktime_resolve_special_method(const LinkInfo& link_info, TRAPS) {
1120 
1121   // Invokespecial is called for multiple special reasons:
1122   // <init>
1123   // local private method invocation, for classes and interfaces
1124   // superclass.method, which can also resolve to a default method
1125   // and the selected method is recalculated relative to the direct superclass
1126   // superinterface.method, which explicitly does not check shadowing
1127   Klass* resolved_klass = link_info.resolved_klass();
1128   Method* resolved_method = NULL;
1129 
1130   if (!resolved_klass->is_interface()) {
1131     resolved_method = resolve_method(link_info, Bytecodes::_invokespecial, CHECK_NULL);
1132   } else {
1133     resolved_method = resolve_interface_method(link_info, Bytecodes::_invokespecial, CHECK_NULL);
1134   }
1135 
1136   // check if method name is <init>, that it is found in same klass as static type
1137   if (resolved_method->name() == vmSymbols::object_initializer_name() &&
1138       resolved_method->method_holder() != resolved_klass) {
1139     ResourceMark rm(THREAD);
1140     stringStream ss;
1141     ss.print("%s: method '", resolved_klass->external_name());
1142     resolved_method->signature()->print_as_signature_external_return_type(&ss);
1143     ss.print(" %s(", resolved_method->name()->as_C_string());
1144     resolved_method->signature()->print_as_signature_external_parameters(&ss);
1145     ss.print(")' not found");
1146     Exceptions::fthrow(
1147       THREAD_AND_LOCATION,
1148       vmSymbols::java_lang_NoSuchMethodError(),
1149       "%s", ss.as_string());
1150     return NULL;
1151   }
1152 
1153   // ensure that invokespecial's interface method reference is in
1154   // a direct superinterface, not an indirect superinterface
1155   Klass* current_klass = link_info.current_klass();
1156   if (current_klass != NULL && resolved_klass->is_interface()) {
1157     InstanceKlass* klass_to_check = InstanceKlass::cast(current_klass);
1158     // Disable verification for the dynamically-generated reflection bytecodes.
1159     bool is_reflect = klass_to_check->is_subclass_of(
1160                         vmClasses::reflect_MagicAccessorImpl_klass());
1161 
1162     if (!is_reflect &&
1163         !klass_to_check->is_same_or_direct_interface(resolved_klass)) {
1164       ResourceMark rm(THREAD);
1165       stringStream ss;
1166       ss.print("Interface method reference: '");
1167       resolved_method->print_external_name(&ss);
1168       ss.print("', is in an indirect superinterface of %s",
1169                current_klass->external_name());
1170       THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1171     }
1172   }
1173 
1174   // check if not static
1175   if (resolved_method->is_static()) {
1176     ResourceMark rm(THREAD);
1177     stringStream ss;
1178     ss.print("Expecting non-static method '");
1179     resolved_method->print_external_name(&ss);
1180     ss.print("'");
1181     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1182   }
1183 
1184   if (log_develop_is_enabled(Trace, itables)) {
1185     trace_method_resolution("invokespecial resolved method: caller-class:",
1186                             current_klass, resolved_klass, resolved_method, true);
1187   }
1188 
1189   return resolved_method;
1190 }
1191 
1192 // throws runtime exceptions
1193 void LinkResolver::runtime_resolve_special_method(CallInfo& result,
1194                                                   const LinkInfo& link_info,
1195                                                   const methodHandle& resolved_method,
1196                                                   Handle recv, TRAPS) {
1197 
1198   Klass* resolved_klass = link_info.resolved_klass();
1199 
1200   // resolved method is selected method unless we have an old-style lookup
1201   // for a superclass method
1202   // Invokespecial for a superinterface, resolved method is selected method,
1203   // no checks for shadowing
1204   methodHandle sel_method(THREAD, resolved_method());
1205 
1206   if (link_info.check_access() &&
1207       // check if the method is not <init>
1208       resolved_method->name() != vmSymbols::object_initializer_name()) {
1209 
1210     Klass* current_klass = link_info.current_klass();
1211 
1212     // Check if the class of the resolved_klass is a superclass
1213     // (not supertype in order to exclude interface classes) of the current class.
1214     // This check is not performed for super.invoke for interface methods
1215     // in super interfaces.
1216     if (current_klass->is_subclass_of(resolved_klass) &&
1217         current_klass != resolved_klass) {
1218       // Lookup super method
1219       Klass* super_klass = current_klass->super();
1220       Method* instance_method = lookup_instance_method_in_klasses(super_klass,
1221                                                      resolved_method->name(),
1222                                                      resolved_method->signature(),
1223                                                      Klass::PrivateLookupMode::find);
1224       sel_method = methodHandle(THREAD, instance_method);
1225 
1226       // check if found
1227       if (sel_method.is_null()) {
1228         ResourceMark rm(THREAD);
1229         stringStream ss;
1230         ss.print("'");
1231         resolved_method->print_external_name(&ss);
1232         ss.print("'");
1233         THROW_MSG(vmSymbols::java_lang_AbstractMethodError(), ss.as_string());
1234       // check loader constraints if found a different method
1235       } else if (link_info.check_loader_constraints() && sel_method() != resolved_method()) {
1236         check_method_loader_constraints(link_info, sel_method, "method", CHECK);
1237       }
1238     }
1239 
1240     // Check that the class of objectref (the receiver) is the current class or interface,
1241     // or a subtype of the current class or interface (the sender), otherwise invokespecial
1242     // throws IllegalAccessError.
1243     // The verifier checks that the sender is a subtype of the class in the I/MR operand.
1244     // The verifier also checks that the receiver is a subtype of the sender, if the sender is
1245     // a class.  If the sender is an interface, the check has to be performed at runtime.
1246     InstanceKlass* sender = InstanceKlass::cast(current_klass);
1247     if (sender->is_interface() && recv.not_null()) {
1248       Klass* receiver_klass = recv->klass();
1249       if (!receiver_klass->is_subtype_of(sender)) {
1250         ResourceMark rm(THREAD);
1251         char buf[500];
1252         jio_snprintf(buf, sizeof(buf),
1253                      "Receiver class %s must be the current class or a subtype of interface %s",
1254                      receiver_klass->external_name(),
1255                      sender->external_name());
1256         THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), buf);
1257       }
1258     }
1259   }
1260 
1261   // check if not static
1262   if (sel_method->is_static()) {
1263     ResourceMark rm(THREAD);
1264     stringStream ss;
1265     ss.print("Expecting non-static method '");
1266     resolved_method->print_external_name(&ss);
1267     ss.print("'");
1268     THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1269   }
1270 
1271   // check if abstract
1272   if (sel_method->is_abstract()) {
1273     ResourceMark rm(THREAD);
1274     stringStream ss;
1275     ss.print("'");
1276     Method::print_external_name(&ss, resolved_klass, sel_method->name(), sel_method->signature());
1277     ss.print("'");
1278     THROW_MSG(vmSymbols::java_lang_AbstractMethodError(), ss.as_string());
1279   }
1280 
1281   if (log_develop_is_enabled(Trace, itables)) {
1282     trace_method_resolution("invokespecial selected method: resolved-class:",
1283                             resolved_klass, resolved_klass, sel_method(), true);
1284   }
1285 
1286   // setup result
1287   result.set_static(resolved_klass, sel_method, CHECK);
1288 }
1289 
1290 void LinkResolver::resolve_virtual_call(CallInfo& result, Handle recv, Klass* receiver_klass,
1291                                         const LinkInfo& link_info,
1292                                         bool check_null_and_abstract, TRAPS) {
1293   Method* resolved_method = linktime_resolve_virtual_method(link_info, CHECK);
1294   runtime_resolve_virtual_method(result, methodHandle(THREAD, resolved_method),
1295                                  link_info.resolved_klass(),
1296                                  recv, receiver_klass,
1297                                  check_null_and_abstract, CHECK);
1298 }
1299 
1300 // throws linktime exceptions
1301 Method* LinkResolver::linktime_resolve_virtual_method(const LinkInfo& link_info,
1302                                                            TRAPS) {
1303   // normal method resolution
1304   Method* resolved_method = resolve_method(link_info, Bytecodes::_invokevirtual, CHECK_NULL);
1305 
1306   assert(resolved_method->name() != vmSymbols::object_initializer_name(), "should have been checked in verifier");
1307   assert(resolved_method->name() != vmSymbols::class_initializer_name (), "should have been checked in verifier");
1308 
1309   // check if private interface method
1310   Klass* resolved_klass = link_info.resolved_klass();
1311   Klass* current_klass = link_info.current_klass();
1312 
1313   // This is impossible, if resolve_klass is an interface, we've thrown icce in resolve_method
1314   if (resolved_klass->is_interface() && resolved_method->is_private()) {
1315     ResourceMark rm(THREAD);
1316     stringStream ss;
1317     ss.print("private interface method requires invokespecial, not invokevirtual: method '");
1318     resolved_method->print_external_name(&ss);
1319     ss.print("', caller-class: %s",
1320              (current_klass == NULL ? "<null>" : current_klass->internal_name()));
1321     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1322   }
1323 
1324   // check if not static
1325   if (resolved_method->is_static()) {
1326     ResourceMark rm(THREAD);
1327     stringStream ss;
1328     ss.print("Expecting non-static method '");
1329     resolved_method->print_external_name(&ss);
1330     ss.print("'");
1331     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1332   }
1333 
1334   if (log_develop_is_enabled(Trace, vtables)) {
1335     trace_method_resolution("invokevirtual resolved method: caller-class:",
1336                             current_klass, resolved_klass, resolved_method, false);
1337   }
1338 
1339   return resolved_method;
1340 }
1341 
1342 // throws runtime exceptions
1343 void LinkResolver::runtime_resolve_virtual_method(CallInfo& result,
1344                                                   const methodHandle& resolved_method,
1345                                                   Klass* resolved_klass,
1346                                                   Handle recv,
1347                                                   Klass* recv_klass,
1348                                                   bool check_null_and_abstract,
1349                                                   TRAPS) {
1350 
1351   // setup default return values
1352   int vtable_index = Method::invalid_vtable_index;
1353   methodHandle selected_method;
1354 
1355   // runtime method resolution
1356   if (check_null_and_abstract && recv.is_null()) { // check if receiver exists
1357     THROW(vmSymbols::java_lang_NullPointerException());
1358   }
1359 
1360   // Virtual methods cannot be resolved before its klass has been linked, for otherwise the Method*'s
1361   // has not been rewritten, and the vtable initialized. Make sure to do this after the nullcheck, since
1362   // a missing receiver might result in a bogus lookup.
1363   assert(resolved_method->method_holder()->is_linked(), "must be linked");
1364 
1365   // do lookup based on receiver klass using the vtable index
1366   if (resolved_method->method_holder()->is_interface()) { // default or miranda method
1367     vtable_index = vtable_index_of_interface_method(resolved_klass, resolved_method);
1368     assert(vtable_index >= 0 , "we should have valid vtable index at this point");
1369 
1370     selected_method = methodHandle(THREAD, recv_klass->method_at_vtable(vtable_index));
1371   } else {
1372     // at this point we are sure that resolved_method is virtual and not
1373     // a default or miranda method; therefore, it must have a valid vtable index.
1374     assert(!resolved_method->has_itable_index(), "");
1375     vtable_index = resolved_method->vtable_index();
1376     // We could get a negative vtable_index of nonvirtual_vtable_index for private
1377     // methods, or for final methods. Private methods never appear in the vtable
1378     // and never override other methods. As an optimization, final methods are
1379     // never put in the vtable, unless they override an existing method.
1380     // So if we do get nonvirtual_vtable_index, it means the selected method is the
1381     // resolved method, and it can never be changed by an override.
1382     if (vtable_index == Method::nonvirtual_vtable_index) {
1383       assert(resolved_method->can_be_statically_bound(), "cannot override this method");
1384       selected_method = resolved_method;
1385     } else {
1386       selected_method = methodHandle(THREAD, recv_klass->method_at_vtable(vtable_index));
1387     }
1388   }
1389 
1390   // check if method exists
1391   if (selected_method.is_null()) {
1392     throw_abstract_method_error(resolved_method, recv_klass, CHECK);
1393   }
1394 
1395   // check if abstract
1396   if (check_null_and_abstract && selected_method->is_abstract()) {
1397     // Pass arguments for generating a verbose error message.
1398     throw_abstract_method_error(resolved_method, selected_method, recv_klass, CHECK);
1399   }
1400 
1401   if (log_develop_is_enabled(Trace, vtables)) {
1402     trace_method_resolution("invokevirtual selected method: receiver-class:",
1403                             recv_klass, resolved_klass, selected_method(),
1404                             false, vtable_index);
1405   }
1406   // setup result
1407   result.set_virtual(resolved_klass, resolved_method, selected_method, vtable_index, CHECK);
1408 }
1409 
1410 void LinkResolver::resolve_interface_call(CallInfo& result, Handle recv, Klass* recv_klass,
1411                                           const LinkInfo& link_info,
1412                                           bool check_null_and_abstract, TRAPS) {
1413   // throws linktime exceptions
1414   Method* resolved_method = linktime_resolve_interface_method(link_info, CHECK);
1415   methodHandle mh(THREAD, resolved_method);
1416   runtime_resolve_interface_method(result, mh, link_info.resolved_klass(),
1417                                    recv, recv_klass, check_null_and_abstract, CHECK);
1418 }
1419 
1420 Method* LinkResolver::linktime_resolve_interface_method(const LinkInfo& link_info,
1421                                                              TRAPS) {
1422   // normal interface method resolution
1423   Method* resolved_method = resolve_interface_method(link_info, Bytecodes::_invokeinterface, CHECK_NULL);
1424   assert(resolved_method->name() != vmSymbols::object_initializer_name(), "should have been checked in verifier");
1425   assert(resolved_method->name() != vmSymbols::class_initializer_name (), "should have been checked in verifier");
1426 
1427   return resolved_method;
1428 }
1429 
1430 // throws runtime exceptions
1431 void LinkResolver::runtime_resolve_interface_method(CallInfo& result,
1432                                                     const methodHandle& resolved_method,
1433                                                     Klass* resolved_klass,
1434                                                     Handle recv,
1435                                                     Klass* recv_klass,
1436                                                     bool check_null_and_abstract, TRAPS) {
1437 
1438   // check if receiver exists
1439   if (check_null_and_abstract && recv.is_null()) {
1440     THROW(vmSymbols::java_lang_NullPointerException());
1441   }
1442 
1443   // check if receiver klass implements the resolved interface
1444   if (!recv_klass->is_subtype_of(resolved_klass)) {
1445     ResourceMark rm(THREAD);
1446     char buf[200];
1447     jio_snprintf(buf, sizeof(buf), "Class %s does not implement the requested interface %s",
1448                  recv_klass->external_name(),
1449                  resolved_klass->external_name());
1450     THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
1451   }
1452 
1453   methodHandle selected_method = resolved_method;
1454 
1455   // resolve the method in the receiver class, unless it is private
1456   if (!resolved_method()->is_private()) {
1457     // do lookup based on receiver klass
1458     // This search must match the linktime preparation search for itable initialization
1459     // to correctly enforce loader constraints for interface method inheritance.
1460     // Private methods are skipped as the resolved method was not private.
1461     Method* method = lookup_instance_method_in_klasses(recv_klass,
1462                                                        resolved_method->name(),
1463                                                        resolved_method->signature(),
1464                                                        Klass::PrivateLookupMode::skip);
1465     selected_method = methodHandle(THREAD, method);
1466 
1467     if (selected_method.is_null() && !check_null_and_abstract) {
1468       // In theory this is a harmless placeholder value, but
1469       // in practice leaving in null affects the nsk default method tests.
1470       // This needs further study.
1471       selected_method = resolved_method;
1472     }
1473     // check if method exists
1474     if (selected_method.is_null()) {
1475       // Pass arguments for generating a verbose error message.
1476       throw_abstract_method_error(resolved_method, recv_klass, CHECK);
1477     }
1478     // check access
1479     // Throw Illegal Access Error if selected_method is not public.
1480     if (!selected_method->is_public()) {
1481       ResourceMark rm(THREAD);
1482       stringStream ss;
1483       ss.print("'");
1484       Method::print_external_name(&ss, recv_klass, selected_method->name(), selected_method->signature());
1485       ss.print("'");
1486       THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), ss.as_string());
1487     }
1488     // check if abstract
1489     if (check_null_and_abstract && selected_method->is_abstract()) {
1490       throw_abstract_method_error(resolved_method, selected_method, recv_klass, CHECK);
1491     }
1492   }
1493 
1494   if (log_develop_is_enabled(Trace, itables)) {
1495     trace_method_resolution("invokeinterface selected method: receiver-class:",
1496                             recv_klass, resolved_klass, selected_method(), true);
1497   }
1498   // setup result
1499   if (resolved_method->has_vtable_index()) {
1500     int vtable_index = resolved_method->vtable_index();
1501     log_develop_trace(itables)("  -- vtable index: %d", vtable_index);
1502     assert(vtable_index == selected_method->vtable_index(), "sanity check");
1503     result.set_virtual(resolved_klass, resolved_method, selected_method, vtable_index, CHECK);
1504   } else if (resolved_method->has_itable_index()) {
1505     int itable_index = resolved_method()->itable_index();
1506     log_develop_trace(itables)("  -- itable index: %d", itable_index);
1507     result.set_interface(resolved_klass, resolved_method, selected_method, itable_index, CHECK);
1508   } else {
1509     int index = resolved_method->vtable_index();
1510     log_develop_trace(itables)("  -- non itable/vtable index: %d", index);
1511     assert(index == Method::nonvirtual_vtable_index, "Oops hit another case!");
1512     assert(resolved_method()->is_private() ||
1513            (resolved_method()->is_final() && resolved_method->method_holder() == vmClasses::Object_klass()),
1514            "Should only have non-virtual invokeinterface for private or final-Object methods!");
1515     assert(resolved_method()->can_be_statically_bound(), "Should only have non-virtual invokeinterface for statically bound methods!");
1516     // This sets up the nonvirtual form of "virtual" call (as needed for final and private methods)
1517     result.set_virtual(resolved_klass, resolved_method, resolved_method, index, CHECK);
1518   }
1519 }
1520 
1521 
1522 Method* LinkResolver::linktime_resolve_interface_method_or_null(
1523                                                  const LinkInfo& link_info) {
1524   EXCEPTION_MARK;
1525   Method* method_result = linktime_resolve_interface_method(link_info, THREAD);
1526   if (HAS_PENDING_EXCEPTION) {
1527     CLEAR_PENDING_EXCEPTION;
1528     return NULL;
1529   } else {
1530     return method_result;
1531   }
1532 }
1533 
1534 Method* LinkResolver::linktime_resolve_virtual_method_or_null(
1535                                                  const LinkInfo& link_info) {
1536   EXCEPTION_MARK;
1537   Method* method_result = linktime_resolve_virtual_method(link_info, THREAD);
1538   if (HAS_PENDING_EXCEPTION) {
1539     CLEAR_PENDING_EXCEPTION;
1540     return NULL;
1541   } else {
1542     return method_result;
1543   }
1544 }
1545 
1546 Method* LinkResolver::resolve_virtual_call_or_null(
1547                                                  Klass* receiver_klass,
1548                                                  const LinkInfo& link_info) {
1549   EXCEPTION_MARK;
1550   CallInfo info;
1551   resolve_virtual_call(info, Handle(), receiver_klass, link_info, false, THREAD);
1552   if (HAS_PENDING_EXCEPTION) {
1553     CLEAR_PENDING_EXCEPTION;
1554     return NULL;
1555   }
1556   return info.selected_method();
1557 }
1558 
1559 Method* LinkResolver::resolve_interface_call_or_null(
1560                                                  Klass* receiver_klass,
1561                                                  const LinkInfo& link_info) {
1562   EXCEPTION_MARK;
1563   CallInfo info;
1564   resolve_interface_call(info, Handle(), receiver_klass, link_info, false, THREAD);
1565   if (HAS_PENDING_EXCEPTION) {
1566     CLEAR_PENDING_EXCEPTION;
1567     return NULL;
1568   }
1569   return info.selected_method();
1570 }
1571 
1572 int LinkResolver::resolve_virtual_vtable_index(Klass* receiver_klass,
1573                                                const LinkInfo& link_info) {
1574   EXCEPTION_MARK;
1575   CallInfo info;
1576   resolve_virtual_call(info, Handle(), receiver_klass, link_info,
1577                        /*check_null_or_abstract*/false, THREAD);
1578   if (HAS_PENDING_EXCEPTION) {
1579     CLEAR_PENDING_EXCEPTION;
1580     return Method::invalid_vtable_index;
1581   }
1582   return info.vtable_index();
1583 }
1584 
1585 Method* LinkResolver::resolve_static_call_or_null(const LinkInfo& link_info) {
1586   EXCEPTION_MARK;
1587   CallInfo info;
1588   resolve_static_call(info, link_info, /*initialize_class*/false, THREAD);
1589   if (HAS_PENDING_EXCEPTION) {
1590     CLEAR_PENDING_EXCEPTION;
1591     return NULL;
1592   }
1593   return info.selected_method();
1594 }
1595 
1596 Method* LinkResolver::resolve_special_call_or_null(const LinkInfo& link_info) {
1597   EXCEPTION_MARK;
1598   CallInfo info;
1599   resolve_special_call(info, Handle(), link_info, THREAD);
1600   if (HAS_PENDING_EXCEPTION) {
1601     CLEAR_PENDING_EXCEPTION;
1602     return NULL;
1603   }
1604   return info.selected_method();
1605 }
1606 
1607 
1608 
1609 //------------------------------------------------------------------------------------------------------------------------
1610 // ConstantPool entries
1611 
1612 void LinkResolver::resolve_invoke(CallInfo& result, Handle recv, const constantPoolHandle& pool, int index, Bytecodes::Code byte, TRAPS) {
1613   switch (byte) {
1614     case Bytecodes::_invokestatic   : resolve_invokestatic   (result,       pool, index, CHECK); break;
1615     case Bytecodes::_invokespecial  : resolve_invokespecial  (result, recv, pool, index, CHECK); break;
1616     case Bytecodes::_invokevirtual  : resolve_invokevirtual  (result, recv, pool, index, CHECK); break;
1617     case Bytecodes::_invokehandle   : resolve_invokehandle   (result,       pool, index, CHECK); break;
1618     case Bytecodes::_invokedynamic  : resolve_invokedynamic  (result,       pool, index, CHECK); break;
1619     case Bytecodes::_invokeinterface: resolve_invokeinterface(result, recv, pool, index, CHECK); break;
1620     default                         :                                                            break;
1621   }
1622   return;
1623 }
1624 
1625 void LinkResolver::resolve_invoke(CallInfo& result, Handle& recv,
1626                              const methodHandle& attached_method,
1627                              Bytecodes::Code byte, TRAPS) {
1628   Klass* defc = attached_method->method_holder();
1629   Symbol* name = attached_method->name();
1630   Symbol* type = attached_method->signature();
1631   LinkInfo link_info(defc, name, type);
1632   switch(byte) {
1633     case Bytecodes::_invokevirtual:
1634       resolve_virtual_call(result, recv, recv->klass(), link_info,
1635                            /*check_null_and_abstract=*/true, CHECK);
1636       break;
1637     case Bytecodes::_invokeinterface:
1638       resolve_interface_call(result, recv, recv->klass(), link_info,
1639                              /*check_null_and_abstract=*/true, CHECK);
1640       break;
1641     case Bytecodes::_invokestatic:
1642       resolve_static_call(result, link_info, /*initialize_class=*/false, CHECK);
1643       break;
1644     case Bytecodes::_invokespecial:
1645       resolve_special_call(result, recv, link_info, CHECK);
1646       break;
1647     default:
1648       fatal("bad call: %s", Bytecodes::name(byte));
1649       break;
1650   }
1651 }
1652 
1653 void LinkResolver::resolve_invokestatic(CallInfo& result, const constantPoolHandle& pool, int index, TRAPS) {
1654   LinkInfo link_info(pool, index, CHECK);
1655   resolve_static_call(result, link_info, /*initialize_class*/true, CHECK);
1656 }
1657 
1658 
1659 void LinkResolver::resolve_invokespecial(CallInfo& result, Handle recv,
1660                                          const constantPoolHandle& pool, int index, TRAPS) {
1661   LinkInfo link_info(pool, index, CHECK);
1662   resolve_special_call(result, recv, link_info, CHECK);
1663 }
1664 
1665 
1666 void LinkResolver::resolve_invokevirtual(CallInfo& result, Handle recv,
1667                                           const constantPoolHandle& pool, int index,
1668                                           TRAPS) {
1669 
1670   LinkInfo link_info(pool, index, CHECK);
1671   Klass* recvrKlass = recv.is_null() ? (Klass*)NULL : recv->klass();
1672   resolve_virtual_call(result, recv, recvrKlass, link_info, /*check_null_or_abstract*/true, CHECK);
1673 }
1674 
1675 
1676 void LinkResolver::resolve_invokeinterface(CallInfo& result, Handle recv, const constantPoolHandle& pool, int index, TRAPS) {
1677   LinkInfo link_info(pool, index, CHECK);
1678   Klass* recvrKlass = recv.is_null() ? (Klass*)NULL : recv->klass();
1679   resolve_interface_call(result, recv, recvrKlass, link_info, true, CHECK);
1680 }
1681 
1682 
1683 void LinkResolver::resolve_invokehandle(CallInfo& result, const constantPoolHandle& pool, int index, TRAPS) {
1684   // This guy is reached from InterpreterRuntime::resolve_invokehandle.
1685   LinkInfo link_info(pool, index, CHECK);
1686   if (log_is_enabled(Info, methodhandles)) {
1687     ResourceMark rm(THREAD);
1688     log_info(methodhandles)("resolve_invokehandle %s %s", link_info.name()->as_C_string(),
1689                             link_info.signature()->as_C_string());
1690   }
1691   resolve_handle_call(result, link_info, CHECK);
1692 }
1693 
1694 void LinkResolver::resolve_handle_call(CallInfo& result,
1695                                        const LinkInfo& link_info,
1696                                        TRAPS) {
1697   // JSR 292:  this must be an implicitly generated method MethodHandle.invokeExact(*...) or similar
1698   Klass* resolved_klass = link_info.resolved_klass();
1699   assert(resolved_klass == vmClasses::MethodHandle_klass() ||
1700          resolved_klass == vmClasses::VarHandle_klass(), "");
1701   assert(MethodHandles::is_signature_polymorphic_name(link_info.name()), "");
1702   Handle       resolved_appendix;
1703   Method* resolved_method = lookup_polymorphic_method(link_info, &resolved_appendix, CHECK);
1704   result.set_handle(resolved_klass, methodHandle(THREAD, resolved_method), resolved_appendix, CHECK);
1705 }
1706 
1707 void LinkResolver::resolve_invokedynamic(CallInfo& result, const constantPoolHandle& pool, int indy_index, TRAPS) {
1708   ConstantPoolCacheEntry* cpce = pool->invokedynamic_cp_cache_entry_at(indy_index);
1709   int pool_index = cpce->constant_pool_index();
1710 
1711   // Resolve the bootstrap specifier (BSM + optional arguments).
1712   BootstrapInfo bootstrap_specifier(pool, pool_index, indy_index);
1713 
1714   // Check if CallSite has been bound already or failed already, and short circuit:
1715   {
1716     bool is_done = bootstrap_specifier.resolve_previously_linked_invokedynamic(result, CHECK);
1717     if (is_done) return;
1718   }
1719 
1720   // The initial step in Call Site Specifier Resolution is to resolve the symbolic
1721   // reference to a method handle which will be the bootstrap method for a dynamic
1722   // call site.  If resolution for the java.lang.invoke.MethodHandle for the bootstrap
1723   // method fails, then a MethodHandleInError is stored at the corresponding bootstrap
1724   // method's CP index for the CONSTANT_MethodHandle_info.  So, there is no need to
1725   // set the indy_rf flag since any subsequent invokedynamic instruction which shares
1726   // this bootstrap method will encounter the resolution of MethodHandleInError.
1727 
1728   resolve_dynamic_call(result, bootstrap_specifier, CHECK);
1729 
1730   LogTarget(Debug, methodhandles, indy) lt_indy;
1731   if (lt_indy.is_enabled()) {
1732     LogStream ls(lt_indy);
1733     bootstrap_specifier.print_msg_on(&ls, "resolve_invokedynamic");
1734   }
1735 
1736   // The returned linkage result is provisional up to the moment
1737   // the interpreter or runtime performs a serialized check of
1738   // the relevant CPCE::f1 field.  This is done by the caller
1739   // of this method, via CPCE::set_dynamic_call, which uses
1740   // an ObjectLocker to do the final serialization of updates
1741   // to CPCE state, including f1.
1742 
1743   // Log dynamic info to CDS classlist.
1744   ArchiveUtils::log_to_classlist(&bootstrap_specifier, CHECK);
1745 }
1746 
1747 void LinkResolver::resolve_dynamic_call(CallInfo& result,
1748                                         BootstrapInfo& bootstrap_specifier,
1749                                         TRAPS) {
1750   // JSR 292:  this must resolve to an implicitly generated method
1751   // such as MH.linkToCallSite(*...) or some other call-site shape.
1752   // The appendix argument is likely to be a freshly-created CallSite.
1753   // It may also be a MethodHandle from an unwrapped ConstantCallSite,
1754   // or any other reference.  The resolved_method as well as the appendix
1755   // are both recorded together via CallInfo::set_handle.
1756   SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);
1757   Exceptions::wrap_dynamic_exception(/* is_indy */ true, THREAD);
1758 
1759   if (HAS_PENDING_EXCEPTION) {
1760     if (!PENDING_EXCEPTION->is_a(vmClasses::LinkageError_klass())) {
1761       // Let any random low-level IE or SOE or OOME just bleed through.
1762       // Basically we pretend that the bootstrap method was never called,
1763       // if it fails this way:  We neither record a successful linkage,
1764       // nor do we memorize a LE for posterity.
1765       return;
1766     }
1767     // JVMS 5.4.3 says: If an attempt by the Java Virtual Machine to resolve
1768     // a symbolic reference fails because an error is thrown that is an
1769     // instance of LinkageError (or a subclass), then subsequent attempts to
1770     // resolve the reference always fail with the same error that was thrown
1771     // as a result of the initial resolution attempt.
1772      bool recorded_res_status = bootstrap_specifier.save_and_throw_indy_exc(CHECK);
1773      if (!recorded_res_status) {
1774        // Another thread got here just before we did.  So, either use the method
1775        // that it resolved or throw the LinkageError exception that it threw.
1776        bool is_done = bootstrap_specifier.resolve_previously_linked_invokedynamic(result, CHECK);
1777        if (is_done) return;
1778      }
1779      assert(bootstrap_specifier.invokedynamic_cp_cache_entry()->indy_resolution_failed(),
1780             "Resolution failure flag wasn't set");
1781   }
1782 
1783   bootstrap_specifier.resolve_newly_linked_invokedynamic(result, CHECK);
1784   // Exceptions::wrap_dynamic_exception not used because
1785   // set_handle doesn't throw linkage errors
1786 }
1787 
1788 // Selected method is abstract.
1789 void LinkResolver::throw_abstract_method_error(const methodHandle& resolved_method,
1790                                                const methodHandle& selected_method,
1791                                                Klass *recv_klass, TRAPS) {
1792   Klass *resolved_klass = resolved_method->method_holder();
1793   ResourceMark rm(THREAD);
1794   stringStream ss;
1795 
1796   if (recv_klass != NULL) {
1797     ss.print("Receiver class %s does not define or inherit an "
1798              "implementation of the",
1799              recv_klass->external_name());
1800   } else {
1801     ss.print("Missing implementation of");
1802   }
1803 
1804   assert(resolved_method.not_null(), "Sanity");
1805   ss.print(" resolved method '%s%s",
1806            resolved_method->is_abstract() ? "abstract " : "",
1807            resolved_method->is_private()  ? "private "  : "");
1808   resolved_method->signature()->print_as_signature_external_return_type(&ss);
1809   ss.print(" %s(", resolved_method->name()->as_C_string());
1810   resolved_method->signature()->print_as_signature_external_parameters(&ss);
1811   ss.print(")' of %s %s.",
1812            resolved_klass->external_kind(),
1813            resolved_klass->external_name());
1814 
1815   if (selected_method.not_null() && !(resolved_method == selected_method)) {
1816     ss.print(" Selected method is '%s%s",
1817              selected_method->is_abstract() ? "abstract " : "",
1818              selected_method->is_private()  ? "private "  : "");
1819     selected_method->print_external_name(&ss);
1820     ss.print("'.");
1821   }
1822 
1823   THROW_MSG(vmSymbols::java_lang_AbstractMethodError(), ss.as_string());
1824 }