methodHandles.cpp 55.5 KB
Newer Older
1
/*
2
 * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
22 23 24
 *
 */

25 26
#include "precompiled.hpp"
#include "classfile/symbolTable.hpp"
27
#include "compiler/compileBroker.hpp"
28
#include "interpreter/interpreter.hpp"
29
#include "interpreter/oopMapCache.hpp"
30 31 32
#include "memory/allocation.inline.hpp"
#include "memory/oopFactory.hpp"
#include "prims/methodHandles.hpp"
33
#include "prims/jvmtiRedefineClassesTrace.hpp"
34
#include "runtime/compilationPolicy.hpp"
35 36 37 38 39
#include "runtime/javaCalls.hpp"
#include "runtime/reflection.hpp"
#include "runtime/signature.hpp"
#include "runtime/stubRoutines.hpp"

40

41 42
/*
 * JSR 292 reference implementation: method handles
43 44 45 46 47 48 49 50 51 52
 * The JDK 7 reference implementation represented method handle
 * combinations as chains.  Each link in the chain had a "vmentry"
 * field which pointed at a bit of assembly code which performed
 * one transformation before dispatching to the next link in the chain.
 *
 * The current reference implementation pushes almost all code generation
 * responsibility to (trusted) Java code.  A method handle contains a
 * pointer to its "LambdaForm", which embodies all details of the method
 * handle's behavior.  The LambdaForm is a normal Java object, managed
 * by a runtime coded in Java.
53 54 55
 */

bool MethodHandles::_enabled = false; // set true after successful native linkage
56
MethodHandlesAdapterBlob* MethodHandles::_adapter_code = NULL;
57 58 59 60

//------------------------------------------------------------------------------
// MethodHandles::generate_adapters
//
61
void MethodHandles::generate_adapters() {
62
  if (!EnableInvokeDynamic || SystemDictionary::MethodHandle_klass() == NULL)  return;
63 64 65 66 67

  assert(_adapter_code == NULL, "generate only once");

  ResourceMark rm;
  TraceTime timer("MethodHandles adapters generation", TraceStartupTime);
68
  _adapter_code = MethodHandlesAdapterBlob::create(adapter_code_size);
69
  if (_adapter_code == NULL)
70 71
    vm_exit_out_of_memory(adapter_code_size, OOM_MALLOC_ERROR,
                          "CodeCache: no room for MethodHandles adapters");
72 73 74 75 76 77
  {
    CodeBuffer code(_adapter_code);
    MethodHandlesAdapterGenerator g(&code);
    g.generate();
    code.log_section_sizes("MethodHandlesAdapterBlob");
  }
78 79 80 81 82
}

//------------------------------------------------------------------------------
// MethodHandlesAdapterGenerator::generate
//
83
void MethodHandlesAdapterGenerator::generate() {
84
  // Generate generic method handle adapters.
85 86 87 88 89 90 91 92 93
  // Generate interpreter entries
  for (Interpreter::MethodKind mk = Interpreter::method_handle_invoke_FIRST;
       mk <= Interpreter::method_handle_invoke_LAST;
       mk = Interpreter::MethodKind(1 + (int)mk)) {
    vmIntrinsics::ID iid = Interpreter::method_handle_intrinsic(mk);
    StubCodeMark mark(this, "MethodHandle::interpreter_entry", vmIntrinsics::name_at(iid));
    address entry = MethodHandles::generate_method_handle_interpreter_entry(_masm, iid);
    if (entry != NULL) {
      Interpreter::set_entry_for_kind(mk, entry);
94
    }
95
    // If the entry is not set, it will throw AbstractMethodError.
96 97 98
  }
}

99 100
void MethodHandles::set_enabled(bool z) {
  if (_enabled != z) {
101
    guarantee(z && EnableInvokeDynamic, "can only enable once, and only if -XX:+EnableInvokeDynamic");
102 103 104 105 106 107
    _enabled = z;
  }
}

// MemberName support

108
// import java_lang_invoke_MemberName.*
109
enum {
110 111 112 113 114
  IS_METHOD            = java_lang_invoke_MemberName::MN_IS_METHOD,
  IS_CONSTRUCTOR       = java_lang_invoke_MemberName::MN_IS_CONSTRUCTOR,
  IS_FIELD             = java_lang_invoke_MemberName::MN_IS_FIELD,
  IS_TYPE              = java_lang_invoke_MemberName::MN_IS_TYPE,
  CALLER_SENSITIVE     = java_lang_invoke_MemberName::MN_CALLER_SENSITIVE,
115 116
  REFERENCE_KIND_SHIFT = java_lang_invoke_MemberName::MN_REFERENCE_KIND_SHIFT,
  REFERENCE_KIND_MASK  = java_lang_invoke_MemberName::MN_REFERENCE_KIND_MASK,
117 118
  SEARCH_SUPERCLASSES  = java_lang_invoke_MemberName::MN_SEARCH_SUPERCLASSES,
  SEARCH_INTERFACES    = java_lang_invoke_MemberName::MN_SEARCH_INTERFACES,
119
  ALL_KINDS      = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE
120 121
};

122 123 124 125 126 127 128
Handle MethodHandles::new_MemberName(TRAPS) {
  Handle empty;
  instanceKlassHandle k(THREAD, SystemDictionary::MemberName_klass());
  if (!k->is_initialized())  k->initialize(CHECK_(empty));
  return Handle(THREAD, k->allocate_instance(THREAD));
}

129
oop MethodHandles::init_MemberName(Handle mname, Handle target) {
130 131
  // This method is used from java.lang.invoke.MemberName constructors.
  // It fills in the new MemberName from a java.lang.reflect.Member.
132 133
  Thread* thread = Thread::current();
  oop target_oop = target();
134
  Klass* target_klass = target_oop->klass();
135
  if (target_klass == SystemDictionary::reflect_Field_klass()) {
136 137
    oop clazz = java_lang_reflect_Field::clazz(target_oop); // fd.field_holder()
    int slot  = java_lang_reflect_Field::slot(target_oop);  // fd.index()
138
    KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
139 140 141 142 143 144 145 146 147 148 149 150
    if (!k.is_null() && k->oop_is_instance()) {
      fieldDescriptor fd(InstanceKlass::cast(k()), slot);
      oop mname2 = init_field_MemberName(mname, fd);
      if (mname2 != NULL) {
        // Since we have the reified name and type handy, add them to the result.
        if (java_lang_invoke_MemberName::name(mname2) == NULL)
          java_lang_invoke_MemberName::set_name(mname2, java_lang_reflect_Field::name(target_oop));
        if (java_lang_invoke_MemberName::type(mname2) == NULL)
          java_lang_invoke_MemberName::set_type(mname2, java_lang_reflect_Field::type(target_oop));
      }
      return mname2;
    }
151 152 153
  } else if (target_klass == SystemDictionary::reflect_Method_klass()) {
    oop clazz  = java_lang_reflect_Method::clazz(target_oop);
    int slot   = java_lang_reflect_Method::slot(target_oop);
154 155 156
    KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
    if (!k.is_null() && k->oop_is_instance()) {
      Method* m = InstanceKlass::cast(k())->method_with_idnum(slot);
157 158 159 160
      if (m == NULL || is_signature_polymorphic(m->intrinsic_id()))
        return NULL;            // do not resolve unless there is a concrete signature
      CallInfo info(m, k());
      return init_method_MemberName(mname, info);
161 162 163 164
    }
  } else if (target_klass == SystemDictionary::reflect_Constructor_klass()) {
    oop clazz  = java_lang_reflect_Constructor::clazz(target_oop);
    int slot   = java_lang_reflect_Constructor::slot(target_oop);
165 166 167
    KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
    if (!k.is_null() && k->oop_is_instance()) {
      Method* m = InstanceKlass::cast(k())->method_with_idnum(slot);
168 169 170
      if (m == NULL)  return NULL;
      CallInfo info(m, k());
      return init_method_MemberName(mname, info);
171
    }
172
  }
173
  return NULL;
174 175
}

176
oop MethodHandles::init_method_MemberName(Handle mname, CallInfo& info, bool intern) {
177 178
  assert(info.resolved_appendix().is_null(), "only normal methods here");
  methodHandle m = info.resolved_method();
J
jrose 已提交
179
  KlassHandle m_klass = m->method_holder();
180 181 182 183 184 185 186
  int flags = (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS );
  int vmindex = Method::invalid_vtable_index;

  switch (info.call_kind()) {
  case CallInfo::itable_call:
    vmindex = info.itable_index();
    // More importantly, the itable index only works with the method holder.
J
jrose 已提交
187
    assert(m_klass->verify_itable_index(vmindex), "");
188
    flags |= IS_METHOD | (JVM_REF_invokeInterface << REFERENCE_KIND_SHIFT);
189 190
    if (TraceInvokeDynamic) {
      ResourceMark rm;
J
jrose 已提交
191 192 193
      tty->print_cr("memberName: invokeinterface method_holder::method: %s, itableindex: %d, access_flags:",
            Method::name_and_sig_as_C_string(m->method_holder(), m->name(), m->signature()),
            vmindex);
194 195 196 197 198 199
       m->access_flags().print_on(tty);
       if (!m->is_abstract()) {
         tty->print("default");
       }
       tty->cr();
    }
200 201 202 203
    break;

  case CallInfo::vtable_call:
    vmindex = info.vtable_index();
204
    flags |= IS_METHOD | (JVM_REF_invokeVirtual << REFERENCE_KIND_SHIFT);
J
jrose 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    assert(info.resolved_klass()->is_subtype_of(m_klass()), "virtual call must be type-safe");
    if (m_klass->is_interface()) {
      // This is a vtable call to an interface method (abstract "miranda method" or default method).
      // The vtable index is meaningless without a class (not interface) receiver type, so get one.
      // (LinkResolver should help us figure this out.)
      KlassHandle m_klass_non_interface = info.resolved_klass();
      if (m_klass_non_interface->is_interface()) {
        m_klass_non_interface = SystemDictionary::Object_klass();
#ifdef ASSERT
        { ResourceMark rm;
          Method* m2 = m_klass_non_interface->vtable()->method_at(vmindex);
          assert(m->name() == m2->name() && m->signature() == m2->signature(),
                 err_msg("at %d, %s != %s", vmindex,
                         m->name_and_sig_as_C_string(), m2->name_and_sig_as_C_string()));
        }
#endif //ASSERT
      }
      if (!m->is_public()) {
        assert(m->is_public(), "virtual call must be to public interface method");
        return NULL;  // elicit an error later in product build
      }
      assert(info.resolved_klass()->is_subtype_of(m_klass_non_interface()), "virtual call must be type-safe");
      m_klass = m_klass_non_interface;
    }
229 230 231
    if (TraceInvokeDynamic) {
      ResourceMark rm;
      tty->print_cr("memberName: invokevirtual method_holder::method: %s, receiver: %s, vtableindex: %d, access_flags:",
J
jrose 已提交
232 233
            Method::name_and_sig_as_C_string(m->method_holder(), m->name(), m->signature()),
            m_klass->internal_name(), vmindex);
234 235 236 237 238 239
       m->access_flags().print_on(tty);
       if (m->is_default_method()) {
         tty->print("default");
       }
       tty->cr();
    }
240 241 242 243 244 245 246 247 248 249 250 251 252 253
    break;

  case CallInfo::direct_call:
    vmindex = Method::nonvirtual_vtable_index;
    if (m->is_static()) {
      flags |= IS_METHOD      | (JVM_REF_invokeStatic  << REFERENCE_KIND_SHIFT);
    } else if (m->is_initializer()) {
      flags |= IS_CONSTRUCTOR | (JVM_REF_invokeSpecial << REFERENCE_KIND_SHIFT);
    } else {
      flags |= IS_METHOD      | (JVM_REF_invokeSpecial << REFERENCE_KIND_SHIFT);
    }
    break;

  default:  assert(false, "bad CallInfo");  return NULL;
254 255
  }

256 257 258 259 260
  // @CallerSensitive annotation detected
  if (m->caller_sensitive()) {
    flags |= CALLER_SENSITIVE;
  }

261
  oop mname_oop = mname();
262
  java_lang_invoke_MemberName::set_flags(   mname_oop, flags);
263
  java_lang_invoke_MemberName::set_vmtarget(mname_oop, m());
264
  java_lang_invoke_MemberName::set_vmindex( mname_oop, vmindex);   // vtable/itable index
J
jrose 已提交
265
  java_lang_invoke_MemberName::set_clazz(   mname_oop, m_klass->java_mirror());
266 267 268
  // Note:  name and type can be lazily computed by resolve_MemberName,
  // if Java code needs them as resolved String and MethodType objects.
  // The clazz must be eagerly stored, because it provides a GC
269
  // root to help keep alive the Method*.
270 271 272
  // If relevant, the vtable or itable value is stored as vmindex.
  // This is done eagerly, since it is readily available without
  // constructing any new objects.
273
  return m->method_holder()->add_member_name(mname, intern);
274 275
}

276 277 278
oop MethodHandles::init_field_MemberName(Handle mname, fieldDescriptor& fd, bool is_setter) {
  int flags = (jushort)( fd.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS );
  flags |= IS_FIELD | ((fd.is_static() ? JVM_REF_getStatic : JVM_REF_getField) << REFERENCE_KIND_SHIFT);
279
  if (is_setter)  flags += ((JVM_REF_putField - JVM_REF_getField) << REFERENCE_KIND_SHIFT);
280 281
  Metadata* vmtarget = fd.field_holder();
  int vmindex        = fd.offset();  // determines the field uniquely when combined with static bit
282
  oop mname_oop = mname();
283
  java_lang_invoke_MemberName::set_flags(mname_oop,    flags);
284 285
  java_lang_invoke_MemberName::set_vmtarget(mname_oop, vmtarget);
  java_lang_invoke_MemberName::set_vmindex(mname_oop,  vmindex);
286 287 288
  java_lang_invoke_MemberName::set_clazz(mname_oop,    fd.field_holder()->java_mirror());
  oop type = field_signature_type_or_null(fd.signature());
  oop name = field_name_or_null(fd.name());
289 290 291 292 293 294 295 296 297 298 299 300
  if (name != NULL)
    java_lang_invoke_MemberName::set_name(mname_oop,   name);
  if (type != NULL)
    java_lang_invoke_MemberName::set_type(mname_oop,   type);
  // Note:  name and type can be lazily computed by resolve_MemberName,
  // if Java code needs them as resolved String and Class objects.
  // Note that the incoming type oop might be pre-resolved (non-null).
  // The base clazz and field offset (vmindex) must be eagerly stored,
  // because they unambiguously identify the field.
  // Although the fieldDescriptor::_index would also identify the field,
  // we do not use it, because it is harder to decode.
  // TO DO: maybe intern mname_oop
301
  return mname();
302 303 304 305 306 307 308 309
}

// JVM 2.9 Special Methods:
// A method is signature polymorphic if and only if all of the following conditions hold :
// * It is declared in the java.lang.invoke.MethodHandle class.
// * It has a single formal parameter of type Object[].
// * It has a return type of Object.
// * It has the ACC_VARARGS and ACC_NATIVE flags set.
310
bool MethodHandles::is_method_handle_invoke_name(Klass* klass, Symbol* name) {
311 312 313 314 315
  if (klass == NULL)
    return false;
  // The following test will fail spuriously during bootstrap of MethodHandle itself:
  //    if (klass != SystemDictionary::MethodHandle_klass())
  // Test the name instead:
H
hseigel 已提交
316
  if (klass->name() != vmSymbols::java_lang_invoke_MethodHandle())
317 318
    return false;
  Symbol* poly_sig = vmSymbols::object_array_object_signature();
319
  Method* m = InstanceKlass::cast(klass)->find_method(name, poly_sig);
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  if (m == NULL)  return false;
  int required = JVM_ACC_NATIVE | JVM_ACC_VARARGS;
  int flags = m->access_flags().as_int();
  return (flags & required) == required;
}


Symbol* MethodHandles::signature_polymorphic_intrinsic_name(vmIntrinsics::ID iid) {
  assert(is_signature_polymorphic_intrinsic(iid), err_msg("iid=%d", iid));
  switch (iid) {
  case vmIntrinsics::_invokeBasic:      return vmSymbols::invokeBasic_name();
  case vmIntrinsics::_linkToVirtual:    return vmSymbols::linkToVirtual_name();
  case vmIntrinsics::_linkToStatic:     return vmSymbols::linkToStatic_name();
  case vmIntrinsics::_linkToSpecial:    return vmSymbols::linkToSpecial_name();
  case vmIntrinsics::_linkToInterface:  return vmSymbols::linkToInterface_name();
  }
  assert(false, "");
  return 0;
}

int MethodHandles::signature_polymorphic_intrinsic_ref_kind(vmIntrinsics::ID iid) {
  switch (iid) {
  case vmIntrinsics::_invokeBasic:      return 0;
  case vmIntrinsics::_linkToVirtual:    return JVM_REF_invokeVirtual;
  case vmIntrinsics::_linkToStatic:     return JVM_REF_invokeStatic;
  case vmIntrinsics::_linkToSpecial:    return JVM_REF_invokeSpecial;
  case vmIntrinsics::_linkToInterface:  return JVM_REF_invokeInterface;
  }
  assert(false, err_msg("iid=%d", iid));
  return 0;
350 351
}

352 353 354 355 356 357 358
vmIntrinsics::ID MethodHandles::signature_polymorphic_name_id(Symbol* name) {
  vmSymbols::SID name_id = vmSymbols::find_sid(name);
  switch (name_id) {
  // The ID _invokeGeneric stands for all non-static signature-polymorphic methods, except built-ins.
  case vmSymbols::VM_SYMBOL_ENUM_NAME(invoke_name):           return vmIntrinsics::_invokeGeneric;
  // The only built-in non-static signature-polymorphic method is MethodHandle.invokeBasic:
  case vmSymbols::VM_SYMBOL_ENUM_NAME(invokeBasic_name):      return vmIntrinsics::_invokeBasic;
359

360 361 362 363 364
  // There is one static signature-polymorphic method for each JVM invocation mode.
  case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToVirtual_name):    return vmIntrinsics::_linkToVirtual;
  case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToStatic_name):     return vmIntrinsics::_linkToStatic;
  case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToSpecial_name):    return vmIntrinsics::_linkToSpecial;
  case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToInterface_name):  return vmIntrinsics::_linkToInterface;
365
  }
366 367

  // Cover the case of invokeExact and any future variants of invokeFoo.
368
  Klass* mh_klass = SystemDictionary::well_known_klass(
369 370 371 372 373 374 375 376 377
                              SystemDictionary::WK_KLASS_ENUM_NAME(MethodHandle_klass) );
  if (mh_klass != NULL && is_method_handle_invoke_name(mh_klass, name))
    return vmIntrinsics::_invokeGeneric;

  // Note: The pseudo-intrinsic _compiledLambdaForm is never linked against.
  // Instead it is used to mark lambda forms bound to invokehandle or invokedynamic.
  return vmIntrinsics::_none;
}

378
vmIntrinsics::ID MethodHandles::signature_polymorphic_name_id(Klass* klass, Symbol* name) {
379
  if (klass != NULL &&
H
hseigel 已提交
380
      klass->name() == vmSymbols::java_lang_invoke_MethodHandle()) {
381 382 383 384 385 386 387
    vmIntrinsics::ID iid = signature_polymorphic_name_id(name);
    if (iid != vmIntrinsics::_none)
      return iid;
    if (is_method_handle_invoke_name(klass, name))
      return vmIntrinsics::_invokeGeneric;
  }
  return vmIntrinsics::_none;
388 389
}

390

391
// convert the external string or reflective type to an internal signature
392
Symbol* MethodHandles::lookup_signature(oop type_str, bool intern_if_not_found, TRAPS) {
393
  if (java_lang_invoke_MethodType::is_instance(type_str)) {
394
    return java_lang_invoke_MethodType::as_signature(type_str, intern_if_not_found, CHECK_NULL);
395 396 397
  } else if (java_lang_Class::is_instance(type_str)) {
    return java_lang_Class::as_signature(type_str, false, CHECK_NULL);
  } else if (java_lang_String::is_instance(type_str)) {
398
    if (intern_if_not_found) {
399 400 401 402 403 404 405 406 407
      return java_lang_String::as_symbol(type_str, CHECK_NULL);
    } else {
      return java_lang_String::as_symbol_or_null(type_str);
    }
  } else {
    THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized type", NULL);
  }
}

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
static const char OBJ_SIG[] = "Ljava/lang/Object;";
enum { OBJ_SIG_LEN = 18 };

bool MethodHandles::is_basic_type_signature(Symbol* sig) {
  assert(vmSymbols::object_signature()->utf8_length() == (int)OBJ_SIG_LEN, "");
  assert(vmSymbols::object_signature()->equals(OBJ_SIG), "");
  const int len = sig->utf8_length();
  for (int i = 0; i < len; i++) {
    switch (sig->byte_at(i)) {
    case 'L':
      // only java/lang/Object is valid here
      if (sig->index_of_at(i, OBJ_SIG, OBJ_SIG_LEN) != i)
        return false;
      i += OBJ_SIG_LEN-1;  //-1 because of i++ in loop
      continue;
    case '(': case ')': case 'V':
    case 'I': case 'J': case 'F': case 'D':
      continue;
    //case '[':
    //case 'Z': case 'B': case 'C': case 'S':
    default:
      return false;
    }
  }
  return true;
}

Symbol* MethodHandles::lookup_basic_type_signature(Symbol* sig, bool keep_last_arg, TRAPS) {
  Symbol* bsig = NULL;
  if (sig == NULL) {
    return sig;
  } else if (is_basic_type_signature(sig)) {
    sig->increment_refcount();
    return sig;  // that was easy
  } else if (sig->byte_at(0) != '(') {
    BasicType bt = char2type(sig->byte_at(0));
    if (is_subword_type(bt)) {
      bsig = vmSymbols::int_signature();
    } else {
      assert(bt == T_OBJECT || bt == T_ARRAY, "is_basic_type_signature was false");
      bsig = vmSymbols::object_signature();
    }
  } else {
    ResourceMark rm;
    stringStream buffer(128);
    buffer.put('(');
    int arg_pos = 0, keep_arg_pos = -1;
    if (keep_last_arg)
      keep_arg_pos = ArgumentCount(sig).size() - 1;
    for (SignatureStream ss(sig); !ss.is_done(); ss.next()) {
      BasicType bt = ss.type();
      size_t this_arg_pos = buffer.size();
      if (ss.at_return_type()) {
        buffer.put(')');
      }
      if (arg_pos == keep_arg_pos) {
        buffer.write((char*) ss.raw_bytes(),
                     (int)   ss.raw_length());
      } else if (bt == T_OBJECT || bt == T_ARRAY) {
        buffer.write(OBJ_SIG, OBJ_SIG_LEN);
      } else {
        if (is_subword_type(bt))
          bt = T_INT;
        buffer.put(type2char(bt));
      }
      arg_pos++;
    }
    const char* sigstr =       buffer.base();
    int         siglen = (int) buffer.size();
    bsig = SymbolTable::new_symbol(sigstr, siglen, THREAD);
  }
  assert(is_basic_type_signature(bsig) ||
         // detune assert in case the injected argument is not a basic type:
         keep_last_arg, "");
  return bsig;
}

void MethodHandles::print_as_basic_type_signature_on(outputStream* st,
                                                     Symbol* sig,
                                                     bool keep_arrays,
                                                     bool keep_basic_names) {
  st = st ? st : tty;
  int len  = sig->utf8_length();
  int array = 0;
  bool prev_type = false;
  for (int i = 0; i < len; i++) {
    char ch = sig->byte_at(i);
    switch (ch) {
    case '(': case ')':
      prev_type = false;
      st->put(ch);
      continue;
    case '[':
      if (!keep_basic_names && keep_arrays)
        st->put(ch);
      array++;
      continue;
    case 'L':
      {
        if (prev_type)  st->put(',');
        int start = i+1, slash = start;
        while (++i < len && (ch = sig->byte_at(i)) != ';') {
          if (ch == '/' || ch == '.' || ch == '$')  slash = i+1;
        }
        if (slash < i)  start = slash;
        if (!keep_basic_names) {
          st->put('L');
        } else {
          for (int j = start; j < i; j++)
            st->put(sig->byte_at(j));
          prev_type = true;
        }
        break;
      }
    default:
      {
        if (array && char2type(ch) != T_ILLEGAL && !keep_arrays) {
          ch = '[';
          array = 0;
        }
        if (prev_type)  st->put(',');
        const char* n = NULL;
        if (keep_basic_names)
          n = type2name(char2type(ch));
        if (n == NULL) {
          // unknown letter, or we don't want to know its name
          st->put(ch);
        } else {
536
          st->print("%s", n);
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
          prev_type = true;
        }
        break;
      }
    }
    // Switch break goes here to take care of array suffix:
    if (prev_type) {
      while (array > 0) {
        st->print("[]");
        --array;
      }
    }
    array = 0;
  }
}



static oop object_java_mirror() {
H
hseigel 已提交
556
  return SystemDictionary::Object_klass()->java_mirror();
557 558
}

559
oop MethodHandles::field_name_or_null(Symbol* s) {
560 561 562 563
  if (s == NULL)  return NULL;
  return StringTable::lookup(s);
}

564
oop MethodHandles::field_signature_type_or_null(Symbol* s) {
565 566 567 568 569 570 571 572 573 574 575 576
  if (s == NULL)  return NULL;
  BasicType bt = FieldType::basic_type(s);
  if (is_java_primitive(bt)) {
    assert(s->utf8_length() == 1, "");
    return java_lang_Class::primitive_mirror(bt);
  }
  // Here are some more short cuts for common types.
  // They are optional, since reference types can be resolved lazily.
  if (bt == T_OBJECT) {
    if (s == vmSymbols::object_signature()) {
      return object_java_mirror();
    } else if (s == vmSymbols::class_signature()) {
H
hseigel 已提交
577
      return SystemDictionary::Class_klass()->java_mirror();
578
    } else if (s == vmSymbols::string_signature()) {
H
hseigel 已提交
579
      return SystemDictionary::String_klass()->java_mirror();
580 581 582 583 584
    }
  }
  return NULL;
}

585

586 587
// An unresolved member name is a mere symbolic reference.
// Resolving it plants a vmtarget/vmindex in it,
588
// which refers directly to JVM internals.
J
jrose 已提交
589
Handle MethodHandles::resolve_MemberName(Handle mname, KlassHandle caller, TRAPS) {
590
  Handle empty;
591
  assert(java_lang_invoke_MemberName::is_instance(mname()), "");
592 593 594 595

  if (java_lang_invoke_MemberName::vmtarget(mname()) != NULL) {
    // Already resolved.
    DEBUG_ONLY(int vmindex = java_lang_invoke_MemberName::vmindex(mname()));
596
    assert(vmindex >= Method::nonvirtual_vtable_index, "");
597 598 599
    return mname;
  }

600 601 602 603
  Handle defc_oop(THREAD, java_lang_invoke_MemberName::clazz(mname()));
  Handle name_str(THREAD, java_lang_invoke_MemberName::name( mname()));
  Handle type_str(THREAD, java_lang_invoke_MemberName::type( mname()));
  int    flags    =       java_lang_invoke_MemberName::flags(mname());
604 605 606 607 608 609 610
  int    ref_kind =       (flags >> REFERENCE_KIND_SHIFT) & REFERENCE_KIND_MASK;
  if (!ref_kind_is_valid(ref_kind)) {
    THROW_MSG_(vmSymbols::java_lang_InternalError(), "obsolete MemberName format", empty);
  }

  DEBUG_ONLY(int old_vmindex);
  assert((old_vmindex = java_lang_invoke_MemberName::vmindex(mname())) == 0, "clean input");
611

612
  if (defc_oop.is_null() || name_str.is_null() || type_str.is_null()) {
613
    THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "nothing to resolve", empty);
614
  }
615 616 617

  instanceKlassHandle defc;
  {
618 619
    Klass* defc_klass = java_lang_Class::as_Klass(defc_oop());
    if (defc_klass == NULL)  return empty;  // a primitive; no resolution possible
H
hseigel 已提交
620 621
    if (!defc_klass->oop_is_instance()) {
      if (!defc_klass->oop_is_array())  return empty;
622
      defc_klass = SystemDictionary::Object_klass();
623
    }
624
    defc = instanceKlassHandle(THREAD, defc_klass);
625 626
  }
  if (defc.is_null()) {
627
    THROW_MSG_(vmSymbols::java_lang_InternalError(), "primitive class", empty);
628
  }
629
  defc->link_class(CHECK_(empty));  // possible safepoint
630 631

  // convert the external string name to an internal symbol
632
  TempNewSymbol name = java_lang_String::as_symbol_or_null(name_str());
633
  if (name == NULL)  return empty;  // no such name
634
  if (name == vmSymbols::class_initializer_name())
635
    return empty; // illegal name
636

637
  vmIntrinsics::ID mh_invoke_id = vmIntrinsics::_none;
638
  if ((flags & ALL_KINDS) == IS_METHOD &&
639 640 641 642 643 644 645 646 647 648 649 650
      (defc() == SystemDictionary::MethodHandle_klass()) &&
      (ref_kind == JVM_REF_invokeVirtual ||
       ref_kind == JVM_REF_invokeSpecial ||
       // static invocation mode is required for _linkToVirtual, etc.:
       ref_kind == JVM_REF_invokeStatic)) {
    vmIntrinsics::ID iid = signature_polymorphic_name_id(name);
    if (iid != vmIntrinsics::_none &&
        ((ref_kind == JVM_REF_invokeStatic) == is_signature_polymorphic_static(iid))) {
      // Virtual methods invoke and invokeExact, plus internal invokers like _invokeBasic.
      // For a static reference it could an internal linkage routine like _linkToVirtual, etc.
      mh_invoke_id = iid;
    }
651
  }
652

653
  // convert the external string or reflective type to an internal signature
654 655
  TempNewSymbol type = lookup_signature(type_str(), (mh_invoke_id != vmIntrinsics::_none), CHECK_(empty));
  if (type == NULL)  return empty;  // no such signature exists in the VM
656 657 658 659 660 661 662

  // Time to do the lookup.
  switch (flags & ALL_KINDS) {
  case IS_METHOD:
    {
      CallInfo result;
      {
663 664
        assert(!HAS_PENDING_EXCEPTION, "");
        if (ref_kind == JVM_REF_invokeStatic) {
665
          LinkResolver::resolve_static_call(result,
J
jrose 已提交
666
                        defc, name, type, caller, caller.not_null(), false, THREAD);
667
        } else if (ref_kind == JVM_REF_invokeInterface) {
668
          LinkResolver::resolve_interface_call(result, Handle(), defc,
J
jrose 已提交
669
                        defc, name, type, caller, caller.not_null(), false, THREAD);
670 671 672
        } else if (mh_invoke_id != vmIntrinsics::_none) {
          assert(!is_signature_polymorphic_static(mh_invoke_id), "");
          LinkResolver::resolve_handle_call(result,
J
jrose 已提交
673
                        defc, name, type, caller, THREAD);
674 675
        } else if (ref_kind == JVM_REF_invokeSpecial) {
          LinkResolver::resolve_special_call(result,
J
jrose 已提交
676
                        defc, name, type, caller, caller.not_null(), THREAD);
677
        } else if (ref_kind == JVM_REF_invokeVirtual) {
678
          LinkResolver::resolve_virtual_call(result, Handle(), defc,
J
jrose 已提交
679
                        defc, name, type, caller, caller.not_null(), false, THREAD);
680 681
        } else {
          assert(false, err_msg("ref_kind=%d", ref_kind));
682 683
        }
        if (HAS_PENDING_EXCEPTION) {
684
          return empty;
685 686
        }
      }
687 688 689 690 691 692 693 694
      if (result.resolved_appendix().not_null()) {
        // The resolved MemberName must not be accompanied by an appendix argument,
        // since there is no way to bind this value into the MemberName.
        // Caller is responsible to prevent this from happening.
        THROW_MSG_(vmSymbols::java_lang_InternalError(), "appendix", empty);
      }
      oop mname2 = init_method_MemberName(mname, result);
      return Handle(THREAD, mname2);
695 696 697 698 699
    }
  case IS_CONSTRUCTOR:
    {
      CallInfo result;
      {
700
        assert(!HAS_PENDING_EXCEPTION, "");
701
        if (name == vmSymbols::object_initializer_name()) {
702
          LinkResolver::resolve_special_call(result,
J
jrose 已提交
703
                        defc, name, type, caller, caller.not_null(), THREAD);
704 705 706 707
        } else {
          break;                // will throw after end of switch
        }
        if (HAS_PENDING_EXCEPTION) {
708
          return empty;
709 710 711
        }
      }
      assert(result.is_statically_bound(), "");
712 713
      oop mname2 = init_method_MemberName(mname, result);
      return Handle(THREAD, mname2);
714 715 716
    }
  case IS_FIELD:
    {
717 718 719
      fieldDescriptor result; // find_field initializes fd if found
      {
        assert(!HAS_PENDING_EXCEPTION, "");
J
jrose 已提交
720
        LinkResolver::resolve_field(result, defc, name, type, caller, Bytecodes::_nop, false, false, THREAD);
721 722 723 724 725 726
        if (HAS_PENDING_EXCEPTION) {
          return empty;
        }
      }
      oop mname2 = init_field_MemberName(mname, result, ref_kind_is_setter(ref_kind));
      return Handle(THREAD, mname2);
727
    }
728
  default:
729
    THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format", empty);
730 731
  }

732
  return empty;
733 734 735 736 737 738 739
}

// Conversely, a member name which is only initialized from JVM internals
// may have null defc, name, and type fields.
// Resolving it plants a vmtarget/vmindex in it,
// which refers directly to JVM internals.
void MethodHandles::expand_MemberName(Handle mname, int suppress, TRAPS) {
740
  assert(java_lang_invoke_MemberName::is_instance(mname()), "");
741
  Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
742
  int vmindex  = java_lang_invoke_MemberName::vmindex(mname());
743
  if (vmtarget == NULL) {
744 745 746
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to expand");
  }

747 748 749 750
  bool have_defc = (java_lang_invoke_MemberName::clazz(mname()) != NULL);
  bool have_name = (java_lang_invoke_MemberName::name(mname()) != NULL);
  bool have_type = (java_lang_invoke_MemberName::type(mname()) != NULL);
  int flags      = java_lang_invoke_MemberName::flags(mname());
751 752 753 754 755 756 757 758 759 760 761 762 763

  if (suppress != 0) {
    if (suppress & _suppress_defc)  have_defc = true;
    if (suppress & _suppress_name)  have_name = true;
    if (suppress & _suppress_type)  have_type = true;
  }

  if (have_defc && have_name && have_type)  return;  // nothing needed

  switch (flags & ALL_KINDS) {
  case IS_METHOD:
  case IS_CONSTRUCTOR:
    {
764 765
      assert(vmtarget->is_method(), "method or constructor vmtarget is Method*");
      methodHandle m(THREAD, (Method*)vmtarget);
766
      DEBUG_ONLY(vmtarget = NULL);  // safety
767 768
      if (m.is_null())  break;
      if (!have_defc) {
769 770
        InstanceKlass* defc = m->method_holder();
        java_lang_invoke_MemberName::set_clazz(mname(), defc->java_mirror());
771 772 773 774
      }
      if (!have_name) {
        //not java_lang_String::create_from_symbol; let's intern member names
        Handle name = StringTable::intern(m->name(), CHECK);
775
        java_lang_invoke_MemberName::set_name(mname(), name());
776 777 778
      }
      if (!have_type) {
        Handle type = java_lang_String::create_from_symbol(m->signature(), CHECK);
779
        java_lang_invoke_MemberName::set_type(mname(), type());
780 781 782 783 784
      }
      return;
    }
  case IS_FIELD:
    {
785
      assert(vmtarget->is_klass(), "field vmtarget is Klass*");
H
hseigel 已提交
786
      if (!((Klass*) vmtarget)->oop_is_instance())  break;
787
      instanceKlassHandle defc(THREAD, (Klass*) vmtarget);
788
      DEBUG_ONLY(vmtarget = NULL);  // safety
789 790 791 792 793
      bool is_static = ((flags & JVM_ACC_STATIC) != 0);
      fieldDescriptor fd; // find_field initializes fd if found
      if (!defc->find_field_from_offset(vmindex, is_static, &fd))
        break;                  // cannot expand
      if (!have_defc) {
794
        java_lang_invoke_MemberName::set_clazz(mname(), defc->java_mirror());
795 796 797 798
      }
      if (!have_name) {
        //not java_lang_String::create_from_symbol; let's intern member names
        Handle name = StringTable::intern(fd.name(), CHECK);
799
        java_lang_invoke_MemberName::set_name(mname(), name());
800 801
      }
      if (!have_type) {
802 803 804 805 806
        // If it is a primitive field type, don't mess with short strings like "I".
        Handle type = field_signature_type_or_null(fd.signature());
        if (type.is_null()) {
          java_lang_String::create_from_symbol(fd.signature(), CHECK);
        }
807
        java_lang_invoke_MemberName::set_type(mname(), type());
808 809 810 811 812 813 814
      }
      return;
    }
  }
  THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
}

815
int MethodHandles::find_MemberNames(KlassHandle k,
816
                                    Symbol* name, Symbol* sig,
817 818
                                    int mflags, KlassHandle caller,
                                    int skip, objArrayHandle results) {
819 820
  // %%% take caller into account!

821 822 823
  Thread* thread = Thread::current();

  if (k.is_null() || !k->oop_is_instance())  return -1;
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850

  int rfill = 0, rlimit = results->length(), rskip = skip;
  // overflow measurement:
  int overflow = 0, overflow_limit = MAX2(1000, rlimit);

  int match_flags = mflags;
  bool search_superc = ((match_flags & SEARCH_SUPERCLASSES) != 0);
  bool search_intfc  = ((match_flags & SEARCH_INTERFACES)   != 0);
  bool local_only = !(search_superc | search_intfc);
  bool classes_only = false;

  if (name != NULL) {
    if (name->utf8_length() == 0)  return 0; // a match is not possible
  }
  if (sig != NULL) {
    if (sig->utf8_length() == 0)  return 0; // a match is not possible
    if (sig->byte_at(0) == '(')
      match_flags &= ~(IS_FIELD | IS_TYPE);
    else
      match_flags &= ~(IS_CONSTRUCTOR | IS_METHOD);
  }

  if ((match_flags & IS_TYPE) != 0) {
    // NYI, and Core Reflection works quite well for this query
  }

  if ((match_flags & IS_FIELD) != 0) {
851
    for (FieldStream st(k(), local_only, !search_intfc); !st.eos(); st.next()) {
852 853 854 855 856 857 858 859
      if (name != NULL && st.name() != name)
          continue;
      if (sig != NULL && st.signature() != sig)
        continue;
      // passed the filters
      if (rskip > 0) {
        --rskip;
      } else if (rfill < rlimit) {
860 861
        Handle result(thread, results->obj_at(rfill++));
        if (!java_lang_invoke_MemberName::is_instance(result()))
862
          return -99;  // caller bug!
863
        oop saved = MethodHandles::init_field_MemberName(result, st.field_descriptor());
864
        if (saved != result())
865
          results->obj_at_put(rfill-1, saved);  // show saved instance to user
866 867 868 869 870 871 872 873
      } else if (++overflow >= overflow_limit) {
        match_flags = 0; break; // got tired of looking at overflow
      }
    }
  }

  if ((match_flags & (IS_METHOD | IS_CONSTRUCTOR)) != 0) {
    // watch out for these guys:
874 875
    Symbol* init_name   = vmSymbols::object_initializer_name();
    Symbol* clinit_name = vmSymbols::class_initializer_name();
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
    if (name == clinit_name)  clinit_name = NULL; // hack for exposing <clinit>
    bool negate_name_test = false;
    // fix name so that it captures the intention of IS_CONSTRUCTOR
    if (!(match_flags & IS_METHOD)) {
      // constructors only
      if (name == NULL) {
        name = init_name;
      } else if (name != init_name) {
        return 0;               // no constructors of this method name
      }
    } else if (!(match_flags & IS_CONSTRUCTOR)) {
      // methods only
      if (name == NULL) {
        name = init_name;
        negate_name_test = true; // if we see the name, we *omit* the entry
      } else if (name == init_name) {
        return 0;               // no methods of this constructor name
      }
    } else {
      // caller will accept either sort; no need to adjust name
    }
897
    for (MethodStream st(k(), local_only, !search_intfc); !st.eos(); st.next()) {
898
      Method* m = st.method();
899
      Symbol* m_name = m->name();
900 901 902 903 904 905 906 907 908 909
      if (m_name == clinit_name)
        continue;
      if (name != NULL && ((m_name != name) ^ negate_name_test))
          continue;
      if (sig != NULL && m->signature() != sig)
        continue;
      // passed the filters
      if (rskip > 0) {
        --rskip;
      } else if (rfill < rlimit) {
910 911
        Handle result(thread, results->obj_at(rfill++));
        if (!java_lang_invoke_MemberName::is_instance(result()))
912
          return -99;  // caller bug!
913
        CallInfo info(m);
914 915 916
        // Since this is going through the methods to create MemberNames, don't search
        // for matching methods already in the table
        oop saved = MethodHandles::init_method_MemberName(result, info, /*intern*/false);
917
        if (saved != result())
918
          results->obj_at_put(rfill-1, saved);  // show saved instance to user
919 920 921 922 923 924 925 926 927
      } else if (++overflow >= overflow_limit) {
        match_flags = 0; break; // got tired of looking at overflow
      }
    }
  }

  // return number of elements we at leasted wanted to initialize
  return rfill + overflow;
}
928 929 930 931 932

//------------------------------------------------------------------------------
// MemberNameTable
//

933 934
MemberNameTable::MemberNameTable(int methods_cnt)
                  : GrowableArray<jweak>(methods_cnt, true) {
935 936 937 938 939 940 941 942 943 944 945 946 947
  assert_locked_or_safepoint(MemberNameTable_lock);
}

MemberNameTable::~MemberNameTable() {
  assert_locked_or_safepoint(MemberNameTable_lock);
  int len = this->length();

  for (int idx = 0; idx < len; idx++) {
    jweak ref = this->at(idx);
    JNIHandles::destroy_weak_global(ref);
  }
}

948
oop MemberNameTable::add_member_name(jweak mem_name_wref) {
949
  assert_locked_or_safepoint(MemberNameTable_lock);
950
  this->push(mem_name_wref);
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
  return JNIHandles::resolve(mem_name_wref);
}

oop MemberNameTable::find_or_add_member_name(jweak mem_name_wref) {
  assert_locked_or_safepoint(MemberNameTable_lock);
  oop new_mem_name = JNIHandles::resolve(mem_name_wref);

  // Find matching member name in the list.
  // This is linear because these are short lists.
  int len = this->length();
  int new_index = len;
  for (int idx = 0; idx < len; idx++) {
    oop mname = JNIHandles::resolve(this->at(idx));
    if (mname == NULL) {
      new_index = idx;
      continue;
    }
    if (java_lang_invoke_MemberName::equals(new_mem_name, mname)) {
      JNIHandles::destroy_weak_global(mem_name_wref);
      return mname;
    }
  }
  // Not found, push the new one, or reuse empty slot
  this->at_put_grow(new_index, mem_name_wref);
  return new_mem_name;
976 977 978
}

#if INCLUDE_JVMTI
979
// It is called at safepoint only for RedefineClasses
980
void MemberNameTable::adjust_method_entries(InstanceKlass* holder, bool * trace_name_printed) {
981
  assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
982
  // For each redefined method
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
  for (int idx = 0; idx < length(); idx++) {
    oop mem_name = JNIHandles::resolve(this->at(idx));
    if (mem_name == NULL) {
      continue;
    }
    Method* old_method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name);

    if (old_method == NULL || !old_method->is_old()) {
      continue; // skip uninteresting entries
    }
    if (old_method->is_deleted()) {
      // skip entries with deleted methods
      continue;
    }
    Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());

    assert(new_method != NULL, "method_with_idnum() should not be NULL");
    assert(old_method != new_method, "sanity check");

    java_lang_invoke_MemberName::set_vmtarget(mem_name, new_method);

    if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
      if (!(*trace_name_printed)) {
        // RC_TRACE_MESG macro has an embedded ResourceMark
        RC_TRACE_MESG(("adjust: name=%s",
                       old_method->method_holder()->external_name()));
        *trace_name_printed = true;
1010
      }
1011 1012 1013 1014
      // RC_TRACE macro has an embedded ResourceMark
      RC_TRACE(0x00400000, ("MemberName method update: %s(%s)",
                            new_method->name()->as_C_string(),
                            new_method->signature()->as_C_string()));
1015 1016 1017 1018 1019
    }
  }
}
#endif // INCLUDE_JVMTI

1020 1021 1022 1023 1024 1025 1026 1027
//
// Here are the native methods in java.lang.invoke.MethodHandleNatives
// They are the private interface between this JVM and the HotSpot-specific
// Java code that implements JSR 292 method handles.
//
// Note:  We use a JVM_ENTRY macro to define each of these, for this is the way
// that intrinsic (non-JNI) native methods are defined in HotSpot.
//
1028

1029 1030 1031 1032 1033 1034 1035 1036
JVM_ENTRY(jint, MHN_getConstant(JNIEnv *env, jobject igcls, jint which)) {
  switch (which) {
  case MethodHandles::GC_COUNT_GWT:
#ifdef COMPILER2
    return true;
#else
    return false;
#endif
1037
  }
1038
  return 0;
1039
}
1040
JVM_END
1041

1042 1043 1044 1045 1046 1047 1048
#ifndef PRODUCT
#define EACH_NAMED_CON(template, requirement) \
    template(MethodHandles,GC_COUNT_GWT) \
    template(java_lang_invoke_MemberName,MN_IS_METHOD) \
    template(java_lang_invoke_MemberName,MN_IS_CONSTRUCTOR) \
    template(java_lang_invoke_MemberName,MN_IS_FIELD) \
    template(java_lang_invoke_MemberName,MN_IS_TYPE) \
1049
    template(java_lang_invoke_MemberName,MN_CALLER_SENSITIVE) \
1050 1051 1052 1053 1054 1055
    template(java_lang_invoke_MemberName,MN_SEARCH_SUPERCLASSES) \
    template(java_lang_invoke_MemberName,MN_SEARCH_INTERFACES) \
    template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_SHIFT) \
    template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_MASK) \
    template(MethodHandles,GC_LAMBDA_SUPPORT) \
    /*end*/
1056

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
#define IGNORE_REQ(req_expr) /* req_expr */
#define ONE_PLUS(scope,value) 1+
static const int con_value_count = EACH_NAMED_CON(ONE_PLUS, IGNORE_REQ) 0;
#define VALUE_COMMA(scope,value) scope::value,
static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA, IGNORE_REQ) 0 };
#define STRING_NULL(scope,value) #value "\0"
static const char con_names[] = { EACH_NAMED_CON(STRING_NULL, IGNORE_REQ) };

static bool advertise_con_value(int which) {
  if (which < 0)  return false;
  bool ok = true;
  int count = 0;
#define INC_COUNT(scope,value) \
  ++count;
#define CHECK_REQ(req_expr) \
  if (which < count)  return ok; \
  ok = (req_expr);
  EACH_NAMED_CON(INC_COUNT, CHECK_REQ);
#undef INC_COUNT
#undef CHECK_REQ
  assert(count == con_value_count, "");
  if (which < count)  return ok;
  return false;
}
1081

1082 1083 1084 1085 1086
#undef ONE_PLUS
#undef VALUE_COMMA
#undef STRING_NULL
#undef EACH_NAMED_CON
#endif // PRODUCT
1087

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
JVM_ENTRY(jint, MHN_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
#ifndef PRODUCT
  if (advertise_con_value(which)) {
    assert(which >= 0 && which < con_value_count, "");
    int con = con_values[which];
    objArrayHandle box(THREAD, (objArrayOop) JNIHandles::resolve(box_jh));
    if (box.not_null() && box->klass() == Universe::objectArrayKlassObj() && box->length() > 0) {
      const char* str = &con_names[0];
      for (int i = 0; i < which; i++)
        str += strlen(str) + 1;   // skip name and null
      oop name = java_lang_String::create_oop_from_str(str, CHECK_0);  // possible safepoint
      box->obj_at_put(0, name);
1100
    }
1101
    return con;
1102
  }
1103 1104
#endif
  return 0;
1105
}
1106
JVM_END
1107 1108

// void init(MemberName self, AccessibleObject ref)
1109
JVM_ENTRY(void, MHN_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
1110 1111
  if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
  if (target_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "target is null"); }
1112
  Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1113 1114
  Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
  MethodHandles::init_MemberName(mname, target);
1115 1116 1117 1118
}
JVM_END

// void expand(MemberName self)
1119
JVM_ENTRY(void, MHN_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1120
  if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
1121 1122 1123 1124 1125 1126
  Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  MethodHandles::expand_MemberName(mname, 0, CHECK);
}
JVM_END

// void resolve(MemberName self, Class<?> caller)
1127 1128
JVM_ENTRY(jobject, MHN_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh)) {
  if (mname_jh == NULL) { THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "mname is null"); }
1129
  Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1130 1131 1132

  // The trusted Java code that calls this method should already have performed
  // access checks on behalf of the given caller.  But, we can verify this.
1133 1134
  if (VerifyMethodHandles && caller_jh != NULL &&
      java_lang_invoke_MemberName::clazz(mname()) != NULL) {
1135
    Klass* reference_klass = java_lang_Class::as_Klass(java_lang_invoke_MemberName::clazz(mname()));
1136 1137 1138 1139 1140 1141
    if (reference_klass != NULL && reference_klass->oop_is_objArray()) {
      reference_klass = ObjArrayKlass::cast(reference_klass)->bottom_klass();
    }

    // Reflection::verify_class_access can only handle instance classes.
    if (reference_klass != NULL && reference_klass->oop_is_instance()) {
1142
      // Emulate LinkResolver::check_klass_accessability.
1143
      Klass* caller = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh));
1144 1145 1146
      if (!Reflection::verify_class_access(caller,
                                           reference_klass,
                                           true)) {
H
hseigel 已提交
1147
        THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), reference_klass->external_name());
1148 1149 1150 1151
      }
    }
  }

J
jrose 已提交
1152 1153 1154 1155 1156
  KlassHandle caller(THREAD,
                     caller_jh == NULL ? (Klass*) NULL :
                     java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh)));
  Handle resolved = MethodHandles::resolve_MemberName(mname, caller, CHECK_NULL);

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
  if (resolved.is_null()) {
    int flags = java_lang_invoke_MemberName::flags(mname());
    int ref_kind = (flags >> REFERENCE_KIND_SHIFT) & REFERENCE_KIND_MASK;
    if (!MethodHandles::ref_kind_is_valid(ref_kind)) {
      THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "obsolete MemberName format");
    }
    if ((flags & ALL_KINDS) == IS_FIELD) {
      THROW_MSG_NULL(vmSymbols::java_lang_NoSuchMethodError(), "field resolution failed");
    } else if ((flags & ALL_KINDS) == IS_METHOD ||
               (flags & ALL_KINDS) == IS_CONSTRUCTOR) {
      THROW_MSG_NULL(vmSymbols::java_lang_NoSuchFieldError(), "method resolution failed");
    } else {
      THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "resolution failed");
    }
  }

  return JNIHandles::make_local(THREAD, resolved());
}
JVM_END

static jlong find_member_field_offset(oop mname, bool must_be_static, TRAPS) {
  if (mname == NULL ||
      java_lang_invoke_MemberName::vmtarget(mname) == NULL) {
    THROW_MSG_0(vmSymbols::java_lang_InternalError(), "mname not resolved");
  } else {
    int flags = java_lang_invoke_MemberName::flags(mname);
    if ((flags & IS_FIELD) != 0 &&
        (must_be_static
         ? (flags & JVM_ACC_STATIC) != 0
         : (flags & JVM_ACC_STATIC) == 0)) {
      int vmindex = java_lang_invoke_MemberName::vmindex(mname);
      return (jlong) vmindex;
    }
  }
  const char* msg = (must_be_static ? "static field required" : "non-static field required");
  THROW_MSG_0(vmSymbols::java_lang_InternalError(), msg);
  return 0;
}

JVM_ENTRY(jlong, MHN_objectFieldOffset(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  return find_member_field_offset(JNIHandles::resolve(mname_jh), false, THREAD);
}
JVM_END

JVM_ENTRY(jlong, MHN_staticFieldOffset(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  return find_member_field_offset(JNIHandles::resolve(mname_jh), true, THREAD);
}
JVM_END

JVM_ENTRY(jobject, MHN_staticFieldBase(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  // use the other function to perform sanity checks:
  jlong ignore = find_member_field_offset(JNIHandles::resolve(mname_jh), true, CHECK_NULL);
  oop clazz = java_lang_invoke_MemberName::clazz(JNIHandles::resolve_non_null(mname_jh));
  return JNIHandles::make_local(THREAD, clazz);
}
JVM_END

JVM_ENTRY(jobject, MHN_getMemberVMInfo(JNIEnv *env, jobject igcls, jobject mname_jh)) {
  if (mname_jh == NULL)  return NULL;
  Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
  intptr_t vmindex  = java_lang_invoke_MemberName::vmindex(mname());
1218
  Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
1219 1220 1221 1222 1223
  objArrayHandle result = oopFactory::new_objArray(SystemDictionary::Object_klass(), 2, CHECK_NULL);
  jvalue vmindex_value; vmindex_value.j = (long)vmindex;
  oop x = java_lang_boxing_object::create(T_LONG, &vmindex_value, CHECK_NULL);
  result->obj_at_put(0, x);
  x = NULL;
1224 1225
  if (vmtarget == NULL) {
    x = NULL;
1226
  } else if (vmtarget->is_klass()) {
H
hseigel 已提交
1227
    x = ((Klass*) vmtarget)->java_mirror();
1228
  } else if (vmtarget->is_method()) {
1229
    x = mname();
1230 1231 1232
  }
  result->obj_at_put(1, x);
  return JNIHandles::make_local(env, result());
1233 1234 1235
}
JVM_END

1236 1237


1238 1239
//  static native int getMembers(Class<?> defc, String matchName, String matchSig,
//          int matchFlags, Class<?> caller, int skip, MemberName[] results);
1240
JVM_ENTRY(jint, MHN_getMembers(JNIEnv *env, jobject igcls,
1241 1242 1243
                               jclass clazz_jh, jstring name_jh, jstring sig_jh,
                               int mflags, jclass caller_jh, jint skip, jobjectArray results_jh)) {
  if (clazz_jh == NULL || results_jh == NULL)  return -1;
1244
  KlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz_jh)));
1245

1246 1247
  objArrayHandle results(THREAD, (objArrayOop) JNIHandles::resolve(results_jh));
  if (results.is_null() || !results->is_objArray())  return -1;
1248

1249 1250
  TempNewSymbol name = NULL;
  TempNewSymbol sig = NULL;
1251 1252 1253 1254 1255 1256 1257 1258 1259
  if (name_jh != NULL) {
    name = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(name_jh));
    if (name == NULL)  return 0; // a match is not possible
  }
  if (sig_jh != NULL) {
    sig = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(sig_jh));
    if (sig == NULL)  return 0; // a match is not possible
  }

1260
  KlassHandle caller;
1261 1262 1263
  if (caller_jh != NULL) {
    oop caller_oop = JNIHandles::resolve_non_null(caller_jh);
    if (!java_lang_Class::is_instance(caller_oop))  return -1;
1264
    caller = KlassHandle(THREAD, java_lang_Class::as_Klass(caller_oop));
1265 1266
  }

1267
  if (name != NULL && sig != NULL && results.not_null()) {
1268 1269 1270 1271
    // try a direct resolve
    // %%% TO DO
  }

1272 1273
  int res = MethodHandles::find_MemberNames(k, name, sig, mflags,
                                            caller, skip, results);
1274 1275 1276 1277 1278
  // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
  return res;
}
JVM_END

1279
JVM_ENTRY(void, MHN_setCallSiteTargetNormal(JNIEnv* env, jobject igcls, jobject call_site_jh, jobject target_jh)) {
1280 1281
  Handle call_site(THREAD, JNIHandles::resolve_non_null(call_site_jh));
  Handle target   (THREAD, JNIHandles::resolve(target_jh));
1282 1283 1284 1285
  {
    // Walk all nmethods depending on this call site.
    MutexLocker mu(Compile_lock, thread);
    Universe::flush_dependents_on(call_site, target);
1286
    java_lang_invoke_CallSite::set_target(call_site(), target());
1287 1288 1289 1290 1291
  }
}
JVM_END

JVM_ENTRY(void, MHN_setCallSiteTargetVolatile(JNIEnv* env, jobject igcls, jobject call_site_jh, jobject target_jh)) {
1292 1293
  Handle call_site(THREAD, JNIHandles::resolve_non_null(call_site_jh));
  Handle target   (THREAD, JNIHandles::resolve(target_jh));
1294 1295 1296 1297
  {
    // Walk all nmethods depending on this call site.
    MutexLocker mu(Compile_lock, thread);
    Universe::flush_dependents_on(call_site, target);
1298
    java_lang_invoke_CallSite::set_target_volatile(call_site(), target());
1299 1300 1301 1302
  }
}
JVM_END

1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
/**
 * Throws a java/lang/UnsupportedOperationException unconditionally.
 * This is required by the specification of MethodHandle.invoke if
 * invoked directly.
 */
JVM_ENTRY(jobject, MH_invoke_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
  THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invoke cannot be invoked reflectively");
  return NULL;
}
JVM_END

/**
 * Throws a java/lang/UnsupportedOperationException unconditionally.
 * This is required by the specification of MethodHandle.invokeExact if
 * invoked directly.
 */
JVM_ENTRY(jobject, MH_invokeExact_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
  THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invokeExact cannot be invoked reflectively");
  return NULL;
}
JVM_END

1325 1326
/// JVM_RegisterMethodHandleMethods

1327 1328
#undef CS  // Solaris builds complain

1329
#define LANG "Ljava/lang/"
1330
#define JLINV "Ljava/lang/invoke/"
1331 1332 1333 1334

#define OBJ   LANG"Object;"
#define CLS   LANG"Class;"
#define STRG  LANG"String;"
1335
#define CS    JLINV"CallSite;"
1336 1337 1338
#define MT    JLINV"MethodType;"
#define MH    JLINV"MethodHandle;"
#define MEM   JLINV"MemberName;"
1339 1340 1341 1342

#define CC (char*)  /*cast a literal from (const char*)*/
#define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)

1343
// These are the native methods on java.lang.invoke.MethodHandleNatives.
1344
static JNINativeMethod MHN_methods[] = {
1345 1346
  {CC"init",                      CC"("MEM""OBJ")V",                     FN_PTR(MHN_init_Mem)},
  {CC"expand",                    CC"("MEM")V",                          FN_PTR(MHN_expand_Mem)},
1347
  {CC"resolve",                   CC"("MEM""CLS")"MEM,                   FN_PTR(MHN_resolve_Mem)},
1348
  {CC"getConstant",               CC"(I)I",                              FN_PTR(MHN_getConstant)},
1349
  //  static native int getNamedCon(int which, Object[] name)
1350
  {CC"getNamedCon",               CC"(I["OBJ")I",                        FN_PTR(MHN_getNamedCon)},
1351 1352
  //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
  //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
1353 1354
  {CC"getMembers",                CC"("CLS""STRG""STRG"I"CLS"I["MEM")I", FN_PTR(MHN_getMembers)},
  {CC"objectFieldOffset",         CC"("MEM")J",                          FN_PTR(MHN_objectFieldOffset)},
1355
  {CC"setCallSiteTargetNormal",   CC"("CS""MH")V",                       FN_PTR(MHN_setCallSiteTargetNormal)},
1356 1357 1358 1359
  {CC"setCallSiteTargetVolatile", CC"("CS""MH")V",                       FN_PTR(MHN_setCallSiteTargetVolatile)},
  {CC"staticFieldOffset",         CC"("MEM")J",                          FN_PTR(MHN_staticFieldOffset)},
  {CC"staticFieldBase",           CC"("MEM")"OBJ,                        FN_PTR(MHN_staticFieldBase)},
  {CC"getMemberVMInfo",           CC"("MEM")"OBJ,                        FN_PTR(MHN_getMemberVMInfo)}
1360 1361
};

1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
static JNINativeMethod MH_methods[] = {
  // UnsupportedOperationException throwers
  {CC"invoke",                    CC"(["OBJ")"OBJ,                       FN_PTR(MH_invoke_UOE)},
  {CC"invokeExact",               CC"(["OBJ")"OBJ,                       FN_PTR(MH_invokeExact_UOE)}
};

/**
 * Helper method to register native methods.
 */
static bool register_natives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
  int status = env->RegisterNatives(clazz, methods, nMethods);
  if (status != JNI_OK || env->ExceptionOccurred()) {
    warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
    env->ExceptionClear();
    return false;
  }
  return true;
}
1380

1381 1382 1383
/**
 * This one function is exported, used by NativeLookup.
 */
1384
JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
1385 1386
  if (!EnableInvokeDynamic) {
    warning("JSR 292 is disabled in this JVM.  Use -XX:+UnlockDiagnosticVMOptions -XX:+EnableInvokeDynamic to enable.");
1387 1388 1389
    return;  // bind nothing
  }

1390
  assert(!MethodHandles::enabled(), "must not be enabled");
1391 1392
  bool enable_MH = true;

1393 1394 1395 1396
  jclass MH_class = NULL;
  if (SystemDictionary::MethodHandle_klass() == NULL) {
    enable_MH = false;
  } else {
H
hseigel 已提交
1397
    oop mirror = SystemDictionary::MethodHandle_klass()->java_mirror();
1398 1399 1400 1401
    MH_class = (jclass) JNIHandles::make_local(env, mirror);
  }

  if (enable_MH) {
1402
    ThreadToNativeFromVM ttnfv(thread);
1403

1404 1405 1406 1407 1408
    if (enable_MH) {
      enable_MH = register_natives(env, MHN_class, MHN_methods, sizeof(MHN_methods)/sizeof(JNINativeMethod));
    }
    if (enable_MH) {
      enable_MH = register_natives(env, MH_class, MH_methods, sizeof(MH_methods)/sizeof(JNINativeMethod));
1409 1410
    }
  }
1411

1412 1413
  if (TraceInvokeDynamic) {
    tty->print_cr("MethodHandle support loaded (using LambdaForms)");
1414 1415 1416
  }

  if (enable_MH) {
1417
    MethodHandles::generate_adapters();
1418 1419
    MethodHandles::set_enabled(true);
  }
1420 1421
}
JVM_END