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