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

1218     }
1219   }
1220   const char* msg = (must_be_static ? "static field required" : "non-static field required");
1221   THROW_MSG_0(vmSymbols::java_lang_InternalError(), msg);
1222   return 0;
1223 }
1224 
1225 JVM_ENTRY(jlong, MHN_objectFieldOffset(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1226   return find_member_field_offset(JNIHandles::resolve(mname_jh), false, THREAD);
1227 }
1228 JVM_END
1229 
1230 JVM_ENTRY(jlong, MHN_staticFieldOffset(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1231   return find_member_field_offset(JNIHandles::resolve(mname_jh), true, THREAD);
1232 }
1233 JVM_END
1234 
1235 JVM_ENTRY(jobject, MHN_staticFieldBase(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1236   // use the other function to perform sanity checks:
1237   jlong ignore = find_member_field_offset(JNIHandles::resolve(mname_jh), true, CHECK_NULL);
1238   oop clazz = java_lang_invoke_MemberName::clazz(JNIHandles::resolve_non_null(mname_jh));
1239   return JNIHandles::make_local(THREAD, clazz);
1240 }
1241 JVM_END
1242 
1243 JVM_ENTRY(jobject, MHN_getMemberVMInfo(JNIEnv *env, jobject igcls, jobject mname_jh)) {
1244   if (mname_jh == NULL)  return NULL;
1245   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
1246   intptr_t vmindex  = java_lang_invoke_MemberName::vmindex(mname());
1247   Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
1248   objArrayHandle result = oopFactory::new_objArray(SystemDictionary::Object_klass(), 2, CHECK_NULL);
1249   jvalue vmindex_value; vmindex_value.j = (long)vmindex;
1250   oop x = java_lang_boxing_object::create(T_LONG, &vmindex_value, CHECK_NULL);
1251   result->obj_at_put(0, x);
1252   x = NULL;
1253   if (vmtarget == NULL) {
1254     x = NULL;
1255   } else if (vmtarget->is_klass()) {
1256     x = ((Klass*) vmtarget)->java_mirror();
1257   } else if (vmtarget->is_method()) {
1258     x = mname();
1259   }
1260   result->obj_at_put(1, x);
1261   return JNIHandles::make_local(env, result());
1262 }
1263 JVM_END
1264 
1265 
1266 
1267 //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
1268 //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
1269 JVM_ENTRY(jint, MHN_getMembers(JNIEnv *env, jobject igcls,
1270                                jclass clazz_jh, jstring name_jh, jstring sig_jh,
1271                                int mflags, jclass caller_jh, jint skip, jobjectArray results_jh)) {
1272   if (clazz_jh == NULL || results_jh == NULL)  return -1;
1273   KlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz_jh)));
1274 
1275   objArrayHandle results(THREAD, (objArrayOop) JNIHandles::resolve(results_jh));
1276   if (results.is_null() || !results->is_objArray())  return -1;
1277 
1278   TempNewSymbol name = NULL;
1279   TempNewSymbol sig = NULL;
1280   if (name_jh != NULL) {
1281     name = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(name_jh));
1282     if (name == NULL)  return 0; // a match is not possible
1283   }
1284   if (sig_jh != NULL) {
1285     sig = java_lang_String::as_symbol_or_null(JNIHandles::resolve_non_null(sig_jh));
1286     if (sig == NULL)  return 0; // a match is not possible
1287   }
1288 
1289   KlassHandle caller;
1290   if (caller_jh != NULL) {
1291     oop caller_oop = JNIHandles::resolve_non_null(caller_jh);
1292     if (!java_lang_Class::is_instance(caller_oop))  return -1;
1293     caller = KlassHandle(THREAD, java_lang_Class::as_Klass(caller_oop));
1294   }
1295 
1296   if (name != NULL && sig != NULL && results.not_null()) {
1297     // try a direct resolve
1298     // %%% TO DO
1299   }
1300 
1301   int res = MethodHandles::find_MemberNames(k, name, sig, mflags,
1302                                             caller, skip, results);
1303   // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
1304   return res;
1305 }
1306 JVM_END
1307 
1308 JVM_ENTRY(void, MHN_setCallSiteTargetNormal(JNIEnv* env, jobject igcls, jobject call_site_jh, jobject target_jh)) {
1309   Handle call_site(THREAD, JNIHandles::resolve_non_null(call_site_jh));
1310   Handle target   (THREAD, JNIHandles::resolve_non_null(target_jh));
1311   {
1312     // Walk all nmethods depending on this call site.
1313     MutexLocker mu(Compile_lock, thread);
1314     MethodHandles::flush_dependent_nmethods(call_site, target);
1315     java_lang_invoke_CallSite::set_target(call_site(), target());
1316   }
1317 }
1318 JVM_END
1319 
1320 JVM_ENTRY(void, MHN_setCallSiteTargetVolatile(JNIEnv* env, jobject igcls, jobject call_site_jh, jobject target_jh)) {
1321   Handle call_site(THREAD, JNIHandles::resolve_non_null(call_site_jh));
1322   Handle target   (THREAD, JNIHandles::resolve_non_null(target_jh));
1323   {
1324     // Walk all nmethods depending on this call site.
1325     MutexLocker mu(Compile_lock, thread);
1326     MethodHandles::flush_dependent_nmethods(call_site, target);
1327     java_lang_invoke_CallSite::set_target_volatile(call_site(), target());
1328   }
1329 }
1330 JVM_END
1331 
1332 JVM_ENTRY(void, MHN_clearCallSiteContext(JNIEnv* env, jobject igcls, jobject context_jh)) {
1333   Handle context(THREAD, JNIHandles::resolve_non_null(context_jh));
1334   {
1335     // Walk all nmethods depending on this call site.
1336     MutexLocker mu1(Compile_lock, thread);
1337 
1338     int marked = 0;
1339     {
1340       MutexLockerEx mu2(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1341       nmethodBucket* b = java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(context());
1342       while(b != NULL) {
1343         nmethod* nm = b->get_nmethod();
1344         if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization()) {
1345           nm->mark_for_deoptimization();
1346           marked++;
1347         }
1348         nmethodBucket* next = b->next();
1349         delete b;
1350         b = next;
1351       }
1352       java_lang_invoke_MethodHandleNatives_CallSiteContext::set_vmdependencies(context(), NULL); // reset context
1353     }
1354     if (marked > 0) {
1355       // At least one nmethod has been marked for deoptimization
1356       VM_Deoptimize op;
1357       VMThread::execute(&op);
1358     }
1359   }
1360 }
1361 JVM_END
1362 
1363 /**
1364  * Throws a java/lang/UnsupportedOperationException unconditionally.
1365  * This is required by the specification of MethodHandle.invoke if
1366  * invoked directly.
1367  */
1368 JVM_ENTRY(jobject, MH_invoke_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
1369   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invoke cannot be invoked reflectively");
1370   return NULL;
1371 }
1372 JVM_END
1373 
1374 /**
1375  * Throws a java/lang/UnsupportedOperationException unconditionally.
1376  * This is required by the specification of MethodHandle.invokeExact if
1377  * invoked directly.
1378  */
1379 JVM_ENTRY(jobject, MH_invokeExact_UOE(JNIEnv* env, jobject mh, jobjectArray args)) {
1380   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "MethodHandle.invokeExact cannot be invoked reflectively");
1381   return NULL;
1382 }
1383 JVM_END
1384 
1385 /// JVM_RegisterMethodHandleMethods
1386 
1387 #undef CS  // Solaris builds complain
1388 
1389 #define LANG "Ljava/lang/"
1390 #define JLINV "Ljava/lang/invoke/"
1391 
1392 #define OBJ   LANG"Object;"
1393 #define CLS   LANG"Class;"
1394 #define STRG  LANG"String;"
1395 #define CS    JLINV"CallSite;"
1396 #define MT    JLINV"MethodType;"
1397 #define MH    JLINV"MethodHandle;"
1398 #define MEM   JLINV"MemberName;"
1399 #define CTX   JLINV"MethodHandleNatives$CallSiteContext;"
1400 
1401 #define CC (char*)  /*cast a literal from (const char*)*/
1402 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
1403 
1404 // These are the native methods on java.lang.invoke.MethodHandleNatives.
1405 static JNINativeMethod MHN_methods[] = {
1406   {CC"init",                      CC"("MEM""OBJ")V",                     FN_PTR(MHN_init_Mem)},
1407   {CC"expand",                    CC"("MEM")V",                          FN_PTR(MHN_expand_Mem)},
1408   {CC"resolve",                   CC"("MEM""CLS")"MEM,                   FN_PTR(MHN_resolve_Mem)},
1409   //  static native int getNamedCon(int which, Object[] name)
1410   {CC"getNamedCon",               CC"(I["OBJ")I",                        FN_PTR(MHN_getNamedCon)},
1411   //  static native int getMembers(Class<?> defc, String matchName, String matchSig,
1412   //          int matchFlags, Class<?> caller, int skip, MemberName[] results);
1413   {CC"getMembers",                CC"("CLS""STRG""STRG"I"CLS"I["MEM")I", FN_PTR(MHN_getMembers)},
1414   {CC"objectFieldOffset",         CC"("MEM")J",                          FN_PTR(MHN_objectFieldOffset)},
1415   {CC"setCallSiteTargetNormal",   CC"("CS""MH")V",                       FN_PTR(MHN_setCallSiteTargetNormal)},
1416   {CC"setCallSiteTargetVolatile", CC"("CS""MH")V",                       FN_PTR(MHN_setCallSiteTargetVolatile)},
1417   {CC"clearCallSiteContext",      CC"("CTX")V",                          FN_PTR(MHN_clearCallSiteContext)},
1418   {CC"staticFieldOffset",         CC"("MEM")J",                          FN_PTR(MHN_staticFieldOffset)},
1419   {CC"staticFieldBase",           CC"("MEM")"OBJ,                        FN_PTR(MHN_staticFieldBase)},
1420   {CC"getMemberVMInfo",           CC"("MEM")"OBJ,                        FN_PTR(MHN_getMemberVMInfo)}
1421 };
1422 
1423 static JNINativeMethod MH_methods[] = {
1424   // UnsupportedOperationException throwers
1425   {CC"invoke",                    CC"(["OBJ")"OBJ,                       FN_PTR(MH_invoke_UOE)},
1426   {CC"invokeExact",               CC"(["OBJ")"OBJ,                       FN_PTR(MH_invokeExact_UOE)}
1427 };
1428 
1429 /**
1430  * Helper method to register native methods.
1431  */
1432 static bool register_natives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
1433   int status = env->RegisterNatives(clazz, methods, nMethods);
1434   if (status != JNI_OK || env->ExceptionOccurred()) {
1435     warning("JSR 292 method handle code is mismatched to this JVM.  Disabling support.");
1436     env->ExceptionClear();
1437     return false;
1438   }
1439   return true;
1440 }
1441 
1442 /**
1443  * This one function is exported, used by NativeLookup.
1444  */
1445 JVM_ENTRY(void, JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass MHN_class)) {
1446   assert(!MethodHandles::enabled(), "must not be enabled");
1447   bool enable_MH = true;
1448 
1449   jclass MH_class = NULL;
1450   if (SystemDictionary::MethodHandle_klass() == NULL) {
1451     enable_MH = false;
1452   } else {
1453     oop mirror = SystemDictionary::MethodHandle_klass()->java_mirror();
1454     MH_class = (jclass) JNIHandles::make_local(env, mirror);
1455   }
1456 
1457   if (enable_MH) {
1458     ThreadToNativeFromVM ttnfv(thread);
1459 
1460     if (enable_MH) {
1461       enable_MH = register_natives(env, MHN_class, MHN_methods, sizeof(MHN_methods)/sizeof(JNINativeMethod));
1462     }
1463     if (enable_MH) {
1464       enable_MH = register_natives(env, MH_class, MH_methods, sizeof(MH_methods)/sizeof(JNINativeMethod));
1465     }
1466   }
1467 
1468   if (TraceInvokeDynamic) {
1469     tty->print_cr("MethodHandle support loaded (using LambdaForms)");
1470   }
1471 
1472   if (enable_MH) {
1473     if (MethodHandles::generate_adapters() == false) {
1474       THROW_MSG(vmSymbols::java_lang_VirtualMachineError(), "Out of space in CodeCache for method handle adapters");
1475     }
1476     MethodHandles::set_enabled(true);
1477   }
1478 }
1479 JVM_END
--- EOF ---