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