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::_withfield ||
 957          byte == Bytecodes::_nofast_getfield  || byte == Bytecodes::_nofast_putfield  ||
 958          (byte == Bytecodes::_nop && !link_info.check_access()), "bad field access bytecode");
 959 
 960   bool is_static = (byte == Bytecodes::_getstatic || byte == Bytecodes::_putstatic);
 961   bool is_put    = (byte == Bytecodes::_putfield  || byte == Bytecodes::_putstatic ||
 962                     byte == Bytecodes::_nofast_putfield || byte == Bytecodes::_withfield);
 963   // Check if there's a resolved klass containing the field
 964   Klass* resolved_klass = link_info.resolved_klass();
 965   Symbol* field = link_info.name();
 966   Symbol* sig = link_info.signature();
 967 
 968   if (resolved_klass == NULL) {
 969     ResourceMark rm(THREAD);
 970     THROW_MSG(vmSymbols::java_lang_NoSuchFieldError(), field->as_C_string());
 971   }
 972 
 973   if (byte == Bytecodes::_withfield && !resolved_klass->is_inline_klass()) {
 974     ResourceMark rm(THREAD);
 975     char msg[200];
 976     jio_snprintf(msg, sizeof(msg), "Bytecode withfield cannot be used on identity class %s", resolved_klass->external_name());
 977     THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), msg);
 978   }
 979 
 980   if (is_put && !is_static && byte != Bytecodes::_withfield && resolved_klass->is_inline_klass()) {
 981     ResourceMark rm(THREAD);
 982     char msg[200];
 983     jio_snprintf(msg, sizeof(msg), "Bytecode putfield cannot be used on primitive class %s", resolved_klass->external_name());
 984     THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), msg);
 985   }
 986 
 987   // Resolve instance field
 988   Klass* sel_klass = resolved_klass->find_field(field, sig, &fd);
 989   // check if field exists; i.e., if a klass containing the field def has been selected
 990   if (sel_klass == NULL) {
 991     ResourceMark rm(THREAD);
 992     THROW_MSG(vmSymbols::java_lang_NoSuchFieldError(), field->as_C_string());
 993   }
 994 
 995   // Access checking may be turned off when calling from within the VM.
 996   Klass* current_klass = link_info.current_klass();
 997   if (link_info.check_access()) {
 998 
 999     // check access
1000     check_field_accessability(current_klass, resolved_klass, sel_klass, fd, CHECK);
1001 
1002     // check for errors
1003     if (is_static != fd.is_static()) {
1004       ResourceMark rm(THREAD);
1005       char msg[200];
1006       jio_snprintf(msg, sizeof(msg), "Expected %s field %s.%s", is_static ? "static" : "non-static", resolved_klass->external_name(), fd.name()->as_C_string());
1007       THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), msg);
1008     }
1009 
1010     // A final field can be modified only
1011     // (1) by methods declared in the class declaring the field and
1012     // (2) by the <clinit> method (in case of a static field)
1013     //     or by the <init> method (in case of an instance field).
1014     // (3) by withfield when field is in a value type and the
1015     //     selected class and current class are nest mates.
1016     if (is_put && fd.access_flags().is_final()) {
1017 
1018       if (sel_klass != current_klass) {
1019         // If byte code is a withfield check if they are nestmates.
1020         bool are_nestmates = false;
1021         if (sel_klass->is_instance_klass() &&
1022             InstanceKlass::cast(sel_klass)->is_inline_klass() &&
1023             current_klass->is_instance_klass()) {
1024           are_nestmates = InstanceKlass::cast(current_klass)->has_nestmate_access_to(InstanceKlass::cast(sel_klass), THREAD);
1025         }
1026         if (!are_nestmates) {
1027           ResourceMark rm(THREAD);
1028           stringStream ss;
1029           ss.print("Update to %s final field %s.%s attempted from a different class (%s) than the field's declaring class",
1030                    is_static ? "static" : "non-static", resolved_klass->external_name(), fd.name()->as_C_string(),
1031                     current_klass->external_name());
1032           THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), ss.as_string());
1033         }
1034       }
1035 
1036       if (fd.constants()->pool_holder()->major_version() >= 53) {
1037         Method* m = link_info.current_method();
1038         assert(m != NULL, "information about the current method must be available for 'put' bytecodes");
1039         bool is_initialized_static_final_update = (byte == Bytecodes::_putstatic &&
1040                                                    fd.is_static() &&
1041                                                    !m->is_class_initializer());
1042         bool is_initialized_instance_final_update = ((byte == Bytecodes::_putfield || byte == Bytecodes::_nofast_putfield) &&
1043                                                      !fd.is_static() &&
1044                                                      !m->is_object_constructor());
1045 
1046         if (is_initialized_static_final_update || is_initialized_instance_final_update) {
1047           ResourceMark rm(THREAD);
1048           stringStream ss;
1049           ss.print("Update to %s final field %s.%s attempted from a different method (%s) than the initializer method %s ",
1050                    is_static ? "static" : "non-static", resolved_klass->external_name(), fd.name()->as_C_string(),
1051                    m->name()->as_C_string(),
1052                    is_static ? "<clinit>" : "<init>");
1053           THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), ss.as_string());
1054         }
1055       }
1056     }
1057 
1058     // initialize resolved_klass if necessary
1059     // note 1: the klass which declared the field must be initialized (i.e, sel_klass)
1060     //         according to the newest JVM spec (5.5, p.170) - was bug (gri 7/28/99)
1061     //
1062     // note 2: we don't want to force initialization if we are just checking
1063     //         if the field access is legal; e.g., during compilation
1064     if (is_static && initialize_class) {
1065       sel_klass->initialize(CHECK);
1066     }
1067   }
1068 
1069   if (link_info.check_loader_constraints() && (sel_klass != current_klass) && (current_klass != NULL)) {
1070     check_field_loader_constraints(field, sig, current_klass, sel_klass, CHECK);
1071   }
1072 
1073   // return information. note that the klass is set to the actual klass containing the
1074   // field, otherwise access of static fields in superclasses will not work.
1075 }
1076 
1077 
1078 //------------------------------------------------------------------------------------------------------------------------
1079 // Invoke resolution
1080 //
1081 // Naming conventions:
1082 //
1083 // resolved_method    the specified method (i.e., static receiver specified via constant pool index)
1084 // sel_method         the selected method  (selected via run-time lookup; e.g., based on dynamic receiver class)
1085 // resolved_klass     the specified klass  (i.e., specified via constant pool index)
1086 // recv_klass         the receiver klass
1087 
1088 
1089 void LinkResolver::resolve_static_call(CallInfo& result,
1090                                        const LinkInfo& link_info,
1091                                        bool initialize_class, TRAPS) {
1092   Method* resolved_method = linktime_resolve_static_method(link_info, CHECK);
1093 
1094   // The resolved class can change as a result of this resolution.
1095   Klass* resolved_klass = resolved_method->method_holder();
1096 
1097   // Initialize klass (this should only happen if everything is ok)
1098   if (initialize_class && resolved_klass->should_be_initialized()) {
1099     resolved_klass->initialize(CHECK);
1100     // Use updated LinkInfo to reresolve with resolved method holder
1101     LinkInfo new_info(resolved_klass, link_info.name(), link_info.signature(),
1102                       link_info.current_klass(),
1103                       link_info.check_access() ? LinkInfo::AccessCheck::required : LinkInfo::AccessCheck::skip,
1104                       link_info.check_loader_constraints() ? LinkInfo::LoaderConstraintCheck::required : LinkInfo::LoaderConstraintCheck::skip);
1105     resolved_method = linktime_resolve_static_method(new_info, CHECK);
1106   }
1107 
1108   // setup result
1109   result.set_static(resolved_klass, methodHandle(THREAD, resolved_method), CHECK);
1110 }
1111 
1112 // throws linktime exceptions
1113 Method* LinkResolver::linktime_resolve_static_method(const LinkInfo& link_info, TRAPS) {
1114 
1115   Klass* resolved_klass = link_info.resolved_klass();
1116   Method* resolved_method;
1117   if (!resolved_klass->is_interface()) {
1118     resolved_method = resolve_method(link_info, Bytecodes::_invokestatic, CHECK_NULL);
1119   } else {
1120     resolved_method = resolve_interface_method(link_info, Bytecodes::_invokestatic, CHECK_NULL);
1121   }
1122   assert(resolved_method->name() != vmSymbols::class_initializer_name(), "should have been checked in verifier");
1123 
1124   // check if static
1125   if (!resolved_method->is_static()) {
1126     ResourceMark rm(THREAD);
1127     stringStream ss;
1128     ss.print("Expected static method '");
1129     resolved_method->print_external_name(&ss);
1130     ss.print("'");
1131     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1132   }
1133   return resolved_method;
1134 }
1135 
1136 
1137 void LinkResolver::resolve_special_call(CallInfo& result,
1138                                         Handle recv,
1139                                         const LinkInfo& link_info,
1140                                         TRAPS) {
1141   Method* resolved_method = linktime_resolve_special_method(link_info, CHECK);
1142   runtime_resolve_special_method(result, link_info, methodHandle(THREAD, resolved_method), recv, CHECK);
1143 }
1144 
1145 // throws linktime exceptions
1146 Method* LinkResolver::linktime_resolve_special_method(const LinkInfo& link_info, TRAPS) {
1147 
1148   // Invokespecial is called for multiple special reasons:
1149   // <init>
1150   // local private method invocation, for classes and interfaces
1151   // superclass.method, which can also resolve to a default method
1152   // and the selected method is recalculated relative to the direct superclass
1153   // superinterface.method, which explicitly does not check shadowing
1154   Klass* resolved_klass = link_info.resolved_klass();
1155   Method* resolved_method = NULL;
1156 
1157   if (!resolved_klass->is_interface()) {
1158     resolved_method = resolve_method(link_info, Bytecodes::_invokespecial, CHECK_NULL);
1159   } else {
1160     resolved_method = resolve_interface_method(link_info, Bytecodes::_invokespecial, CHECK_NULL);
1161   }
1162 
1163   // check if method name is <init>, that it is found in same klass as static type
1164   // Since this method is never inherited from a super, any appearance here under
1165   // the wrong class would be an error.
1166   if (resolved_method->name() == vmSymbols::object_initializer_name() &&
1167       resolved_method->method_holder() != resolved_klass) {
1168     ResourceMark rm(THREAD);
1169     stringStream ss;
1170     ss.print("%s: method '", resolved_klass->external_name());
1171     resolved_method->signature()->print_as_signature_external_return_type(&ss);
1172     ss.print(" %s(", resolved_method->name()->as_C_string());
1173     resolved_method->signature()->print_as_signature_external_parameters(&ss);
1174     ss.print(")' not found");
1175     Exceptions::fthrow(
1176       THREAD_AND_LOCATION,
1177       vmSymbols::java_lang_NoSuchMethodError(),
1178       "%s", ss.as_string());
1179     return NULL;
1180   }
1181 
1182   // ensure that invokespecial's interface method reference is in
1183   // a direct superinterface, not an indirect superinterface
1184   Klass* current_klass = link_info.current_klass();
1185   if (current_klass != NULL && resolved_klass->is_interface()) {
1186     InstanceKlass* klass_to_check = InstanceKlass::cast(current_klass);
1187     // Disable verification for the dynamically-generated reflection bytecodes.
1188     bool is_reflect = klass_to_check->is_subclass_of(
1189                         vmClasses::reflect_MagicAccessorImpl_klass());
1190 
1191     if (!is_reflect &&
1192         !klass_to_check->is_same_or_direct_interface(resolved_klass)) {
1193       ResourceMark rm(THREAD);
1194       stringStream ss;
1195       ss.print("Interface method reference: '");
1196       resolved_method->print_external_name(&ss);
1197       ss.print("', is in an indirect superinterface of %s",
1198                current_klass->external_name());
1199       THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1200     }
1201   }
1202 
1203   // check if not static
1204   if (resolved_method->is_static()) {
1205     ResourceMark rm(THREAD);
1206     stringStream ss;
1207     ss.print("Expecting non-static method '");
1208     resolved_method->print_external_name(&ss);
1209     ss.print("'");
1210     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1211   }
1212 
1213   if (log_develop_is_enabled(Trace, itables)) {
1214     trace_method_resolution("invokespecial resolved method: caller-class:",
1215                             current_klass, resolved_klass, resolved_method, true);
1216   }
1217 
1218   return resolved_method;
1219 }
1220 
1221 // throws runtime exceptions
1222 void LinkResolver::runtime_resolve_special_method(CallInfo& result,
1223                                                   const LinkInfo& link_info,
1224                                                   const methodHandle& resolved_method,
1225                                                   Handle recv, TRAPS) {
1226 
1227   Klass* resolved_klass = link_info.resolved_klass();
1228 
1229   // resolved method is selected method unless we have an old-style lookup
1230   // for a superclass method
1231   // Invokespecial for a superinterface, resolved method is selected method,
1232   // no checks for shadowing
1233   methodHandle sel_method(THREAD, resolved_method());
1234 
1235   if (link_info.check_access() &&
1236       // check if the method is not <init>, which is never inherited
1237       resolved_method->name() != vmSymbols::object_initializer_name()) {
1238 
1239     Klass* current_klass = link_info.current_klass();
1240 
1241     // Check if the class of the resolved_klass is a superclass
1242     // (not supertype in order to exclude interface classes) of the current class.
1243     // This check is not performed for super.invoke for interface methods
1244     // in super interfaces.
1245     if (current_klass->is_subclass_of(resolved_klass) &&
1246         current_klass != resolved_klass) {
1247       // Lookup super method
1248       Klass* super_klass = current_klass->super();
1249       Method* instance_method = lookup_instance_method_in_klasses(super_klass,
1250                                                      resolved_method->name(),
1251                                                      resolved_method->signature(),
1252                                                      Klass::PrivateLookupMode::find);
1253       sel_method = methodHandle(THREAD, instance_method);
1254 
1255       // check if found
1256       if (sel_method.is_null()) {
1257         ResourceMark rm(THREAD);
1258         stringStream ss;
1259         ss.print("'");
1260         resolved_method->print_external_name(&ss);
1261         ss.print("'");
1262         THROW_MSG(vmSymbols::java_lang_AbstractMethodError(), ss.as_string());
1263       // check loader constraints if found a different method
1264       } else if (link_info.check_loader_constraints() && sel_method() != resolved_method()) {
1265         check_method_loader_constraints(link_info, sel_method, "method", CHECK);
1266       }
1267     }
1268 
1269     // Check that the class of objectref (the receiver) is the current class or interface,
1270     // or a subtype of the current class or interface (the sender), otherwise invokespecial
1271     // throws IllegalAccessError.
1272     // The verifier checks that the sender is a subtype of the class in the I/MR operand.
1273     // The verifier also checks that the receiver is a subtype of the sender, if the sender is
1274     // a class.  If the sender is an interface, the check has to be performed at runtime.
1275     InstanceKlass* sender = InstanceKlass::cast(current_klass);
1276     if (sender->is_interface() && recv.not_null()) {
1277       Klass* receiver_klass = recv->klass();
1278       if (!receiver_klass->is_subtype_of(sender)) {
1279         ResourceMark rm(THREAD);
1280         char buf[500];
1281         jio_snprintf(buf, sizeof(buf),
1282                      "Receiver class %s must be the current class or a subtype of interface %s",
1283                      receiver_klass->external_name(),
1284                      sender->external_name());
1285         THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), buf);
1286       }
1287     }
1288   }
1289 
1290   // check if not static
1291   if (sel_method->is_static()) {
1292     ResourceMark rm(THREAD);
1293     stringStream ss;
1294     ss.print("Expecting non-static method '");
1295     resolved_method->print_external_name(&ss);
1296     ss.print("'");
1297     THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1298   }
1299 
1300   // check if abstract
1301   if (sel_method->is_abstract()) {
1302     ResourceMark rm(THREAD);
1303     stringStream ss;
1304     ss.print("'");
1305     Method::print_external_name(&ss, resolved_klass, sel_method->name(), sel_method->signature());
1306     ss.print("'");
1307     THROW_MSG(vmSymbols::java_lang_AbstractMethodError(), ss.as_string());
1308   }
1309 
1310   if (log_develop_is_enabled(Trace, itables)) {
1311     trace_method_resolution("invokespecial selected method: resolved-class:",
1312                             resolved_klass, resolved_klass, sel_method(), true);
1313   }
1314 
1315   // setup result
1316   result.set_static(resolved_klass, sel_method, CHECK);
1317 }
1318 
1319 void LinkResolver::resolve_virtual_call(CallInfo& result, Handle recv, Klass* receiver_klass,
1320                                         const LinkInfo& link_info,
1321                                         bool check_null_and_abstract, TRAPS) {
1322   Method* resolved_method = linktime_resolve_virtual_method(link_info, CHECK);
1323   runtime_resolve_virtual_method(result, methodHandle(THREAD, resolved_method),
1324                                  link_info.resolved_klass(),
1325                                  recv, receiver_klass,
1326                                  check_null_and_abstract, CHECK);
1327 }
1328 
1329 // throws linktime exceptions
1330 Method* LinkResolver::linktime_resolve_virtual_method(const LinkInfo& link_info,
1331                                                            TRAPS) {
1332   // normal method resolution
1333   Method* resolved_method = resolve_method(link_info, Bytecodes::_invokevirtual, CHECK_NULL);
1334 
1335   assert(resolved_method->name() != vmSymbols::object_initializer_name(), "should have been checked in verifier");
1336   assert(resolved_method->name() != vmSymbols::class_initializer_name (), "should have been checked in verifier");
1337 
1338   // check if private interface method
1339   Klass* resolved_klass = link_info.resolved_klass();
1340   Klass* current_klass = link_info.current_klass();
1341 
1342   // This is impossible, if resolve_klass is an interface, we've thrown icce in resolve_method
1343   if (resolved_klass->is_interface() && resolved_method->is_private()) {
1344     ResourceMark rm(THREAD);
1345     stringStream ss;
1346     ss.print("private interface method requires invokespecial, not invokevirtual: method '");
1347     resolved_method->print_external_name(&ss);
1348     ss.print("', caller-class: %s",
1349              (current_klass == NULL ? "<null>" : current_klass->internal_name()));
1350     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1351   }
1352 
1353   // check if not static
1354   if (resolved_method->is_static()) {
1355     ResourceMark rm(THREAD);
1356     stringStream ss;
1357     ss.print("Expecting non-static method '");
1358     resolved_method->print_external_name(&ss);
1359     ss.print("'");
1360     THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
1361   }
1362 
1363   if (log_develop_is_enabled(Trace, vtables)) {
1364     trace_method_resolution("invokevirtual resolved method: caller-class:",
1365                             current_klass, resolved_klass, resolved_method, false);
1366   }
1367 
1368   return resolved_method;
1369 }
1370 
1371 // throws runtime exceptions
1372 void LinkResolver::runtime_resolve_virtual_method(CallInfo& result,
1373                                                   const methodHandle& resolved_method,
1374                                                   Klass* resolved_klass,
1375                                                   Handle recv,
1376                                                   Klass* recv_klass,
1377                                                   bool check_null_and_abstract,
1378                                                   TRAPS) {
1379 
1380   // setup default return values
1381   int vtable_index = Method::invalid_vtable_index;
1382   methodHandle selected_method;
1383 
1384   // runtime method resolution
1385   if (check_null_and_abstract && recv.is_null()) { // check if receiver exists
1386     THROW(vmSymbols::java_lang_NullPointerException());
1387   }
1388 
1389   // Virtual methods cannot be resolved before its klass has been linked, for otherwise the Method*'s
1390   // has not been rewritten, and the vtable initialized. Make sure to do this after the nullcheck, since
1391   // a missing receiver might result in a bogus lookup.
1392   assert(resolved_method->method_holder()->is_linked(), "must be linked");
1393 
1394   // do lookup based on receiver klass using the vtable index
1395   if (resolved_method->method_holder()->is_interface()) { // default or miranda method
1396     vtable_index = vtable_index_of_interface_method(resolved_klass, resolved_method);
1397     assert(vtable_index >= 0 , "we should have valid vtable index at this point");
1398 
1399     selected_method = methodHandle(THREAD, recv_klass->method_at_vtable(vtable_index));
1400   } else {
1401     // at this point we are sure that resolved_method is virtual and not
1402     // a default or miranda method; therefore, it must have a valid vtable index.
1403     assert(!resolved_method->has_itable_index(), "");
1404     vtable_index = resolved_method->vtable_index();
1405     // We could get a negative vtable_index of nonvirtual_vtable_index for private
1406     // methods, or for final methods. Private methods never appear in the vtable
1407     // and never override other methods. As an optimization, final methods are
1408     // never put in the vtable, unless they override an existing method.
1409     // So if we do get nonvirtual_vtable_index, it means the selected method is the
1410     // resolved method, and it can never be changed by an override.
1411     if (vtable_index == Method::nonvirtual_vtable_index) {
1412       assert(resolved_method->can_be_statically_bound(), "cannot override this method");
1413       selected_method = resolved_method;
1414     } else {
1415       selected_method = methodHandle(THREAD, recv_klass->method_at_vtable(vtable_index));
1416     }
1417   }
1418 
1419   // check if method exists
1420   if (selected_method.is_null()) {
1421     throw_abstract_method_error(resolved_method, recv_klass, CHECK);
1422   }
1423 
1424   // check if abstract
1425   if (check_null_and_abstract && selected_method->is_abstract()) {
1426     // Pass arguments for generating a verbose error message.
1427     throw_abstract_method_error(resolved_method, selected_method, recv_klass, CHECK);
1428   }
1429 
1430   if (log_develop_is_enabled(Trace, vtables)) {
1431     trace_method_resolution("invokevirtual selected method: receiver-class:",
1432                             recv_klass, resolved_klass, selected_method(),
1433                             false, vtable_index);
1434   }
1435   // setup result
1436   result.set_virtual(resolved_klass, resolved_method, selected_method, vtable_index, CHECK);
1437 }
1438 
1439 void LinkResolver::resolve_interface_call(CallInfo& result, Handle recv, Klass* recv_klass,
1440                                           const LinkInfo& link_info,
1441                                           bool check_null_and_abstract, TRAPS) {
1442   // throws linktime exceptions
1443   Method* resolved_method = linktime_resolve_interface_method(link_info, CHECK);
1444   methodHandle mh(THREAD, resolved_method);
1445   runtime_resolve_interface_method(result, mh, link_info.resolved_klass(),
1446                                    recv, recv_klass, check_null_and_abstract, CHECK);
1447 }
1448 
1449 Method* LinkResolver::linktime_resolve_interface_method(const LinkInfo& link_info,
1450                                                              TRAPS) {
1451   // normal interface method resolution
1452   Method* resolved_method = resolve_interface_method(link_info, Bytecodes::_invokeinterface, CHECK_NULL);
1453   assert(resolved_method->name() != vmSymbols::object_initializer_name(), "should have been checked in verifier");
1454   assert(resolved_method->name() != vmSymbols::class_initializer_name (), "should have been checked in verifier");
1455 
1456   return resolved_method;
1457 }
1458 
1459 // throws runtime exceptions
1460 void LinkResolver::runtime_resolve_interface_method(CallInfo& result,
1461                                                     const methodHandle& resolved_method,
1462                                                     Klass* resolved_klass,
1463                                                     Handle recv,
1464                                                     Klass* recv_klass,
1465                                                     bool check_null_and_abstract, TRAPS) {
1466 
1467   // check if receiver exists
1468   if (check_null_and_abstract && recv.is_null()) {
1469     THROW(vmSymbols::java_lang_NullPointerException());
1470   }
1471 
1472   // check if receiver klass implements the resolved interface
1473   if (!recv_klass->is_subtype_of(resolved_klass)) {
1474     ResourceMark rm(THREAD);
1475     char buf[200];
1476     jio_snprintf(buf, sizeof(buf), "Class %s does not implement the requested interface %s",
1477                  recv_klass->external_name(),
1478                  resolved_klass->external_name());
1479     THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
1480   }
1481 
1482   methodHandle selected_method = resolved_method;
1483 
1484   // resolve the method in the receiver class, unless it is private
1485   if (!resolved_method()->is_private()) {
1486     // do lookup based on receiver klass
1487     // This search must match the linktime preparation search for itable initialization
1488     // to correctly enforce loader constraints for interface method inheritance.
1489     // Private methods are skipped as the resolved method was not private.
1490     Method* method = lookup_instance_method_in_klasses(recv_klass,
1491                                                        resolved_method->name(),
1492                                                        resolved_method->signature(),
1493                                                        Klass::PrivateLookupMode::skip);
1494     selected_method = methodHandle(THREAD, method);
1495 
1496     if (selected_method.is_null() && !check_null_and_abstract) {
1497       // In theory this is a harmless placeholder value, but
1498       // in practice leaving in null affects the nsk default method tests.
1499       // This needs further study.
1500       selected_method = resolved_method;
1501     }
1502     // check if method exists
1503     if (selected_method.is_null()) {
1504       // Pass arguments for generating a verbose error message.
1505       throw_abstract_method_error(resolved_method, recv_klass, CHECK);
1506     }
1507     // check access
1508     // Throw Illegal Access Error if selected_method is not public.
1509     if (!selected_method->is_public()) {
1510       ResourceMark rm(THREAD);
1511       stringStream ss;
1512       ss.print("'");
1513       Method::print_external_name(&ss, recv_klass, selected_method->name(), selected_method->signature());
1514       ss.print("'");
1515       THROW_MSG(vmSymbols::java_lang_IllegalAccessError(), ss.as_string());
1516     }
1517     // check if abstract
1518     if (check_null_and_abstract && selected_method->is_abstract()) {
1519       throw_abstract_method_error(resolved_method, selected_method, recv_klass, CHECK);
1520     }
1521   }
1522 
1523   if (log_develop_is_enabled(Trace, itables)) {
1524     trace_method_resolution("invokeinterface selected method: receiver-class:",
1525                             recv_klass, resolved_klass, selected_method(), true);
1526   }
1527   // setup result
1528   if (resolved_method->has_vtable_index()) {
1529     int vtable_index = resolved_method->vtable_index();
1530     log_develop_trace(itables)("  -- vtable index: %d", vtable_index);
1531     assert(vtable_index == selected_method->vtable_index(), "sanity check");
1532     result.set_virtual(resolved_klass, resolved_method, selected_method, vtable_index, CHECK);
1533   } else if (resolved_method->has_itable_index()) {
1534     int itable_index = resolved_method()->itable_index();
1535     log_develop_trace(itables)("  -- itable index: %d", itable_index);
1536     result.set_interface(resolved_klass, resolved_method, selected_method, itable_index, CHECK);
1537   } else {
1538     int index = resolved_method->vtable_index();
1539     log_develop_trace(itables)("  -- non itable/vtable index: %d", index);
1540     assert(index == Method::nonvirtual_vtable_index, "Oops hit another case!");
1541     assert(resolved_method()->is_private() ||
1542            (resolved_method()->is_final() && resolved_method->method_holder() == vmClasses::Object_klass()),
1543            "Should only have non-virtual invokeinterface for private or final-Object methods!");
1544     assert(resolved_method()->can_be_statically_bound(), "Should only have non-virtual invokeinterface for statically bound methods!");
1545     // This sets up the nonvirtual form of "virtual" call (as needed for final and private methods)
1546     result.set_virtual(resolved_klass, resolved_method, resolved_method, index, CHECK);
1547   }
1548 }
1549 
1550 
1551 Method* LinkResolver::linktime_resolve_interface_method_or_null(
1552                                                  const LinkInfo& link_info) {
1553   EXCEPTION_MARK;
1554   Method* method_result = linktime_resolve_interface_method(link_info, THREAD);
1555   if (HAS_PENDING_EXCEPTION) {
1556     CLEAR_PENDING_EXCEPTION;
1557     return NULL;
1558   } else {
1559     return method_result;
1560   }
1561 }
1562 
1563 Method* LinkResolver::linktime_resolve_virtual_method_or_null(
1564                                                  const LinkInfo& link_info) {
1565   EXCEPTION_MARK;
1566   Method* method_result = linktime_resolve_virtual_method(link_info, THREAD);
1567   if (HAS_PENDING_EXCEPTION) {
1568     CLEAR_PENDING_EXCEPTION;
1569     return NULL;
1570   } else {
1571     return method_result;
1572   }
1573 }
1574 
1575 Method* LinkResolver::resolve_virtual_call_or_null(
1576                                                  Klass* receiver_klass,
1577                                                  const LinkInfo& link_info) {
1578   EXCEPTION_MARK;
1579   CallInfo info;
1580   resolve_virtual_call(info, Handle(), receiver_klass, link_info, false, THREAD);
1581   if (HAS_PENDING_EXCEPTION) {
1582     CLEAR_PENDING_EXCEPTION;
1583     return NULL;
1584   }
1585   return info.selected_method();
1586 }
1587 
1588 Method* LinkResolver::resolve_interface_call_or_null(
1589                                                  Klass* receiver_klass,
1590                                                  const LinkInfo& link_info) {
1591   EXCEPTION_MARK;
1592   CallInfo info;
1593   resolve_interface_call(info, Handle(), receiver_klass, link_info, false, THREAD);
1594   if (HAS_PENDING_EXCEPTION) {
1595     CLEAR_PENDING_EXCEPTION;
1596     return NULL;
1597   }
1598   return info.selected_method();
1599 }
1600 
1601 int LinkResolver::resolve_virtual_vtable_index(Klass* receiver_klass,
1602                                                const LinkInfo& link_info) {
1603   EXCEPTION_MARK;
1604   CallInfo info;
1605   resolve_virtual_call(info, Handle(), receiver_klass, link_info,
1606                        /*check_null_or_abstract*/false, THREAD);
1607   if (HAS_PENDING_EXCEPTION) {
1608     CLEAR_PENDING_EXCEPTION;
1609     return Method::invalid_vtable_index;
1610   }
1611   return info.vtable_index();
1612 }
1613 
1614 Method* LinkResolver::resolve_static_call_or_null(const LinkInfo& link_info) {
1615   EXCEPTION_MARK;
1616   CallInfo info;
1617   resolve_static_call(info, link_info, /*initialize_class*/false, THREAD);
1618   if (HAS_PENDING_EXCEPTION) {
1619     CLEAR_PENDING_EXCEPTION;
1620     return NULL;
1621   }
1622   return info.selected_method();
1623 }
1624 
1625 Method* LinkResolver::resolve_special_call_or_null(const LinkInfo& link_info) {
1626   EXCEPTION_MARK;
1627   CallInfo info;
1628   resolve_special_call(info, Handle(), link_info, THREAD);
1629   if (HAS_PENDING_EXCEPTION) {
1630     CLEAR_PENDING_EXCEPTION;
1631     return NULL;
1632   }
1633   return info.selected_method();
1634 }
1635 
1636 
1637 
1638 //------------------------------------------------------------------------------------------------------------------------
1639 // ConstantPool entries
1640 
1641 void LinkResolver::resolve_invoke(CallInfo& result, Handle recv, const constantPoolHandle& pool, int index, Bytecodes::Code byte, TRAPS) {
1642   switch (byte) {
1643     case Bytecodes::_invokestatic   : resolve_invokestatic   (result,       pool, index, CHECK); break;
1644     case Bytecodes::_invokespecial  : resolve_invokespecial  (result, recv, pool, index, CHECK); break;
1645     case Bytecodes::_invokevirtual  : resolve_invokevirtual  (result, recv, pool, index, CHECK); break;
1646     case Bytecodes::_invokehandle   : resolve_invokehandle   (result,       pool, index, CHECK); break;
1647     case Bytecodes::_invokedynamic  : resolve_invokedynamic  (result,       pool, index, CHECK); break;
1648     case Bytecodes::_invokeinterface: resolve_invokeinterface(result, recv, pool, index, CHECK); break;
1649     default                         :                                                            break;
1650   }
1651   return;
1652 }
1653 
1654 void LinkResolver::resolve_invoke(CallInfo& result, Handle& recv,
1655                                   const methodHandle& attached_method,
1656                                   Bytecodes::Code byte, bool check_null_and_abstract, TRAPS) {
1657   Klass* defc = attached_method->method_holder();
1658   Symbol* name = attached_method->name();
1659   Symbol* type = attached_method->signature();
1660   LinkInfo link_info(defc, name, type);
1661   Klass* recv_klass = recv.is_null() ? defc : recv->klass();
1662   switch(byte) {
1663     case Bytecodes::_invokevirtual:
1664       resolve_virtual_call(result, recv, recv_klass, link_info,
1665                            check_null_and_abstract, CHECK);
1666       break;
1667     case Bytecodes::_invokeinterface:
1668       resolve_interface_call(result, recv, recv_klass, link_info,
1669                              check_null_and_abstract, CHECK);
1670       break;
1671     case Bytecodes::_invokestatic:
1672       resolve_static_call(result, link_info, /*initialize_class=*/false, CHECK);
1673       break;
1674     case Bytecodes::_invokespecial:
1675       resolve_special_call(result, recv, link_info, CHECK);
1676       break;
1677     default:
1678       fatal("bad call: %s", Bytecodes::name(byte));
1679       break;
1680   }
1681 }
1682 
1683 void LinkResolver::resolve_invokestatic(CallInfo& result, const constantPoolHandle& pool, int index, TRAPS) {
1684   LinkInfo link_info(pool, index, CHECK);
1685   resolve_static_call(result, link_info, /*initialize_class*/true, CHECK);
1686 }
1687 
1688 
1689 void LinkResolver::resolve_invokespecial(CallInfo& result, Handle recv,
1690                                          const constantPoolHandle& pool, int index, TRAPS) {
1691   LinkInfo link_info(pool, index, CHECK);
1692   resolve_special_call(result, recv, link_info, CHECK);
1693 }
1694 
1695 
1696 void LinkResolver::resolve_invokevirtual(CallInfo& result, Handle recv,
1697                                           const constantPoolHandle& pool, int index,
1698                                           TRAPS) {
1699 
1700   LinkInfo link_info(pool, index, CHECK);
1701   Klass* recvrKlass = recv.is_null() ? (Klass*)NULL : recv->klass();
1702   resolve_virtual_call(result, recv, recvrKlass, link_info, /*check_null_or_abstract*/true, CHECK);
1703 }
1704 
1705 
1706 void LinkResolver::resolve_invokeinterface(CallInfo& result, Handle recv, const constantPoolHandle& pool, int index, TRAPS) {
1707   LinkInfo link_info(pool, index, CHECK);
1708   Klass* recvrKlass = recv.is_null() ? (Klass*)NULL : recv->klass();
1709   resolve_interface_call(result, recv, recvrKlass, link_info, true, CHECK);
1710 }
1711 
1712 
1713 void LinkResolver::resolve_invokehandle(CallInfo& result, const constantPoolHandle& pool, int index, TRAPS) {
1714   // This guy is reached from InterpreterRuntime::resolve_invokehandle.
1715   LinkInfo link_info(pool, index, CHECK);
1716   if (log_is_enabled(Info, methodhandles)) {
1717     ResourceMark rm(THREAD);
1718     log_info(methodhandles)("resolve_invokehandle %s %s", link_info.name()->as_C_string(),
1719                             link_info.signature()->as_C_string());
1720   }
1721   resolve_handle_call(result, link_info, CHECK);
1722 }
1723 
1724 void LinkResolver::resolve_handle_call(CallInfo& result,
1725                                        const LinkInfo& link_info,
1726                                        TRAPS) {
1727   // JSR 292:  this must be an implicitly generated method MethodHandle.invokeExact(*...) or similar
1728   Klass* resolved_klass = link_info.resolved_klass();
1729   assert(resolved_klass == vmClasses::MethodHandle_klass() ||
1730          resolved_klass == vmClasses::VarHandle_klass(), "");
1731   assert(MethodHandles::is_signature_polymorphic_name(link_info.name()), "");
1732   Handle       resolved_appendix;
1733   Method* resolved_method = lookup_polymorphic_method(link_info, &resolved_appendix, CHECK);
1734   result.set_handle(resolved_klass, methodHandle(THREAD, resolved_method), resolved_appendix, CHECK);
1735 }
1736 
1737 void LinkResolver::resolve_invokedynamic(CallInfo& result, const constantPoolHandle& pool, int indy_index, TRAPS) {
1738   ConstantPoolCacheEntry* cpce = pool->invokedynamic_cp_cache_entry_at(indy_index);
1739   int pool_index = cpce->constant_pool_index();
1740 
1741   // Resolve the bootstrap specifier (BSM + optional arguments).
1742   BootstrapInfo bootstrap_specifier(pool, pool_index, indy_index);
1743 
1744   // Check if CallSite has been bound already or failed already, and short circuit:
1745   {
1746     bool is_done = bootstrap_specifier.resolve_previously_linked_invokedynamic(result, CHECK);
1747     if (is_done) return;
1748   }
1749 
1750   // The initial step in Call Site Specifier Resolution is to resolve the symbolic
1751   // reference to a method handle which will be the bootstrap method for a dynamic
1752   // call site.  If resolution for the java.lang.invoke.MethodHandle for the bootstrap
1753   // method fails, then a MethodHandleInError is stored at the corresponding bootstrap
1754   // method's CP index for the CONSTANT_MethodHandle_info.  So, there is no need to
1755   // set the indy_rf flag since any subsequent invokedynamic instruction which shares
1756   // this bootstrap method will encounter the resolution of MethodHandleInError.
1757 
1758   resolve_dynamic_call(result, bootstrap_specifier, CHECK);
1759 
1760   LogTarget(Debug, methodhandles, indy) lt_indy;
1761   if (lt_indy.is_enabled()) {
1762     LogStream ls(lt_indy);
1763     bootstrap_specifier.print_msg_on(&ls, "resolve_invokedynamic");
1764   }
1765 
1766   // The returned linkage result is provisional up to the moment
1767   // the interpreter or runtime performs a serialized check of
1768   // the relevant CPCE::f1 field.  This is done by the caller
1769   // of this method, via CPCE::set_dynamic_call, which uses
1770   // an ObjectLocker to do the final serialization of updates
1771   // to CPCE state, including f1.
1772 
1773   // Log dynamic info to CDS classlist.
1774   ArchiveUtils::log_to_classlist(&bootstrap_specifier, CHECK);
1775 }
1776 
1777 void LinkResolver::resolve_dynamic_call(CallInfo& result,
1778                                         BootstrapInfo& bootstrap_specifier,
1779                                         TRAPS) {
1780   // JSR 292:  this must resolve to an implicitly generated method
1781   // such as MH.linkToCallSite(*...) or some other call-site shape.
1782   // The appendix argument is likely to be a freshly-created CallSite.
1783   // It may also be a MethodHandle from an unwrapped ConstantCallSite,
1784   // or any other reference.  The resolved_method as well as the appendix
1785   // are both recorded together via CallInfo::set_handle.
1786   SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);
1787   Exceptions::wrap_dynamic_exception(/* is_indy */ true, THREAD);
1788 
1789   if (HAS_PENDING_EXCEPTION) {
1790     if (!PENDING_EXCEPTION->is_a(vmClasses::LinkageError_klass())) {
1791       // Let any random low-level IE or SOE or OOME just bleed through.
1792       // Basically we pretend that the bootstrap method was never called,
1793       // if it fails this way:  We neither record a successful linkage,
1794       // nor do we memorize a LE for posterity.
1795       return;
1796     }
1797     // JVMS 5.4.3 says: If an attempt by the Java Virtual Machine to resolve
1798     // a symbolic reference fails because an error is thrown that is an
1799     // instance of LinkageError (or a subclass), then subsequent attempts to
1800     // resolve the reference always fail with the same error that was thrown
1801     // as a result of the initial resolution attempt.
1802      bool recorded_res_status = bootstrap_specifier.save_and_throw_indy_exc(CHECK);
1803      if (!recorded_res_status) {
1804        // Another thread got here just before we did.  So, either use the method
1805        // that it resolved or throw the LinkageError exception that it threw.
1806        bool is_done = bootstrap_specifier.resolve_previously_linked_invokedynamic(result, CHECK);
1807        if (is_done) return;
1808      }
1809      assert(bootstrap_specifier.invokedynamic_cp_cache_entry()->indy_resolution_failed(),
1810             "Resolution failure flag wasn't set");
1811   }
1812 
1813   bootstrap_specifier.resolve_newly_linked_invokedynamic(result, CHECK);
1814   // Exceptions::wrap_dynamic_exception not used because
1815   // set_handle doesn't throw linkage errors
1816 }
1817 
1818 // Selected method is abstract.
1819 void LinkResolver::throw_abstract_method_error(const methodHandle& resolved_method,
1820                                                const methodHandle& selected_method,
1821                                                Klass *recv_klass, TRAPS) {
1822   Klass *resolved_klass = resolved_method->method_holder();
1823   ResourceMark rm(THREAD);
1824   stringStream ss;
1825 
1826   if (recv_klass != NULL) {
1827     ss.print("Receiver class %s does not define or inherit an "
1828              "implementation of the",
1829              recv_klass->external_name());
1830   } else {
1831     ss.print("Missing implementation of");
1832   }
1833 
1834   assert(resolved_method.not_null(), "Sanity");
1835   ss.print(" resolved method '%s%s",
1836            resolved_method->is_abstract() ? "abstract " : "",
1837            resolved_method->is_private()  ? "private "  : "");
1838   resolved_method->signature()->print_as_signature_external_return_type(&ss);
1839   ss.print(" %s(", resolved_method->name()->as_C_string());
1840   resolved_method->signature()->print_as_signature_external_parameters(&ss);
1841   ss.print(")' of %s %s.",
1842            resolved_klass->external_kind(),
1843            resolved_klass->external_name());
1844 
1845   if (selected_method.not_null() && !(resolved_method == selected_method)) {
1846     ss.print(" Selected method is '%s%s",
1847              selected_method->is_abstract() ? "abstract " : "",
1848              selected_method->is_private()  ? "private "  : "");
1849     selected_method->print_external_name(&ss);
1850     ss.print("'.");
1851   }
1852 
1853   THROW_MSG(vmSymbols::java_lang_AbstractMethodError(), ss.as_string());
1854 }