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