1 /*
   2  * Copyright (c) 2008, 2014, 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/stringTable.hpp"
  27 #include "compiler/compileBroker.hpp"
  28 #include "interpreter/interpreter.hpp"
  29 #include "interpreter/oopMapCache.hpp"
  30 #include "memory/allocation.inline.hpp"
  31 #include "memory/oopFactory.hpp"
  32 #include "prims/jvmtiRedefineClassesTrace.hpp"
  33 #include "prims/methodHandles.hpp"
  34 #include "runtime/compilationPolicy.hpp"
  35 #include "runtime/javaCalls.hpp"
  36 #include "runtime/reflection.hpp"
  37 #include "runtime/signature.hpp"
  38 #include "runtime/stubRoutines.hpp"
  39 
  40 
  41 /*
  42  * JSR 292 reference implementation: method handles
  43  * The JDK 7 reference implementation represented method handle
  44  * combinations as chains.  Each link in the chain had a "vmentry"
  45  * field which pointed at a bit of assembly code which performed
  46  * one transformation before dispatching to the next link in the chain.
  47  *
  48  * The current reference implementation pushes almost all code generation
  49  * responsibility to (trusted) Java code.  A method handle contains a
  50  * pointer to its "LambdaForm", which embodies all details of the method
  51  * handle's behavior.  The LambdaForm is a normal Java object, managed
  52  * 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 // MethodHandles::generate_adapters
  60 //
  61 void MethodHandles::generate_adapters() {
  62   if (SystemDictionary::MethodHandle_klass() == NULL)  return;
  63 
  64   assert(_adapter_code == NULL, "generate only once");
  65 
  66   ResourceMark rm;
  67   TraceTime timer("MethodHandles adapters generation", TraceStartupTime);
  68   _adapter_code = MethodHandlesAdapterBlob::create(adapter_code_size);
  69   if (_adapter_code == NULL)
  70     vm_exit_out_of_memory(adapter_code_size, OOM_MALLOC_ERROR,
  71                           "CodeCache: no room for MethodHandles adapters");
  72   {
  73     CodeBuffer code(_adapter_code);
  74     MethodHandlesAdapterGenerator g(&code);
  75     g.generate();
  76     code.log_section_sizes("MethodHandlesAdapterBlob");
  77   }
  78 }
  79 
  80 //------------------------------------------------------------------------------
  81 // MethodHandlesAdapterGenerator::generate
  82 //
  83 void MethodHandlesAdapterGenerator::generate() {
  84   // Generate generic method handle adapters.
  85   // Generate interpreter entries
  86   for (Interpreter::MethodKind mk = Interpreter::method_handle_invoke_FIRST;
  87        mk <= Interpreter::method_handle_invoke_LAST;
  88        mk = Interpreter::MethodKind(1 + (int)mk)) {
  89     vmIntrinsics::ID iid = Interpreter::method_handle_intrinsic(mk);
  90     StubCodeMark mark(this, "MethodHandle::interpreter_entry", vmIntrinsics::name_at(iid));
  91     address entry = MethodHandles::generate_method_handle_interpreter_entry(_masm, iid);
  92     if (entry != NULL) {
  93       Interpreter::set_entry_for_kind(mk, entry);
  94     }
  95     // If the entry is not set, it will throw AbstractMethodError.
  96   }
  97 }
  98 
  99 void MethodHandles::set_enabled(bool z) {
 100   if (_enabled != z) {
 101     guarantee(z, "can only enable once");
 102     _enabled = z;
 103   }
 104 }
 105 
 106 // MemberName support
 107 
 108 // import java_lang_invoke_MemberName.*
 109 enum {
 110   IS_METHOD            = java_lang_invoke_MemberName::MN_IS_METHOD,
 111   IS_CONSTRUCTOR       = java_lang_invoke_MemberName::MN_IS_CONSTRUCTOR,
 112   IS_FIELD             = java_lang_invoke_MemberName::MN_IS_FIELD,
 113   IS_TYPE              = java_lang_invoke_MemberName::MN_IS_TYPE,
 114   CALLER_SENSITIVE     = java_lang_invoke_MemberName::MN_CALLER_SENSITIVE,
 115   REFERENCE_KIND_SHIFT = java_lang_invoke_MemberName::MN_REFERENCE_KIND_SHIFT,
 116   REFERENCE_KIND_MASK  = java_lang_invoke_MemberName::MN_REFERENCE_KIND_MASK,
 117   SEARCH_SUPERCLASSES  = java_lang_invoke_MemberName::MN_SEARCH_SUPERCLASSES,
 118   SEARCH_INTERFACES    = java_lang_invoke_MemberName::MN_SEARCH_INTERFACES,
 119   ALL_KINDS      = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE
 120 };
 121 
 122 Handle MethodHandles::new_MemberName(TRAPS) {
 123   Handle empty;
 124   instanceKlassHandle k(THREAD, SystemDictionary::MemberName_klass());
 125   if (!k->is_initialized())  k->initialize(CHECK_(empty));
 126   return Handle(THREAD, k->allocate_instance(THREAD));
 127 }
 128 
 129 oop MethodHandles::init_MemberName(Handle mname, Handle target) {
 130   // This method is used from java.lang.invoke.MemberName constructors.
 131   // It fills in the new MemberName from a java.lang.reflect.Member.
 132   Thread* thread = Thread::current();
 133   oop target_oop = target();
 134   Klass* target_klass = target_oop->klass();
 135   if (target_klass == SystemDictionary::reflect_Field_klass()) {
 136     oop clazz = java_lang_reflect_Field::clazz(target_oop); // fd.field_holder()
 137     int slot  = java_lang_reflect_Field::slot(target_oop);  // fd.index()
 138     KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
 139     if (!k.is_null() && k->oop_is_instance()) {
 140       fieldDescriptor fd(InstanceKlass::cast(k()), slot);
 141       oop mname2 = init_field_MemberName(mname, fd);
 142       if (mname2 != NULL) {
 143         // Since we have the reified name and type handy, add them to the result.
 144         if (java_lang_invoke_MemberName::name(mname2) == NULL)
 145           java_lang_invoke_MemberName::set_name(mname2, java_lang_reflect_Field::name(target_oop));
 146         if (java_lang_invoke_MemberName::type(mname2) == NULL)
 147           java_lang_invoke_MemberName::set_type(mname2, java_lang_reflect_Field::type(target_oop));
 148       }
 149       return mname2;
 150     }
 151   } else if (target_klass == SystemDictionary::reflect_Method_klass()) {
 152     oop clazz  = java_lang_reflect_Method::clazz(target_oop);
 153     int slot   = java_lang_reflect_Method::slot(target_oop);
 154     KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
 155     if (!k.is_null() && k->oop_is_instance()) {
 156       Method* m = InstanceKlass::cast(k())->method_with_idnum(slot);
 157       if (m == NULL || is_signature_polymorphic(m->intrinsic_id()))
 158         return NULL;            // do not resolve unless there is a concrete signature
 159       CallInfo info(m, k());
 160       return init_method_MemberName(mname, info);
 161     }
 162   } else if (target_klass == SystemDictionary::reflect_Constructor_klass()) {
 163     oop clazz  = java_lang_reflect_Constructor::clazz(target_oop);
 164     int slot   = java_lang_reflect_Constructor::slot(target_oop);
 165     KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
 166     if (!k.is_null() && k->oop_is_instance()) {
 167       Method* m = InstanceKlass::cast(k())->method_with_idnum(slot);
 168       if (m == NULL)  return NULL;
 169       CallInfo info(m, k());
 170       return init_method_MemberName(mname, info);
 171     }
 172   }
 173   return NULL;
 174 }
 175 
 176 oop MethodHandles::init_method_MemberName(Handle mname, CallInfo& info) {
 177   assert(info.resolved_appendix().is_null(), "only normal methods here");
 178   methodHandle m = info.resolved_method();
 179   KlassHandle m_klass = m->method_holder();
 180   int flags = (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS );
 181   int vmindex = Method::invalid_vtable_index;
 182 
 183   switch (info.call_kind()) {
 184   case CallInfo::itable_call:
 185     vmindex = info.itable_index();
 186     // More importantly, the itable index only works with the method holder.
 187     assert(m_klass->verify_itable_index(vmindex), "");
 188     flags |= IS_METHOD | (JVM_REF_invokeInterface << REFERENCE_KIND_SHIFT);
 189     if (TraceInvokeDynamic) {
 190       ResourceMark rm;
 191       tty->print_cr("memberName: invokeinterface method_holder::method: %s, itableindex: %d, access_flags:",
 192             Method::name_and_sig_as_C_string(m->method_holder(), m->name(), m->signature()),
 193             vmindex);
 194        m->access_flags().print_on(tty);
 195        if (!m->is_abstract()) {
 196          tty->print("default");
 197        }
 198        tty->cr();
 199     }
 200     break;
 201 
 202   case CallInfo::vtable_call:
 203     vmindex = info.vtable_index();
 204     flags |= IS_METHOD | (JVM_REF_invokeVirtual << REFERENCE_KIND_SHIFT);
 205     assert(info.resolved_klass()->is_subtype_of(m_klass()), "virtual call must be type-safe");
 206     if (m_klass->is_interface()) {
 207       // This is a vtable call to an interface method (abstract "miranda method" or default method).
 208       // The vtable index is meaningless without a class (not interface) receiver type, so get one.
 209       // (LinkResolver should help us figure this out.)
 210       KlassHandle m_klass_non_interface = info.resolved_klass();
 211       if (m_klass_non_interface->is_interface()) {
 212         m_klass_non_interface = SystemDictionary::Object_klass();
 213 #ifdef ASSERT
 214         { ResourceMark rm;
 215           Method* m2 = m_klass_non_interface->vtable()->method_at(vmindex);
 216           assert(m->name() == m2->name() && m->signature() == m2->signature(),
 217                  err_msg("at %d, %s != %s", vmindex,
 218                          m->name_and_sig_as_C_string(), m2->name_and_sig_as_C_string()));
 219         }
 220 #endif //ASSERT
 221       }
 222       if (!m->is_public()) {
 223         assert(m->is_public(), "virtual call must be to public interface method");
 224         return NULL;  // elicit an error later in product build
 225       }
 226       assert(info.resolved_klass()->is_subtype_of(m_klass_non_interface()), "virtual call must be type-safe");
 227       m_klass = m_klass_non_interface;
 228     }
 229     if (TraceInvokeDynamic) {
 230       ResourceMark rm;
 231       tty->print_cr("memberName: invokevirtual method_holder::method: %s, receiver: %s, vtableindex: %d, access_flags:",
 232             Method::name_and_sig_as_C_string(m->method_holder(), m->name(), m->signature()),
 233             m_klass->internal_name(), vmindex);
 234        m->access_flags().print_on(tty);
 235        if (m->is_default_method()) {
 236          tty->print("default");
 237        }
 238        tty->cr();
 239     }
 240     break;
 241 
 242   case CallInfo::direct_call:
 243     vmindex = Method::nonvirtual_vtable_index;
 244     if (m->is_static()) {
 245       flags |= IS_METHOD      | (JVM_REF_invokeStatic  << REFERENCE_KIND_SHIFT);
 246     } else if (m->is_initializer()) {
 247       flags |= IS_CONSTRUCTOR | (JVM_REF_invokeSpecial << REFERENCE_KIND_SHIFT);
 248     } else {
 249       flags |= IS_METHOD      | (JVM_REF_invokeSpecial << REFERENCE_KIND_SHIFT);
 250     }
 251     break;
 252 
 253   default:  assert(false, "bad CallInfo");  return NULL;
 254   }
 255 
 256   // @CallerSensitive annotation detected
 257   if (m->caller_sensitive()) {
 258     flags |= CALLER_SENSITIVE;
 259   }
 260 
 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
 265   java_lang_invoke_MemberName::set_clazz(   mname_oop, m_klass->java_mirror());
 266   // Note:  name and type can be lazily computed by resolve_MemberName,
 267   // if Java code needs them as resolved String and MethodType objects.
 268   // The clazz must be eagerly stored, because it provides a GC
 269   // root to help keep alive the Method*.
 270   // If relevant, the vtable or itable value is stored as vmindex.
 271   // This is done eagerly, since it is readily available without
 272   // constructing any new objects.
 273 
 274   return mname();
 275 }
 276 
 277 oop MethodHandles::init_field_MemberName(Handle mname, fieldDescriptor& fd, bool is_setter) {
 278   int flags = (jushort)( fd.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS );
 279   flags |= IS_FIELD | ((fd.is_static() ? JVM_REF_getStatic : JVM_REF_getField) << REFERENCE_KIND_SHIFT);
 280   if (is_setter)  flags += ((JVM_REF_putField - JVM_REF_getField) << REFERENCE_KIND_SHIFT);
 281   Metadata* vmtarget = fd.field_holder();
 282   int vmindex        = fd.offset();  // determines the field uniquely when combined with static bit
 283   oop mname_oop = mname();
 284   java_lang_invoke_MemberName::set_flags(mname_oop,    flags);
 285   java_lang_invoke_MemberName::set_vmtarget(mname_oop, vmtarget);
 286   java_lang_invoke_MemberName::set_vmindex(mname_oop,  vmindex);
 287   java_lang_invoke_MemberName::set_clazz(mname_oop,    fd.field_holder()->java_mirror());
 288   oop type = field_signature_type_or_null(fd.signature());
 289   oop name = field_name_or_null(fd.name());
 290   if (name != NULL)
 291     java_lang_invoke_MemberName::set_name(mname_oop,   name);
 292   if (type != NULL)
 293     java_lang_invoke_MemberName::set_type(mname_oop,   type);
 294   // Note:  name and type can be lazily computed by resolve_MemberName,
 295   // if Java code needs them as resolved String and Class objects.
 296   // Note that the incoming type oop might be pre-resolved (non-null).
 297   // The base clazz and field offset (vmindex) must be eagerly stored,
 298   // because they unambiguously identify the field.
 299   // Although the fieldDescriptor::_index would also identify the field,
 300   // we do not use it, because it is harder to decode.
 301   // TO DO: maybe intern mname_oop
 302   return mname();
 303 }
 304 
 305 // JVM 2.9 Special Methods:
 306 // A method is signature polymorphic if and only if all of the following conditions hold :
 307 // * It is declared in the java.lang.invoke.MethodHandle class.
 308 // * It has a single formal parameter of type Object[].
 309 // * It has a return type of Object.
 310 // * It has the ACC_VARARGS and ACC_NATIVE flags set.
 311 bool MethodHandles::is_method_handle_invoke_name(Klass* klass, Symbol* name) {
 312   if (klass == NULL)
 313     return false;
 314   // The following test will fail spuriously during bootstrap of MethodHandle itself:
 315   //    if (klass != SystemDictionary::MethodHandle_klass())
 316   // Test the name instead:
 317   if (klass->name() != vmSymbols::java_lang_invoke_MethodHandle())
 318     return false;
 319   Symbol* poly_sig = vmSymbols::object_array_object_signature();
 320   Method* m = InstanceKlass::cast(klass)->find_method(name, poly_sig);
 321   if (m == NULL)  return false;
 322   int required = JVM_ACC_NATIVE | JVM_ACC_VARARGS;
 323   int flags = m->access_flags().as_int();
 324   return (flags & required) == required;
 325 }
 326 
 327 
 328 Symbol* MethodHandles::signature_polymorphic_intrinsic_name(vmIntrinsics::ID iid) {
 329   assert(is_signature_polymorphic_intrinsic(iid), err_msg("iid=%d", iid));
 330   switch (iid) {
 331   case vmIntrinsics::_invokeBasic:      return vmSymbols::invokeBasic_name();
 332   case vmIntrinsics::_linkToVirtual:    return vmSymbols::linkToVirtual_name();
 333   case vmIntrinsics::_linkToStatic:     return vmSymbols::linkToStatic_name();
 334   case vmIntrinsics::_linkToSpecial:    return vmSymbols::linkToSpecial_name();
 335   case vmIntrinsics::_linkToInterface:  return vmSymbols::linkToInterface_name();
 336   }
 337   assert(false, "");
 338   return 0;
 339 }
 340 
 341 int MethodHandles::signature_polymorphic_intrinsic_ref_kind(vmIntrinsics::ID iid) {
 342   switch (iid) {
 343   case vmIntrinsics::_invokeBasic:      return 0;
 344   case vmIntrinsics::_linkToVirtual:    return JVM_REF_invokeVirtual;
 345   case vmIntrinsics::_linkToStatic:     return JVM_REF_invokeStatic;
 346   case vmIntrinsics::_linkToSpecial:    return JVM_REF_invokeSpecial;
 347   case vmIntrinsics::_linkToInterface:  return JVM_REF_invokeInterface;
 348   }
 349   assert(false, err_msg("iid=%d", iid));
 350   return 0;
 351 }
 352 
 353 vmIntrinsics::ID MethodHandles::signature_polymorphic_name_id(Symbol* name) {
 354   vmSymbols::SID name_id = vmSymbols::find_sid(name);
 355   switch (name_id) {
 356   // The ID _invokeGeneric stands for all non-static signature-polymorphic methods, except built-ins.
 357   case vmSymbols::VM_SYMBOL_ENUM_NAME(invoke_name):           return vmIntrinsics::_invokeGeneric;
 358   // The only built-in non-static signature-polymorphic method is MethodHandle.invokeBasic:
 359   case vmSymbols::VM_SYMBOL_ENUM_NAME(invokeBasic_name):      return vmIntrinsics::_invokeBasic;
 360 
 361   // There is one static signature-polymorphic method for each JVM invocation mode.
 362   case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToVirtual_name):    return vmIntrinsics::_linkToVirtual;
 363   case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToStatic_name):     return vmIntrinsics::_linkToStatic;
 364   case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToSpecial_name):    return vmIntrinsics::_linkToSpecial;
 365   case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToInterface_name):  return vmIntrinsics::_linkToInterface;
 366   }
 367 
 368   // Cover the case of invokeExact and any future variants of invokeFoo.
 369   Klass* mh_klass = SystemDictionary::well_known_klass(
 370                               SystemDictionary::WK_KLASS_ENUM_NAME(MethodHandle_klass) );
 371   if (mh_klass != NULL && is_method_handle_invoke_name(mh_klass, name))
 372     return vmIntrinsics::_invokeGeneric;
 373 
 374   // Note: The pseudo-intrinsic _compiledLambdaForm is never linked against.
 375   // Instead it is used to mark lambda forms bound to invokehandle or invokedynamic.
 376   return vmIntrinsics::_none;
 377 }
 378 
 379 vmIntrinsics::ID MethodHandles::signature_polymorphic_name_id(Klass* klass, Symbol* name) {
 380   if (klass != NULL &&
 381       klass->name() == vmSymbols::java_lang_invoke_MethodHandle()) {
 382     vmIntrinsics::ID iid = signature_polymorphic_name_id(name);
 383     if (iid != vmIntrinsics::_none)
 384       return iid;
 385     if (is_method_handle_invoke_name(klass, name))
 386       return vmIntrinsics::_invokeGeneric;
 387   }
 388   return vmIntrinsics::_none;
 389 }
 390 
 391 
 392 // convert the external string or reflective type to an internal signature
 393 Symbol* MethodHandles::lookup_signature(oop type_str, bool intern_if_not_found, TRAPS) {
 394   if (java_lang_invoke_MethodType::is_instance(type_str)) {
 395     return java_lang_invoke_MethodType::as_signature(type_str, intern_if_not_found, CHECK_NULL);
 396   } else if (java_lang_Class::is_instance(type_str)) {
 397     return java_lang_Class::as_signature(type_str, false, CHECK_NULL);
 398   } else if (java_lang_String::is_instance(type_str)) {
 399     if (intern_if_not_found) {
 400       return java_lang_String::as_symbol(type_str, CHECK_NULL);
 401     } else {
 402       return java_lang_String::as_symbol_or_null(type_str);
 403     }
 404   } else {
 405     THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized type", NULL);
 406   }
 407 }
 408 
 409 static const char OBJ_SIG[] = "Ljava/lang/Object;";
 410 enum { OBJ_SIG_LEN = 18 };
 411 
 412 bool MethodHandles::is_basic_type_signature(Symbol* sig) {
 413   assert(vmSymbols::object_signature()->utf8_length() == (int)OBJ_SIG_LEN, "");
 414   assert(vmSymbols::object_signature()->equals(OBJ_SIG), "");
 415   const int len = sig->utf8_length();
 416   for (int i = 0; i < len; i++) {
 417     switch (sig->byte_at(i)) {
 418     case 'L':
 419       // only java/lang/Object is valid here
 420       if (sig->index_of_at(i, OBJ_SIG, OBJ_SIG_LEN) != i)
 421         return false;
 422       i += OBJ_SIG_LEN-1;  //-1 because of i++ in loop
 423       continue;
 424     case '(': case ')': case 'V':
 425     case 'I': case 'J': case 'F': case 'D':
 426       continue;
 427     //case '[':
 428     //case 'Z': case 'B': case 'C': case 'S':
 429     default:
 430       return false;
 431     }
 432   }
 433   return true;
 434 }
 435 
 436 Symbol* MethodHandles::lookup_basic_type_signature(Symbol* sig, bool keep_last_arg, TRAPS) {
 437   Symbol* bsig = NULL;
 438   if (sig == NULL) {
 439     return sig;
 440   } else if (is_basic_type_signature(sig)) {
 441     sig->increment_refcount();
 442     return sig;  // that was easy
 443   } else if (sig->byte_at(0) != '(') {
 444     BasicType bt = char2type(sig->byte_at(0));
 445     if (is_subword_type(bt)) {
 446       bsig = vmSymbols::int_signature();
 447     } else {
 448       assert(bt == T_OBJECT || bt == T_ARRAY, "is_basic_type_signature was false");
 449       bsig = vmSymbols::object_signature();
 450     }
 451   } else {
 452     ResourceMark rm;
 453     stringStream buffer(128);
 454     buffer.put('(');
 455     int arg_pos = 0, keep_arg_pos = -1;
 456     if (keep_last_arg)
 457       keep_arg_pos = ArgumentCount(sig).size() - 1;
 458     for (SignatureStream ss(sig); !ss.is_done(); ss.next()) {
 459       BasicType bt = ss.type();
 460       size_t this_arg_pos = buffer.size();
 461       if (ss.at_return_type()) {
 462         buffer.put(')');
 463       }
 464       if (arg_pos == keep_arg_pos) {
 465         buffer.write((char*) ss.raw_bytes(),
 466                      (int)   ss.raw_length());
 467       } else if (bt == T_OBJECT || bt == T_ARRAY) {
 468         buffer.write(OBJ_SIG, OBJ_SIG_LEN);
 469       } else {
 470         if (is_subword_type(bt))
 471           bt = T_INT;
 472         buffer.put(type2char(bt));
 473       }
 474       arg_pos++;
 475     }
 476     const char* sigstr =       buffer.base();
 477     int         siglen = (int) buffer.size();
 478     bsig = SymbolTable::new_symbol(sigstr, siglen, THREAD);
 479   }
 480   assert(is_basic_type_signature(bsig) ||
 481          // detune assert in case the injected argument is not a basic type:
 482          keep_last_arg, "");
 483   return bsig;
 484 }
 485 
 486 void MethodHandles::print_as_basic_type_signature_on(outputStream* st,
 487                                                      Symbol* sig,
 488                                                      bool keep_arrays,
 489                                                      bool keep_basic_names) {
 490   st = st ? st : tty;
 491   int len  = sig->utf8_length();
 492   int array = 0;
 493   bool prev_type = false;
 494   for (int i = 0; i < len; i++) {
 495     char ch = sig->byte_at(i);
 496     switch (ch) {
 497     case '(': case ')':
 498       prev_type = false;
 499       st->put(ch);
 500       continue;
 501     case '[':
 502       if (!keep_basic_names && keep_arrays)
 503         st->put(ch);
 504       array++;
 505       continue;
 506     case 'L':
 507       {
 508         if (prev_type)  st->put(',');
 509         int start = i+1, slash = start;
 510         while (++i < len && (ch = sig->byte_at(i)) != ';') {
 511           if (ch == '/' || ch == '.' || ch == '$')  slash = i+1;
 512         }
 513         if (slash < i)  start = slash;
 514         if (!keep_basic_names) {
 515           st->put('L');
 516         } else {
 517           for (int j = start; j < i; j++)
 518             st->put(sig->byte_at(j));
 519           prev_type = true;
 520         }
 521         break;
 522       }
 523     default:
 524       {
 525         if (array && char2type(ch) != T_ILLEGAL && !keep_arrays) {
 526           ch = '[';
 527           array = 0;
 528         }
 529         if (prev_type)  st->put(',');
 530         const char* n = NULL;
 531         if (keep_basic_names)
 532           n = type2name(char2type(ch));
 533         if (n == NULL) {
 534           // unknown letter, or we don't want to know its name
 535           st->put(ch);
 536         } else {
 537           st->print("%s", n);
 538           prev_type = true;
 539         }
 540         break;
 541       }
 542     }
 543     // Switch break goes here to take care of array suffix:
 544     if (prev_type) {
 545       while (array > 0) {
 546         st->print("[]");
 547         --array;
 548       }
 549     }
 550     array = 0;
 551   }
 552 }
 553 
 554 
 555 
 556 static oop object_java_mirror() {
 557   return SystemDictionary::Object_klass()->java_mirror();
 558 }
 559 
 560 oop MethodHandles::field_name_or_null(Symbol* s) {
 561   if (s == NULL)  return NULL;
 562   return StringTable::lookup(s);
 563 }
 564 
 565 oop MethodHandles::field_signature_type_or_null(Symbol* s) {
 566   if (s == NULL)  return NULL;
 567   BasicType bt = FieldType::basic_type(s);
 568   if (is_java_primitive(bt)) {
 569     assert(s->utf8_length() == 1, "");
 570     return java_lang_Class::primitive_mirror(bt);
 571   }
 572   // Here are some more short cuts for common types.
 573   // They are optional, since reference types can be resolved lazily.
 574   if (bt == T_OBJECT) {
 575     if (s == vmSymbols::object_signature()) {
 576       return object_java_mirror();
 577     } else if (s == vmSymbols::class_signature()) {
 578       return SystemDictionary::Class_klass()->java_mirror();
 579     } else if (s == vmSymbols::string_signature()) {
 580       return SystemDictionary::String_klass()->java_mirror();
 581     }
 582   }
 583   return NULL;
 584 }
 585 
 586 
 587 // An unresolved member name is a mere symbolic reference.
 588 // Resolving it plants a vmtarget/vmindex in it,
 589 // which refers directly to JVM internals.
 590 Handle MethodHandles::resolve_MemberName(Handle mname, KlassHandle caller, TRAPS) {
 591   Handle empty;
 592   assert(java_lang_invoke_MemberName::is_instance(mname()), "");
 593 
 594   if (java_lang_invoke_MemberName::vmtarget(mname()) != NULL) {
 595     // Already resolved.
 596     DEBUG_ONLY(int vmindex = java_lang_invoke_MemberName::vmindex(mname()));
 597     assert(vmindex >= Method::nonvirtual_vtable_index, "");
 598     return mname;
 599   }
 600 
 601   Handle defc_oop(THREAD, java_lang_invoke_MemberName::clazz(mname()));
 602   Handle name_str(THREAD, java_lang_invoke_MemberName::name( mname()));
 603   Handle type_str(THREAD, java_lang_invoke_MemberName::type( mname()));
 604   int    flags    =       java_lang_invoke_MemberName::flags(mname());
 605   int    ref_kind =       (flags >> REFERENCE_KIND_SHIFT) & REFERENCE_KIND_MASK;
 606   if (!ref_kind_is_valid(ref_kind)) {
 607     THROW_MSG_(vmSymbols::java_lang_InternalError(), "obsolete MemberName format", empty);
 608   }
 609 
 610   DEBUG_ONLY(int old_vmindex);
 611   assert((old_vmindex = java_lang_invoke_MemberName::vmindex(mname())) == 0, "clean input");
 612 
 613   if (defc_oop.is_null() || name_str.is_null() || type_str.is_null()) {
 614     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "nothing to resolve", empty);
 615   }
 616 
 617   instanceKlassHandle defc;
 618   {
 619     Klass* defc_klass = java_lang_Class::as_Klass(defc_oop());
 620     if (defc_klass == NULL)  return empty;  // a primitive; no resolution possible
 621     if (!defc_klass->oop_is_instance()) {
 622       if (!defc_klass->oop_is_array())  return empty;
 623       defc_klass = SystemDictionary::Object_klass();
 624     }
 625     defc = instanceKlassHandle(THREAD, defc_klass);
 626   }
 627   if (defc.is_null()) {
 628     THROW_MSG_(vmSymbols::java_lang_InternalError(), "primitive class", empty);
 629   }
 630   defc->link_class(CHECK_(empty));  // possible safepoint
 631 
 632   // convert the external string name to an internal symbol
 633   TempNewSymbol name = java_lang_String::as_symbol_or_null(name_str());
 634   if (name == NULL)  return empty;  // no such name
 635   if (name == vmSymbols::class_initializer_name())
 636     return empty; // illegal name
 637 
 638   vmIntrinsics::ID mh_invoke_id = vmIntrinsics::_none;
 639   if ((flags & ALL_KINDS) == IS_METHOD &&
 640       (defc() == SystemDictionary::MethodHandle_klass()) &&
 641       (ref_kind == JVM_REF_invokeVirtual ||
 642        ref_kind == JVM_REF_invokeSpecial ||
 643        // static invocation mode is required for _linkToVirtual, etc.:
 644        ref_kind == JVM_REF_invokeStatic)) {
 645     vmIntrinsics::ID iid = signature_polymorphic_name_id(name);
 646     if (iid != vmIntrinsics::_none &&
 647         ((ref_kind == JVM_REF_invokeStatic) == is_signature_polymorphic_static(iid))) {
 648       // Virtual methods invoke and invokeExact, plus internal invokers like _invokeBasic.
 649       // For a static reference it could an internal linkage routine like _linkToVirtual, etc.
 650       mh_invoke_id = iid;
 651     }
 652   }
 653 
 654   // convert the external string or reflective type to an internal signature
 655   TempNewSymbol type = lookup_signature(type_str(), (mh_invoke_id != vmIntrinsics::_none), CHECK_(empty));
 656   if (type == NULL)  return empty;  // no such signature exists in the VM
 657 
 658   // Time to do the lookup.
 659   switch (flags & ALL_KINDS) {
 660   case IS_METHOD:
 661     {
 662       CallInfo result;
 663       {
 664         assert(!HAS_PENDING_EXCEPTION, "");
 665         if (ref_kind == JVM_REF_invokeStatic) {
 666           LinkResolver::resolve_static_call(result,
 667                         defc, name, type, caller, caller.not_null(), false, THREAD);
 668         } else if (ref_kind == JVM_REF_invokeInterface) {
 669           LinkResolver::resolve_interface_call(result, Handle(), defc,
 670                         defc, name, type, caller, caller.not_null(), false, THREAD);
 671         } else if (mh_invoke_id != vmIntrinsics::_none) {
 672           assert(!is_signature_polymorphic_static(mh_invoke_id), "");
 673           LinkResolver::resolve_handle_call(result,
 674                         defc, name, type, caller, THREAD);
 675         } else if (ref_kind == JVM_REF_invokeSpecial) {
 676           LinkResolver::resolve_special_call(result,
 677                         defc, name, type, caller, caller.not_null(), THREAD);
 678         } else if (ref_kind == JVM_REF_invokeVirtual) {
 679           LinkResolver::resolve_virtual_call(result, Handle(), defc,
 680                         defc, name, type, caller, caller.not_null(), false, THREAD);
 681         } else {
 682           assert(false, err_msg("ref_kind=%d", ref_kind));
 683         }
 684         if (HAS_PENDING_EXCEPTION) {
 685           return empty;
 686         }
 687       }
 688       if (result.resolved_appendix().not_null()) {
 689         // The resolved MemberName must not be accompanied by an appendix argument,
 690         // since there is no way to bind this value into the MemberName.
 691         // Caller is responsible to prevent this from happening.
 692         THROW_MSG_(vmSymbols::java_lang_InternalError(), "appendix", empty);
 693       }
 694       oop mname2 = init_method_MemberName(mname, result);
 695       return Handle(THREAD, mname2);
 696     }
 697   case IS_CONSTRUCTOR:
 698     {
 699       CallInfo result;
 700       {
 701         assert(!HAS_PENDING_EXCEPTION, "");
 702         if (name == vmSymbols::object_initializer_name()) {
 703           LinkResolver::resolve_special_call(result,
 704                         defc, name, type, caller, caller.not_null(), THREAD);
 705         } else {
 706           break;                // will throw after end of switch
 707         }
 708         if (HAS_PENDING_EXCEPTION) {
 709           return empty;
 710         }
 711       }
 712       assert(result.is_statically_bound(), "");
 713       oop mname2 = init_method_MemberName(mname, result);
 714       return Handle(THREAD, mname2);
 715     }
 716   case IS_FIELD:
 717     {
 718       fieldDescriptor result; // find_field initializes fd if found
 719       {
 720         assert(!HAS_PENDING_EXCEPTION, "");
 721         LinkResolver::resolve_field(result, defc, name, type, caller, Bytecodes::_nop, false, false, THREAD);
 722         if (HAS_PENDING_EXCEPTION) {
 723           return empty;
 724         }
 725       }
 726       oop mname2 = init_field_MemberName(mname, result, ref_kind_is_setter(ref_kind));
 727       return Handle(THREAD, mname2);
 728     }
 729   default:
 730     THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format", empty);
 731   }
 732 
 733   return empty;
 734 }
 735 
 736 // Conversely, a member name which is only initialized from JVM internals
 737 // may have null defc, name, and type fields.
 738 // Resolving it plants a vmtarget/vmindex in it,
 739 // which refers directly to JVM internals.
 740 void MethodHandles::expand_MemberName(Handle mname, int suppress, TRAPS) {
 741   assert(java_lang_invoke_MemberName::is_instance(mname()), "");
 742   Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
 743   int vmindex  = java_lang_invoke_MemberName::vmindex(mname());
 744   if (vmtarget == NULL) {
 745     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to expand");
 746   }
 747 
 748   bool have_defc = (java_lang_invoke_MemberName::clazz(mname()) != NULL);
 749   bool have_name = (java_lang_invoke_MemberName::name(mname()) != NULL);
 750   bool have_type = (java_lang_invoke_MemberName::type(mname()) != NULL);
 751   int flags      = java_lang_invoke_MemberName::flags(mname());
 752 
 753   if (suppress != 0) {
 754     if (suppress & _suppress_defc)  have_defc = true;
 755     if (suppress & _suppress_name)  have_name = true;
 756     if (suppress & _suppress_type)  have_type = true;
 757   }
 758 
 759   if (have_defc && have_name && have_type)  return;  // nothing needed
 760 
 761   switch (flags & ALL_KINDS) {
 762   case IS_METHOD:
 763   case IS_CONSTRUCTOR:
 764     {
 765       assert(vmtarget->is_method(), "method or constructor vmtarget is Method*");
 766       methodHandle m(THREAD, (Method*)vmtarget);
 767       DEBUG_ONLY(vmtarget = NULL);  // safety
 768       if (m.is_null())  break;
 769       if (!have_defc) {
 770         InstanceKlass* defc = m->method_holder();
 771         java_lang_invoke_MemberName::set_clazz(mname(), defc->java_mirror());
 772       }
 773       if (!have_name) {
 774         //not java_lang_String::create_from_symbol; let's intern member names
 775         Handle name = StringTable::intern(m->name(), CHECK);
 776         java_lang_invoke_MemberName::set_name(mname(), name());
 777       }
 778       if (!have_type) {
 779         Handle type = java_lang_String::create_from_symbol(m->signature(), CHECK);
 780         java_lang_invoke_MemberName::set_type(mname(), type());
 781       }
 782       return;
 783     }
 784   case IS_FIELD:
 785     {
 786       assert(vmtarget->is_klass(), "field vmtarget is Klass*");
 787       if (!((Klass*) vmtarget)->oop_is_instance())  break;
 788       instanceKlassHandle defc(THREAD, (Klass*) vmtarget);
 789       DEBUG_ONLY(vmtarget = NULL);  // safety
 790       bool is_static = ((flags & JVM_ACC_STATIC) != 0);
 791       fieldDescriptor fd; // find_field initializes fd if found
 792       if (!defc->find_field_from_offset(vmindex, is_static, &fd))
 793         break;                  // cannot expand
 794       if (!have_defc) {
 795         java_lang_invoke_MemberName::set_clazz(mname(), defc->java_mirror());
 796       }
 797       if (!have_name) {
 798         //not java_lang_String::create_from_symbol; let's intern member names
 799         Handle name = StringTable::intern(fd.name(), CHECK);
 800         java_lang_invoke_MemberName::set_name(mname(), name());
 801       }
 802       if (!have_type) {
 803         // If it is a primitive field type, don't mess with short strings like "I".
 804         Handle type = field_signature_type_or_null(fd.signature());
 805         if (type.is_null()) {
 806           java_lang_String::create_from_symbol(fd.signature(), CHECK);
 807         }
 808         java_lang_invoke_MemberName::set_type(mname(), type());
 809       }
 810       return;
 811     }
 812   }
 813   THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
 814 }
 815 
 816 int MethodHandles::find_MemberNames(KlassHandle k,
 817                                     Symbol* name, Symbol* sig,
 818                                     int mflags, KlassHandle caller,
 819                                     int skip, objArrayHandle results) {
 820   // %%% take caller into account!
 821 
 822   Thread* thread = Thread::current();
 823 
 824   if (k.is_null() || !k->oop_is_instance())  return -1;
 825 
 826   int rfill = 0, rlimit = results->length(), rskip = skip;
 827   // overflow measurement:
 828   int overflow = 0, overflow_limit = MAX2(1000, rlimit);
 829 
 830   int match_flags = mflags;
 831   bool search_superc = ((match_flags & SEARCH_SUPERCLASSES) != 0);
 832   bool search_intfc  = ((match_flags & SEARCH_INTERFACES)   != 0);
 833   bool local_only = !(search_superc | search_intfc);
 834   bool classes_only = false;
 835 
 836   if (name != NULL) {
 837     if (name->utf8_length() == 0)  return 0; // a match is not possible
 838   }
 839   if (sig != NULL) {
 840     if (sig->utf8_length() == 0)  return 0; // a match is not possible
 841     if (sig->byte_at(0) == '(')
 842       match_flags &= ~(IS_FIELD | IS_TYPE);
 843     else
 844       match_flags &= ~(IS_CONSTRUCTOR | IS_METHOD);
 845   }
 846 
 847   if ((match_flags & IS_TYPE) != 0) {
 848     // NYI, and Core Reflection works quite well for this query
 849   }
 850 
 851   if ((match_flags & IS_FIELD) != 0) {
 852     for (FieldStream st(k(), local_only, !search_intfc); !st.eos(); st.next()) {
 853       if (name != NULL && st.name() != name)
 854           continue;
 855       if (sig != NULL && st.signature() != sig)
 856         continue;
 857       // passed the filters
 858       if (rskip > 0) {
 859         --rskip;
 860       } else if (rfill < rlimit) {
 861         Handle result(thread, results->obj_at(rfill++));
 862         if (!java_lang_invoke_MemberName::is_instance(result()))
 863           return -99;  // caller bug!
 864         oop saved = MethodHandles::init_field_MemberName(result, st.field_descriptor());
 865         if (saved != result())
 866           results->obj_at_put(rfill-1, saved);  // show saved instance to user
 867       } else if (++overflow >= overflow_limit) {
 868         match_flags = 0; break; // got tired of looking at overflow
 869       }
 870     }
 871   }
 872 
 873   if ((match_flags & (IS_METHOD | IS_CONSTRUCTOR)) != 0) {
 874     // watch out for these guys:
 875     Symbol* init_name   = vmSymbols::object_initializer_name();
 876     Symbol* clinit_name = vmSymbols::class_initializer_name();
 877     if (name == clinit_name)  clinit_name = NULL; // hack for exposing <clinit>
 878     bool negate_name_test = false;
 879     // fix name so that it captures the intention of IS_CONSTRUCTOR
 880     if (!(match_flags & IS_METHOD)) {
 881       // constructors only
 882       if (name == NULL) {
 883         name = init_name;
 884       } else if (name != init_name) {
 885         return 0;               // no constructors of this method name
 886       }
 887     } else if (!(match_flags & IS_CONSTRUCTOR)) {
 888       // methods only
 889       if (name == NULL) {
 890         name = init_name;
 891         negate_name_test = true; // if we see the name, we *omit* the entry
 892       } else if (name == init_name) {
 893         return 0;               // no methods of this constructor name
 894       }
 895     } else {
 896       // caller will accept either sort; no need to adjust name
 897     }
 898     for (MethodStream st(k(), local_only, !search_intfc); !st.eos(); st.next()) {
 899       Method* m = st.method();
 900       Symbol* m_name = m->name();
 901       if (m_name == clinit_name)
 902         continue;
 903       if (name != NULL && ((m_name != name) ^ negate_name_test))
 904           continue;
 905       if (sig != NULL && m->signature() != sig)
 906         continue;
 907       // passed the filters
 908       if (rskip > 0) {
 909         --rskip;
 910       } else if (rfill < rlimit) {
 911         Handle result(thread, results->obj_at(rfill++));
 912         if (!java_lang_invoke_MemberName::is_instance(result()))
 913           return -99;  // caller bug!
 914         CallInfo info(m);
 915         oop saved = MethodHandles::init_method_MemberName(result, info);
 916         if (saved != result())
 917           results->obj_at_put(rfill-1, saved);  // show saved instance to user
 918       } else if (++overflow >= overflow_limit) {
 919         match_flags = 0; break; // got tired of looking at overflow
 920       }
 921     }
 922   }
 923 
 924   // return number of elements we at leasted wanted to initialize
 925   return rfill + overflow;
 926 }
 927 
 928 //
 929 // Here are the native methods in java.lang.invoke.MethodHandleNatives
 930 // They are the private interface between this JVM and the HotSpot-specific
 931 // Java code that implements JSR 292 method handles.
 932 //
 933 // Note:  We use a JVM_ENTRY macro to define each of these, for this is the way
 934 // that intrinsic (non-JNI) native methods are defined in HotSpot.
 935 //
 936 
 937 JVM_ENTRY(jint, MHN_getConstant(JNIEnv *env, jobject igcls, jint which)) {
 938   switch (which) {
 939   case MethodHandles::GC_COUNT_GWT:
 940 #ifdef COMPILER2
 941     return true;
 942 #else
 943     return false;
 944 #endif
 945   }
 946   return 0;
 947 }
 948 JVM_END
 949 
 950 #ifndef PRODUCT
 951 #define EACH_NAMED_CON(template, requirement) \
 952     template(MethodHandles,GC_COUNT_GWT) \
 953     template(java_lang_invoke_MemberName,MN_IS_METHOD) \
 954     template(java_lang_invoke_MemberName,MN_IS_CONSTRUCTOR) \
 955     template(java_lang_invoke_MemberName,MN_IS_FIELD) \
 956     template(java_lang_invoke_MemberName,MN_IS_TYPE) \
 957     template(java_lang_invoke_MemberName,MN_CALLER_SENSITIVE) \
 958     template(java_lang_invoke_MemberName,MN_SEARCH_SUPERCLASSES) \
 959     template(java_lang_invoke_MemberName,MN_SEARCH_INTERFACES) \
 960     template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_SHIFT) \
 961     template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_MASK) \
 962     template(MethodHandles,GC_LAMBDA_SUPPORT) \
 963     /*end*/
 964 
 965 #define IGNORE_REQ(req_expr) /* req_expr */
 966 #define ONE_PLUS(scope,value) 1+
 967 static const int con_value_count = EACH_NAMED_CON(ONE_PLUS, IGNORE_REQ) 0;
 968 #define VALUE_COMMA(scope,value) scope::value,
 969 static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA, IGNORE_REQ) 0 };
 970 #define STRING_NULL(scope,value) #value "\0"
 971 static const char con_names[] = { EACH_NAMED_CON(STRING_NULL, IGNORE_REQ) };
 972 
 973 static bool advertise_con_value(int which) {
 974   if (which < 0)  return false;
 975   bool ok = true;
 976   int count = 0;
 977 #define INC_COUNT(scope,value) \
 978   ++count;
 979 #define CHECK_REQ(req_expr) \
 980   if (which < count)  return ok; \
 981   ok = (req_expr);
 982   EACH_NAMED_CON(INC_COUNT, CHECK_REQ);
 983 #undef INC_COUNT
 984 #undef CHECK_REQ
 985   assert(count == con_value_count, "");
 986   if (which < count)  return ok;
 987   return false;
 988 }
 989 
 990 #undef ONE_PLUS
 991 #undef VALUE_COMMA
 992 #undef STRING_NULL
 993 #undef EACH_NAMED_CON
 994 #endif // PRODUCT
 995 
 996 JVM_ENTRY(jint, MHN_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
 997 #ifndef PRODUCT
 998   if (advertise_con_value(which)) {
 999     assert(which >= 0 && which < con_value_count, "");
1000     int con = con_values[which];
1001     objArrayHandle box(THREAD, (objArrayOop) JNIHandles::resolve(box_jh));
1002     if (box.not_null() && box->klass() == Universe::objectArrayKlassObj() && box->length() > 0) {
1003       const char* str = &con_names[0];
1004       for (int i = 0; i < which; i++)
1005         str += strlen(str) + 1;   // skip name and null
1006       oop name = java_lang_String::create_oop_from_str(str, CHECK_0);  // possible safepoint
1007       box->obj_at_put(0, name);
1008     }
1009     return con;
1010   }
1011 #endif
1012   return 0;
1013 }
1014 JVM_END
1015 
1016 // void init(MemberName self, AccessibleObject ref)
1017 JVM_ENTRY(void, MHN_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
1018   if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
1019   if (target_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "target is null"); }
1020   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1021   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
1022   MethodHandles::init_MemberName(mname, target);
1023 }
1024 JVM_END
1025 
1026 // void expand(MemberName self)
1027 JVM_ENTRY(void, MHN_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1028   if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
1029   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1030   MethodHandles::expand_MemberName(mname, 0, CHECK);
1031 }
1032 JVM_END
1033 
1034 // void resolve(MemberName self, Class<?> caller)
1035 JVM_ENTRY(jobject, MHN_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh)) {
1036   if (mname_jh == NULL) { THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "mname is null"); }
1037   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1038 
1039   // The trusted Java code that calls this method should already have performed
1040   // access checks on behalf of the given caller.  But, we can verify this.
1041   if (VerifyMethodHandles && caller_jh != NULL &&
1042       java_lang_invoke_MemberName::clazz(mname()) != NULL) {
1043     Klass* reference_klass = java_lang_Class::as_Klass(java_lang_invoke_MemberName::clazz(mname()));
1044     if (reference_klass != NULL && reference_klass->oop_is_objArray()) {
1045       reference_klass = ObjArrayKlass::cast(reference_klass)->bottom_klass();
1046     }
1047 
1048     // Reflection::verify_class_access can only handle instance classes.
1049     if (reference_klass != NULL && reference_klass->oop_is_instance()) {
1050       // Emulate LinkResolver::check_klass_accessability.
1051       Klass* caller = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh));
1052       if (!Reflection::verify_class_access(caller,
1053                                            reference_klass,
1054                                            true)) {
1055         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), reference_klass->external_name());
1056       }
1057     }
1058   }
1059 
1060   KlassHandle caller(THREAD,
1061                      caller_jh == NULL ? (Klass*) NULL :
1062                      java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh)));
1063   Handle resolved = MethodHandles::resolve_MemberName(mname, caller, CHECK_NULL);
1064 
1065   if (resolved.is_null()) {
1066     int flags = java_lang_invoke_MemberName::flags(mname());
1067     int ref_kind = (flags >> REFERENCE_KIND_SHIFT) & REFERENCE_KIND_MASK;
1068     if (!MethodHandles::ref_kind_is_valid(ref_kind)) {
1069       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "obsolete MemberName format");
1070     }
1071     if ((flags & ALL_KINDS) == IS_FIELD) {
1072       THROW_MSG_NULL(vmSymbols::java_lang_NoSuchMethodError(), "field resolution failed");
1073     } else if ((flags & ALL_KINDS) == IS_METHOD ||
1074                (flags & ALL_KINDS) == IS_CONSTRUCTOR) {
1075       THROW_MSG_NULL(vmSymbols::java_lang_NoSuchFieldError(), "method resolution failed");
1076     } else {
1077       THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "resolution failed");
1078     }
1079   }
1080 
1081   return JNIHandles::make_local(THREAD, resolved());
1082 }
1083 JVM_END
1084 
1085 static jlong find_member_field_offset(oop mname, bool must_be_static, TRAPS) {
1086   if (mname == NULL ||
1087       java_lang_invoke_MemberName::vmtarget(mname) == NULL) {
1088     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "mname not resolved");
1089   } else {
1090     int flags = java_lang_invoke_MemberName::flags(mname);
1091     if ((flags & IS_FIELD) != 0 &&
1092         (must_be_static
1093          ? (flags & JVM_ACC_STATIC) != 0
1094          : (flags & JVM_ACC_STATIC) == 0)) {
1095       int vmindex = java_lang_invoke_MemberName::vmindex(mname);
1096       return (jlong) vmindex;
1097     }
1098   }
1099   const char* msg = (must_be_static ? "static field required" : "non-static field required");
1100   THROW_MSG_0(vmSymbols::java_lang_InternalError(), msg);
1101   return 0;
1102 }
1103 
1104 JVM_ENTRY(jlong, MHN_objectFieldOffset(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1105   return find_member_field_offset(JNIHandles::resolve(mname_jh), false, THREAD);
1106 }
1107 JVM_END
1108 
1109 JVM_ENTRY(jlong, MHN_staticFieldOffset(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1110   return find_member_field_offset(JNIHandles::resolve(mname_jh), true, THREAD);
1111 }
1112 JVM_END
1113 
1114 JVM_ENTRY(jobject, MHN_staticFieldBase(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1115   // use the other function to perform sanity checks:
1116   jlong ignore = find_member_field_offset(JNIHandles::resolve(mname_jh), true, CHECK_NULL);
1117   oop clazz = java_lang_invoke_MemberName::clazz(JNIHandles::resolve_non_null(mname_jh));
1118   return JNIHandles::make_local(THREAD, clazz);
1119 }
1120 JVM_END
1121 
1122 JVM_ENTRY(jobject, MHN_getMemberVMInfo(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1123   if (mname_jh == NULL)  return NULL;
1124   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1125   intptr_t vmindex  = java_lang_invoke_MemberName::vmindex(mname());
1126   Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
1127   objArrayHandle result = oopFactory::new_objArray(SystemDictionary::Object_klass(), 2, CHECK_NULL);
1128   jvalue vmindex_value; vmindex_value.j = (long)vmindex;
1129   oop x = java_lang_boxing_object::create(T_LONG, &vmindex_value, CHECK_NULL);
1130   result->obj_at_put(0, x);
1131   x = NULL;
1132   if (vmtarget == NULL) {
1133     x = NULL;
1134   } else if (vmtarget->is_klass()) {
1135     x = ((Klass*) vmtarget)->java_mirror();
1136   } else if (vmtarget->is_method()) {
1137     x = mname();
1138   }
1139   result->obj_at_put(1, x);
1140   return JNIHandles::make_local(env, result());
1141 }
1142 JVM_END
1143 
1144 
1145 
1146 //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
1147 //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
1148 JVM_ENTRY(jint, MHN_getMembers(JNIEnv *env, jobject igcls,
1149                                jclass clazz_jh, jstring name_jh, jstring sig_jh,
1150                                int mflags, jclass caller_jh, jint skip, jobjectArray results_jh)) {
1151   if (clazz_jh == NULL || results_jh == NULL)  return -1;
1152   KlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz_jh)));
1153 
1154   objArrayHandle results(THREAD, (objArrayOop) JNIHandles::resolve(results_jh));
1155   if (results.is_null() || !results->is_objArray())  return -1;
1156 
1157   TempNewSymbol name = NULL;
1158   TempNewSymbol sig = NULL;
1159   if (name_jh != NULL) {
1160     name = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(name_jh));
1161     if (name == NULL)  return 0; // a match is not possible
1162   }
1163   if (sig_jh != NULL) {
1164     sig = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(sig_jh));
1165     if (sig == NULL)  return 0; // a match is not possible
1166   }
1167 
1168   KlassHandle caller;
1169   if (caller_jh != NULL) {
1170     oop caller_oop = JNIHandles::resolve_non_null(caller_jh);
1171     if (!java_lang_Class::is_instance(caller_oop))  return -1;
1172     caller = KlassHandle(THREAD, java_lang_Class::as_Klass(caller_oop));
1173   }
1174 
1175   if (name != NULL && sig != NULL && results.not_null()) {
1176     // try a direct resolve
1177     // %%% TO DO
1178   }
1179 
1180   int res = MethodHandles::find_MemberNames(k, name, sig, mflags,
1181                                             caller, skip, results);
1182   // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
1183   return res;
1184 }
1185 JVM_END
1186 
1187 JVM_ENTRY(void, MHN_setCallSiteTargetNormal(JNIEnv* env, jobject igcls, jobject call_site_jh, jobject target_jh)) {
1188   Handle call_site(THREAD, JNIHandles::resolve_non_null(call_site_jh));
1189   Handle target   (THREAD, JNIHandles::resolve(target_jh));
1190   {
1191     // Walk all nmethods depending on this call site.
1192     MutexLocker mu(Compile_lock, thread);
1193     Universe::flush_dependents_on(call_site, target);
1194     java_lang_invoke_CallSite::set_target(call_site(), target());
1195   }
1196 }
1197 JVM_END
1198 
1199 JVM_ENTRY(void, MHN_setCallSiteTargetVolatile(JNIEnv* env, jobject igcls, jobject call_site_jh, jobject target_jh)) {
1200   Handle call_site(THREAD, JNIHandles::resolve_non_null(call_site_jh));
1201   Handle target   (THREAD, JNIHandles::resolve(target_jh));
1202   {
1203     // Walk all nmethods depending on this call site.
1204     MutexLocker mu(Compile_lock, thread);
1205     Universe::flush_dependents_on(call_site, target);
1206     java_lang_invoke_CallSite::set_target_volatile(call_site(), target());
1207   }
1208 }
1209 JVM_END
1210 
1211 /**
1212  * Throws a java/lang/UnsupportedOperationException unconditionally.
1213  * This is required by the specification of MethodHandle.invoke if
1214  * invoked directly.
1215  */
1216 JVM_ENTRY(jobject, MH_invoke_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
1217   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invoke cannot be invoked reflectively");
1218   return NULL;
1219 }
1220 JVM_END
1221 
1222 /**
1223  * Throws a java/lang/UnsupportedOperationException unconditionally.
1224  * This is required by the specification of MethodHandle.invokeExact if
1225  * invoked directly.
1226  */
1227 JVM_ENTRY(jobject, MH_invokeExact_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
1228   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invokeExact cannot be invoked reflectively");
1229   return NULL;
1230 }
1231 JVM_END
1232 
1233 /// JVM_RegisterMethodHandleMethods
1234 
1235 #undef CS  // Solaris builds complain
1236 
1237 #define LANG "Ljava/lang/"
1238 #define JLINV "Ljava/lang/invoke/"
1239 
1240 #define OBJ   LANG"Object;"
1241 #define CLS   LANG"Class;"
1242 #define STRG  LANG"String;"
1243 #define CS    JLINV"CallSite;"
1244 #define MT    JLINV"MethodType;"
1245 #define MH    JLINV"MethodHandle;"
1246 #define MEM   JLINV"MemberName;"
1247 
1248 #define CC (char*)  /*cast a literal from (const char*)*/
1249 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1250 
1251 // These are the native methods on java.lang.invoke.MethodHandleNatives.
1252 static JNINativeMethod MHN_methods[] = {
1253   {CC"init",                      CC"("MEM""OBJ")V",                     FN_PTR(MHN_init_Mem)},
1254   {CC"expand",                    CC"("MEM")V",                          FN_PTR(MHN_expand_Mem)},
1255   {CC"resolve",                   CC"("MEM""CLS")"MEM,                   FN_PTR(MHN_resolve_Mem)},
1256   {CC"getConstant",               CC"(I)I",                              FN_PTR(MHN_getConstant)},
1257   //  static native int getNamedCon(int which, Object[] name)
1258   {CC"getNamedCon",               CC"(I["OBJ")I",                        FN_PTR(MHN_getNamedCon)},
1259   //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
1260   //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
1261   {CC"getMembers",                CC"("CLS""STRG""STRG"I"CLS"I["MEM")I", FN_PTR(MHN_getMembers)},
1262   {CC"objectFieldOffset",         CC"("MEM")J",                          FN_PTR(MHN_objectFieldOffset)},
1263   {CC"setCallSiteTargetNormal",   CC"("CS""MH")V",                       FN_PTR(MHN_setCallSiteTargetNormal)},
1264   {CC"setCallSiteTargetVolatile", CC"("CS""MH")V",                       FN_PTR(MHN_setCallSiteTargetVolatile)},
1265   {CC"staticFieldOffset",         CC"("MEM")J",                          FN_PTR(MHN_staticFieldOffset)},
1266   {CC"staticFieldBase",           CC"("MEM")"OBJ,                        FN_PTR(MHN_staticFieldBase)},
1267   {CC"getMemberVMInfo",           CC"("MEM")"OBJ,                        FN_PTR(MHN_getMemberVMInfo)}
1268 };
1269 
1270 static JNINativeMethod MH_methods[] = {
1271   // UnsupportedOperationException throwers
1272   {CC"invoke",                    CC"(["OBJ")"OBJ,                       FN_PTR(MH_invoke_UOE)},
1273   {CC"invokeExact",               CC"(["OBJ")"OBJ,                       FN_PTR(MH_invokeExact_UOE)}
1274 };
1275 
1276 /**
1277  * Helper method to register native methods.
1278  */
1279 static bool register_natives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
1280   int status = env->RegisterNatives(clazz, methods, nMethods);
1281   if (status != JNI_OK || env->ExceptionOccurred()) {
1282     warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
1283     env->ExceptionClear();
1284     return false;
1285   }
1286   return true;
1287 }
1288 
1289 /**
1290  * This one function is exported, used by NativeLookup.
1291  */
1292 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
1293   assert(!MethodHandles::enabled(), "must not be enabled");
1294   bool enable_MH = true;
1295 
1296   jclass MH_class = NULL;
1297   if (SystemDictionary::MethodHandle_klass() == NULL) {
1298     enable_MH = false;
1299   } else {
1300     oop mirror = SystemDictionary::MethodHandle_klass()->java_mirror();
1301     MH_class = (jclass) JNIHandles::make_local(env, mirror);
1302   }
1303 
1304   if (enable_MH) {
1305     ThreadToNativeFromVM ttnfv(thread);
1306 
1307     if (enable_MH) {
1308       enable_MH = register_natives(env, MHN_class, MHN_methods, sizeof(MHN_methods)/sizeof(JNINativeMethod));
1309     }
1310     if (enable_MH) {
1311       enable_MH = register_natives(env, MH_class, MH_methods, sizeof(MH_methods)/sizeof(JNINativeMethod));
1312     }
1313   }
1314 
1315   if (TraceInvokeDynamic) {
1316     tty->print_cr("MethodHandle support loaded (using LambdaForms)");
1317   }
1318 
1319   if (enable_MH) {
1320     MethodHandles::generate_adapters();
1321     MethodHandles::set_enabled(true);
1322   }
1323 }
1324 JVM_END