1 /* 2 * Copyright (c) 1997, 2025, 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 "cds/aotMetaspace.hpp" 26 #include "cds/cdsConfig.hpp" 27 #include "cds/cppVtables.hpp" 28 #include "classfile/classLoader.hpp" 29 #include "classfile/classLoaderDataGraph.hpp" 30 #include "classfile/metadataOnStackMark.hpp" 31 #include "classfile/symbolTable.hpp" 32 #include "classfile/systemDictionary.hpp" 33 #include "classfile/vmClasses.hpp" 34 #include "code/aotCodeCache.hpp" 35 #include "code/codeCache.hpp" 36 #include "code/debugInfoRec.hpp" 37 #include "compiler/compilationPolicy.hpp" 38 #include "gc/shared/collectedHeap.inline.hpp" 39 #include "interpreter/bytecodes.hpp" 40 #include "interpreter/bytecodeStream.hpp" 41 #include "interpreter/bytecodeTracer.hpp" 42 #include "interpreter/interpreter.hpp" 43 #include "interpreter/oopMapCache.hpp" 44 #include "logging/log.hpp" 45 #include "logging/logStream.hpp" 46 #include "logging/logTag.hpp" 47 #include "memory/allocation.inline.hpp" 48 #include "memory/metadataFactory.hpp" 49 #include "memory/metaspaceClosure.hpp" 50 #include "memory/oopFactory.hpp" 51 #include "memory/resourceArea.hpp" 52 #include "memory/universe.hpp" 53 #include "nmt/memTracker.hpp" 54 #include "oops/constantPool.hpp" 55 #include "oops/constMethod.hpp" 56 #include "oops/jmethodIDTable.hpp" 57 #include "oops/klass.inline.hpp" 58 #include "oops/method.inline.hpp" 59 #include "oops/methodData.hpp" 60 #include "oops/objArrayKlass.hpp" 61 #include "oops/objArrayOop.inline.hpp" 62 #include "oops/oop.inline.hpp" 63 #include "oops/symbol.hpp" 64 #include "oops/trainingData.hpp" 65 #include "prims/jvmtiExport.hpp" 66 #include "prims/methodHandles.hpp" 67 #include "runtime/arguments.hpp" 68 #include "runtime/atomic.hpp" 69 #include "runtime/continuationEntry.hpp" 70 #include "runtime/frame.inline.hpp" 71 #include "runtime/handles.inline.hpp" 72 #include "runtime/init.hpp" 73 #include "runtime/java.hpp" 74 #include "runtime/orderAccess.hpp" 75 #include "runtime/perfData.hpp" 76 #include "runtime/relocator.hpp" 77 #include "runtime/safepointVerifiers.hpp" 78 #include "runtime/sharedRuntime.hpp" 79 #include "runtime/signature.hpp" 80 #include "runtime/threads.hpp" 81 #include "runtime/vm_version.hpp" 82 #include "utilities/align.hpp" 83 #include "utilities/quickSort.hpp" 84 #include "utilities/vmError.hpp" 85 #include "utilities/xmlstream.hpp" 86 87 // Implementation of Method 88 89 Method* Method::allocate(ClassLoaderData* loader_data, 90 int byte_code_size, 91 AccessFlags access_flags, 92 InlineTableSizes* sizes, 93 ConstMethod::MethodType method_type, 94 Symbol* name, 95 TRAPS) { 96 assert(!access_flags.is_native() || byte_code_size == 0, 97 "native methods should not contain byte codes"); 98 ConstMethod* cm = ConstMethod::allocate(loader_data, 99 byte_code_size, 100 sizes, 101 method_type, 102 CHECK_NULL); 103 int size = Method::size(access_flags.is_native()); 104 return new (loader_data, size, MetaspaceObj::MethodType, THREAD) Method(cm, access_flags, name); 105 } 106 107 Method::Method(ConstMethod* xconst, AccessFlags access_flags, Symbol* name) { 108 NoSafepointVerifier no_safepoint; 109 set_constMethod(xconst); 110 set_access_flags(access_flags); 111 set_intrinsic_id(vmIntrinsics::_none); 112 clear_method_data(); 113 clear_method_counters(); 114 set_vtable_index(Method::garbage_vtable_index); 115 116 // Fix and bury in Method* 117 set_interpreter_entry(nullptr); // sets i2i entry and from_int 118 set_adapter_entry(nullptr); 119 Method::clear_code(); // from_c/from_i get set to c2i/i2i 120 set_preload_code(nullptr); 121 set_aot_code_entry(nullptr); 122 123 if (access_flags.is_native()) { 124 clear_native_function(); 125 set_signature_handler(nullptr); 126 } 127 128 NOT_PRODUCT(set_compiled_invocation_count(0);) 129 // Name is very useful for debugging. 130 NOT_PRODUCT(_name = name;) 131 } 132 133 // Release Method*. The nmethod will be gone when we get here because 134 // we've walked the code cache. 135 void Method::deallocate_contents(ClassLoaderData* loader_data) { 136 MetadataFactory::free_metadata(loader_data, constMethod()); 137 set_constMethod(nullptr); 138 MetadataFactory::free_metadata(loader_data, method_data()); 139 clear_method_data(); 140 MetadataFactory::free_metadata(loader_data, method_counters()); 141 clear_method_counters(); 142 set_adapter_entry(nullptr); 143 // The nmethod will be gone when we get here. 144 if (code() != nullptr) _code = nullptr; 145 if (aot_code_entry() != nullptr) { 146 set_preload_code(nullptr); 147 AOTCodeCache::invalidate(aot_code_entry()); 148 set_aot_code_entry(nullptr); 149 } 150 } 151 152 void Method::release_C_heap_structures() { 153 if (method_data()) { 154 method_data()->release_C_heap_structures(); 155 156 // Destroy MethodData embedded lock 157 method_data()->~MethodData(); 158 } 159 } 160 161 address Method::get_i2c_entry() { 162 if (is_abstract()) { 163 return SharedRuntime::throw_AbstractMethodError_entry(); 164 } 165 assert(adapter() != nullptr, "must have"); 166 return adapter()->get_i2c_entry(); 167 } 168 169 address Method::get_c2i_entry() { 170 if (is_abstract()) { 171 return SharedRuntime::get_handle_wrong_method_abstract_stub(); 172 } 173 assert(adapter() != nullptr, "must have"); 174 return adapter()->get_c2i_entry(); 175 } 176 177 address Method::get_c2i_unverified_entry() { 178 assert(adapter() != nullptr, "must have"); 179 return adapter()->get_c2i_unverified_entry(); 180 } 181 182 address Method::get_c2i_no_clinit_check_entry() { 183 assert(VM_Version::supports_fast_class_init_checks(), ""); 184 assert(adapter() != nullptr, "must have"); 185 return adapter()->get_c2i_no_clinit_check_entry(); 186 } 187 188 char* Method::name_and_sig_as_C_string() const { 189 return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature()); 190 } 191 192 char* Method::name_and_sig_as_C_string(char* buf, int size) const { 193 return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature(), buf, size); 194 } 195 196 char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature) { 197 const char* klass_name = klass->external_name(); 198 int klass_name_len = (int)strlen(klass_name); 199 int method_name_len = method_name->utf8_length(); 200 int len = klass_name_len + 2 + method_name_len + signature->utf8_length(); 201 char* dest = NEW_RESOURCE_ARRAY(char, len + 1); 202 strcpy(dest, klass_name); 203 dest[klass_name_len + 0] = ':'; 204 dest[klass_name_len + 1] = ':'; 205 strcpy(&dest[klass_name_len + 2], method_name->as_C_string()); 206 strcpy(&dest[klass_name_len + 2 + method_name_len], signature->as_C_string()); 207 dest[len] = 0; 208 return dest; 209 } 210 211 char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size) { 212 Symbol* klass_name = klass->name(); 213 klass_name->as_klass_external_name(buf, size); 214 int len = (int)strlen(buf); 215 216 if (len < size - 1) { 217 buf[len++] = '.'; 218 219 method_name->as_C_string(&(buf[len]), size - len); 220 len = (int)strlen(buf); 221 222 signature->as_C_string(&(buf[len]), size - len); 223 } 224 225 return buf; 226 } 227 228 const char* Method::external_name() const { 229 return external_name(constants()->pool_holder(), name(), signature()); 230 } 231 232 void Method::print_external_name(outputStream *os) const { 233 print_external_name(os, constants()->pool_holder(), name(), signature()); 234 } 235 236 const char* Method::external_name(Klass* klass, Symbol* method_name, Symbol* signature) { 237 stringStream ss; 238 print_external_name(&ss, klass, method_name, signature); 239 return ss.as_string(); 240 } 241 242 void Method::print_external_name(outputStream *os, Klass* klass, Symbol* method_name, Symbol* signature) { 243 signature->print_as_signature_external_return_type(os); 244 os->print(" %s.%s(", klass->external_name(), method_name->as_C_string()); 245 signature->print_as_signature_external_parameters(os); 246 os->print(")"); 247 } 248 249 int Method::fast_exception_handler_bci_for(const methodHandle& mh, Klass* ex_klass, int throw_bci, TRAPS) { 250 if (log_is_enabled(Debug, exceptions)) { 251 ResourceMark rm(THREAD); 252 log_debug(exceptions)("Looking for catch handler for exception of type \"%s\" in method \"%s\"", 253 ex_klass == nullptr ? "null" : ex_klass->external_name(), mh->name()->as_C_string()); 254 } 255 // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index) 256 // access exception table 257 ExceptionTable table(mh()); 258 int length = table.length(); 259 // iterate through all entries sequentially 260 constantPoolHandle pool(THREAD, mh->constants()); 261 for (int i = 0; i < length; i ++) { 262 //reacquire the table in case a GC happened 263 ExceptionTable table(mh()); 264 int beg_bci = table.start_pc(i); 265 int end_bci = table.end_pc(i); 266 assert(beg_bci <= end_bci, "inconsistent exception table"); 267 log_debug(exceptions)(" - checking exception table entry for BCI %d to %d", 268 beg_bci, end_bci); 269 270 if (beg_bci <= throw_bci && throw_bci < end_bci) { 271 // exception handler bci range covers throw_bci => investigate further 272 log_debug(exceptions)(" - entry covers throw point BCI %d", throw_bci); 273 274 int handler_bci = table.handler_pc(i); 275 int klass_index = table.catch_type_index(i); 276 if (klass_index == 0) { 277 if (log_is_enabled(Info, exceptions)) { 278 ResourceMark rm(THREAD); 279 log_info(exceptions)("Found catch-all handler for exception of type \"%s\" in method \"%s\" at BCI: %d", 280 ex_klass == nullptr ? "null" : ex_klass->external_name(), mh->name()->as_C_string(), handler_bci); 281 } 282 return handler_bci; 283 } else if (ex_klass == nullptr) { 284 // Is this even possible? 285 if (log_is_enabled(Info, exceptions)) { 286 ResourceMark rm(THREAD); 287 log_info(exceptions)("null exception class is implicitly caught by handler in method \"%s\" at BCI: %d", 288 mh()->name()->as_C_string(), handler_bci); 289 } 290 return handler_bci; 291 } else { 292 if (log_is_enabled(Debug, exceptions)) { 293 ResourceMark rm(THREAD); 294 log_debug(exceptions)(" - resolving catch type \"%s\"", 295 pool->klass_name_at(klass_index)->as_C_string()); 296 } 297 // we know the exception class => get the constraint class 298 // this may require loading of the constraint class; if verification 299 // fails or some other exception occurs, return handler_bci 300 Klass* k = pool->klass_at(klass_index, THREAD); 301 if (HAS_PENDING_EXCEPTION) { 302 if (log_is_enabled(Debug, exceptions)) { 303 ResourceMark rm(THREAD); 304 log_debug(exceptions)(" - exception \"%s\" occurred resolving catch type", 305 PENDING_EXCEPTION->klass()->external_name()); 306 } 307 return handler_bci; 308 } 309 assert(k != nullptr, "klass not loaded"); 310 if (ex_klass->is_subtype_of(k)) { 311 if (log_is_enabled(Info, exceptions)) { 312 ResourceMark rm(THREAD); 313 log_info(exceptions)("Found matching handler for exception of type \"%s\" in method \"%s\" at BCI: %d", 314 ex_klass == nullptr ? "null" : ex_klass->external_name(), mh->name()->as_C_string(), handler_bci); 315 } 316 return handler_bci; 317 } 318 } 319 } 320 } 321 322 if (log_is_enabled(Debug, exceptions)) { 323 ResourceMark rm(THREAD); 324 log_debug(exceptions)("No catch handler found for exception of type \"%s\" in method \"%s\"", 325 ex_klass->external_name(), mh->name()->as_C_string()); 326 } 327 328 return -1; 329 } 330 331 void Method::mask_for(int bci, InterpreterOopMap* mask) { 332 methodHandle h_this(Thread::current(), this); 333 mask_for(h_this, bci, mask); 334 } 335 336 void Method::mask_for(const methodHandle& this_mh, int bci, InterpreterOopMap* mask) { 337 assert(this_mh() == this, "Sanity"); 338 method_holder()->mask_for(this_mh, bci, mask); 339 } 340 341 int Method::bci_from(address bcp) const { 342 if (is_native() && bcp == nullptr) { 343 return 0; 344 } 345 // Do not have a ResourceMark here because AsyncGetCallTrace stack walking code 346 // may call this after interrupting a nested ResourceMark. 347 assert((is_native() && bcp == code_base()) || contains(bcp) || VMError::is_error_reported(), 348 "bcp doesn't belong to this method. bcp: " PTR_FORMAT, p2i(bcp)); 349 350 return int(bcp - code_base()); 351 } 352 353 354 int Method::validate_bci(int bci) const { 355 // Called from the verifier, and should return -1 if not valid. 356 return ((is_native() && bci == 0) || (!is_native() && 0 <= bci && bci < code_size())) ? bci : -1; 357 } 358 359 // Return bci if it appears to be a valid bcp 360 // Return -1 otherwise. 361 // Used by profiling code, when invalid data is a possibility. 362 // The caller is responsible for validating the Method* itself. 363 int Method::validate_bci_from_bcp(address bcp) const { 364 // keep bci as -1 if not a valid bci 365 int bci = -1; 366 if (bcp == nullptr || bcp == code_base()) { 367 // code_size() may return 0 and we allow 0 here 368 // the method may be native 369 bci = 0; 370 } else if (contains(bcp)) { 371 bci = int(bcp - code_base()); 372 } 373 // Assert that if we have dodged any asserts, bci is negative. 374 assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0"); 375 return bci; 376 } 377 378 address Method::bcp_from(int bci) const { 379 assert((is_native() && bci == 0) || (!is_native() && 0 <= bci && bci < code_size()), 380 "illegal bci: %d for %s method", bci, is_native() ? "native" : "non-native"); 381 address bcp = code_base() + bci; 382 assert((is_native() && bcp == code_base()) || contains(bcp), "bcp doesn't belong to this method"); 383 return bcp; 384 } 385 386 address Method::bcp_from(address bcp) const { 387 if (is_native() && bcp == nullptr) { 388 return code_base(); 389 } else { 390 return bcp; 391 } 392 } 393 394 int Method::size(bool is_native) { 395 // If native, then include pointers for native_function and signature_handler 396 int extra_bytes = (is_native) ? 2*sizeof(address*) : 0; 397 int extra_words = align_up(extra_bytes, BytesPerWord) / BytesPerWord; 398 return align_metadata_size(header_size() + extra_words); 399 } 400 401 Symbol* Method::klass_name() const { 402 return method_holder()->name(); 403 } 404 405 void Method::metaspace_pointers_do(MetaspaceClosure* it) { 406 LogStreamHandle(Trace, aot) lsh; 407 if (lsh.is_enabled()) { 408 lsh.print("Iter(Method): %p ", this); 409 print_external_name(&lsh); 410 lsh.cr(); 411 } 412 if (method_holder() != nullptr && !method_holder()->is_rewritten()) { 413 // holder is null for MH intrinsic methods 414 it->push(&_constMethod, MetaspaceClosure::_writable); 415 } else { 416 it->push(&_constMethod); 417 } 418 it->push(&_adapter); 419 it->push(&_method_data); 420 it->push(&_method_counters); 421 NOT_PRODUCT(it->push(&_name);) 422 } 423 424 #if INCLUDE_CDS 425 // Attempt to return method to original state. Clear any pointers 426 // (to objects outside the shared spaces). We won't be able to predict 427 // where they should point in a new JVM. Further initialize some 428 // entries now in order allow them to be write protected later. 429 430 void Method::remove_unshareable_info() { 431 unlink_method(); 432 if (method_data() != nullptr) { 433 method_data()->remove_unshareable_info(); 434 } 435 if (method_counters() != nullptr) { 436 method_counters()->remove_unshareable_info(); 437 } 438 if (CDSConfig::is_dumping_adapters() && _adapter != nullptr) { 439 _adapter->remove_unshareable_info(); 440 _adapter = nullptr; 441 } 442 if (method_data() != nullptr) { 443 method_data()->remove_unshareable_info(); 444 } 445 if (method_counters() != nullptr) { 446 method_counters()->remove_unshareable_info(); 447 } 448 JFR_ONLY(REMOVE_METHOD_ID(this);) 449 } 450 451 void Method::restore_unshareable_info(TRAPS) { 452 assert(is_method() && is_valid_method(this), "ensure C++ vtable is restored"); 453 if (method_data() != nullptr) { 454 method_data()->restore_unshareable_info(CHECK); 455 } 456 if (method_counters() != nullptr) { 457 method_counters()->restore_unshareable_info(CHECK); 458 } 459 if (_adapter != nullptr) { 460 assert(_adapter->is_linked(), "must be"); 461 _from_compiled_entry = _adapter->get_c2i_entry(); 462 } 463 if (method_data() != nullptr) { 464 method_data()->restore_unshareable_info(CHECK); 465 } 466 if (method_counters() != nullptr) { 467 method_counters()->restore_unshareable_info(CHECK); 468 } 469 assert(!queued_for_compilation(), "method's queued_for_compilation flag should not be set"); 470 assert(!pending_queue_processed(), "method's pending_queued_processed flag should not be set"); 471 } 472 #endif 473 474 void Method::set_vtable_index(int index) { 475 if (in_aot_cache() && !AOTMetaspace::remapped_readwrite() && method_holder()->verified_at_dump_time()) { 476 // At runtime initialize_vtable is rerun as part of link_class_impl() 477 // for a shared class loaded by the non-boot loader to obtain the loader 478 // constraints based on the runtime classloaders' context. 479 return; // don't write into the shared class 480 } else { 481 _vtable_index = index; 482 } 483 } 484 485 void Method::set_itable_index(int index) { 486 if (in_aot_cache() && !AOTMetaspace::remapped_readwrite() && method_holder()->verified_at_dump_time()) { 487 // At runtime initialize_itable is rerun as part of link_class_impl() 488 // for a shared class loaded by the non-boot loader to obtain the loader 489 // constraints based on the runtime classloaders' context. The dumptime 490 // itable index should be the same as the runtime index. 491 assert(_vtable_index == itable_index_max - index, 492 "archived itable index is different from runtime index"); 493 return; // don't write into the shared class 494 } else { 495 _vtable_index = itable_index_max - index; 496 } 497 assert(valid_itable_index(), ""); 498 } 499 500 // The RegisterNatives call being attempted tried to register with a method that 501 // is not native. Ask JVM TI what prefixes have been specified. Then check 502 // to see if the native method is now wrapped with the prefixes. See the 503 // SetNativeMethodPrefix(es) functions in the JVM TI Spec for details. 504 static Method* find_prefixed_native(Klass* k, Symbol* name, Symbol* signature, TRAPS) { 505 #if INCLUDE_JVMTI 506 ResourceMark rm(THREAD); 507 Method* method; 508 int name_len = name->utf8_length(); 509 char* name_str = name->as_utf8(); 510 int prefix_count; 511 char** prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count); 512 for (int i = 0; i < prefix_count; i++) { 513 char* prefix = prefixes[i]; 514 int prefix_len = (int)strlen(prefix); 515 516 // try adding this prefix to the method name and see if it matches another method name 517 int trial_len = name_len + prefix_len; 518 char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1); 519 strcpy(trial_name_str, prefix); 520 strcat(trial_name_str, name_str); 521 TempNewSymbol trial_name = SymbolTable::probe(trial_name_str, trial_len); 522 if (trial_name == nullptr) { 523 continue; // no such symbol, so this prefix wasn't used, try the next prefix 524 } 525 method = k->lookup_method(trial_name, signature); 526 if (method == nullptr) { 527 continue; // signature doesn't match, try the next prefix 528 } 529 if (method->is_native()) { 530 method->set_is_prefixed_native(); 531 return method; // wahoo, we found a prefixed version of the method, return it 532 } 533 // found as non-native, so prefix is good, add it, probably just need more prefixes 534 name_len = trial_len; 535 name_str = trial_name_str; 536 } 537 #endif // INCLUDE_JVMTI 538 return nullptr; // not found 539 } 540 541 bool Method::register_native(Klass* k, Symbol* name, Symbol* signature, address entry, TRAPS) { 542 Method* method = k->lookup_method(name, signature); 543 if (method == nullptr) { 544 ResourceMark rm(THREAD); 545 stringStream st; 546 st.print("Method '"); 547 print_external_name(&st, k, name, signature); 548 st.print("' name or signature does not match"); 549 THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), false); 550 } 551 if (!method->is_native()) { 552 // trying to register to a non-native method, see if a JVM TI agent has added prefix(es) 553 method = find_prefixed_native(k, name, signature, THREAD); 554 if (method == nullptr) { 555 ResourceMark rm(THREAD); 556 stringStream st; 557 st.print("Method '"); 558 print_external_name(&st, k, name, signature); 559 st.print("' is not declared as native"); 560 THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), false); 561 } 562 } 563 564 if (entry != nullptr) { 565 method->set_native_function(entry, native_bind_event_is_interesting); 566 } else { 567 method->clear_native_function(); 568 } 569 if (log_is_enabled(Debug, jni, resolve)) { 570 ResourceMark rm(THREAD); 571 log_debug(jni, resolve)("[Registering JNI native method %s.%s]", 572 method->method_holder()->external_name(), 573 method->name()->as_C_string()); 574 } 575 return true; 576 } 577 578 bool Method::was_executed_more_than(int n) { 579 // Invocation counter is reset when the Method* is compiled. 580 // If the method has compiled code we therefore assume it has 581 // be executed more than n times. 582 if (is_accessor() || is_empty_method() || (code() != nullptr)) { 583 // interpreter doesn't bump invocation counter of trivial methods 584 // compiler does not bump invocation counter of compiled methods 585 return true; 586 } 587 else if ((method_counters() != nullptr && 588 method_counters()->invocation_counter()->carry()) || 589 (method_data() != nullptr && 590 method_data()->invocation_counter()->carry())) { 591 // The carry bit is set when the counter overflows and causes 592 // a compilation to occur. We don't know how many times 593 // the counter has been reset, so we simply assume it has 594 // been executed more than n times. 595 return true; 596 } else { 597 return invocation_count() > n; 598 } 599 } 600 601 void Method::print_invocation_count(outputStream* st) { 602 //---< compose+print method return type, klass, name, and signature >--- 603 if (is_static()) { st->print("static "); } 604 if (is_final()) { st->print("final "); } 605 if (is_synchronized()) { st->print("synchronized "); } 606 if (is_native()) { st->print("native "); } 607 st->print("%s::", method_holder()->external_name()); 608 name()->print_symbol_on(st); 609 signature()->print_symbol_on(st); 610 611 if (WizardMode) { 612 // dump the size of the byte codes 613 st->print(" {%d}", code_size()); 614 } 615 st->cr(); 616 617 // Counting based on signed int counters tends to overflow with 618 // longer-running workloads on fast machines. The counters under 619 // consideration here, however, are limited in range by counting 620 // logic. See InvocationCounter:count_limit for example. 621 // No "overflow precautions" need to be implemented here. 622 st->print_cr (" interpreter_invocation_count: " INT32_FORMAT_W(11), interpreter_invocation_count()); 623 st->print_cr (" invocation_counter: " INT32_FORMAT_W(11), invocation_count()); 624 st->print_cr (" backedge_counter: " INT32_FORMAT_W(11), backedge_count()); 625 626 if (method_data() != nullptr) { 627 st->print_cr (" decompile_count: " UINT32_FORMAT_W(11), method_data()->decompile_count()); 628 } 629 630 #ifndef PRODUCT 631 if (CountCompiledCalls) { 632 st->print_cr (" compiled_invocation_count: " INT64_FORMAT_W(11), compiled_invocation_count()); 633 } 634 #endif 635 } 636 637 MethodTrainingData* Method::training_data_or_null() const { 638 MethodCounters* mcs = method_counters(); 639 if (mcs == nullptr) { 640 return nullptr; 641 } else { 642 MethodTrainingData* mtd = mcs->method_training_data(); 643 if (mtd == mcs->method_training_data_sentinel()) { 644 return nullptr; 645 } 646 return mtd; 647 } 648 } 649 650 bool Method::init_training_data(MethodTrainingData* td) { 651 MethodCounters* mcs = method_counters(); 652 if (mcs == nullptr) { 653 return false; 654 } else { 655 return mcs->init_method_training_data(td); 656 } 657 } 658 659 bool Method::install_training_method_data(const methodHandle& method) { 660 MethodTrainingData* mtd = MethodTrainingData::find(method); 661 if (mtd != nullptr && mtd->final_profile() != nullptr) { 662 Atomic::replace_if_null(&method->_method_data, mtd->final_profile()); 663 return true; 664 } 665 return false; 666 } 667 668 // Build a MethodData* object to hold profiling information collected on this 669 // method when requested. 670 void Method::build_profiling_method_data(const methodHandle& method, TRAPS) { 671 if (install_training_method_data(method)) { 672 return; 673 } 674 // Do not profile the method if metaspace has hit an OOM previously 675 // allocating profiling data. Callers clear pending exception so don't 676 // add one here. 677 if (ClassLoaderDataGraph::has_metaspace_oom()) { 678 return; 679 } 680 681 ClassLoaderData* loader_data = method->method_holder()->class_loader_data(); 682 MethodData* method_data = MethodData::allocate(loader_data, method, THREAD); 683 if (HAS_PENDING_EXCEPTION) { 684 CompileBroker::log_metaspace_failure(); 685 ClassLoaderDataGraph::set_metaspace_oom(true); 686 return; // return the exception (which is cleared) 687 } 688 689 if (!Atomic::replace_if_null(&method->_method_data, method_data)) { 690 MetadataFactory::free_metadata(loader_data, method_data); 691 return; 692 } 693 694 if (ForceProfiling && TrainingData::need_data()) { 695 MethodTrainingData* mtd = MethodTrainingData::make(method, false); 696 guarantee(mtd != nullptr, ""); 697 } 698 699 if (PrintMethodData) { 700 ResourceMark rm(THREAD); 701 tty->print("build_profiling_method_data for "); 702 method->print_name(tty); 703 tty->cr(); 704 // At the end of the run, the MDO, full of data, will be dumped. 705 } 706 } 707 708 MethodCounters* Method::build_method_counters(Thread* current, Method* m) { 709 // Do not profile the method if metaspace has hit an OOM previously 710 if (ClassLoaderDataGraph::has_metaspace_oom()) { 711 return nullptr; 712 } 713 714 methodHandle mh(current, m); 715 MethodCounters* counters; 716 if (current->is_Java_thread()) { 717 JavaThread* THREAD = JavaThread::cast(current); // For exception macros. 718 // Use the TRAPS version for a JavaThread so it will adjust the GC threshold 719 // if needed. 720 counters = MethodCounters::allocate_with_exception(mh, THREAD); 721 if (HAS_PENDING_EXCEPTION) { 722 CLEAR_PENDING_EXCEPTION; 723 } 724 } else { 725 // Call metaspace allocation that doesn't throw exception if the 726 // current thread isn't a JavaThread, ie. the VMThread. 727 counters = MethodCounters::allocate_no_exception(mh); 728 } 729 730 if (counters == nullptr) { 731 CompileBroker::log_metaspace_failure(); 732 ClassLoaderDataGraph::set_metaspace_oom(true); 733 return nullptr; 734 } 735 736 if (!mh->init_method_counters(counters)) { 737 MetadataFactory::free_metadata(mh->method_holder()->class_loader_data(), counters); 738 } 739 740 if (ForceProfiling && TrainingData::need_data()) { 741 MethodTrainingData* mtd = MethodTrainingData::make(mh, false); 742 guarantee(mtd != nullptr, ""); 743 } 744 745 return mh->method_counters(); 746 } 747 748 bool Method::init_method_counters(MethodCounters* counters) { 749 // Try to install a pointer to MethodCounters, return true on success. 750 return Atomic::replace_if_null(&_method_counters, counters); 751 } 752 753 void Method::set_exception_handler_entered(int handler_bci) { 754 if (ProfileExceptionHandlers) { 755 MethodData* mdo = method_data(); 756 if (mdo != nullptr) { 757 BitData handler_data = mdo->exception_handler_bci_to_data(handler_bci); 758 handler_data.set_exception_handler_entered(); 759 } 760 } 761 } 762 763 int Method::extra_stack_words() { 764 // not an inline function, to avoid a header dependency on Interpreter 765 return extra_stack_entries() * Interpreter::stackElementSize; 766 } 767 768 bool Method::compute_has_loops_flag() { 769 BytecodeStream bcs(methodHandle(Thread::current(), this)); 770 Bytecodes::Code bc; 771 772 while ((bc = bcs.next()) >= 0) { 773 switch (bc) { 774 case Bytecodes::_ifeq: 775 case Bytecodes::_ifnull: 776 case Bytecodes::_iflt: 777 case Bytecodes::_ifle: 778 case Bytecodes::_ifne: 779 case Bytecodes::_ifnonnull: 780 case Bytecodes::_ifgt: 781 case Bytecodes::_ifge: 782 case Bytecodes::_if_icmpeq: 783 case Bytecodes::_if_icmpne: 784 case Bytecodes::_if_icmplt: 785 case Bytecodes::_if_icmpgt: 786 case Bytecodes::_if_icmple: 787 case Bytecodes::_if_icmpge: 788 case Bytecodes::_if_acmpeq: 789 case Bytecodes::_if_acmpne: 790 case Bytecodes::_goto: 791 case Bytecodes::_jsr: 792 if (bcs.dest() < bcs.next_bci()) { 793 return set_has_loops(); 794 } 795 break; 796 797 case Bytecodes::_goto_w: 798 case Bytecodes::_jsr_w: 799 if (bcs.dest_w() < bcs.next_bci()) { 800 return set_has_loops(); 801 } 802 break; 803 804 case Bytecodes::_lookupswitch: { 805 Bytecode_lookupswitch lookupswitch(this, bcs.bcp()); 806 if (lookupswitch.default_offset() < 0) { 807 return set_has_loops(); 808 } else { 809 for (int i = 0; i < lookupswitch.number_of_pairs(); ++i) { 810 LookupswitchPair pair = lookupswitch.pair_at(i); 811 if (pair.offset() < 0) { 812 return set_has_loops(); 813 } 814 } 815 } 816 break; 817 } 818 case Bytecodes::_tableswitch: { 819 Bytecode_tableswitch tableswitch(this, bcs.bcp()); 820 if (tableswitch.default_offset() < 0) { 821 return set_has_loops(); 822 } else { 823 for (int i = 0; i < tableswitch.length(); ++i) { 824 if (tableswitch.dest_offset_at(i) < 0) { 825 return set_has_loops(); 826 } 827 } 828 } 829 break; 830 } 831 default: 832 break; 833 } 834 } 835 836 _flags.set_has_loops_flag_init(true); 837 return false; 838 } 839 840 bool Method::is_final_method(AccessFlags class_access_flags) const { 841 // or "does_not_require_vtable_entry" 842 // default method or overpass can occur, is not final (reuses vtable entry) 843 // private methods in classes get vtable entries for backward class compatibility. 844 if (is_overpass() || is_default_method()) return false; 845 return is_final() || class_access_flags.is_final(); 846 } 847 848 bool Method::is_final_method() const { 849 return is_final_method(method_holder()->access_flags()); 850 } 851 852 bool Method::is_default_method() const { 853 if (method_holder() != nullptr && 854 method_holder()->is_interface() && 855 !is_abstract() && !is_private()) { 856 return true; 857 } else { 858 return false; 859 } 860 } 861 862 bool Method::can_be_statically_bound(AccessFlags class_access_flags) const { 863 if (is_final_method(class_access_flags)) return true; 864 #ifdef ASSERT 865 bool is_nonv = (vtable_index() == nonvirtual_vtable_index); 866 if (class_access_flags.is_interface()) { 867 ResourceMark rm; 868 assert(is_nonv == is_static() || is_nonv == is_private(), 869 "nonvirtual unexpected for non-static, non-private: %s", 870 name_and_sig_as_C_string()); 871 } 872 #endif 873 assert(valid_vtable_index() || valid_itable_index(), "method must be linked before we ask this question"); 874 return vtable_index() == nonvirtual_vtable_index; 875 } 876 877 bool Method::can_be_statically_bound() const { 878 return can_be_statically_bound(method_holder()->access_flags()); 879 } 880 881 bool Method::can_be_statically_bound(InstanceKlass* context) const { 882 return (method_holder() == context) && can_be_statically_bound(); 883 } 884 885 /** 886 * Returns false if this is one of specially treated methods for 887 * which we have to provide stack trace in throw in compiled code. 888 * Returns true otherwise. 889 */ 890 bool Method::can_omit_stack_trace() { 891 if (klass_name() == vmSymbols::sun_invoke_util_ValueConversions()) { 892 return false; // All methods in sun.invoke.util.ValueConversions 893 } 894 return true; 895 } 896 897 bool Method::is_accessor() const { 898 return is_getter() || is_setter(); 899 } 900 901 bool Method::is_getter() const { 902 if (code_size() != 5) return false; 903 if (size_of_parameters() != 1) return false; 904 if (java_code_at(0) != Bytecodes::_aload_0) return false; 905 if (java_code_at(1) != Bytecodes::_getfield) return false; 906 switch (java_code_at(4)) { 907 case Bytecodes::_ireturn: 908 case Bytecodes::_lreturn: 909 case Bytecodes::_freturn: 910 case Bytecodes::_dreturn: 911 case Bytecodes::_areturn: 912 break; 913 default: 914 return false; 915 } 916 return true; 917 } 918 919 bool Method::is_setter() const { 920 if (code_size() != 6) return false; 921 if (java_code_at(0) != Bytecodes::_aload_0) return false; 922 switch (java_code_at(1)) { 923 case Bytecodes::_iload_1: 924 case Bytecodes::_aload_1: 925 case Bytecodes::_fload_1: 926 if (size_of_parameters() != 2) return false; 927 break; 928 case Bytecodes::_dload_1: 929 case Bytecodes::_lload_1: 930 if (size_of_parameters() != 3) return false; 931 break; 932 default: 933 return false; 934 } 935 if (java_code_at(2) != Bytecodes::_putfield) return false; 936 if (java_code_at(5) != Bytecodes::_return) return false; 937 return true; 938 } 939 940 bool Method::is_constant_getter() const { 941 int last_index = code_size() - 1; 942 // Check if the first 1-3 bytecodes are a constant push 943 // and the last bytecode is a return. 944 return (2 <= code_size() && code_size() <= 4 && 945 Bytecodes::is_const(java_code_at(0)) && 946 Bytecodes::length_for(java_code_at(0)) == last_index && 947 Bytecodes::is_return(java_code_at(last_index))); 948 } 949 950 bool Method::has_valid_initializer_flags() const { 951 return (is_static() || 952 method_holder()->major_version() < 51); 953 } 954 955 bool Method::is_static_initializer() const { 956 // For classfiles version 51 or greater, ensure that the clinit method is 957 // static. Non-static methods with the name "<clinit>" are not static 958 // initializers. (older classfiles exempted for backward compatibility) 959 return name() == vmSymbols::class_initializer_name() && 960 has_valid_initializer_flags(); 961 } 962 963 bool Method::is_object_initializer() const { 964 return name() == vmSymbols::object_initializer_name(); 965 } 966 967 bool Method::needs_clinit_barrier() const { 968 return is_static() && !method_holder()->is_initialized(); 969 } 970 971 bool Method::code_has_clinit_barriers() const { 972 nmethod* nm = code(); 973 return (nm != nullptr) && nm->has_clinit_barriers(); 974 } 975 976 bool Method::is_object_wait0() const { 977 return klass_name() == vmSymbols::java_lang_Object() 978 && name() == vmSymbols::wait_name(); 979 } 980 981 objArrayHandle Method::resolved_checked_exceptions_impl(Method* method, TRAPS) { 982 int length = method->checked_exceptions_length(); 983 if (length == 0) { // common case 984 return objArrayHandle(THREAD, Universe::the_empty_class_array()); 985 } else { 986 methodHandle h_this(THREAD, method); 987 objArrayOop m_oop = oopFactory::new_objArray(vmClasses::Class_klass(), length, CHECK_(objArrayHandle())); 988 objArrayHandle mirrors (THREAD, m_oop); 989 for (int i = 0; i < length; i++) { 990 CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe 991 Klass* k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle())); 992 if (log_is_enabled(Warning, exceptions) && 993 !k->is_subclass_of(vmClasses::Throwable_klass())) { 994 ResourceMark rm(THREAD); 995 log_warning(exceptions)( 996 "Class %s in throws clause of method %s is not a subtype of class java.lang.Throwable", 997 k->external_name(), method->external_name()); 998 } 999 mirrors->obj_at_put(i, k->java_mirror()); 1000 } 1001 return mirrors; 1002 } 1003 }; 1004 1005 1006 int Method::line_number_from_bci(int bci) const { 1007 int best_bci = 0; 1008 int best_line = -1; 1009 if (bci == SynchronizationEntryBCI) bci = 0; 1010 if (0 <= bci && bci < code_size() && has_linenumber_table()) { 1011 // The line numbers are a short array of 2-tuples [start_pc, line_number]. 1012 // Not necessarily sorted and not necessarily one-to-one. 1013 CompressedLineNumberReadStream stream(compressed_linenumber_table()); 1014 while (stream.read_pair()) { 1015 if (stream.bci() == bci) { 1016 // perfect match 1017 return stream.line(); 1018 } else { 1019 // update best_bci/line 1020 if (stream.bci() < bci && stream.bci() >= best_bci) { 1021 best_bci = stream.bci(); 1022 best_line = stream.line(); 1023 } 1024 } 1025 } 1026 } 1027 return best_line; 1028 } 1029 1030 1031 bool Method::is_klass_loaded_by_klass_index(int klass_index) const { 1032 if( constants()->tag_at(klass_index).is_unresolved_klass() ) { 1033 Thread *thread = Thread::current(); 1034 Symbol* klass_name = constants()->klass_name_at(klass_index); 1035 Handle loader(thread, method_holder()->class_loader()); 1036 return SystemDictionary::find_instance_klass(thread, klass_name, loader) != nullptr; 1037 } else { 1038 return true; 1039 } 1040 } 1041 1042 1043 bool Method::is_klass_loaded(int refinfo_index, Bytecodes::Code bc, bool must_be_resolved) const { 1044 int klass_index = constants()->klass_ref_index_at(refinfo_index, bc); 1045 if (must_be_resolved) { 1046 // Make sure klass is resolved in constantpool. 1047 if (constants()->tag_at(klass_index).is_unresolved_klass()) return false; 1048 } 1049 return is_klass_loaded_by_klass_index(klass_index); 1050 } 1051 1052 1053 void Method::set_native_function(address function, bool post_event_flag) { 1054 assert(function != nullptr, "use clear_native_function to unregister natives"); 1055 assert(!is_special_native_intrinsic() || function == SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), ""); 1056 address* native_function = native_function_addr(); 1057 1058 // We can see racers trying to place the same native function into place. Once 1059 // is plenty. 1060 address current = *native_function; 1061 if (current == function) return; 1062 if (post_event_flag && JvmtiExport::should_post_native_method_bind() && 1063 function != nullptr) { 1064 // native_method_throw_unsatisfied_link_error_entry() should only 1065 // be passed when post_event_flag is false. 1066 assert(function != 1067 SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), 1068 "post_event_flag mismatch"); 1069 1070 // post the bind event, and possible change the bind function 1071 JvmtiExport::post_native_method_bind(this, &function); 1072 } 1073 *native_function = function; 1074 // This function can be called more than once. We must make sure that we always 1075 // use the latest registered method -> check if a stub already has been generated. 1076 // If so, we have to make it not_entrant. 1077 nmethod* nm = code(); // Put it into local variable to guard against concurrent updates 1078 if (nm != nullptr) { 1079 nm->make_not_entrant(nmethod::InvalidationReason::SET_NATIVE_FUNCTION); 1080 } 1081 } 1082 1083 1084 bool Method::has_native_function() const { 1085 if (is_special_native_intrinsic()) 1086 return false; // special-cased in SharedRuntime::generate_native_wrapper 1087 address func = native_function(); 1088 return (func != nullptr && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry()); 1089 } 1090 1091 1092 void Method::clear_native_function() { 1093 // Note: is_method_handle_intrinsic() is allowed here. 1094 set_native_function( 1095 SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), 1096 !native_bind_event_is_interesting); 1097 this->unlink_code(); 1098 } 1099 1100 1101 void Method::set_signature_handler(address handler) { 1102 address* signature_handler = signature_handler_addr(); 1103 *signature_handler = handler; 1104 } 1105 1106 1107 void Method::print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason) { 1108 assert(reason != nullptr, "must provide a reason"); 1109 if (PrintCompilation && report) { 1110 ttyLocker ttyl; 1111 tty->print("made not %scompilable on ", is_osr ? "OSR " : ""); 1112 if (comp_level == CompLevel_all) { 1113 tty->print("all levels "); 1114 } else { 1115 tty->print("level %d ", comp_level); 1116 } 1117 this->print_short_name(tty); 1118 int size = this->code_size(); 1119 if (size > 0) { 1120 tty->print(" (%d bytes)", size); 1121 } 1122 if (reason != nullptr) { 1123 tty->print(" %s", reason); 1124 } 1125 tty->cr(); 1126 } 1127 if ((TraceDeoptimization || LogCompilation) && (xtty != nullptr)) { 1128 ttyLocker ttyl; 1129 xtty->begin_elem("make_not_compilable thread='%zu' osr='%d' level='%d'", 1130 os::current_thread_id(), is_osr, comp_level); 1131 if (reason != nullptr) { 1132 xtty->print(" reason=\'%s\'", reason); 1133 } 1134 xtty->method(this); 1135 xtty->stamp(); 1136 xtty->end_elem(); 1137 } 1138 } 1139 1140 bool Method::is_always_compilable() const { 1141 // Generated adapters must be compiled 1142 if (is_special_native_intrinsic() && is_synthetic()) { 1143 assert(!is_not_c1_compilable(), "sanity check"); 1144 assert(!is_not_c2_compilable(), "sanity check"); 1145 return true; 1146 } 1147 1148 return false; 1149 } 1150 1151 bool Method::is_not_compilable(int comp_level) const { 1152 if (number_of_breakpoints() > 0) 1153 return true; 1154 if (is_always_compilable()) 1155 return false; 1156 if (comp_level == CompLevel_any) 1157 return is_not_c1_compilable() && is_not_c2_compilable(); 1158 if (is_c1_compile(comp_level)) 1159 return is_not_c1_compilable(); 1160 if (is_c2_compile(comp_level)) 1161 return is_not_c2_compilable(); 1162 return false; 1163 } 1164 1165 // call this when compiler finds that this method is not compilable 1166 void Method::set_not_compilable(const char* reason, int comp_level, bool report) { 1167 if (is_always_compilable()) { 1168 // Don't mark a method which should be always compilable 1169 return; 1170 } 1171 print_made_not_compilable(comp_level, /*is_osr*/ false, report, reason); 1172 if (comp_level == CompLevel_all) { 1173 set_is_not_c1_compilable(); 1174 set_is_not_c2_compilable(); 1175 } else { 1176 if (is_c1_compile(comp_level)) 1177 set_is_not_c1_compilable(); 1178 if (is_c2_compile(comp_level)) 1179 set_is_not_c2_compilable(); 1180 } 1181 assert(!CompilationPolicy::can_be_compiled(methodHandle(Thread::current(), this), comp_level), "sanity check"); 1182 } 1183 1184 bool Method::is_not_osr_compilable(int comp_level) const { 1185 if (is_not_compilable(comp_level)) 1186 return true; 1187 if (comp_level == CompLevel_any) 1188 return is_not_c1_osr_compilable() && is_not_c2_osr_compilable(); 1189 if (is_c1_compile(comp_level)) 1190 return is_not_c1_osr_compilable(); 1191 if (is_c2_compile(comp_level)) 1192 return is_not_c2_osr_compilable(); 1193 return false; 1194 } 1195 1196 void Method::set_not_osr_compilable(const char* reason, int comp_level, bool report) { 1197 print_made_not_compilable(comp_level, /*is_osr*/ true, report, reason); 1198 if (comp_level == CompLevel_all) { 1199 set_is_not_c1_osr_compilable(); 1200 set_is_not_c2_osr_compilable(); 1201 } else { 1202 if (is_c1_compile(comp_level)) 1203 set_is_not_c1_osr_compilable(); 1204 if (is_c2_compile(comp_level)) 1205 set_is_not_c2_osr_compilable(); 1206 } 1207 assert(!CompilationPolicy::can_be_osr_compiled(methodHandle(Thread::current(), this), comp_level), "sanity check"); 1208 } 1209 1210 // Revert to using the interpreter and clear out the nmethod 1211 void Method::clear_code() { 1212 // this may be null if c2i adapters have not been made yet 1213 // Only should happen at allocate time. 1214 if (adapter() == nullptr) { 1215 _from_compiled_entry = nullptr; 1216 } else { 1217 _from_compiled_entry = adapter()->get_c2i_entry(); 1218 } 1219 OrderAccess::storestore(); 1220 _from_interpreted_entry = _i2i_entry; 1221 OrderAccess::storestore(); 1222 _code = nullptr; 1223 } 1224 1225 void Method::unlink_code(nmethod *compare) { 1226 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 1227 // We need to check if either the _code or _from_compiled_code_entry_point 1228 // refer to this nmethod because there is a race in setting these two fields 1229 // in Method* as seen in bugid 4947125. 1230 if (code() == compare || 1231 from_compiled_entry() == compare->verified_entry_point()) { 1232 clear_code(); 1233 } 1234 } 1235 1236 void Method::unlink_code() { 1237 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 1238 clear_code(); 1239 } 1240 1241 #if INCLUDE_CDS 1242 // Called by class data sharing to remove any entry points (which are not shared) 1243 void Method::unlink_method() { 1244 assert(CDSConfig::is_dumping_archive(), "sanity"); 1245 _code = nullptr; 1246 if (!CDSConfig::is_dumping_adapters()) { 1247 _adapter = nullptr; 1248 } 1249 _i2i_entry = nullptr; 1250 _from_compiled_entry = nullptr; 1251 _from_interpreted_entry = nullptr; 1252 1253 if (is_native()) { 1254 *native_function_addr() = nullptr; 1255 set_signature_handler(nullptr); 1256 } 1257 NOT_PRODUCT(set_compiled_invocation_count(0);) 1258 1259 clear_method_data(); 1260 clear_method_counters(); 1261 clear_is_not_c1_compilable(); 1262 clear_is_not_c1_osr_compilable(); 1263 clear_is_not_c2_compilable(); 1264 clear_is_not_c2_osr_compilable(); 1265 clear_queued_for_compilation(); 1266 set_pending_queue_processed(false); 1267 1268 remove_unshareable_flags(); 1269 } 1270 1271 void Method::remove_unshareable_flags() { 1272 // clear all the flags that shouldn't be in the archived version 1273 assert(!is_old(), "must be"); 1274 assert(!is_obsolete(), "must be"); 1275 assert(!is_deleted(), "must be"); 1276 1277 set_is_prefixed_native(false); 1278 set_queued_for_compilation(false); 1279 set_pending_queue_processed(false); 1280 set_is_not_c2_compilable(false); 1281 set_is_not_c1_compilable(false); 1282 set_is_not_c2_osr_compilable(false); 1283 set_on_stack_flag(false); 1284 set_has_upcall_on_method_entry(false); 1285 set_has_upcall_on_method_exit(false); 1286 } 1287 #endif 1288 1289 // Called when the method_holder is getting linked. Setup entrypoints so the method 1290 // is ready to be called from interpreter, compiler, and vtables. 1291 void Method::link_method(const methodHandle& h_method, TRAPS) { 1292 if (log_is_enabled(Info, perf, class, link)) { 1293 ClassLoader::perf_ik_link_methods_count()->inc(); 1294 } 1295 1296 // If the code cache is full, we may reenter this function for the 1297 // leftover methods that weren't linked. 1298 if (adapter() != nullptr) { 1299 if (adapter()->in_aot_cache()) { 1300 assert(adapter()->is_linked(), "Adapter is shared but not linked"); 1301 } else { 1302 return; 1303 } 1304 } 1305 assert( _code == nullptr, "nothing compiled yet" ); 1306 1307 // Setup interpreter entrypoint 1308 assert(this == h_method(), "wrong h_method()" ); 1309 1310 assert(adapter() == nullptr || adapter()->is_linked(), "init'd to null or restored from cache"); 1311 address entry = Interpreter::entry_for_method(h_method); 1312 assert(entry != nullptr, "interpreter entry must be non-null"); 1313 // Sets both _i2i_entry and _from_interpreted_entry 1314 set_interpreter_entry(entry); 1315 1316 // Don't overwrite already registered native entries. 1317 if (is_native() && !has_native_function()) { 1318 set_native_function( 1319 SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), 1320 !native_bind_event_is_interesting); 1321 } 1322 1323 // Setup compiler entrypoint. This is made eagerly, so we do not need 1324 // special handling of vtables. An alternative is to make adapters more 1325 // lazily by calling make_adapter() from from_compiled_entry() for the 1326 // normal calls. For vtable calls life gets more complicated. When a 1327 // call-site goes mega-morphic we need adapters in all methods which can be 1328 // called from the vtable. We need adapters on such methods that get loaded 1329 // later. Ditto for mega-morphic itable calls. If this proves to be a 1330 // problem we'll make these lazily later. 1331 if (is_abstract()) { 1332 h_method->_from_compiled_entry = SharedRuntime::get_handle_wrong_method_abstract_stub(); 1333 } else if (_adapter == nullptr) { 1334 (void) make_adapters(h_method, CHECK); 1335 assert(adapter()->is_linked(), "Adapter must have been linked"); 1336 h_method->_from_compiled_entry = adapter()->get_c2i_entry(); 1337 } 1338 1339 // ONLY USE the h_method now as make_adapter may have blocked 1340 1341 if (h_method->is_continuation_native_intrinsic()) { 1342 _from_interpreted_entry = nullptr; 1343 _from_compiled_entry = nullptr; 1344 _i2i_entry = nullptr; 1345 if (Continuations::enabled()) { 1346 assert(!Threads::is_vm_complete(), "should only be called during vm init"); 1347 AdapterHandlerLibrary::create_native_wrapper(h_method); 1348 if (!h_method->has_compiled_code()) { 1349 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Initial size of CodeCache is too small"); 1350 } 1351 assert(_from_interpreted_entry == get_i2c_entry(), "invariant"); 1352 } 1353 } 1354 if (_preload_code != nullptr && !_aot_code_entry->not_entrant()) { 1355 MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag); 1356 set_code(h_method, _preload_code); 1357 assert(((nmethod*)_preload_code)->aot_code_entry() == _aot_code_entry, "sanity"); 1358 } 1359 } 1360 1361 address Method::make_adapters(const methodHandle& mh, TRAPS) { 1362 assert(!mh->is_abstract(), "abstract methods do not have adapters"); 1363 PerfTraceElapsedTime timer(ClassLoader::perf_method_adapters_time()); 1364 1365 // Adapters for compiled code are made eagerly here. They are fairly 1366 // small (generally < 100 bytes) and quick to make (and cached and shared) 1367 // so making them eagerly shouldn't be too expensive. 1368 AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh); 1369 if (adapter == nullptr ) { 1370 if (!is_init_completed()) { 1371 // Don't throw exceptions during VM initialization because java.lang.* classes 1372 // might not have been initialized, causing problems when constructing the 1373 // Java exception object. 1374 vm_exit_during_initialization("Out of space in CodeCache for adapters"); 1375 } else { 1376 THROW_MSG_NULL(vmSymbols::java_lang_OutOfMemoryError(), "Out of space in CodeCache for adapters"); 1377 } 1378 } 1379 1380 mh->set_adapter_entry(adapter); 1381 return adapter->get_c2i_entry(); 1382 } 1383 1384 // The verified_code_entry() must be called when a invoke is resolved 1385 // on this method. 1386 1387 // It returns the compiled code entry point, after asserting not null. 1388 // This function is called after potential safepoints so that nmethod 1389 // or adapter that it points to is still live and valid. 1390 // This function must not hit a safepoint! 1391 address Method::verified_code_entry() { 1392 DEBUG_ONLY(NoSafepointVerifier nsv;) 1393 assert(_from_compiled_entry != nullptr, "must be set"); 1394 return _from_compiled_entry; 1395 } 1396 1397 // Check that if an nmethod ref exists, it has a backlink to this or no backlink at all 1398 // (could be racing a deopt). 1399 // Not inline to avoid circular ref. 1400 bool Method::check_code() const { 1401 // cached in a register or local. There's a race on the value of the field. 1402 nmethod *code = Atomic::load_acquire(&_code); 1403 return code == nullptr || (code->method() == nullptr) || (code->method() == (Method*)this && !code->is_osr_method()); 1404 } 1405 1406 // Install compiled code. Instantly it can execute. 1407 void Method::set_code(const methodHandle& mh, nmethod *code) { 1408 assert_lock_strong(NMethodState_lock); 1409 assert( code, "use clear_code to remove code" ); 1410 assert( mh->check_code(), "" ); 1411 1412 guarantee(mh->adapter() != nullptr, "Adapter blob must already exist!"); 1413 1414 // These writes must happen in this order, because the interpreter will 1415 // directly jump to from_interpreted_entry which jumps to an i2c adapter 1416 // which jumps to _from_compiled_entry. 1417 mh->_code = code; // Assign before allowing compiled code to exec 1418 1419 int comp_level = code->comp_level(); 1420 // In theory there could be a race here. In practice it is unlikely 1421 // and not worth worrying about. 1422 if (comp_level > mh->highest_comp_level()) { 1423 mh->set_highest_comp_level(comp_level); 1424 } 1425 1426 OrderAccess::storestore(); 1427 mh->_from_compiled_entry = code->verified_entry_point(); 1428 OrderAccess::storestore(); 1429 1430 if (mh->is_continuation_native_intrinsic()) { 1431 assert(mh->_from_interpreted_entry == nullptr, "initialized incorrectly"); // see link_method 1432 1433 if (mh->is_continuation_enter_intrinsic()) { 1434 // This is the entry used when we're in interpreter-only mode; see InterpreterMacroAssembler::jump_from_interpreted 1435 mh->_i2i_entry = ContinuationEntry::interpreted_entry(); 1436 } else if (mh->is_continuation_yield_intrinsic()) { 1437 mh->_i2i_entry = mh->get_i2c_entry(); 1438 } else { 1439 guarantee(false, "Unknown Continuation native intrinsic"); 1440 } 1441 // This must come last, as it is what's tested in LinkResolver::resolve_static_call 1442 Atomic::release_store(&mh->_from_interpreted_entry , mh->get_i2c_entry()); 1443 } else if (!mh->is_method_handle_intrinsic()) { 1444 // Instantly compiled code can execute. 1445 mh->_from_interpreted_entry = mh->get_i2c_entry(); 1446 } 1447 } 1448 1449 1450 bool Method::is_overridden_in(Klass* k) const { 1451 InstanceKlass* ik = InstanceKlass::cast(k); 1452 1453 if (ik->is_interface()) return false; 1454 1455 // If method is an interface, we skip it - except if it 1456 // is a miranda method 1457 if (method_holder()->is_interface()) { 1458 // Check that method is not a miranda method 1459 if (ik->lookup_method(name(), signature()) == nullptr) { 1460 // No implementation exist - so miranda method 1461 return false; 1462 } 1463 return true; 1464 } 1465 1466 assert(ik->is_subclass_of(method_holder()), "should be subklass"); 1467 if (!has_vtable_index()) { 1468 return false; 1469 } else { 1470 Method* vt_m = ik->method_at_vtable(vtable_index()); 1471 return vt_m != this; 1472 } 1473 } 1474 1475 1476 // give advice about whether this Method* should be cached or not 1477 bool Method::should_not_be_cached() const { 1478 if (is_old()) { 1479 // This method has been redefined. It is either EMCP or obsolete 1480 // and we don't want to cache it because that would pin the method 1481 // down and prevent it from being collectible if and when it 1482 // finishes executing. 1483 return true; 1484 } 1485 1486 // caching this method should be just fine 1487 return false; 1488 } 1489 1490 1491 /** 1492 * Returns true if this is one of the specially treated methods for 1493 * security related stack walks (like Reflection.getCallerClass). 1494 */ 1495 bool Method::is_ignored_by_security_stack_walk() const { 1496 if (intrinsic_id() == vmIntrinsics::_invoke) { 1497 // This is Method.invoke() -- ignore it 1498 return true; 1499 } 1500 if (method_holder()->is_subclass_of(vmClasses::reflect_MethodAccessorImpl_klass())) { 1501 // This is an auxiliary frame -- ignore it 1502 return true; 1503 } 1504 if (is_method_handle_intrinsic() || is_compiled_lambda_form()) { 1505 // This is an internal adapter frame for method handles -- ignore it 1506 return true; 1507 } 1508 return false; 1509 } 1510 1511 1512 // Constant pool structure for invoke methods: 1513 enum { 1514 _imcp_invoke_name = 1, // utf8: 'invokeExact', etc. 1515 _imcp_invoke_signature, // utf8: (variable Symbol*) 1516 _imcp_limit 1517 }; 1518 1519 // Test if this method is an MH adapter frame generated by Java code. 1520 // Cf. java/lang/invoke/InvokerBytecodeGenerator 1521 bool Method::is_compiled_lambda_form() const { 1522 return intrinsic_id() == vmIntrinsics::_compiledLambdaForm; 1523 } 1524 1525 // Test if this method is an internal MH primitive method. 1526 bool Method::is_method_handle_intrinsic() const { 1527 vmIntrinsics::ID iid = intrinsic_id(); 1528 return (MethodHandles::is_signature_polymorphic(iid) && 1529 MethodHandles::is_signature_polymorphic_intrinsic(iid)); 1530 } 1531 1532 bool Method::has_member_arg() const { 1533 vmIntrinsics::ID iid = intrinsic_id(); 1534 return (MethodHandles::is_signature_polymorphic(iid) && 1535 MethodHandles::has_member_arg(iid)); 1536 } 1537 1538 // Make an instance of a signature-polymorphic internal MH primitive. 1539 methodHandle Method::make_method_handle_intrinsic(vmIntrinsics::ID iid, 1540 Symbol* signature, 1541 TRAPS) { 1542 ResourceMark rm(THREAD); 1543 methodHandle empty; 1544 1545 InstanceKlass* holder = vmClasses::MethodHandle_klass(); 1546 Symbol* name = MethodHandles::signature_polymorphic_intrinsic_name(iid); 1547 assert(iid == MethodHandles::signature_polymorphic_name_id(name), ""); 1548 1549 log_info(methodhandles)("make_method_handle_intrinsic MH.%s%s", name->as_C_string(), signature->as_C_string()); 1550 1551 // invariant: cp->symbol_at_put is preceded by a refcount increment (more usually a lookup) 1552 name->increment_refcount(); 1553 signature->increment_refcount(); 1554 1555 int cp_length = _imcp_limit; 1556 ClassLoaderData* loader_data = holder->class_loader_data(); 1557 constantPoolHandle cp; 1558 { 1559 ConstantPool* cp_oop = ConstantPool::allocate(loader_data, cp_length, CHECK_(empty)); 1560 cp = constantPoolHandle(THREAD, cp_oop); 1561 } 1562 cp->copy_fields(holder->constants()); 1563 cp->set_pool_holder(holder); 1564 cp->symbol_at_put(_imcp_invoke_name, name); 1565 cp->symbol_at_put(_imcp_invoke_signature, signature); 1566 cp->set_has_preresolution(); 1567 cp->set_is_for_method_handle_intrinsic(); 1568 1569 // decide on access bits: public or not? 1570 u2 flags_bits = (JVM_ACC_NATIVE | JVM_ACC_SYNTHETIC | JVM_ACC_FINAL); 1571 bool must_be_static = MethodHandles::is_signature_polymorphic_static(iid); 1572 if (must_be_static) flags_bits |= JVM_ACC_STATIC; 1573 assert((flags_bits & JVM_ACC_PUBLIC) == 0, "do not expose these methods"); 1574 1575 methodHandle m; 1576 { 1577 InlineTableSizes sizes; 1578 Method* m_oop = Method::allocate(loader_data, 0, 1579 accessFlags_from(flags_bits), &sizes, 1580 ConstMethod::NORMAL, 1581 name, 1582 CHECK_(empty)); 1583 m = methodHandle(THREAD, m_oop); 1584 } 1585 m->set_constants(cp()); 1586 m->set_name_index(_imcp_invoke_name); 1587 m->set_signature_index(_imcp_invoke_signature); 1588 assert(MethodHandles::is_signature_polymorphic_name(m->name()), ""); 1589 assert(m->signature() == signature, ""); 1590 m->constMethod()->compute_from_signature(signature, must_be_static); 1591 m->init_intrinsic_id(klass_id_for_intrinsics(m->method_holder())); 1592 assert(m->is_method_handle_intrinsic(), ""); 1593 #ifdef ASSERT 1594 if (!MethodHandles::is_signature_polymorphic(m->intrinsic_id())) m->print(); 1595 assert(MethodHandles::is_signature_polymorphic(m->intrinsic_id()), "must be an invoker"); 1596 assert(m->intrinsic_id() == iid, "correctly predicted iid"); 1597 #endif //ASSERT 1598 1599 // Finally, set up its entry points. 1600 assert(m->can_be_statically_bound(), ""); 1601 m->set_vtable_index(Method::nonvirtual_vtable_index); 1602 m->link_method(m, CHECK_(empty)); 1603 1604 if (iid == vmIntrinsics::_linkToNative) { 1605 m->set_interpreter_entry(m->adapter()->get_i2c_entry()); 1606 } 1607 if (log_is_enabled(Debug, methodhandles)) { 1608 LogTarget(Debug, methodhandles) lt; 1609 LogStream ls(lt); 1610 m->print_on(&ls); 1611 } 1612 1613 return m; 1614 } 1615 1616 #if INCLUDE_CDS 1617 void Method::restore_archived_method_handle_intrinsic(methodHandle m, TRAPS) { 1618 if (m->adapter() != nullptr) { 1619 m->set_from_compiled_entry(m->adapter()->get_c2i_entry()); 1620 } 1621 m->link_method(m, CHECK); 1622 1623 if (m->intrinsic_id() == vmIntrinsics::_linkToNative) { 1624 m->set_interpreter_entry(m->adapter()->get_i2c_entry()); 1625 } 1626 } 1627 #endif 1628 1629 Klass* Method::check_non_bcp_klass(Klass* klass) { 1630 if (klass != nullptr && klass->class_loader() != nullptr) { 1631 if (klass->is_objArray_klass()) 1632 klass = ObjArrayKlass::cast(klass)->bottom_klass(); 1633 return klass; 1634 } 1635 return nullptr; 1636 } 1637 1638 1639 methodHandle Method::clone_with_new_data(const methodHandle& m, u_char* new_code, int new_code_length, 1640 u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) { 1641 // Code below does not work for native methods - they should never get rewritten anyway 1642 assert(!m->is_native(), "cannot rewrite native methods"); 1643 // Allocate new Method* 1644 AccessFlags flags = m->access_flags(); 1645 1646 ConstMethod* cm = m->constMethod(); 1647 int checked_exceptions_len = cm->checked_exceptions_length(); 1648 int localvariable_len = cm->localvariable_table_length(); 1649 int exception_table_len = cm->exception_table_length(); 1650 int method_parameters_len = cm->method_parameters_length(); 1651 int method_annotations_len = cm->method_annotations_length(); 1652 int parameter_annotations_len = cm->parameter_annotations_length(); 1653 int type_annotations_len = cm->type_annotations_length(); 1654 int default_annotations_len = cm->default_annotations_length(); 1655 1656 InlineTableSizes sizes( 1657 localvariable_len, 1658 new_compressed_linenumber_size, 1659 exception_table_len, 1660 checked_exceptions_len, 1661 method_parameters_len, 1662 cm->generic_signature_index(), 1663 method_annotations_len, 1664 parameter_annotations_len, 1665 type_annotations_len, 1666 default_annotations_len, 1667 0); 1668 1669 ClassLoaderData* loader_data = m->method_holder()->class_loader_data(); 1670 Method* newm_oop = Method::allocate(loader_data, 1671 new_code_length, 1672 flags, 1673 &sizes, 1674 m->method_type(), 1675 m->name(), 1676 CHECK_(methodHandle())); 1677 methodHandle newm (THREAD, newm_oop); 1678 1679 // Create a shallow copy of Method part, but be careful to preserve the new ConstMethod* 1680 ConstMethod* newcm = newm->constMethod(); 1681 int new_const_method_size = newm->constMethod()->size(); 1682 1683 // This works because the source and target are both Methods. Some compilers 1684 // (e.g., clang) complain that the target vtable pointer will be stomped, 1685 // so cast away newm()'s and m()'s Methodness. 1686 memcpy((void*)newm(), (void*)m(), sizeof(Method)); 1687 1688 // Create shallow copy of ConstMethod. 1689 memcpy(newcm, m->constMethod(), sizeof(ConstMethod)); 1690 1691 // Reset correct method/const method, method size, and parameter info 1692 newm->set_constMethod(newcm); 1693 newm->constMethod()->set_code_size(new_code_length); 1694 newm->constMethod()->set_constMethod_size(new_const_method_size); 1695 assert(newm->code_size() == new_code_length, "check"); 1696 assert(newm->method_parameters_length() == method_parameters_len, "check"); 1697 assert(newm->checked_exceptions_length() == checked_exceptions_len, "check"); 1698 assert(newm->exception_table_length() == exception_table_len, "check"); 1699 assert(newm->localvariable_table_length() == localvariable_len, "check"); 1700 // Copy new byte codes 1701 memcpy(newm->code_base(), new_code, new_code_length); 1702 // Copy line number table 1703 if (new_compressed_linenumber_size > 0) { 1704 memcpy(newm->compressed_linenumber_table(), 1705 new_compressed_linenumber_table, 1706 new_compressed_linenumber_size); 1707 } 1708 // Copy method_parameters 1709 if (method_parameters_len > 0) { 1710 memcpy(newm->method_parameters_start(), 1711 m->method_parameters_start(), 1712 method_parameters_len * sizeof(MethodParametersElement)); 1713 } 1714 // Copy checked_exceptions 1715 if (checked_exceptions_len > 0) { 1716 memcpy(newm->checked_exceptions_start(), 1717 m->checked_exceptions_start(), 1718 checked_exceptions_len * sizeof(CheckedExceptionElement)); 1719 } 1720 // Copy exception table 1721 if (exception_table_len > 0) { 1722 memcpy(newm->exception_table_start(), 1723 m->exception_table_start(), 1724 exception_table_len * sizeof(ExceptionTableElement)); 1725 } 1726 // Copy local variable number table 1727 if (localvariable_len > 0) { 1728 memcpy(newm->localvariable_table_start(), 1729 m->localvariable_table_start(), 1730 localvariable_len * sizeof(LocalVariableTableElement)); 1731 } 1732 // Copy stackmap table 1733 if (m->has_stackmap_table()) { 1734 int code_attribute_length = m->stackmap_data()->length(); 1735 Array<u1>* stackmap_data = 1736 MetadataFactory::new_array<u1>(loader_data, code_attribute_length, 0, CHECK_(methodHandle())); 1737 memcpy((void*)stackmap_data->adr_at(0), 1738 (void*)m->stackmap_data()->adr_at(0), code_attribute_length); 1739 newm->set_stackmap_data(stackmap_data); 1740 } 1741 1742 // copy annotations over to new method 1743 newcm->copy_annotations_from(loader_data, cm, CHECK_(methodHandle())); 1744 return newm; 1745 } 1746 1747 vmSymbolID Method::klass_id_for_intrinsics(const Klass* holder) { 1748 // if loader is not the default loader (i.e., non-null), we can't know the intrinsics 1749 // because we are not loading from core libraries 1750 // exception: the AES intrinsics come from lib/ext/sunjce_provider.jar 1751 // which does not use the class default class loader so we check for its loader here 1752 const InstanceKlass* ik = InstanceKlass::cast(holder); 1753 if ((ik->class_loader() != nullptr) && !SystemDictionary::is_platform_class_loader(ik->class_loader())) { 1754 return vmSymbolID::NO_SID; // regardless of name, no intrinsics here 1755 } 1756 1757 // see if the klass name is well-known: 1758 Symbol* klass_name = ik->name(); 1759 vmSymbolID id = vmSymbols::find_sid(klass_name); 1760 if (id != vmSymbolID::NO_SID && vmIntrinsics::class_has_intrinsics(id)) { 1761 return id; 1762 } else { 1763 return vmSymbolID::NO_SID; 1764 } 1765 } 1766 1767 void Method::init_intrinsic_id(vmSymbolID klass_id) { 1768 assert(_intrinsic_id == static_cast<int>(vmIntrinsics::_none), "do this just once"); 1769 const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte)); 1770 assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size"); 1771 assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), ""); 1772 1773 // the klass name is well-known: 1774 assert(klass_id == klass_id_for_intrinsics(method_holder()), "must be"); 1775 assert(klass_id != vmSymbolID::NO_SID, "caller responsibility"); 1776 1777 // ditto for method and signature: 1778 vmSymbolID name_id = vmSymbols::find_sid(name()); 1779 if (klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle) 1780 && klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle) 1781 && name_id == vmSymbolID::NO_SID) { 1782 return; 1783 } 1784 vmSymbolID sig_id = vmSymbols::find_sid(signature()); 1785 if (klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle) 1786 && klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle) 1787 && sig_id == vmSymbolID::NO_SID) { 1788 return; 1789 } 1790 1791 u2 flags = access_flags().as_method_flags(); 1792 vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags); 1793 if (id != vmIntrinsics::_none) { 1794 set_intrinsic_id(id); 1795 if (id == vmIntrinsics::_Class_cast) { 1796 // Even if the intrinsic is rejected, we want to inline this simple method. 1797 set_force_inline(); 1798 } 1799 return; 1800 } 1801 1802 // A few slightly irregular cases: 1803 switch (klass_id) { 1804 // Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*., VarHandle 1805 case VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle): 1806 case VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle): 1807 if (!is_native()) break; 1808 id = MethodHandles::signature_polymorphic_name_id(method_holder(), name()); 1809 if (is_static() != MethodHandles::is_signature_polymorphic_static(id)) 1810 id = vmIntrinsics::_none; 1811 break; 1812 1813 default: 1814 break; 1815 } 1816 1817 if (id != vmIntrinsics::_none) { 1818 // Set up its iid. It is an alias method. 1819 set_intrinsic_id(id); 1820 return; 1821 } 1822 } 1823 1824 bool Method::load_signature_classes(const methodHandle& m, TRAPS) { 1825 if (!THREAD->can_call_java()) { 1826 // There is nothing useful this routine can do from within the Compile thread. 1827 // Hopefully, the signature contains only well-known classes. 1828 // We could scan for this and return true/false, but the caller won't care. 1829 return false; 1830 } 1831 bool sig_is_loaded = true; 1832 ResourceMark rm(THREAD); 1833 for (ResolvingSignatureStream ss(m()); !ss.is_done(); ss.next()) { 1834 if (ss.is_reference()) { 1835 // load everything, including arrays "[Lfoo;" 1836 Klass* klass = ss.as_klass(SignatureStream::ReturnNull, THREAD); 1837 // We are loading classes eagerly. If a ClassNotFoundException or 1838 // a LinkageError was generated, be sure to ignore it. 1839 if (HAS_PENDING_EXCEPTION) { 1840 if (PENDING_EXCEPTION->is_a(vmClasses::ClassNotFoundException_klass()) || 1841 PENDING_EXCEPTION->is_a(vmClasses::LinkageError_klass())) { 1842 CLEAR_PENDING_EXCEPTION; 1843 } else { 1844 return false; 1845 } 1846 } 1847 if( klass == nullptr) { sig_is_loaded = false; } 1848 } 1849 } 1850 return sig_is_loaded; 1851 } 1852 1853 // Exposed so field engineers can debug VM 1854 void Method::print_short_name(outputStream* st) const { 1855 ResourceMark rm; 1856 #ifdef PRODUCT 1857 st->print(" %s::", method_holder()->external_name()); 1858 #else 1859 st->print(" %s::", method_holder()->internal_name()); 1860 #endif 1861 name()->print_symbol_on(st); 1862 if (WizardMode) signature()->print_symbol_on(st); 1863 else if (MethodHandles::is_signature_polymorphic(intrinsic_id())) 1864 MethodHandles::print_as_basic_type_signature_on(st, signature()); 1865 } 1866 1867 // Comparer for sorting an object array containing 1868 // Method*s. 1869 static int method_comparator(Method* a, Method* b) { 1870 return a->name()->fast_compare(b->name()); 1871 } 1872 1873 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array 1874 // default_methods also uses this without the ordering for fast find_method 1875 void Method::sort_methods(Array<Method*>* methods, bool set_idnums, method_comparator_func func) { 1876 int length = methods->length(); 1877 if (length > 1) { 1878 if (func == nullptr) { 1879 func = method_comparator; 1880 } 1881 { 1882 NoSafepointVerifier nsv; 1883 QuickSort::sort(methods->data(), length, func); 1884 } 1885 // Reset method ordering 1886 if (set_idnums) { 1887 for (u2 i = 0; i < length; i++) { 1888 Method* m = methods->at(i); 1889 m->set_method_idnum(i); 1890 m->set_orig_method_idnum(i); 1891 } 1892 } 1893 } 1894 } 1895 1896 //----------------------------------------------------------------------------------- 1897 // Non-product code unless JVM/TI needs it 1898 1899 #if !defined(PRODUCT) || INCLUDE_JVMTI 1900 class SignatureTypePrinter : public SignatureTypeNames { 1901 private: 1902 outputStream* _st; 1903 bool _use_separator; 1904 1905 void type_name(const char* name) { 1906 if (_use_separator) _st->print(", "); 1907 _st->print("%s", name); 1908 _use_separator = true; 1909 } 1910 1911 public: 1912 SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) { 1913 _st = st; 1914 _use_separator = false; 1915 } 1916 1917 void print_parameters() { _use_separator = false; do_parameters_on(this); } 1918 void print_returntype() { _use_separator = false; do_type(return_type()); } 1919 }; 1920 1921 1922 void Method::print_name(outputStream* st) const { 1923 Thread *thread = Thread::current(); 1924 ResourceMark rm(thread); 1925 st->print("%s ", is_static() ? "static" : "virtual"); 1926 if (WizardMode) { 1927 st->print("%s.", method_holder()->internal_name()); 1928 name()->print_symbol_on(st); 1929 signature()->print_symbol_on(st); 1930 } else { 1931 SignatureTypePrinter sig(signature(), st); 1932 sig.print_returntype(); 1933 st->print(" %s.", method_holder()->internal_name()); 1934 name()->print_symbol_on(st); 1935 st->print("("); 1936 sig.print_parameters(); 1937 st->print(")"); 1938 } 1939 } 1940 #endif // !PRODUCT || INCLUDE_JVMTI 1941 1942 1943 void Method::print_codes_on(outputStream* st, int flags) const { 1944 print_codes_on(0, code_size(), st, flags); 1945 } 1946 1947 void Method::print_codes_on(int from, int to, outputStream* st, int flags) const { 1948 Thread *thread = Thread::current(); 1949 ResourceMark rm(thread); 1950 methodHandle mh (thread, (Method*)this); 1951 BytecodeTracer::print_method_codes(mh, from, to, st, flags); 1952 } 1953 1954 CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) { 1955 _bci = 0; 1956 _line = 0; 1957 }; 1958 1959 bool CompressedLineNumberReadStream::read_pair() { 1960 jubyte next = read_byte(); 1961 // Check for terminator 1962 if (next == 0) return false; 1963 if (next == 0xFF) { 1964 // Escape character, regular compression used 1965 _bci += read_signed_int(); 1966 _line += read_signed_int(); 1967 } else { 1968 // Single byte compression used 1969 _bci += next >> 3; 1970 _line += next & 0x7; 1971 } 1972 return true; 1973 } 1974 1975 #if INCLUDE_JVMTI 1976 1977 Bytecodes::Code Method::orig_bytecode_at(int bci) const { 1978 BreakpointInfo* bp = method_holder()->breakpoints(); 1979 for (; bp != nullptr; bp = bp->next()) { 1980 if (bp->match(this, bci)) { 1981 return bp->orig_bytecode(); 1982 } 1983 } 1984 { 1985 ResourceMark rm; 1986 fatal("no original bytecode found in %s at bci %d", name_and_sig_as_C_string(), bci); 1987 } 1988 return Bytecodes::_shouldnotreachhere; 1989 } 1990 1991 void Method::set_orig_bytecode_at(int bci, Bytecodes::Code code) { 1992 assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way"); 1993 BreakpointInfo* bp = method_holder()->breakpoints(); 1994 for (; bp != nullptr; bp = bp->next()) { 1995 if (bp->match(this, bci)) { 1996 bp->set_orig_bytecode(code); 1997 // and continue, in case there is more than one 1998 } 1999 } 2000 } 2001 2002 void Method::set_breakpoint(int bci) { 2003 InstanceKlass* ik = method_holder(); 2004 BreakpointInfo *bp = new BreakpointInfo(this, bci); 2005 bp->set_next(ik->breakpoints()); 2006 ik->set_breakpoints(bp); 2007 // do this last: 2008 bp->set(this); 2009 } 2010 2011 static void clear_matches(Method* m, int bci) { 2012 InstanceKlass* ik = m->method_holder(); 2013 BreakpointInfo* prev_bp = nullptr; 2014 BreakpointInfo* next_bp; 2015 for (BreakpointInfo* bp = ik->breakpoints(); bp != nullptr; bp = next_bp) { 2016 next_bp = bp->next(); 2017 // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint). 2018 if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) { 2019 // do this first: 2020 bp->clear(m); 2021 // unhook it 2022 if (prev_bp != nullptr) 2023 prev_bp->set_next(next_bp); 2024 else 2025 ik->set_breakpoints(next_bp); 2026 delete bp; 2027 // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods 2028 // at same location. So we have multiple matching (method_index and bci) 2029 // BreakpointInfo nodes in BreakpointInfo list. We should just delete one 2030 // breakpoint for clear_breakpoint request and keep all other method versions 2031 // BreakpointInfo for future clear_breakpoint request. 2032 // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints) 2033 // which is being called when class is unloaded. We delete all the Breakpoint 2034 // information for all versions of method. We may not correctly restore the original 2035 // bytecode in all method versions, but that is ok. Because the class is being unloaded 2036 // so these methods won't be used anymore. 2037 if (bci >= 0) { 2038 break; 2039 } 2040 } else { 2041 // This one is a keeper. 2042 prev_bp = bp; 2043 } 2044 } 2045 } 2046 2047 void Method::clear_breakpoint(int bci) { 2048 assert(bci >= 0, ""); 2049 clear_matches(this, bci); 2050 } 2051 2052 void Method::clear_all_breakpoints() { 2053 clear_matches(this, -1); 2054 } 2055 2056 #endif // INCLUDE_JVMTI 2057 2058 int Method::highest_osr_comp_level() const { 2059 const MethodCounters* mcs = method_counters(); 2060 if (mcs != nullptr) { 2061 return mcs->highest_osr_comp_level(); 2062 } else { 2063 return CompLevel_none; 2064 } 2065 } 2066 2067 void Method::set_highest_comp_level(int level) { 2068 MethodCounters* mcs = method_counters(); 2069 if (mcs != nullptr) { 2070 mcs->set_highest_comp_level(level); 2071 } 2072 } 2073 2074 void Method::set_highest_osr_comp_level(int level) { 2075 MethodCounters* mcs = method_counters(); 2076 if (mcs != nullptr) { 2077 mcs->set_highest_osr_comp_level(level); 2078 } 2079 } 2080 2081 #if INCLUDE_JVMTI 2082 2083 BreakpointInfo::BreakpointInfo(Method* m, int bci) { 2084 _bci = bci; 2085 _name_index = m->name_index(); 2086 _signature_index = m->signature_index(); 2087 _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci); 2088 if (_orig_bytecode == Bytecodes::_breakpoint) 2089 _orig_bytecode = m->orig_bytecode_at(_bci); 2090 _next = nullptr; 2091 } 2092 2093 void BreakpointInfo::set(Method* method) { 2094 #ifdef ASSERT 2095 { 2096 Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci); 2097 if (code == Bytecodes::_breakpoint) 2098 code = method->orig_bytecode_at(_bci); 2099 assert(orig_bytecode() == code, "original bytecode must be the same"); 2100 } 2101 #endif 2102 Thread *thread = Thread::current(); 2103 *method->bcp_from(_bci) = Bytecodes::_breakpoint; 2104 method->incr_number_of_breakpoints(thread); 2105 { 2106 // Deoptimize all dependents on this method 2107 HandleMark hm(thread); 2108 methodHandle mh(thread, method); 2109 CodeCache::mark_dependents_on_method_for_breakpoint(mh); 2110 } 2111 } 2112 2113 void BreakpointInfo::clear(Method* method) { 2114 *method->bcp_from(_bci) = orig_bytecode(); 2115 assert(method->number_of_breakpoints() > 0, "must not go negative"); 2116 method->decr_number_of_breakpoints(Thread::current()); 2117 } 2118 2119 #endif // INCLUDE_JVMTI 2120 2121 // jmethodID handling 2122 // jmethodIDs are 64-bit integers that will never run out and are mapped in a table 2123 // to their Method and vice versa. If JNI code has access to stale jmethodID, this 2124 // wastes no memory but the Method* returned is null. 2125 2126 // Add a method id to the jmethod_ids 2127 jmethodID Method::make_jmethod_id(ClassLoaderData* cld, Method* m) { 2128 // Have to add jmethod_ids() to class loader data thread-safely. 2129 // Also have to add the method to the InstanceKlass list safely, which the lock 2130 // protects as well. 2131 assert(JmethodIdCreation_lock->owned_by_self(), "sanity check"); 2132 jmethodID jmid = JmethodIDTable::make_jmethod_id(m); 2133 assert(jmid != nullptr, "must be created"); 2134 2135 // Add to growable array in CLD. 2136 cld->add_jmethod_id(jmid); 2137 return jmid; 2138 } 2139 2140 // This looks in the InstanceKlass cache, then calls back to make_jmethod_id if not found. 2141 jmethodID Method::jmethod_id() { 2142 return method_holder()->get_jmethod_id(this); 2143 } 2144 2145 // Get the Method out of the table given the method id. 2146 Method* Method::resolve_jmethod_id(jmethodID mid) { 2147 assert(mid != nullptr, "JNI method id should not be null"); 2148 return JmethodIDTable::resolve_jmethod_id(mid); 2149 } 2150 2151 void Method::change_method_associated_with_jmethod_id(jmethodID jmid, Method* new_method) { 2152 // Can't assert the method_holder is the same because the new method has the 2153 // scratch method holder. 2154 assert(resolve_jmethod_id(jmid)->method_holder()->class_loader() 2155 == new_method->method_holder()->class_loader() || 2156 new_method->method_holder()->class_loader() == nullptr, // allow substitution to Unsafe method 2157 "changing to a different class loader"); 2158 JmethodIDTable::change_method_associated_with_jmethod_id(jmid, new_method); 2159 } 2160 2161 // If there's a jmethodID for this method, clear the Method 2162 // but leave jmethodID for this method in the table. 2163 // It's deallocated with class unloading. 2164 void Method::clear_jmethod_id() { 2165 jmethodID mid = method_holder()->jmethod_id_or_null(this); 2166 if (mid != nullptr) { 2167 JmethodIDTable::clear_jmethod_id(mid, this); 2168 } 2169 } 2170 2171 bool Method::validate_jmethod_id(jmethodID mid) { 2172 Method* m = resolve_jmethod_id(mid); 2173 assert(m != nullptr, "should be called with non-null method"); 2174 InstanceKlass* ik = m->method_holder(); 2175 ClassLoaderData* cld = ik->class_loader_data(); 2176 if (cld->jmethod_ids() == nullptr) return false; 2177 return (cld->jmethod_ids()->contains(mid)); 2178 } 2179 2180 Method* Method::checked_resolve_jmethod_id(jmethodID mid) { 2181 if (mid == nullptr) return nullptr; 2182 Method* o = resolve_jmethod_id(mid); 2183 if (o == nullptr) { 2184 return nullptr; 2185 } 2186 // Method should otherwise be valid. Assert for testing. 2187 assert(is_valid_method(o), "should be valid jmethodid"); 2188 // If the method's class holder object is unreferenced, but not yet marked as 2189 // unloaded, we need to return null here too because after a safepoint, its memory 2190 // will be reclaimed. 2191 return o->method_holder()->is_loader_alive() ? o : nullptr; 2192 } 2193 2194 void Method::set_on_stack(const bool value) { 2195 // Set both the method itself and its constant pool. The constant pool 2196 // on stack means some method referring to it is also on the stack. 2197 constants()->set_on_stack(value); 2198 2199 bool already_set = on_stack_flag(); 2200 set_on_stack_flag(value); 2201 if (value && !already_set) { 2202 MetadataOnStackMark::record(this); 2203 } 2204 } 2205 2206 void Method::record_gc_epoch() { 2207 // If any method is on the stack in continuations, none of them can be reclaimed, 2208 // so save the marking cycle to check for the whole class in the cpCache. 2209 // The cpCache is writeable. 2210 constants()->cache()->record_gc_epoch(); 2211 } 2212 2213 bool Method::has_method_vptr(const void* ptr) { 2214 Method m; 2215 // This assumes that the vtbl pointer is the first word of a C++ object. 2216 return dereference_vptr(&m) == dereference_vptr(ptr); 2217 } 2218 2219 // Check that this pointer is valid by checking that the vtbl pointer matches 2220 bool Method::is_valid_method(const Method* m) { 2221 if (m == nullptr) { 2222 return false; 2223 } else if ((intptr_t(m) & (wordSize-1)) != 0) { 2224 // Quick sanity check on pointer. 2225 return false; 2226 } else if (!os::is_readable_range(m, m + 1)) { 2227 return false; 2228 } else if (m->in_aot_cache()) { 2229 return CppVtables::is_valid_shared_method(m); 2230 } else if (Metaspace::contains_non_shared(m)) { 2231 return has_method_vptr((const void*)m); 2232 } else { 2233 return false; 2234 } 2235 } 2236 2237 // Printing 2238 2239 #ifndef PRODUCT 2240 2241 void Method::print_on(outputStream* st) const { 2242 ResourceMark rm; 2243 assert(is_method(), "must be method"); 2244 st->print_cr("%s", internal_name()); 2245 st->print_cr(" - this oop: " PTR_FORMAT, p2i(this)); 2246 st->print (" - method holder: "); method_holder()->print_value_on(st); st->cr(); 2247 st->print (" - constants: " PTR_FORMAT " ", p2i(constants())); 2248 constants()->print_value_on(st); st->cr(); 2249 st->print (" - access: 0x%x ", access_flags().as_method_flags()); access_flags().print_on(st); st->cr(); 2250 st->print (" - flags: 0x%x ", _flags.as_int()); _flags.print_on(st); st->cr(); 2251 st->print (" - name: "); name()->print_value_on(st); st->cr(); 2252 st->print (" - signature: "); signature()->print_value_on(st); st->cr(); 2253 st->print_cr(" - max stack: %d", max_stack()); 2254 st->print_cr(" - max locals: %d", max_locals()); 2255 st->print_cr(" - size of params: %d", size_of_parameters()); 2256 st->print_cr(" - method size: %d", method_size()); 2257 if (intrinsic_id() != vmIntrinsics::_none) 2258 st->print_cr(" - intrinsic id: %d %s", vmIntrinsics::as_int(intrinsic_id()), vmIntrinsics::name_at(intrinsic_id())); 2259 if (highest_comp_level() != CompLevel_none) 2260 st->print_cr(" - highest level: %d", highest_comp_level()); 2261 st->print_cr(" - vtable index: %d", _vtable_index); 2262 st->print_cr(" - i2i entry: " PTR_FORMAT, p2i(interpreter_entry())); 2263 st->print( " - adapters: "); 2264 AdapterHandlerEntry* a = ((Method*)this)->adapter(); 2265 if (a == nullptr) 2266 st->print_cr(PTR_FORMAT, p2i(a)); 2267 else 2268 a->print_adapter_on(st); 2269 st->print_cr(" - compiled entry " PTR_FORMAT, p2i(from_compiled_entry())); 2270 st->print_cr(" - code size: %d", code_size()); 2271 if (code_size() != 0) { 2272 st->print_cr(" - code start: " PTR_FORMAT, p2i(code_base())); 2273 st->print_cr(" - code end (excl): " PTR_FORMAT, p2i(code_base() + code_size())); 2274 } 2275 if (method_data() != nullptr) { 2276 st->print_cr(" - method data: " PTR_FORMAT, p2i(method_data())); 2277 } 2278 st->print_cr(" - checked ex length: %d", checked_exceptions_length()); 2279 if (checked_exceptions_length() > 0) { 2280 CheckedExceptionElement* table = checked_exceptions_start(); 2281 st->print_cr(" - checked ex start: " PTR_FORMAT, p2i(table)); 2282 if (Verbose) { 2283 for (int i = 0; i < checked_exceptions_length(); i++) { 2284 st->print_cr(" - throws %s", constants()->printable_name_at(table[i].class_cp_index)); 2285 } 2286 } 2287 } 2288 if (has_linenumber_table()) { 2289 u_char* table = compressed_linenumber_table(); 2290 st->print_cr(" - linenumber start: " PTR_FORMAT, p2i(table)); 2291 if (Verbose) { 2292 CompressedLineNumberReadStream stream(table); 2293 while (stream.read_pair()) { 2294 st->print_cr(" - line %d: %d", stream.line(), stream.bci()); 2295 } 2296 } 2297 } 2298 st->print_cr(" - localvar length: %d", localvariable_table_length()); 2299 if (localvariable_table_length() > 0) { 2300 LocalVariableTableElement* table = localvariable_table_start(); 2301 st->print_cr(" - localvar start: " PTR_FORMAT, p2i(table)); 2302 if (Verbose) { 2303 for (int i = 0; i < localvariable_table_length(); i++) { 2304 int bci = table[i].start_bci; 2305 int len = table[i].length; 2306 const char* name = constants()->printable_name_at(table[i].name_cp_index); 2307 const char* desc = constants()->printable_name_at(table[i].descriptor_cp_index); 2308 int slot = table[i].slot; 2309 st->print_cr(" - %s %s bci=%d len=%d slot=%d", desc, name, bci, len, slot); 2310 } 2311 } 2312 } 2313 if (code() != nullptr) { 2314 st->print (" - compiled code: "); 2315 code()->print_value_on(st); 2316 } 2317 if (is_native()) { 2318 st->print_cr(" - native function: " PTR_FORMAT, p2i(native_function())); 2319 st->print_cr(" - signature handler: " PTR_FORMAT, p2i(signature_handler())); 2320 } 2321 } 2322 2323 void Method::print_linkage_flags(outputStream* st) { 2324 access_flags().print_on(st); 2325 if (is_default_method()) { 2326 st->print("default "); 2327 } 2328 if (is_overpass()) { 2329 st->print("overpass "); 2330 } 2331 } 2332 #endif //PRODUCT 2333 2334 void Method::print_value_on(outputStream* st) const { 2335 assert(is_method(), "must be method"); 2336 st->print("%s", internal_name()); 2337 print_address_on(st); 2338 st->print(" "); 2339 name()->print_value_on(st); 2340 st->print(" "); 2341 signature()->print_value_on(st); 2342 st->print(" in "); 2343 method_holder()->print_value_on(st); 2344 if (WizardMode) st->print("#%d", _vtable_index); 2345 if (WizardMode) st->print("[%d,%d]", size_of_parameters(), max_locals()); 2346 if (WizardMode && code() != nullptr) st->print(" ((nmethod*)%p)", code()); 2347 } 2348 2349 // Verification 2350 2351 void Method::verify_on(outputStream* st) { 2352 guarantee(is_method(), "object must be method"); 2353 guarantee(constants()->is_constantPool(), "should be constant pool"); 2354 MethodData* md = method_data(); 2355 guarantee(md == nullptr || 2356 md->is_methodData(), "should be method data"); 2357 }