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