1 /*
   2  * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "classfile/stringTable.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "interpreter/interpreter.hpp"
  31 #include "interpreter/oopMapCache.hpp"
  32 #include "interpreter/linkResolver.hpp"
  33 #include "memory/allocation.inline.hpp"
  34 #include "memory/oopFactory.hpp"
  35 #include "oops/objArrayOop.inline.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "prims/methodHandles.hpp"
  38 #include "prims/jvmtiRedefineClassesTrace.hpp"
  39 #include "prims/unsafe.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       Interpreter::set_entry_for_kind(mk, entry);
 105     }
 106     // If the entry is not set, it will throw AbstractMethodError.
 107   }
 108 }
 109 
 110 void MethodHandles::set_enabled(bool z) {
 111   if (_enabled != z) {
 112     guarantee(z, "can only enable once");
 113     _enabled = z;
 114   }
 115 }
 116 
 117 // MemberName support
 118 
 119 // import java_lang_invoke_MemberName.*
 120 enum {
 121   IS_METHOD            = java_lang_invoke_MemberName::MN_IS_METHOD,
 122   IS_CONSTRUCTOR       = java_lang_invoke_MemberName::MN_IS_CONSTRUCTOR,
 123   IS_FIELD             = java_lang_invoke_MemberName::MN_IS_FIELD,
 124   IS_TYPE              = java_lang_invoke_MemberName::MN_IS_TYPE,
 125   CALLER_SENSITIVE     = java_lang_invoke_MemberName::MN_CALLER_SENSITIVE,
 126   REFERENCE_KIND_SHIFT = java_lang_invoke_MemberName::MN_REFERENCE_KIND_SHIFT,
 127   REFERENCE_KIND_MASK  = java_lang_invoke_MemberName::MN_REFERENCE_KIND_MASK,
 128   SEARCH_SUPERCLASSES  = java_lang_invoke_MemberName::MN_SEARCH_SUPERCLASSES,
 129   SEARCH_INTERFACES    = java_lang_invoke_MemberName::MN_SEARCH_INTERFACES,
 130   ALL_KINDS      = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE
 131 };
 132 
 133 Handle MethodHandles::new_MemberName(TRAPS) {
 134   Handle empty;
 135   instanceKlassHandle k(THREAD, SystemDictionary::MemberName_klass());
 136   if (!k->is_initialized())  k->initialize(CHECK_(empty));
 137   return Handle(THREAD, k->allocate_instance(THREAD));
 138 }
 139 
 140 oop MethodHandles::init_MemberName(Handle mname, Handle target) {
 141   // This method is used from java.lang.invoke.MemberName constructors.
 142   // It fills in the new MemberName from a java.lang.reflect.Member.
 143   Thread* thread = Thread::current();
 144   oop target_oop = target();
 145   Klass* target_klass = target_oop->klass();
 146   if (target_klass == SystemDictionary::reflect_Field_klass()) {
 147     oop clazz = java_lang_reflect_Field::clazz(target_oop); // fd.field_holder()
 148     int slot  = java_lang_reflect_Field::slot(target_oop);  // fd.index()
 149     KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
 150     if (!k.is_null() && k->oop_is_instance()) {
 151       fieldDescriptor fd(InstanceKlass::cast(k()), slot);
 152       oop mname2 = init_field_MemberName(mname, fd);
 153       if (mname2 != NULL) {
 154         // Since we have the reified name and type handy, add them to the result.
 155         if (java_lang_invoke_MemberName::name(mname2) == NULL)
 156           java_lang_invoke_MemberName::set_name(mname2, java_lang_reflect_Field::name(target_oop));
 157         if (java_lang_invoke_MemberName::type(mname2) == NULL)
 158           java_lang_invoke_MemberName::set_type(mname2, java_lang_reflect_Field::type(target_oop));
 159       }
 160       return mname2;
 161     }
 162   } else if (target_klass == SystemDictionary::reflect_Method_klass()) {
 163     oop clazz  = java_lang_reflect_Method::clazz(target_oop);
 164     int slot   = java_lang_reflect_Method::slot(target_oop);
 165     KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
 166     if (!k.is_null() && k->oop_is_instance()) {
 167       Method* m = InstanceKlass::cast(k())->method_with_idnum(slot);
 168       if (m == NULL || is_signature_polymorphic(m->intrinsic_id()))
 169         return NULL;            // do not resolve unless there is a concrete signature
 170       CallInfo info(m, k());
 171       return init_method_MemberName(mname, info);
 172     }
 173   } else if (target_klass == SystemDictionary::reflect_Constructor_klass()) {
 174     oop clazz  = java_lang_reflect_Constructor::clazz(target_oop);
 175     int slot   = java_lang_reflect_Constructor::slot(target_oop);
 176     KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
 177     if (!k.is_null() && k->oop_is_instance()) {
 178       Method* m = InstanceKlass::cast(k())->method_with_idnum(slot);
 179       if (m == NULL)  return NULL;
 180       CallInfo info(m, k());
 181       return init_method_MemberName(mname, info);
 182     }
 183   }
 184   return NULL;
 185 }
 186 
 187 oop MethodHandles::init_method_MemberName(Handle mname, CallInfo& info) {
 188   assert(info.resolved_appendix().is_null(), "only normal methods here");
 189   methodHandle m = info.resolved_method();
 190   assert(m.not_null(), "null method handle");
 191   KlassHandle m_klass = m->method_holder();
 192   assert(m.not_null(), "null holder for method handle");
 193   int flags = (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS );
 194   int vmindex = Method::invalid_vtable_index;
 195 
 196   switch (info.call_kind()) {
 197   case CallInfo::itable_call:
 198     vmindex = info.itable_index();
 199     // More importantly, the itable index only works with the method holder.
 200     assert(m_klass->verify_itable_index(vmindex), "");
 201     flags |= IS_METHOD | (JVM_REF_invokeInterface << REFERENCE_KIND_SHIFT);
 202     if (TraceInvokeDynamic) {
 203       ResourceMark rm;
 204       tty->print_cr("memberName: invokeinterface method_holder::method: %s, itableindex: %d, access_flags:",
 205             Method::name_and_sig_as_C_string(m->method_holder(), m->name(), m->signature()),
 206             vmindex);
 207        m->access_flags().print_on(tty);
 208        if (!m->is_abstract()) {
 209          tty->print("default");
 210        }
 211        tty->cr();
 212     }
 213     break;
 214 
 215   case CallInfo::vtable_call:
 216     vmindex = info.vtable_index();
 217     flags |= IS_METHOD | (JVM_REF_invokeVirtual << REFERENCE_KIND_SHIFT);
 218     assert(info.resolved_klass()->is_subtype_of(m_klass()), "virtual call must be type-safe");
 219     if (m_klass->is_interface()) {
 220       // This is a vtable call to an interface method (abstract "miranda method" or default method).
 221       // The vtable index is meaningless without a class (not interface) receiver type, so get one.
 222       // (LinkResolver should help us figure this out.)
 223       KlassHandle m_klass_non_interface = info.resolved_klass();
 224       if (m_klass_non_interface->is_interface()) {
 225         m_klass_non_interface = SystemDictionary::Object_klass();
 226 #ifdef ASSERT
 227         { ResourceMark rm;
 228           Method* m2 = m_klass_non_interface->vtable()->method_at(vmindex);
 229           assert(m->name() == m2->name() && m->signature() == m2->signature(),
 230                  err_msg("at %d, %s != %s", vmindex,
 231                          m->name_and_sig_as_C_string(), m2->name_and_sig_as_C_string()));
 232         }
 233 #endif //ASSERT
 234       }
 235       if (!m->is_public()) {
 236         assert(m->is_public(), "virtual call must be to public interface method");
 237         return NULL;  // elicit an error later in product build
 238       }
 239       assert(info.resolved_klass()->is_subtype_of(m_klass_non_interface()), "virtual call must be type-safe");
 240       m_klass = m_klass_non_interface;
 241     }
 242     if (TraceInvokeDynamic) {
 243       ResourceMark rm;
 244       tty->print_cr("memberName: invokevirtual method_holder::method: %s, receiver: %s, vtableindex: %d, access_flags:",
 245             Method::name_and_sig_as_C_string(m->method_holder(), m->name(), m->signature()),
 246             m_klass->internal_name(), vmindex);
 247        m->access_flags().print_on(tty);
 248        if (m->is_default_method()) {
 249          tty->print("default");
 250        }
 251        tty->cr();
 252     }
 253     break;
 254 
 255   case CallInfo::direct_call:
 256     vmindex = Method::nonvirtual_vtable_index;
 257     if (m->is_static()) {
 258       flags |= IS_METHOD      | (JVM_REF_invokeStatic  << REFERENCE_KIND_SHIFT);
 259     } else if (m->is_initializer()) {
 260       flags |= IS_CONSTRUCTOR | (JVM_REF_invokeSpecial << REFERENCE_KIND_SHIFT);
 261     } else {
 262       flags |= IS_METHOD      | (JVM_REF_invokeSpecial << REFERENCE_KIND_SHIFT);
 263     }
 264     break;
 265 
 266   default:  assert(false, "bad CallInfo");  return NULL;
 267   }
 268 
 269   // @CallerSensitive annotation detected
 270   if (m->caller_sensitive()) {
 271     flags |= CALLER_SENSITIVE;
 272   }
 273 
 274   oop mname_oop = mname();
 275   java_lang_invoke_MemberName::set_flags(   mname_oop, flags);
 276   java_lang_invoke_MemberName::set_vmtarget(mname_oop, m());
 277   java_lang_invoke_MemberName::set_vmindex( mname_oop, vmindex);   // vtable/itable index
 278   java_lang_invoke_MemberName::set_clazz(   mname_oop, m_klass->java_mirror());
 279   // Note:  name and type can be lazily computed by resolve_MemberName,
 280   // if Java code needs them as resolved String and MethodType objects.
 281   // The clazz must be eagerly stored, because it provides a GC
 282   // root to help keep alive the Method*.
 283   // If relevant, the vtable or itable value is stored as vmindex.
 284   // This is done eagerly, since it is readily available without
 285   // constructing any new objects.
 286   // TO DO: maybe intern mname_oop
 287   if (m->method_holder()->add_member_name(mname)) {
 288     return mname();
 289   } else {
 290     // Redefinition caused this to fail.  Return NULL (and an exception?)
 291     return NULL;
 292   }
 293 }
 294 
 295 oop MethodHandles::init_field_MemberName(Handle mname, fieldDescriptor& fd, bool is_setter) {
 296   int flags = (jushort)( fd.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS );
 297   flags |= IS_FIELD | ((fd.is_static() ? JVM_REF_getStatic : JVM_REF_getField) << REFERENCE_KIND_SHIFT);
 298   if (is_setter)  flags += ((JVM_REF_putField - JVM_REF_getField) << REFERENCE_KIND_SHIFT);
 299   Metadata* vmtarget = fd.field_holder();
 300   int vmindex        = fd.offset();  // determines the field uniquely when combined with static bit
 301   oop mname_oop = mname();
 302   java_lang_invoke_MemberName::set_flags(mname_oop,    flags);
 303   java_lang_invoke_MemberName::set_vmtarget(mname_oop, vmtarget);
 304   java_lang_invoke_MemberName::set_vmindex(mname_oop,  vmindex);
 305   java_lang_invoke_MemberName::set_clazz(mname_oop,    fd.field_holder()->java_mirror());
 306   oop type = field_signature_type_or_null(fd.signature());
 307   oop name = field_name_or_null(fd.name());
 308   if (name != NULL)
 309     java_lang_invoke_MemberName::set_name(mname_oop,   name);
 310   if (type != NULL)
 311     java_lang_invoke_MemberName::set_type(mname_oop,   type);
 312   // Note:  name and type can be lazily computed by resolve_MemberName,
 313   // if Java code needs them as resolved String and Class objects.
 314   // Note that the incoming type oop might be pre-resolved (non-null).
 315   // The base clazz and field offset (vmindex) must be eagerly stored,
 316   // because they unambiguously identify the field.
 317   // Although the fieldDescriptor::_index would also identify the field,
 318   // we do not use it, because it is harder to decode.
 319   // TO DO: maybe intern mname_oop
 320   return mname();
 321 }
 322 
 323 // JVM 2.9 Special Methods:
 324 // A method is signature polymorphic if and only if all of the following conditions hold :
 325 // * It is declared in the java.lang.invoke.MethodHandle class.
 326 // * It has a single formal parameter of type Object[].
 327 // * It has a return type of Object.
 328 // * It has the ACC_VARARGS and ACC_NATIVE flags set.
 329 bool MethodHandles::is_method_handle_invoke_name(Klass* klass, Symbol* name) {
 330   if (klass == NULL)
 331     return false;
 332   // The following test will fail spuriously during bootstrap of MethodHandle itself:
 333   //    if (klass != SystemDictionary::MethodHandle_klass())
 334   // Test the name instead:
 335   if (klass->name() != vmSymbols::java_lang_invoke_MethodHandle())
 336     return false;
 337   Symbol* poly_sig = vmSymbols::object_array_object_signature();
 338   Method* m = InstanceKlass::cast(klass)->find_method(name, poly_sig);
 339   if (m == NULL)  return false;
 340   int required = JVM_ACC_NATIVE | JVM_ACC_VARARGS;
 341   int flags = m->access_flags().as_int();
 342   return (flags & required) == required;
 343 }
 344 
 345 
 346 Symbol* MethodHandles::signature_polymorphic_intrinsic_name(vmIntrinsics::ID iid) {
 347   assert(is_signature_polymorphic_intrinsic(iid), err_msg("iid=%d", iid));
 348   switch (iid) {
 349   case vmIntrinsics::_invokeBasic:      return vmSymbols::invokeBasic_name();
 350   case vmIntrinsics::_linkToVirtual:    return vmSymbols::linkToVirtual_name();
 351   case vmIntrinsics::_linkToStatic:     return vmSymbols::linkToStatic_name();
 352   case vmIntrinsics::_linkToSpecial:    return vmSymbols::linkToSpecial_name();
 353   case vmIntrinsics::_linkToInterface:  return vmSymbols::linkToInterface_name();
 354   }
 355   assert(false, "");
 356   return 0;
 357 }
 358 
 359 int MethodHandles::signature_polymorphic_intrinsic_ref_kind(vmIntrinsics::ID iid) {
 360   switch (iid) {
 361   case vmIntrinsics::_invokeBasic:      return 0;
 362   case vmIntrinsics::_linkToVirtual:    return JVM_REF_invokeVirtual;
 363   case vmIntrinsics::_linkToStatic:     return JVM_REF_invokeStatic;
 364   case vmIntrinsics::_linkToSpecial:    return JVM_REF_invokeSpecial;
 365   case vmIntrinsics::_linkToInterface:  return JVM_REF_invokeInterface;
 366   }
 367   assert(false, err_msg("iid=%d", iid));
 368   return 0;
 369 }
 370 
 371 vmIntrinsics::ID MethodHandles::signature_polymorphic_name_id(Symbol* name) {
 372   vmSymbols::SID name_id = vmSymbols::find_sid(name);
 373   switch (name_id) {
 374   // The ID _invokeGeneric stands for all non-static signature-polymorphic methods, except built-ins.
 375   case vmSymbols::VM_SYMBOL_ENUM_NAME(invoke_name):           return vmIntrinsics::_invokeGeneric;
 376   // The only built-in non-static signature-polymorphic method is MethodHandle.invokeBasic:
 377   case vmSymbols::VM_SYMBOL_ENUM_NAME(invokeBasic_name):      return vmIntrinsics::_invokeBasic;
 378 
 379   // There is one static signature-polymorphic method for each JVM invocation mode.
 380   case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToVirtual_name):    return vmIntrinsics::_linkToVirtual;
 381   case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToStatic_name):     return vmIntrinsics::_linkToStatic;
 382   case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToSpecial_name):    return vmIntrinsics::_linkToSpecial;
 383   case vmSymbols::VM_SYMBOL_ENUM_NAME(linkToInterface_name):  return vmIntrinsics::_linkToInterface;
 384   }
 385 
 386   // Cover the case of invokeExact and any future variants of invokeFoo.
 387   Klass* mh_klass = SystemDictionary::well_known_klass(
 388                               SystemDictionary::WK_KLASS_ENUM_NAME(MethodHandle_klass) );
 389   if (mh_klass != NULL && is_method_handle_invoke_name(mh_klass, name))
 390     return vmIntrinsics::_invokeGeneric;
 391 
 392   // Note: The pseudo-intrinsic _compiledLambdaForm is never linked against.
 393   // Instead it is used to mark lambda forms bound to invokehandle or invokedynamic.
 394   return vmIntrinsics::_none;
 395 }
 396 
 397 vmIntrinsics::ID MethodHandles::signature_polymorphic_name_id(Klass* klass, Symbol* name) {
 398   if (klass != NULL &&
 399       klass->name() == vmSymbols::java_lang_invoke_MethodHandle()) {
 400     vmIntrinsics::ID iid = signature_polymorphic_name_id(name);
 401     if (iid != vmIntrinsics::_none)
 402       return iid;
 403     if (is_method_handle_invoke_name(klass, name))
 404       return vmIntrinsics::_invokeGeneric;
 405   }
 406   return vmIntrinsics::_none;
 407 }
 408 
 409 
 410 // convert the external string or reflective type to an internal signature
 411 Symbol* MethodHandles::lookup_signature(oop type_str, bool intern_if_not_found, TRAPS) {
 412   if (java_lang_invoke_MethodType::is_instance(type_str)) {
 413     return java_lang_invoke_MethodType::as_signature(type_str, intern_if_not_found, THREAD);
 414   } else if (java_lang_Class::is_instance(type_str)) {
 415     return java_lang_Class::as_signature(type_str, false, THREAD);
 416   } else if (java_lang_String::is_instance_inlined(type_str)) {
 417     if (intern_if_not_found) {
 418       return java_lang_String::as_symbol(type_str, THREAD);
 419     } else {
 420       return java_lang_String::as_symbol_or_null(type_str);
 421     }
 422   } else {
 423     THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized type", NULL);
 424   }
 425 }
 426 
 427 static const char OBJ_SIG[] = "Ljava/lang/Object;";
 428 enum { OBJ_SIG_LEN = 18 };
 429 
 430 bool MethodHandles::is_basic_type_signature(Symbol* sig) {
 431   assert(vmSymbols::object_signature()->utf8_length() == (int)OBJ_SIG_LEN, "");
 432   assert(vmSymbols::object_signature()->equals(OBJ_SIG), "");
 433   const int len = sig->utf8_length();
 434   for (int i = 0; i < len; i++) {
 435     switch (sig->byte_at(i)) {
 436     case 'L':
 437       // only java/lang/Object is valid here
 438       if (sig->index_of_at(i, OBJ_SIG, OBJ_SIG_LEN) != i)
 439         return false;
 440       i += OBJ_SIG_LEN-1;  //-1 because of i++ in loop
 441       continue;
 442     case '(': case ')': case 'V':
 443     case 'I': case 'J': case 'F': case 'D':
 444       continue;
 445     //case '[':
 446     //case 'Z': case 'B': case 'C': case 'S':
 447     default:
 448       return false;
 449     }
 450   }
 451   return true;
 452 }
 453 
 454 Symbol* MethodHandles::lookup_basic_type_signature(Symbol* sig, bool keep_last_arg, TRAPS) {
 455   Symbol* bsig = NULL;
 456   if (sig == NULL) {
 457     return sig;
 458   } else if (is_basic_type_signature(sig)) {
 459     sig->increment_refcount();
 460     return sig;  // that was easy
 461   } else if (sig->byte_at(0) != '(') {
 462     BasicType bt = char2type(sig->byte_at(0));
 463     if (is_subword_type(bt)) {
 464       bsig = vmSymbols::int_signature();
 465     } else {
 466       assert(bt == T_OBJECT || bt == T_ARRAY, "is_basic_type_signature was false");
 467       bsig = vmSymbols::object_signature();
 468     }
 469   } else {
 470     ResourceMark rm;
 471     stringStream buffer(128);
 472     buffer.put('(');
 473     int arg_pos = 0, keep_arg_pos = -1;
 474     if (keep_last_arg)
 475       keep_arg_pos = ArgumentCount(sig).size() - 1;
 476     for (SignatureStream ss(sig); !ss.is_done(); ss.next()) {
 477       BasicType bt = ss.type();
 478       size_t this_arg_pos = buffer.size();
 479       if (ss.at_return_type()) {
 480         buffer.put(')');
 481       }
 482       if (arg_pos == keep_arg_pos) {
 483         buffer.write((char*) ss.raw_bytes(),
 484                      (int)   ss.raw_length());
 485       } else if (bt == T_OBJECT || bt == T_ARRAY) {
 486         buffer.write(OBJ_SIG, OBJ_SIG_LEN);
 487       } else {
 488         if (is_subword_type(bt))
 489           bt = T_INT;
 490         buffer.put(type2char(bt));
 491       }
 492       arg_pos++;
 493     }
 494     const char* sigstr =       buffer.base();
 495     int         siglen = (int) buffer.size();
 496     bsig = SymbolTable::new_symbol(sigstr, siglen, THREAD);
 497   }
 498   assert(is_basic_type_signature(bsig) ||
 499          // detune assert in case the injected argument is not a basic type:
 500          keep_last_arg, "");
 501   return bsig;
 502 }
 503 
 504 void MethodHandles::print_as_basic_type_signature_on(outputStream* st,
 505                                                      Symbol* sig,
 506                                                      bool keep_arrays,
 507                                                      bool keep_basic_names) {
 508   st = st ? st : tty;
 509   int len  = sig->utf8_length();
 510   int array = 0;
 511   bool prev_type = false;
 512   for (int i = 0; i < len; i++) {
 513     char ch = sig->byte_at(i);
 514     switch (ch) {
 515     case '(': case ')':
 516       prev_type = false;
 517       st->put(ch);
 518       continue;
 519     case '[':
 520       if (!keep_basic_names && keep_arrays)
 521         st->put(ch);
 522       array++;
 523       continue;
 524     case 'L':
 525       {
 526         if (prev_type)  st->put(',');
 527         int start = i+1, slash = start;
 528         while (++i < len && (ch = sig->byte_at(i)) != ';') {
 529           if (ch == '/' || ch == '.' || ch == '$')  slash = i+1;
 530         }
 531         if (slash < i)  start = slash;
 532         if (!keep_basic_names) {
 533           st->put('L');
 534         } else {
 535           for (int j = start; j < i; j++)
 536             st->put(sig->byte_at(j));
 537           prev_type = true;
 538         }
 539         break;
 540       }
 541     default:
 542       {
 543         if (array && char2type(ch) != T_ILLEGAL && !keep_arrays) {
 544           ch = '[';
 545           array = 0;
 546         }
 547         if (prev_type)  st->put(',');
 548         const char* n = NULL;
 549         if (keep_basic_names)
 550           n = type2name(char2type(ch));
 551         if (n == NULL) {
 552           // unknown letter, or we don't want to know its name
 553           st->put(ch);
 554         } else {
 555           st->print("%s", n);
 556           prev_type = true;
 557         }
 558         break;
 559       }
 560     }
 561     // Switch break goes here to take care of array suffix:
 562     if (prev_type) {
 563       while (array > 0) {
 564         st->print("[]");
 565         --array;
 566       }
 567     }
 568     array = 0;
 569   }
 570 }
 571 
 572 
 573 
 574 static oop object_java_mirror() {
 575   return SystemDictionary::Object_klass()->java_mirror();
 576 }
 577 
 578 oop MethodHandles::field_name_or_null(Symbol* s) {
 579   if (s == NULL)  return NULL;
 580   return StringTable::lookup(s);
 581 }
 582 
 583 oop MethodHandles::field_signature_type_or_null(Symbol* s) {
 584   if (s == NULL)  return NULL;
 585   BasicType bt = FieldType::basic_type(s);
 586   if (is_java_primitive(bt)) {
 587     assert(s->utf8_length() == 1, "");
 588     return java_lang_Class::primitive_mirror(bt);
 589   }
 590   // Here are some more short cuts for common types.
 591   // They are optional, since reference types can be resolved lazily.
 592   if (bt == T_OBJECT) {
 593     if (s == vmSymbols::object_signature()) {
 594       return object_java_mirror();
 595     } else if (s == vmSymbols::class_signature()) {
 596       return SystemDictionary::Class_klass()->java_mirror();
 597     } else if (s == vmSymbols::string_signature()) {
 598       return SystemDictionary::String_klass()->java_mirror();
 599     }
 600   }
 601   return NULL;
 602 }
 603 
 604 
 605 // An unresolved member name is a mere symbolic reference.
 606 // Resolving it plants a vmtarget/vmindex in it,
 607 // which refers directly to JVM internals.
 608 Handle MethodHandles::resolve_MemberName(Handle mname, KlassHandle caller, TRAPS) {
 609   Handle empty;
 610   assert(java_lang_invoke_MemberName::is_instance(mname()), "");
 611 
 612   if (java_lang_invoke_MemberName::vmtarget(mname()) != NULL) {
 613     // Already resolved.
 614     DEBUG_ONLY(int vmindex = java_lang_invoke_MemberName::vmindex(mname()));
 615     assert(vmindex >= Method::nonvirtual_vtable_index, "");
 616     return mname;
 617   }
 618 
 619   Handle defc_oop(THREAD, java_lang_invoke_MemberName::clazz(mname()));
 620   Handle name_str(THREAD, java_lang_invoke_MemberName::name( mname()));
 621   Handle type_str(THREAD, java_lang_invoke_MemberName::type( mname()));
 622   int    flags    =       java_lang_invoke_MemberName::flags(mname());
 623   int    ref_kind =       (flags >> REFERENCE_KIND_SHIFT) & REFERENCE_KIND_MASK;
 624   if (!ref_kind_is_valid(ref_kind)) {
 625     THROW_MSG_(vmSymbols::java_lang_InternalError(), "obsolete MemberName format", empty);
 626   }
 627 
 628   DEBUG_ONLY(int old_vmindex);
 629   assert((old_vmindex = java_lang_invoke_MemberName::vmindex(mname())) == 0, "clean input");
 630 
 631   if (defc_oop.is_null() || name_str.is_null() || type_str.is_null()) {
 632     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "nothing to resolve", empty);
 633   }
 634 
 635   instanceKlassHandle defc;
 636   {
 637     Klass* defc_klass = java_lang_Class::as_Klass(defc_oop());
 638     if (defc_klass == NULL)  return empty;  // a primitive; no resolution possible
 639     if (!defc_klass->oop_is_instance()) {
 640       if (!defc_klass->oop_is_array())  return empty;
 641       defc_klass = SystemDictionary::Object_klass();
 642     }
 643     defc = instanceKlassHandle(THREAD, defc_klass);
 644   }
 645   if (defc.is_null()) {
 646     THROW_MSG_(vmSymbols::java_lang_InternalError(), "primitive class", empty);
 647   }
 648   defc->link_class(CHECK_(empty));  // possible safepoint
 649 
 650   // convert the external string name to an internal symbol
 651   TempNewSymbol name = java_lang_String::as_symbol_or_null(name_str());
 652   if (name == NULL)  return empty;  // no such name
 653   if (name == vmSymbols::class_initializer_name())
 654     return empty; // illegal name
 655 
 656   vmIntrinsics::ID mh_invoke_id = vmIntrinsics::_none;
 657   if ((flags & ALL_KINDS) == IS_METHOD &&
 658       (defc() == SystemDictionary::MethodHandle_klass()) &&
 659       (ref_kind == JVM_REF_invokeVirtual ||
 660        ref_kind == JVM_REF_invokeSpecial ||
 661        // static invocation mode is required for _linkToVirtual, etc.:
 662        ref_kind == JVM_REF_invokeStatic)) {
 663     vmIntrinsics::ID iid = signature_polymorphic_name_id(name);
 664     if (iid != vmIntrinsics::_none &&
 665         ((ref_kind == JVM_REF_invokeStatic) == is_signature_polymorphic_static(iid))) {
 666       // Virtual methods invoke and invokeExact, plus internal invokers like _invokeBasic.
 667       // For a static reference it could an internal linkage routine like _linkToVirtual, etc.
 668       mh_invoke_id = iid;
 669     }
 670   }
 671 
 672   // convert the external string or reflective type to an internal signature
 673   TempNewSymbol type = lookup_signature(type_str(), (mh_invoke_id != vmIntrinsics::_none), CHECK_(empty));
 674   if (type == NULL)  return empty;  // no such signature exists in the VM
 675 
 676   // Time to do the lookup.
 677   switch (flags & ALL_KINDS) {
 678   case IS_METHOD:
 679     {
 680       CallInfo result;
 681       LinkInfo link_info(defc, name, type, caller, caller.not_null());
 682       {
 683         assert(!HAS_PENDING_EXCEPTION, "");
 684         if (ref_kind == JVM_REF_invokeStatic) {
 685           LinkResolver::resolve_static_call(result,
 686                         link_info, false, THREAD);
 687         } else if (ref_kind == JVM_REF_invokeInterface) {
 688           LinkResolver::resolve_interface_call(result, Handle(), defc,
 689                         link_info, false, THREAD);
 690         } else if (mh_invoke_id != vmIntrinsics::_none) {
 691           assert(!is_signature_polymorphic_static(mh_invoke_id), "");
 692           LinkResolver::resolve_handle_call(result, link_info, THREAD);
 693         } else if (ref_kind == JVM_REF_invokeSpecial) {
 694           LinkResolver::resolve_special_call(result,
 695                         link_info, THREAD);
 696         } else if (ref_kind == JVM_REF_invokeVirtual) {
 697           LinkResolver::resolve_virtual_call(result, Handle(), defc,
 698                         link_info, false, THREAD);
 699         } else {
 700           assert(false, err_msg("ref_kind=%d", ref_kind));
 701         }
 702         if (HAS_PENDING_EXCEPTION) {
 703           return empty;
 704         }
 705       }
 706       if (result.resolved_appendix().not_null()) {
 707         // The resolved MemberName must not be accompanied by an appendix argument,
 708         // since there is no way to bind this value into the MemberName.
 709         // Caller is responsible to prevent this from happening.
 710         THROW_MSG_(vmSymbols::java_lang_InternalError(), "appendix", empty);
 711       }
 712       oop mname2 = init_method_MemberName(mname, result);
 713       return Handle(THREAD, mname2);
 714     }
 715   case IS_CONSTRUCTOR:
 716     {
 717       CallInfo result;
 718       LinkInfo link_info(defc, name, type, caller, caller.not_null());
 719       {
 720         assert(!HAS_PENDING_EXCEPTION, "");
 721         if (name == vmSymbols::object_initializer_name()) {
 722           LinkResolver::resolve_special_call(result, link_info, THREAD);
 723         } else {
 724           break;                // will throw after end of switch
 725         }
 726         if (HAS_PENDING_EXCEPTION) {
 727           return empty;
 728         }
 729       }
 730       assert(result.is_statically_bound(), "");
 731       oop mname2 = init_method_MemberName(mname, result);
 732       return Handle(THREAD, mname2);
 733     }
 734   case IS_FIELD:
 735     {
 736       fieldDescriptor result; // find_field initializes fd if found
 737       {
 738         assert(!HAS_PENDING_EXCEPTION, "");
 739         LinkInfo link_info(defc, name, type, caller, /*check_access*/false);
 740         LinkResolver::resolve_field(result, link_info, Bytecodes::_nop, false, THREAD);
 741         if (HAS_PENDING_EXCEPTION) {
 742           return empty;
 743         }
 744       }
 745       oop mname2 = init_field_MemberName(mname, result, ref_kind_is_setter(ref_kind));
 746       return Handle(THREAD, mname2);
 747     }
 748   default:
 749     THROW_MSG_(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format", empty);
 750   }
 751 
 752   return empty;
 753 }
 754 
 755 // Conversely, a member name which is only initialized from JVM internals
 756 // may have null defc, name, and type fields.
 757 // Resolving it plants a vmtarget/vmindex in it,
 758 // which refers directly to JVM internals.
 759 void MethodHandles::expand_MemberName(Handle mname, int suppress, TRAPS) {
 760   assert(java_lang_invoke_MemberName::is_instance(mname()), "");
 761   Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
 762   int vmindex  = java_lang_invoke_MemberName::vmindex(mname());
 763   if (vmtarget == NULL) {
 764     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nothing to expand");
 765   }
 766 
 767   bool have_defc = (java_lang_invoke_MemberName::clazz(mname()) != NULL);
 768   bool have_name = (java_lang_invoke_MemberName::name(mname()) != NULL);
 769   bool have_type = (java_lang_invoke_MemberName::type(mname()) != NULL);
 770   int flags      = java_lang_invoke_MemberName::flags(mname());
 771 
 772   if (suppress != 0) {
 773     if (suppress & _suppress_defc)  have_defc = true;
 774     if (suppress & _suppress_name)  have_name = true;
 775     if (suppress & _suppress_type)  have_type = true;
 776   }
 777 
 778   if (have_defc && have_name && have_type)  return;  // nothing needed
 779 
 780   switch (flags & ALL_KINDS) {
 781   case IS_METHOD:
 782   case IS_CONSTRUCTOR:
 783     {
 784       assert(vmtarget->is_method(), "method or constructor vmtarget is Method*");
 785       methodHandle m(THREAD, (Method*)vmtarget);
 786       DEBUG_ONLY(vmtarget = NULL);  // safety
 787       if (m.is_null())  break;
 788       if (!have_defc) {
 789         InstanceKlass* defc = m->method_holder();
 790         java_lang_invoke_MemberName::set_clazz(mname(), defc->java_mirror());
 791       }
 792       if (!have_name) {
 793         //not java_lang_String::create_from_symbol; let's intern member names
 794         Handle name = StringTable::intern(m->name(), CHECK);
 795         java_lang_invoke_MemberName::set_name(mname(), name());
 796       }
 797       if (!have_type) {
 798         Handle type = java_lang_String::create_from_symbol(m->signature(), CHECK);
 799         java_lang_invoke_MemberName::set_type(mname(), type());
 800       }
 801       return;
 802     }
 803   case IS_FIELD:
 804     {
 805       assert(vmtarget->is_klass(), "field vmtarget is Klass*");
 806       if (!((Klass*) vmtarget)->oop_is_instance())  break;
 807       instanceKlassHandle defc(THREAD, (Klass*) vmtarget);
 808       DEBUG_ONLY(vmtarget = NULL);  // safety
 809       bool is_static = ((flags & JVM_ACC_STATIC) != 0);
 810       fieldDescriptor fd; // find_field initializes fd if found
 811       if (!defc->find_field_from_offset(vmindex, is_static, &fd))
 812         break;                  // cannot expand
 813       if (!have_defc) {
 814         java_lang_invoke_MemberName::set_clazz(mname(), defc->java_mirror());
 815       }
 816       if (!have_name) {
 817         //not java_lang_String::create_from_symbol; let's intern member names
 818         Handle name = StringTable::intern(fd.name(), CHECK);
 819         java_lang_invoke_MemberName::set_name(mname(), name());
 820       }
 821       if (!have_type) {
 822         // If it is a primitive field type, don't mess with short strings like "I".
 823         Handle type = field_signature_type_or_null(fd.signature());
 824         if (type.is_null()) {
 825           java_lang_String::create_from_symbol(fd.signature(), CHECK);
 826         }
 827         java_lang_invoke_MemberName::set_type(mname(), type());
 828       }
 829       return;
 830     }
 831   }
 832   THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
 833 }
 834 
 835 int MethodHandles::find_MemberNames(KlassHandle k,
 836                                     Symbol* name, Symbol* sig,
 837                                     int mflags, KlassHandle caller,
 838                                     int skip, objArrayHandle results) {
 839   // %%% take caller into account!
 840 
 841   Thread* thread = Thread::current();
 842 
 843   if (k.is_null() || !k->oop_is_instance())  return -1;
 844 
 845   int rfill = 0, rlimit = results->length(), rskip = skip;
 846   // overflow measurement:
 847   int overflow = 0, overflow_limit = MAX2(1000, rlimit);
 848 
 849   int match_flags = mflags;
 850   bool search_superc = ((match_flags & SEARCH_SUPERCLASSES) != 0);
 851   bool search_intfc  = ((match_flags & SEARCH_INTERFACES)   != 0);
 852   bool local_only = !(search_superc | search_intfc);
 853   bool classes_only = false;
 854 
 855   if (name != NULL) {
 856     if (name->utf8_length() == 0)  return 0; // a match is not possible
 857   }
 858   if (sig != NULL) {
 859     if (sig->utf8_length() == 0)  return 0; // a match is not possible
 860     if (sig->byte_at(0) == '(')
 861       match_flags &= ~(IS_FIELD | IS_TYPE);
 862     else
 863       match_flags &= ~(IS_CONSTRUCTOR | IS_METHOD);
 864   }
 865 
 866   if ((match_flags & IS_TYPE) != 0) {
 867     // NYI, and Core Reflection works quite well for this query
 868   }
 869 
 870   if ((match_flags & IS_FIELD) != 0) {
 871     for (FieldStream st(k(), local_only, !search_intfc); !st.eos(); st.next()) {
 872       if (name != NULL && st.name() != name)
 873           continue;
 874       if (sig != NULL && st.signature() != sig)
 875         continue;
 876       // passed the filters
 877       if (rskip > 0) {
 878         --rskip;
 879       } else if (rfill < rlimit) {
 880         Handle result(thread, results->obj_at(rfill++));
 881         if (!java_lang_invoke_MemberName::is_instance(result()))
 882           return -99;  // caller bug!
 883         oop saved = MethodHandles::init_field_MemberName(result, st.field_descriptor());
 884         if (saved != result())
 885           results->obj_at_put(rfill-1, saved);  // show saved instance to user
 886       } else if (++overflow >= overflow_limit) {
 887         match_flags = 0; break; // got tired of looking at overflow
 888       }
 889     }
 890   }
 891 
 892   if ((match_flags & (IS_METHOD | IS_CONSTRUCTOR)) != 0) {
 893     // watch out for these guys:
 894     Symbol* init_name   = vmSymbols::object_initializer_name();
 895     Symbol* clinit_name = vmSymbols::class_initializer_name();
 896     if (name == clinit_name)  clinit_name = NULL; // hack for exposing <clinit>
 897     bool negate_name_test = false;
 898     // fix name so that it captures the intention of IS_CONSTRUCTOR
 899     if (!(match_flags & IS_METHOD)) {
 900       // constructors only
 901       if (name == NULL) {
 902         name = init_name;
 903       } else if (name != init_name) {
 904         return 0;               // no constructors of this method name
 905       }
 906     } else if (!(match_flags & IS_CONSTRUCTOR)) {
 907       // methods only
 908       if (name == NULL) {
 909         name = init_name;
 910         negate_name_test = true; // if we see the name, we *omit* the entry
 911       } else if (name == init_name) {
 912         return 0;               // no methods of this constructor name
 913       }
 914     } else {
 915       // caller will accept either sort; no need to adjust name
 916     }
 917     for (MethodStream st(k(), local_only, !search_intfc); !st.eos(); st.next()) {
 918       Method* m = st.method();
 919       Symbol* m_name = m->name();
 920       if (m_name == clinit_name)
 921         continue;
 922       if (name != NULL && ((m_name != name) ^ negate_name_test))
 923           continue;
 924       if (sig != NULL && m->signature() != sig)
 925         continue;
 926       // passed the filters
 927       if (rskip > 0) {
 928         --rskip;
 929       } else if (rfill < rlimit) {
 930         Handle result(thread, results->obj_at(rfill++));
 931         if (!java_lang_invoke_MemberName::is_instance(result()))
 932           return -99;  // caller bug!
 933         CallInfo info(m);
 934         oop saved = MethodHandles::init_method_MemberName(result, info);
 935         if (saved != result())
 936           results->obj_at_put(rfill-1, saved);  // show saved instance to user
 937       } else if (++overflow >= overflow_limit) {
 938         match_flags = 0; break; // got tired of looking at overflow
 939       }
 940     }
 941   }
 942 
 943   // return number of elements we at leasted wanted to initialize
 944   return rfill + overflow;
 945 }
 946 
 947 void MethodHandles::add_dependent_nmethod(oop call_site, nmethod* nm) {
 948   assert_locked_or_safepoint(CodeCache_lock);
 949 
 950   oop context = java_lang_invoke_CallSite::context(call_site);
 951   nmethodBucket* deps = java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(context);
 952 
 953   nmethodBucket* new_deps = nmethodBucket::add_dependent_nmethod(deps, nm);
 954   if (deps != new_deps) {
 955     java_lang_invoke_MethodHandleNatives_CallSiteContext::set_vmdependencies(context, new_deps);
 956   }
 957 }
 958 
 959 void MethodHandles::remove_dependent_nmethod(oop call_site, nmethod* nm) {
 960   assert_locked_or_safepoint(CodeCache_lock);
 961 
 962   oop context = java_lang_invoke_CallSite::context(call_site);
 963   nmethodBucket* deps = java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(context);
 964 
 965   if (nmethodBucket::remove_dependent_nmethod(deps, nm)) {
 966     nmethodBucket* new_deps = nmethodBucket::clean_dependent_nmethods(deps);
 967     if (deps != new_deps) {
 968       java_lang_invoke_MethodHandleNatives_CallSiteContext::set_vmdependencies(context, new_deps);
 969     }
 970   }
 971 }
 972 
 973 void MethodHandles::flush_dependent_nmethods(Handle call_site, Handle target) {
 974   assert_lock_strong(Compile_lock);
 975 
 976   int marked = 0;
 977   CallSiteDepChange changes(call_site(), target());
 978   {
 979     MutexLockerEx mu2(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 980 
 981     oop context = java_lang_invoke_CallSite::context(call_site());
 982     nmethodBucket* deps = java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(context);
 983 
 984     marked = nmethodBucket::mark_dependent_nmethods(deps, changes);
 985     if (marked > 0) {
 986       nmethodBucket* new_deps = nmethodBucket::clean_dependent_nmethods(deps);
 987       if (deps != new_deps) {
 988         java_lang_invoke_MethodHandleNatives_CallSiteContext::set_vmdependencies(context, new_deps);
 989       }
 990     }
 991   }
 992   if (marked > 0) {
 993     // At least one nmethod has been marked for deoptimization
 994     VM_Deoptimize op;
 995     VMThread::execute(&op);
 996   }
 997 }
 998 
 999 //------------------------------------------------------------------------------
1000 // MemberNameTable
1001 //
1002 
1003 MemberNameTable::MemberNameTable(int methods_cnt)
1004                   : GrowableArray<jweak>(methods_cnt, true) {
1005   assert_locked_or_safepoint(MemberNameTable_lock);
1006 }
1007 
1008 MemberNameTable::~MemberNameTable() {
1009   assert_locked_or_safepoint(MemberNameTable_lock);
1010   int len = this->length();
1011 
1012   for (int idx = 0; idx < len; idx++) {
1013     jweak ref = this->at(idx);
1014     JNIHandles::destroy_weak_global(ref);
1015   }
1016 }
1017 
1018 void MemberNameTable::add_member_name(jweak mem_name_wref) {
1019   assert_locked_or_safepoint(MemberNameTable_lock);
1020   this->push(mem_name_wref);
1021 }
1022 
1023 #if INCLUDE_JVMTI
1024 // It is called at safepoint only for RedefineClasses
1025 void MemberNameTable::adjust_method_entries(InstanceKlass* holder, bool * trace_name_printed) {
1026   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
1027   // For each redefined method
1028   for (int idx = 0; idx < length(); idx++) {
1029     oop mem_name = JNIHandles::resolve(this->at(idx));
1030     if (mem_name == NULL) {
1031       continue;
1032     }
1033     Method* old_method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name);
1034 
1035     if (old_method == NULL || !old_method->is_old()) {
1036       continue; // skip uninteresting entries
1037     }
1038     if (old_method->is_deleted()) {
1039       // skip entries with deleted methods
1040       continue;
1041     }
1042     Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
1043 
1044     assert(new_method != NULL, "method_with_idnum() should not be NULL");
1045     assert(old_method != new_method, "sanity check");
1046 
1047     java_lang_invoke_MemberName::set_vmtarget(mem_name, new_method);
1048 
1049     if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
1050       if (!(*trace_name_printed)) {
1051         // RC_TRACE_MESG macro has an embedded ResourceMark
1052         RC_TRACE_MESG(("adjust: name=%s",
1053                        old_method->method_holder()->external_name()));
1054         *trace_name_printed = true;
1055       }
1056       // RC_TRACE macro has an embedded ResourceMark
1057       RC_TRACE(0x00400000, ("MemberName method update: %s(%s)",
1058                             new_method->name()->as_C_string(),
1059                             new_method->signature()->as_C_string()));
1060     }
1061   }
1062 }
1063 #endif // INCLUDE_JVMTI
1064 
1065 //
1066 // Here are the native methods in java.lang.invoke.MethodHandleNatives
1067 // They are the private interface between this JVM and the HotSpot-specific
1068 // Java code that implements JSR 292 method handles.
1069 //
1070 // Note:  We use a JVM_ENTRY macro to define each of these, for this is the way
1071 // that intrinsic (non-JNI) native methods are defined in HotSpot.
1072 //
1073 
1074 #ifndef PRODUCT
1075 #define EACH_NAMED_CON(template, requirement) \
1076     template(java_lang_invoke_MemberName,MN_IS_METHOD) \
1077     template(java_lang_invoke_MemberName,MN_IS_CONSTRUCTOR) \
1078     template(java_lang_invoke_MemberName,MN_IS_FIELD) \
1079     template(java_lang_invoke_MemberName,MN_IS_TYPE) \
1080     template(java_lang_invoke_MemberName,MN_CALLER_SENSITIVE) \
1081     template(java_lang_invoke_MemberName,MN_SEARCH_SUPERCLASSES) \
1082     template(java_lang_invoke_MemberName,MN_SEARCH_INTERFACES) \
1083     template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_SHIFT) \
1084     template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_MASK) \
1085     /*end*/
1086 
1087 #define IGNORE_REQ(req_expr) /* req_expr */
1088 #define ONE_PLUS(scope,value) 1+
1089 static const int con_value_count = EACH_NAMED_CON(ONE_PLUS, IGNORE_REQ) 0;
1090 #define VALUE_COMMA(scope,value) scope::value,
1091 static const int con_values[con_value_count+1] = { EACH_NAMED_CON(VALUE_COMMA, IGNORE_REQ) 0 };
1092 #define STRING_NULL(scope,value) #value "\0"
1093 static const char con_names[] = { EACH_NAMED_CON(STRING_NULL, IGNORE_REQ) };
1094 
1095 static bool advertise_con_value(int which) {
1096   if (which < 0)  return false;
1097   bool ok = true;
1098   int count = 0;
1099 #define INC_COUNT(scope,value) \
1100   ++count;
1101 #define CHECK_REQ(req_expr) \
1102   if (which < count)  return ok; \
1103   ok = (req_expr);
1104   EACH_NAMED_CON(INC_COUNT, CHECK_REQ);
1105 #undef INC_COUNT
1106 #undef CHECK_REQ
1107   assert(count == con_value_count, "");
1108   if (which < count)  return ok;
1109   return false;
1110 }
1111 
1112 #undef ONE_PLUS
1113 #undef VALUE_COMMA
1114 #undef STRING_NULL
1115 #undef EACH_NAMED_CON
1116 #endif // PRODUCT
1117 
1118 JVM_ENTRY(jint, MHN_getNamedCon(JNIEnv *env, jobject igcls, jint which, jobjectArray box_jh)) {
1119 #ifndef PRODUCT
1120   if (advertise_con_value(which)) {
1121     assert(which >= 0 && which < con_value_count, "");
1122     int con = con_values[which];
1123     objArrayHandle box(THREAD, (objArrayOop) JNIHandles::resolve(box_jh));
1124     if (box.not_null() && box->klass() == Universe::objectArrayKlassObj() && box->length() > 0) {
1125       const char* str = &con_names[0];
1126       for (int i = 0; i < which; i++)
1127         str += strlen(str) + 1;   // skip name and null
1128       oop name = java_lang_String::create_oop_from_str(str, CHECK_0);  // possible safepoint
1129       box->obj_at_put(0, name);
1130     }
1131     return con;
1132   }
1133 #endif
1134   return 0;
1135 }
1136 JVM_END
1137 
1138 // void init(MemberName self, AccessibleObject ref)
1139 JVM_ENTRY(void, MHN_init_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jobject target_jh)) {
1140   if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
1141   if (target_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "target is null"); }
1142   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1143   Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
1144   MethodHandles::init_MemberName(mname, target);
1145 }
1146 JVM_END
1147 
1148 // void expand(MemberName self)
1149 JVM_ENTRY(void, MHN_expand_Mem(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1150   if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
1151   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1152   MethodHandles::expand_MemberName(mname, 0, CHECK);
1153 }
1154 JVM_END
1155 
1156 // void resolve(MemberName self, Class<?> caller)
1157 JVM_ENTRY(jobject, MHN_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, jclass caller_jh)) {
1158   if (mname_jh == NULL) { THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "mname is null"); }
1159   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1160 
1161   // The trusted Java code that calls this method should already have performed
1162   // access checks on behalf of the given caller.  But, we can verify this.
1163   if (VerifyMethodHandles && caller_jh != NULL &&
1164       java_lang_invoke_MemberName::clazz(mname()) != NULL) {
1165     Klass* reference_klass = java_lang_Class::as_Klass(java_lang_invoke_MemberName::clazz(mname()));
1166     if (reference_klass != NULL && reference_klass->oop_is_objArray()) {
1167       reference_klass = ObjArrayKlass::cast(reference_klass)->bottom_klass();
1168     }
1169 
1170     // Reflection::verify_class_access can only handle instance classes.
1171     if (reference_klass != NULL && reference_klass->oop_is_instance()) {
1172       // Emulate LinkResolver::check_klass_accessability.
1173       Klass* caller = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh));
1174       if (!Reflection::verify_class_access(caller,
1175                                            reference_klass,
1176                                            true)) {
1177         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), reference_klass->external_name());
1178       }
1179     }
1180   }
1181 
1182   KlassHandle caller(THREAD,
1183                      caller_jh == NULL ? (Klass*) NULL :
1184                      java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh)));
1185   Handle resolved = MethodHandles::resolve_MemberName(mname, caller, CHECK_NULL);
1186 
1187   if (resolved.is_null()) {
1188     int flags = java_lang_invoke_MemberName::flags(mname());
1189     int ref_kind = (flags >> REFERENCE_KIND_SHIFT) & REFERENCE_KIND_MASK;
1190     if (!MethodHandles::ref_kind_is_valid(ref_kind)) {
1191       THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "obsolete MemberName format");
1192     }
1193     if ((flags & ALL_KINDS) == IS_FIELD) {
1194       THROW_MSG_NULL(vmSymbols::java_lang_NoSuchMethodError(), "field resolution failed");
1195     } else if ((flags & ALL_KINDS) == IS_METHOD ||
1196                (flags & ALL_KINDS) == IS_CONSTRUCTOR) {
1197       THROW_MSG_NULL(vmSymbols::java_lang_NoSuchFieldError(), "method resolution failed");
1198     } else {
1199       THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "resolution failed");
1200     }
1201   }
1202 
1203   return JNIHandles::make_local(THREAD, resolved());
1204 }
1205 JVM_END
1206 
1207 static jlong find_member_field_offset(oop mname, bool must_be_static, TRAPS) {
1208   if (mname == NULL ||
1209       java_lang_invoke_MemberName::vmtarget(mname) == NULL) {
1210     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "mname not resolved");
1211   } else {
1212     int flags = java_lang_invoke_MemberName::flags(mname);
1213     if ((flags & IS_FIELD) != 0 &&
1214         (must_be_static
1215          ? (flags & JVM_ACC_STATIC) != 0
1216          : (flags & JVM_ACC_STATIC) == 0)) {
1217       int vmindex = java_lang_invoke_MemberName::vmindex(mname);
1218       bool is_final = (flags & JVM_ACC_FINAL) != 0;
1219       return Unsafe::field_offset_from_byte_offset(vmindex, is_final);
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       marked = nmethodBucket::release(b);









1345       java_lang_invoke_MethodHandleNatives_CallSiteContext::set_vmdependencies(context(), NULL); // reset context
1346     }
1347     if (marked > 0) {
1348       // At least one nmethod has been marked for deoptimization
1349       VM_Deoptimize op;
1350       VMThread::execute(&op);
1351     }
1352   }
1353 }
1354 JVM_END
1355 
1356 /**
1357  * Throws a java/lang/UnsupportedOperationException unconditionally.
1358  * This is required by the specification of MethodHandle.invoke if
1359  * invoked directly.
1360  */
1361 JVM_ENTRY(jobject, MH_invoke_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
1362   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invoke cannot be invoked reflectively");
1363   return NULL;
1364 }
1365 JVM_END
1366 
1367 /**
1368  * Throws a java/lang/UnsupportedOperationException unconditionally.
1369  * This is required by the specification of MethodHandle.invokeExact if
1370  * invoked directly.
1371  */
1372 JVM_ENTRY(jobject, MH_invokeExact_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
1373   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invokeExact cannot be invoked reflectively");
1374   return NULL;
1375 }
1376 JVM_END
1377 
1378 /// JVM_RegisterMethodHandleMethods
1379 
1380 #undef CS  // Solaris builds complain
1381 
1382 #define LANG "Ljava/lang/"
1383 #define JLINV "Ljava/lang/invoke/"
1384 
1385 #define OBJ   LANG"Object;"
1386 #define CLS   LANG"Class;"
1387 #define STRG  LANG"String;"
1388 #define CS    JLINV"CallSite;"
1389 #define MT    JLINV"MethodType;"
1390 #define MH    JLINV"MethodHandle;"
1391 #define MEM   JLINV"MemberName;"
1392 #define CTX   JLINV"MethodHandleNatives$CallSiteContext;"
1393 
1394 #define CC (char*)  /*cast a literal from (const char*)*/
1395 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1396 
1397 // These are the native methods on java.lang.invoke.MethodHandleNatives.
1398 static JNINativeMethod MHN_methods[] = {
1399   {CC"init",                      CC"("MEM""OBJ")V",                     FN_PTR(MHN_init_Mem)},
1400   {CC"expand",                    CC"("MEM")V",                          FN_PTR(MHN_expand_Mem)},
1401   {CC"resolve",                   CC"("MEM""CLS")"MEM,                   FN_PTR(MHN_resolve_Mem)},
1402   //  static native int getNamedCon(int which, Object[] name)
1403   {CC"getNamedCon",               CC"(I["OBJ")I",                        FN_PTR(MHN_getNamedCon)},
1404   //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
1405   //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
1406   {CC"getMembers",                CC"("CLS""STRG""STRG"I"CLS"I["MEM")I", FN_PTR(MHN_getMembers)},
1407   {CC"objectFieldOffset",         CC"("MEM")J",                          FN_PTR(MHN_objectFieldOffset)},
1408   {CC"setCallSiteTargetNormal",   CC"("CS""MH")V",                       FN_PTR(MHN_setCallSiteTargetNormal)},
1409   {CC"setCallSiteTargetVolatile", CC"("CS""MH")V",                       FN_PTR(MHN_setCallSiteTargetVolatile)},
1410   {CC"clearCallSiteContext",      CC"("CTX")V",                          FN_PTR(MHN_clearCallSiteContext)},
1411   {CC"staticFieldOffset",         CC"("MEM")J",                          FN_PTR(MHN_staticFieldOffset)},
1412   {CC"staticFieldBase",           CC"("MEM")"OBJ,                        FN_PTR(MHN_staticFieldBase)},
1413   {CC"getMemberVMInfo",           CC"("MEM")"OBJ,                        FN_PTR(MHN_getMemberVMInfo)}
1414 };
1415 
1416 static JNINativeMethod MH_methods[] = {
1417   // UnsupportedOperationException throwers
1418   {CC"invoke",                    CC"(["OBJ")"OBJ,                       FN_PTR(MH_invoke_UOE)},
1419   {CC"invokeExact",               CC"(["OBJ")"OBJ,                       FN_PTR(MH_invokeExact_UOE)}
1420 };
1421 
1422 /**
1423  * Helper method to register native methods.
1424  */
1425 static bool register_natives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
1426   int status = env->RegisterNatives(clazz, methods, nMethods);
1427   if (status != JNI_OK || env->ExceptionOccurred()) {
1428     warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
1429     env->ExceptionClear();
1430     return false;
1431   }
1432   return true;
1433 }
1434 
1435 /**
1436  * This one function is exported, used by NativeLookup.
1437  */
1438 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
1439   assert(!MethodHandles::enabled(), "must not be enabled");
1440   bool enable_MH = true;
1441 
1442   jclass MH_class = NULL;
1443   if (SystemDictionary::MethodHandle_klass() == NULL) {
1444     enable_MH = false;
1445   } else {
1446     oop mirror = SystemDictionary::MethodHandle_klass()->java_mirror();
1447     MH_class = (jclass) JNIHandles::make_local(env, mirror);
1448   }
1449 
1450   if (enable_MH) {
1451     ThreadToNativeFromVM ttnfv(thread);
1452 
1453     if (enable_MH) {
1454       enable_MH = register_natives(env, MHN_class, MHN_methods, sizeof(MHN_methods)/sizeof(JNINativeMethod));
1455     }
1456     if (enable_MH) {
1457       enable_MH = register_natives(env, MH_class, MH_methods, sizeof(MH_methods)/sizeof(JNINativeMethod));
1458     }
1459   }
1460 
1461   if (TraceInvokeDynamic) {
1462     tty->print_cr("MethodHandle support loaded (using LambdaForms)");
1463   }
1464 
1465   if (enable_MH) {
1466     if (MethodHandles::generate_adapters() == false) {
1467       THROW_MSG(vmSymbols::java_lang_VirtualMachineError(), "Out of space in CodeCache for method handle adapters");
1468     }
1469     MethodHandles::set_enabled(true);
1470   }
1471 }
1472 JVM_END
--- EOF ---