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