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