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