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