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 "classfile/classLoader.hpp" 26 #include "classfile/javaClasses.inline.hpp" 27 #include "classfile/stringTable.hpp" 28 #include "classfile/vmClasses.hpp" 29 #include "classfile/vmSymbols.hpp" 30 #include "code/codeCache.hpp" 31 #include "code/compiledIC.hpp" 32 #include "code/nmethod.inline.hpp" 33 #include "code/scopeDesc.hpp" 34 #include "code/vtableStubs.hpp" 35 #include "compiler/abstractCompiler.hpp" 36 #include "compiler/compileBroker.hpp" 37 #include "compiler/disassembler.hpp" 38 #include "gc/shared/barrierSet.hpp" 39 #include "gc/shared/collectedHeap.hpp" 40 #include "gc/shared/gcLocker.inline.hpp" 41 #include "interpreter/interpreter.hpp" 42 #include "interpreter/interpreterRuntime.hpp" 43 #include "jvm.h" 44 #include "jfr/jfrEvents.hpp" 45 #include "logging/log.hpp" 46 #include "memory/resourceArea.hpp" 47 #include "memory/universe.hpp" 48 #include "metaprogramming/primitiveConversions.hpp" 49 #include "oops/klass.hpp" 50 #include "oops/method.inline.hpp" 51 #include "oops/objArrayKlass.hpp" 52 #include "oops/oop.inline.hpp" 53 #include "prims/forte.hpp" 54 #include "prims/jvmtiExport.hpp" 55 #include "prims/jvmtiThreadState.hpp" 56 #include "prims/methodHandles.hpp" 57 #include "prims/nativeLookup.hpp" 58 #include "runtime/arguments.hpp" 59 #include "runtime/atomic.hpp" 60 #include "runtime/basicLock.inline.hpp" 61 #include "runtime/frame.inline.hpp" 62 #include "runtime/handles.inline.hpp" 63 #include "runtime/init.hpp" 64 #include "runtime/interfaceSupport.inline.hpp" 65 #include "runtime/java.hpp" 66 #include "runtime/javaCalls.hpp" 67 #include "runtime/jniHandles.inline.hpp" 68 #include "runtime/perfData.hpp" 69 #include "runtime/sharedRuntime.hpp" 70 #include "runtime/stackWatermarkSet.hpp" 71 #include "runtime/stubRoutines.hpp" 72 #include "runtime/synchronizer.inline.hpp" 73 #include "runtime/timerTrace.hpp" 74 #include "runtime/vframe.inline.hpp" 75 #include "runtime/vframeArray.hpp" 76 #include "runtime/vm_version.hpp" 77 #include "utilities/copy.hpp" 78 #include "utilities/dtrace.hpp" 79 #include "utilities/events.hpp" 80 #include "utilities/globalDefinitions.hpp" 81 #include "utilities/resourceHash.hpp" 82 #include "utilities/macros.hpp" 83 #include "utilities/xmlstream.hpp" 84 #ifdef COMPILER1 85 #include "c1/c1_Runtime1.hpp" 86 #endif 87 #if INCLUDE_JFR 88 #include "jfr/jfr.hpp" 89 #endif 90 91 // Shared runtime stub routines reside in their own unique blob with a 92 // single entry point 93 94 95 #define SHARED_STUB_FIELD_DEFINE(name, type) \ 96 type SharedRuntime::BLOB_FIELD_NAME(name); 97 SHARED_STUBS_DO(SHARED_STUB_FIELD_DEFINE) 98 #undef SHARED_STUB_FIELD_DEFINE 99 100 nmethod* SharedRuntime::_cont_doYield_stub; 101 102 #define SHARED_STUB_NAME_DECLARE(name, type) "Shared Runtime " # name "_blob", 103 const char *SharedRuntime::_stub_names[] = { 104 SHARED_STUBS_DO(SHARED_STUB_NAME_DECLARE) 105 }; 106 107 //----------------------------generate_stubs----------------------------------- 108 void SharedRuntime::generate_initial_stubs() { 109 // Build this early so it's available for the interpreter. 110 _throw_StackOverflowError_blob = 111 generate_throw_exception(SharedStubId::throw_StackOverflowError_id, 112 CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError)); 113 } 114 115 void SharedRuntime::generate_stubs() { 116 _wrong_method_blob = 117 generate_resolve_blob(SharedStubId::wrong_method_id, 118 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method)); 119 _wrong_method_abstract_blob = 120 generate_resolve_blob(SharedStubId::wrong_method_abstract_id, 121 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract)); 122 _ic_miss_blob = 123 generate_resolve_blob(SharedStubId::ic_miss_id, 124 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss)); 125 _resolve_opt_virtual_call_blob = 126 generate_resolve_blob(SharedStubId::resolve_opt_virtual_call_id, 127 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C)); 128 _resolve_virtual_call_blob = 129 generate_resolve_blob(SharedStubId::resolve_virtual_call_id, 130 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C)); 131 _resolve_static_call_blob = 132 generate_resolve_blob(SharedStubId::resolve_static_call_id, 133 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C)); 134 135 _throw_delayed_StackOverflowError_blob = 136 generate_throw_exception(SharedStubId::throw_delayed_StackOverflowError_id, 137 CAST_FROM_FN_PTR(address, SharedRuntime::throw_delayed_StackOverflowError)); 138 139 _throw_AbstractMethodError_blob = 140 generate_throw_exception(SharedStubId::throw_AbstractMethodError_id, 141 CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError)); 142 143 _throw_IncompatibleClassChangeError_blob = 144 generate_throw_exception(SharedStubId::throw_IncompatibleClassChangeError_id, 145 CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError)); 146 147 _throw_NullPointerException_at_call_blob = 148 generate_throw_exception(SharedStubId::throw_NullPointerException_at_call_id, 149 CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call)); 150 151 AdapterHandlerLibrary::initialize(); 152 153 #if COMPILER2_OR_JVMCI 154 // Vectors are generated only by C2 and JVMCI. 155 bool support_wide = is_wide_vector(MaxVectorSize); 156 if (support_wide) { 157 _polling_page_vectors_safepoint_handler_blob = 158 generate_handler_blob(SharedStubId::polling_page_vectors_safepoint_handler_id, 159 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception)); 160 } 161 #endif // COMPILER2_OR_JVMCI 162 _polling_page_safepoint_handler_blob = 163 generate_handler_blob(SharedStubId::polling_page_safepoint_handler_id, 164 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception)); 165 _polling_page_return_handler_blob = 166 generate_handler_blob(SharedStubId::polling_page_return_handler_id, 167 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception)); 168 169 generate_deopt_blob(); 170 } 171 172 #if INCLUDE_JFR 173 //------------------------------generate jfr runtime stubs ------ 174 void SharedRuntime::generate_jfr_stubs() { 175 ResourceMark rm; 176 const char* timer_msg = "SharedRuntime generate_jfr_stubs"; 177 TraceTime timer(timer_msg, TRACETIME_LOG(Info, startuptime)); 178 179 _jfr_write_checkpoint_blob = generate_jfr_write_checkpoint(); 180 _jfr_return_lease_blob = generate_jfr_return_lease(); 181 } 182 183 #endif // INCLUDE_JFR 184 185 #include <math.h> 186 187 // Implementation of SharedRuntime 188 189 #ifndef PRODUCT 190 // For statistics 191 uint SharedRuntime::_ic_miss_ctr = 0; 192 uint SharedRuntime::_wrong_method_ctr = 0; 193 uint SharedRuntime::_resolve_static_ctr = 0; 194 uint SharedRuntime::_resolve_virtual_ctr = 0; 195 uint SharedRuntime::_resolve_opt_virtual_ctr = 0; 196 uint SharedRuntime::_implicit_null_throws = 0; 197 uint SharedRuntime::_implicit_div0_throws = 0; 198 199 int64_t SharedRuntime::_nof_normal_calls = 0; 200 int64_t SharedRuntime::_nof_inlined_calls = 0; 201 int64_t SharedRuntime::_nof_megamorphic_calls = 0; 202 int64_t SharedRuntime::_nof_static_calls = 0; 203 int64_t SharedRuntime::_nof_inlined_static_calls = 0; 204 int64_t SharedRuntime::_nof_interface_calls = 0; 205 int64_t SharedRuntime::_nof_inlined_interface_calls = 0; 206 207 uint SharedRuntime::_new_instance_ctr=0; 208 uint SharedRuntime::_new_array_ctr=0; 209 uint SharedRuntime::_multi2_ctr=0; 210 uint SharedRuntime::_multi3_ctr=0; 211 uint SharedRuntime::_multi4_ctr=0; 212 uint SharedRuntime::_multi5_ctr=0; 213 uint SharedRuntime::_mon_enter_stub_ctr=0; 214 uint SharedRuntime::_mon_exit_stub_ctr=0; 215 uint SharedRuntime::_mon_enter_ctr=0; 216 uint SharedRuntime::_mon_exit_ctr=0; 217 uint SharedRuntime::_partial_subtype_ctr=0; 218 uint SharedRuntime::_jbyte_array_copy_ctr=0; 219 uint SharedRuntime::_jshort_array_copy_ctr=0; 220 uint SharedRuntime::_jint_array_copy_ctr=0; 221 uint SharedRuntime::_jlong_array_copy_ctr=0; 222 uint SharedRuntime::_oop_array_copy_ctr=0; 223 uint SharedRuntime::_checkcast_array_copy_ctr=0; 224 uint SharedRuntime::_unsafe_array_copy_ctr=0; 225 uint SharedRuntime::_generic_array_copy_ctr=0; 226 uint SharedRuntime::_slow_array_copy_ctr=0; 227 uint SharedRuntime::_find_handler_ctr=0; 228 uint SharedRuntime::_rethrow_ctr=0; 229 uint SharedRuntime::_unsafe_set_memory_ctr=0; 230 231 int SharedRuntime::_ICmiss_index = 0; 232 int SharedRuntime::_ICmiss_count[SharedRuntime::maxICmiss_count]; 233 address SharedRuntime::_ICmiss_at[SharedRuntime::maxICmiss_count]; 234 235 236 void SharedRuntime::trace_ic_miss(address at) { 237 for (int i = 0; i < _ICmiss_index; i++) { 238 if (_ICmiss_at[i] == at) { 239 _ICmiss_count[i]++; 240 return; 241 } 242 } 243 int index = _ICmiss_index++; 244 if (_ICmiss_index >= maxICmiss_count) _ICmiss_index = maxICmiss_count - 1; 245 _ICmiss_at[index] = at; 246 _ICmiss_count[index] = 1; 247 } 248 249 void SharedRuntime::print_ic_miss_histogram() { 250 if (ICMissHistogram) { 251 tty->print_cr("IC Miss Histogram:"); 252 int tot_misses = 0; 253 for (int i = 0; i < _ICmiss_index; i++) { 254 tty->print_cr(" at: " INTPTR_FORMAT " nof: %d", p2i(_ICmiss_at[i]), _ICmiss_count[i]); 255 tot_misses += _ICmiss_count[i]; 256 } 257 tty->print_cr("Total IC misses: %7d", tot_misses); 258 } 259 } 260 #endif // PRODUCT 261 262 263 JRT_LEAF(jlong, SharedRuntime::lmul(jlong y, jlong x)) 264 return x * y; 265 JRT_END 266 267 268 JRT_LEAF(jlong, SharedRuntime::ldiv(jlong y, jlong x)) 269 if (x == min_jlong && y == CONST64(-1)) { 270 return x; 271 } else { 272 return x / y; 273 } 274 JRT_END 275 276 277 JRT_LEAF(jlong, SharedRuntime::lrem(jlong y, jlong x)) 278 if (x == min_jlong && y == CONST64(-1)) { 279 return 0; 280 } else { 281 return x % y; 282 } 283 JRT_END 284 285 286 #ifdef _WIN64 287 const juint float_sign_mask = 0x7FFFFFFF; 288 const juint float_infinity = 0x7F800000; 289 const julong double_sign_mask = CONST64(0x7FFFFFFFFFFFFFFF); 290 const julong double_infinity = CONST64(0x7FF0000000000000); 291 #endif 292 293 #if !defined(X86) 294 JRT_LEAF(jfloat, SharedRuntime::frem(jfloat x, jfloat y)) 295 #ifdef _WIN64 296 // 64-bit Windows on amd64 returns the wrong values for 297 // infinity operands. 298 juint xbits = PrimitiveConversions::cast<juint>(x); 299 juint ybits = PrimitiveConversions::cast<juint>(y); 300 // x Mod Infinity == x unless x is infinity 301 if (((xbits & float_sign_mask) != float_infinity) && 302 ((ybits & float_sign_mask) == float_infinity) ) { 303 return x; 304 } 305 return ((jfloat)fmod_winx64((double)x, (double)y)); 306 #else 307 return ((jfloat)fmod((double)x,(double)y)); 308 #endif 309 JRT_END 310 311 JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y)) 312 #ifdef _WIN64 313 julong xbits = PrimitiveConversions::cast<julong>(x); 314 julong ybits = PrimitiveConversions::cast<julong>(y); 315 // x Mod Infinity == x unless x is infinity 316 if (((xbits & double_sign_mask) != double_infinity) && 317 ((ybits & double_sign_mask) == double_infinity) ) { 318 return x; 319 } 320 return ((jdouble)fmod_winx64((double)x, (double)y)); 321 #else 322 return ((jdouble)fmod((double)x,(double)y)); 323 #endif 324 JRT_END 325 #endif // !X86 326 327 JRT_LEAF(jfloat, SharedRuntime::i2f(jint x)) 328 return (jfloat)x; 329 JRT_END 330 331 #ifdef __SOFTFP__ 332 JRT_LEAF(jfloat, SharedRuntime::fadd(jfloat x, jfloat y)) 333 return x + y; 334 JRT_END 335 336 JRT_LEAF(jfloat, SharedRuntime::fsub(jfloat x, jfloat y)) 337 return x - y; 338 JRT_END 339 340 JRT_LEAF(jfloat, SharedRuntime::fmul(jfloat x, jfloat y)) 341 return x * y; 342 JRT_END 343 344 JRT_LEAF(jfloat, SharedRuntime::fdiv(jfloat x, jfloat y)) 345 return x / y; 346 JRT_END 347 348 JRT_LEAF(jdouble, SharedRuntime::dadd(jdouble x, jdouble y)) 349 return x + y; 350 JRT_END 351 352 JRT_LEAF(jdouble, SharedRuntime::dsub(jdouble x, jdouble y)) 353 return x - y; 354 JRT_END 355 356 JRT_LEAF(jdouble, SharedRuntime::dmul(jdouble x, jdouble y)) 357 return x * y; 358 JRT_END 359 360 JRT_LEAF(jdouble, SharedRuntime::ddiv(jdouble x, jdouble y)) 361 return x / y; 362 JRT_END 363 364 JRT_LEAF(jdouble, SharedRuntime::i2d(jint x)) 365 return (jdouble)x; 366 JRT_END 367 368 JRT_LEAF(jdouble, SharedRuntime::f2d(jfloat x)) 369 return (jdouble)x; 370 JRT_END 371 372 JRT_LEAF(int, SharedRuntime::fcmpl(float x, float y)) 373 return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan*/ 374 JRT_END 375 376 JRT_LEAF(int, SharedRuntime::fcmpg(float x, float y)) 377 return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */ 378 JRT_END 379 380 JRT_LEAF(int, SharedRuntime::dcmpl(double x, double y)) 381 return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan */ 382 JRT_END 383 384 JRT_LEAF(int, SharedRuntime::dcmpg(double x, double y)) 385 return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */ 386 JRT_END 387 388 // Functions to return the opposite of the aeabi functions for nan. 389 JRT_LEAF(int, SharedRuntime::unordered_fcmplt(float x, float y)) 390 return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 391 JRT_END 392 393 JRT_LEAF(int, SharedRuntime::unordered_dcmplt(double x, double y)) 394 return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 395 JRT_END 396 397 JRT_LEAF(int, SharedRuntime::unordered_fcmple(float x, float y)) 398 return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 399 JRT_END 400 401 JRT_LEAF(int, SharedRuntime::unordered_dcmple(double x, double y)) 402 return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 403 JRT_END 404 405 JRT_LEAF(int, SharedRuntime::unordered_fcmpge(float x, float y)) 406 return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 407 JRT_END 408 409 JRT_LEAF(int, SharedRuntime::unordered_dcmpge(double x, double y)) 410 return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 411 JRT_END 412 413 JRT_LEAF(int, SharedRuntime::unordered_fcmpgt(float x, float y)) 414 return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 415 JRT_END 416 417 JRT_LEAF(int, SharedRuntime::unordered_dcmpgt(double x, double y)) 418 return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 419 JRT_END 420 421 // Intrinsics make gcc generate code for these. 422 float SharedRuntime::fneg(float f) { 423 return -f; 424 } 425 426 double SharedRuntime::dneg(double f) { 427 return -f; 428 } 429 430 #endif // __SOFTFP__ 431 432 #if defined(__SOFTFP__) || defined(E500V2) 433 // Intrinsics make gcc generate code for these. 434 double SharedRuntime::dabs(double f) { 435 return (f <= (double)0.0) ? (double)0.0 - f : f; 436 } 437 438 #endif 439 440 #if defined(__SOFTFP__) || defined(PPC) 441 double SharedRuntime::dsqrt(double f) { 442 return sqrt(f); 443 } 444 #endif 445 446 JRT_LEAF(jint, SharedRuntime::f2i(jfloat x)) 447 if (g_isnan(x)) 448 return 0; 449 if (x >= (jfloat) max_jint) 450 return max_jint; 451 if (x <= (jfloat) min_jint) 452 return min_jint; 453 return (jint) x; 454 JRT_END 455 456 457 JRT_LEAF(jlong, SharedRuntime::f2l(jfloat x)) 458 if (g_isnan(x)) 459 return 0; 460 if (x >= (jfloat) max_jlong) 461 return max_jlong; 462 if (x <= (jfloat) min_jlong) 463 return min_jlong; 464 return (jlong) x; 465 JRT_END 466 467 468 JRT_LEAF(jint, SharedRuntime::d2i(jdouble x)) 469 if (g_isnan(x)) 470 return 0; 471 if (x >= (jdouble) max_jint) 472 return max_jint; 473 if (x <= (jdouble) min_jint) 474 return min_jint; 475 return (jint) x; 476 JRT_END 477 478 479 JRT_LEAF(jlong, SharedRuntime::d2l(jdouble x)) 480 if (g_isnan(x)) 481 return 0; 482 if (x >= (jdouble) max_jlong) 483 return max_jlong; 484 if (x <= (jdouble) min_jlong) 485 return min_jlong; 486 return (jlong) x; 487 JRT_END 488 489 490 JRT_LEAF(jfloat, SharedRuntime::d2f(jdouble x)) 491 return (jfloat)x; 492 JRT_END 493 494 495 JRT_LEAF(jfloat, SharedRuntime::l2f(jlong x)) 496 return (jfloat)x; 497 JRT_END 498 499 500 JRT_LEAF(jdouble, SharedRuntime::l2d(jlong x)) 501 return (jdouble)x; 502 JRT_END 503 504 505 // Exception handling across interpreter/compiler boundaries 506 // 507 // exception_handler_for_return_address(...) returns the continuation address. 508 // The continuation address is the entry point of the exception handler of the 509 // previous frame depending on the return address. 510 511 address SharedRuntime::raw_exception_handler_for_return_address(JavaThread* current, address return_address) { 512 // Note: This is called when we have unwound the frame of the callee that did 513 // throw an exception. So far, no check has been performed by the StackWatermarkSet. 514 // Notably, the stack is not walkable at this point, and hence the check must 515 // be deferred until later. Specifically, any of the handlers returned here in 516 // this function, will get dispatched to, and call deferred checks to 517 // StackWatermarkSet::after_unwind at a point where the stack is walkable. 518 assert(frame::verify_return_pc(return_address), "must be a return address: " INTPTR_FORMAT, p2i(return_address)); 519 assert(current->frames_to_pop_failed_realloc() == 0 || Interpreter::contains(return_address), "missed frames to pop?"); 520 521 // Reset method handle flag. 522 current->set_is_method_handle_return(false); 523 524 #if INCLUDE_JVMCI 525 // JVMCI's ExceptionHandlerStub expects the thread local exception PC to be clear 526 // and other exception handler continuations do not read it 527 current->set_exception_pc(nullptr); 528 #endif // INCLUDE_JVMCI 529 530 if (Continuation::is_return_barrier_entry(return_address)) { 531 return StubRoutines::cont_returnBarrierExc(); 532 } 533 534 // The fastest case first 535 CodeBlob* blob = CodeCache::find_blob(return_address); 536 nmethod* nm = (blob != nullptr) ? blob->as_nmethod_or_null() : nullptr; 537 if (nm != nullptr) { 538 // Set flag if return address is a method handle call site. 539 current->set_is_method_handle_return(nm->is_method_handle_return(return_address)); 540 // native nmethods don't have exception handlers 541 assert(!nm->is_native_method() || nm->method()->is_continuation_enter_intrinsic(), "no exception handler"); 542 assert(nm->header_begin() != nm->exception_begin(), "no exception handler"); 543 if (nm->is_deopt_pc(return_address)) { 544 // If we come here because of a stack overflow, the stack may be 545 // unguarded. Reguard the stack otherwise if we return to the 546 // deopt blob and the stack bang causes a stack overflow we 547 // crash. 548 StackOverflow* overflow_state = current->stack_overflow_state(); 549 bool guard_pages_enabled = overflow_state->reguard_stack_if_needed(); 550 if (overflow_state->reserved_stack_activation() != current->stack_base()) { 551 overflow_state->set_reserved_stack_activation(current->stack_base()); 552 } 553 assert(guard_pages_enabled, "stack banging in deopt blob may cause crash"); 554 // The deferred StackWatermarkSet::after_unwind check will be performed in 555 // Deoptimization::fetch_unroll_info (with exec_mode == Unpack_exception) 556 return SharedRuntime::deopt_blob()->unpack_with_exception(); 557 } else { 558 // The deferred StackWatermarkSet::after_unwind check will be performed in 559 // * OptoRuntime::handle_exception_C_helper for C2 code 560 // * exception_handler_for_pc_helper via Runtime1::handle_exception_from_callee_id for C1 code 561 return nm->exception_begin(); 562 } 563 } 564 565 // Entry code 566 if (StubRoutines::returns_to_call_stub(return_address)) { 567 // The deferred StackWatermarkSet::after_unwind check will be performed in 568 // JavaCallWrapper::~JavaCallWrapper 569 return StubRoutines::catch_exception_entry(); 570 } 571 if (blob != nullptr && blob->is_upcall_stub()) { 572 return StubRoutines::upcall_stub_exception_handler(); 573 } 574 // Interpreted code 575 if (Interpreter::contains(return_address)) { 576 // The deferred StackWatermarkSet::after_unwind check will be performed in 577 // InterpreterRuntime::exception_handler_for_exception 578 return Interpreter::rethrow_exception_entry(); 579 } 580 581 guarantee(blob == nullptr || !blob->is_runtime_stub(), "caller should have skipped stub"); 582 guarantee(!VtableStubs::contains(return_address), "null exceptions in vtables should have been handled already!"); 583 584 #ifndef PRODUCT 585 { ResourceMark rm; 586 tty->print_cr("No exception handler found for exception at " INTPTR_FORMAT " - potential problems:", p2i(return_address)); 587 os::print_location(tty, (intptr_t)return_address); 588 tty->print_cr("a) exception happened in (new?) code stubs/buffers that is not handled here"); 589 tty->print_cr("b) other problem"); 590 } 591 #endif // PRODUCT 592 ShouldNotReachHere(); 593 return nullptr; 594 } 595 596 597 JRT_LEAF(address, SharedRuntime::exception_handler_for_return_address(JavaThread* current, address return_address)) 598 return raw_exception_handler_for_return_address(current, return_address); 599 JRT_END 600 601 602 address SharedRuntime::get_poll_stub(address pc) { 603 address stub; 604 // Look up the code blob 605 CodeBlob *cb = CodeCache::find_blob(pc); 606 607 // Should be an nmethod 608 guarantee(cb != nullptr && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod"); 609 610 // Look up the relocation information 611 assert(cb->as_nmethod()->is_at_poll_or_poll_return(pc), 612 "safepoint polling: type must be poll at pc " INTPTR_FORMAT, p2i(pc)); 613 614 #ifdef ASSERT 615 if (!((NativeInstruction*)pc)->is_safepoint_poll()) { 616 tty->print_cr("bad pc: " PTR_FORMAT, p2i(pc)); 617 Disassembler::decode(cb); 618 fatal("Only polling locations are used for safepoint"); 619 } 620 #endif 621 622 bool at_poll_return = cb->as_nmethod()->is_at_poll_return(pc); 623 bool has_wide_vectors = cb->as_nmethod()->has_wide_vectors(); 624 if (at_poll_return) { 625 assert(SharedRuntime::polling_page_return_handler_blob() != nullptr, 626 "polling page return stub not created yet"); 627 stub = SharedRuntime::polling_page_return_handler_blob()->entry_point(); 628 } else if (has_wide_vectors) { 629 assert(SharedRuntime::polling_page_vectors_safepoint_handler_blob() != nullptr, 630 "polling page vectors safepoint stub not created yet"); 631 stub = SharedRuntime::polling_page_vectors_safepoint_handler_blob()->entry_point(); 632 } else { 633 assert(SharedRuntime::polling_page_safepoint_handler_blob() != nullptr, 634 "polling page safepoint stub not created yet"); 635 stub = SharedRuntime::polling_page_safepoint_handler_blob()->entry_point(); 636 } 637 log_debug(safepoint)("... found polling page %s exception at pc = " 638 INTPTR_FORMAT ", stub =" INTPTR_FORMAT, 639 at_poll_return ? "return" : "loop", 640 (intptr_t)pc, (intptr_t)stub); 641 return stub; 642 } 643 644 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Handle h_exception) { 645 if (JvmtiExport::can_post_on_exceptions()) { 646 vframeStream vfst(current, true); 647 methodHandle method = methodHandle(current, vfst.method()); 648 address bcp = method()->bcp_from(vfst.bci()); 649 JvmtiExport::post_exception_throw(current, method(), bcp, h_exception()); 650 } 651 652 #if INCLUDE_JVMCI 653 if (EnableJVMCI) { 654 vframeStream vfst(current, true); 655 methodHandle method = methodHandle(current, vfst.method()); 656 int bci = vfst.bci(); 657 MethodData* trap_mdo = method->method_data(); 658 if (trap_mdo != nullptr) { 659 // Set exception_seen if the exceptional bytecode is an invoke 660 Bytecode_invoke call = Bytecode_invoke_check(method, bci); 661 if (call.is_valid()) { 662 ResourceMark rm(current); 663 664 // Lock to read ProfileData, and ensure lock is not broken by a safepoint 665 MutexLocker ml(trap_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag); 666 667 ProfileData* pdata = trap_mdo->allocate_bci_to_data(bci, nullptr); 668 if (pdata != nullptr && pdata->is_BitData()) { 669 BitData* bit_data = (BitData*) pdata; 670 bit_data->set_exception_seen(); 671 } 672 } 673 } 674 } 675 #endif 676 677 Exceptions::_throw(current, __FILE__, __LINE__, h_exception); 678 } 679 680 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Symbol* name, const char *message) { 681 Handle h_exception = Exceptions::new_exception(current, name, message); 682 throw_and_post_jvmti_exception(current, h_exception); 683 } 684 685 #if INCLUDE_JVMTI 686 JRT_ENTRY(void, SharedRuntime::notify_jvmti_vthread_start(oopDesc* vt, jboolean hide, JavaThread* current)) 687 assert(hide == JNI_FALSE, "must be VTMS transition finish"); 688 jobject vthread = JNIHandles::make_local(const_cast<oopDesc*>(vt)); 689 JvmtiVTMSTransitionDisabler::VTMS_vthread_start(vthread); 690 JNIHandles::destroy_local(vthread); 691 JRT_END 692 693 JRT_ENTRY(void, SharedRuntime::notify_jvmti_vthread_end(oopDesc* vt, jboolean hide, JavaThread* current)) 694 assert(hide == JNI_TRUE, "must be VTMS transition start"); 695 jobject vthread = JNIHandles::make_local(const_cast<oopDesc*>(vt)); 696 JvmtiVTMSTransitionDisabler::VTMS_vthread_end(vthread); 697 JNIHandles::destroy_local(vthread); 698 JRT_END 699 700 JRT_ENTRY(void, SharedRuntime::notify_jvmti_vthread_mount(oopDesc* vt, jboolean hide, JavaThread* current)) 701 jobject vthread = JNIHandles::make_local(const_cast<oopDesc*>(vt)); 702 JvmtiVTMSTransitionDisabler::VTMS_vthread_mount(vthread, hide); 703 JNIHandles::destroy_local(vthread); 704 JRT_END 705 706 JRT_ENTRY(void, SharedRuntime::notify_jvmti_vthread_unmount(oopDesc* vt, jboolean hide, JavaThread* current)) 707 jobject vthread = JNIHandles::make_local(const_cast<oopDesc*>(vt)); 708 JvmtiVTMSTransitionDisabler::VTMS_vthread_unmount(vthread, hide); 709 JNIHandles::destroy_local(vthread); 710 JRT_END 711 #endif // INCLUDE_JVMTI 712 713 // The interpreter code to call this tracing function is only 714 // called/generated when UL is on for redefine, class and has the right level 715 // and tags. Since obsolete methods are never compiled, we don't have 716 // to modify the compilers to generate calls to this function. 717 // 718 JRT_LEAF(int, SharedRuntime::rc_trace_method_entry( 719 JavaThread* thread, Method* method)) 720 if (method->is_obsolete()) { 721 // We are calling an obsolete method, but this is not necessarily 722 // an error. Our method could have been redefined just after we 723 // fetched the Method* from the constant pool. 724 ResourceMark rm; 725 log_trace(redefine, class, obsolete)("calling obsolete method '%s'", method->name_and_sig_as_C_string()); 726 } 727 return 0; 728 JRT_END 729 730 // ret_pc points into caller; we are returning caller's exception handler 731 // for given exception 732 // Note that the implementation of this method assumes it's only called when an exception has actually occured 733 address SharedRuntime::compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception, 734 bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred) { 735 assert(nm != nullptr, "must exist"); 736 ResourceMark rm; 737 738 #if INCLUDE_JVMCI 739 if (nm->is_compiled_by_jvmci()) { 740 // lookup exception handler for this pc 741 int catch_pco = pointer_delta_as_int(ret_pc, nm->code_begin()); 742 ExceptionHandlerTable table(nm); 743 HandlerTableEntry *t = table.entry_for(catch_pco, -1, 0); 744 if (t != nullptr) { 745 return nm->code_begin() + t->pco(); 746 } else { 747 return Deoptimization::deoptimize_for_missing_exception_handler(nm); 748 } 749 } 750 #endif // INCLUDE_JVMCI 751 752 ScopeDesc* sd = nm->scope_desc_at(ret_pc); 753 // determine handler bci, if any 754 EXCEPTION_MARK; 755 756 int handler_bci = -1; 757 int scope_depth = 0; 758 if (!force_unwind) { 759 int bci = sd->bci(); 760 bool recursive_exception = false; 761 do { 762 bool skip_scope_increment = false; 763 // exception handler lookup 764 Klass* ek = exception->klass(); 765 methodHandle mh(THREAD, sd->method()); 766 handler_bci = Method::fast_exception_handler_bci_for(mh, ek, bci, THREAD); 767 if (HAS_PENDING_EXCEPTION) { 768 recursive_exception = true; 769 // We threw an exception while trying to find the exception handler. 770 // Transfer the new exception to the exception handle which will 771 // be set into thread local storage, and do another lookup for an 772 // exception handler for this exception, this time starting at the 773 // BCI of the exception handler which caused the exception to be 774 // thrown (bugs 4307310 and 4546590). Set "exception" reference 775 // argument to ensure that the correct exception is thrown (4870175). 776 recursive_exception_occurred = true; 777 exception = Handle(THREAD, PENDING_EXCEPTION); 778 CLEAR_PENDING_EXCEPTION; 779 if (handler_bci >= 0) { 780 bci = handler_bci; 781 handler_bci = -1; 782 skip_scope_increment = true; 783 } 784 } 785 else { 786 recursive_exception = false; 787 } 788 if (!top_frame_only && handler_bci < 0 && !skip_scope_increment) { 789 sd = sd->sender(); 790 if (sd != nullptr) { 791 bci = sd->bci(); 792 } 793 ++scope_depth; 794 } 795 } while (recursive_exception || (!top_frame_only && handler_bci < 0 && sd != nullptr)); 796 } 797 798 // found handling method => lookup exception handler 799 int catch_pco = pointer_delta_as_int(ret_pc, nm->code_begin()); 800 801 ExceptionHandlerTable table(nm); 802 HandlerTableEntry *t = table.entry_for(catch_pco, handler_bci, scope_depth); 803 if (t == nullptr && (nm->is_compiled_by_c1() || handler_bci != -1)) { 804 // Allow abbreviated catch tables. The idea is to allow a method 805 // to materialize its exceptions without committing to the exact 806 // routing of exceptions. In particular this is needed for adding 807 // a synthetic handler to unlock monitors when inlining 808 // synchronized methods since the unlock path isn't represented in 809 // the bytecodes. 810 t = table.entry_for(catch_pco, -1, 0); 811 } 812 813 #ifdef COMPILER1 814 if (t == nullptr && nm->is_compiled_by_c1()) { 815 assert(nm->unwind_handler_begin() != nullptr, ""); 816 return nm->unwind_handler_begin(); 817 } 818 #endif 819 820 if (t == nullptr) { 821 ttyLocker ttyl; 822 tty->print_cr("MISSING EXCEPTION HANDLER for pc " INTPTR_FORMAT " and handler bci %d, catch_pco: %d", p2i(ret_pc), handler_bci, catch_pco); 823 tty->print_cr(" Exception:"); 824 exception->print(); 825 tty->cr(); 826 tty->print_cr(" Compiled exception table :"); 827 table.print(); 828 nm->print(); 829 nm->print_code(); 830 guarantee(false, "missing exception handler"); 831 return nullptr; 832 } 833 834 if (handler_bci != -1) { // did we find a handler in this method? 835 sd->method()->set_exception_handler_entered(handler_bci); // profile 836 } 837 return nm->code_begin() + t->pco(); 838 } 839 840 JRT_ENTRY(void, SharedRuntime::throw_AbstractMethodError(JavaThread* current)) 841 // These errors occur only at call sites 842 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_AbstractMethodError()); 843 JRT_END 844 845 JRT_ENTRY(void, SharedRuntime::throw_IncompatibleClassChangeError(JavaThread* current)) 846 // These errors occur only at call sites 847 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError(), "vtable stub"); 848 JRT_END 849 850 JRT_ENTRY(void, SharedRuntime::throw_ArithmeticException(JavaThread* current)) 851 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero"); 852 JRT_END 853 854 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException(JavaThread* current)) 855 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), nullptr); 856 JRT_END 857 858 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException_at_call(JavaThread* current)) 859 // This entry point is effectively only used for NullPointerExceptions which occur at inline 860 // cache sites (when the callee activation is not yet set up) so we are at a call site 861 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), nullptr); 862 JRT_END 863 864 JRT_ENTRY(void, SharedRuntime::throw_StackOverflowError(JavaThread* current)) 865 throw_StackOverflowError_common(current, false); 866 JRT_END 867 868 JRT_ENTRY(void, SharedRuntime::throw_delayed_StackOverflowError(JavaThread* current)) 869 throw_StackOverflowError_common(current, true); 870 JRT_END 871 872 void SharedRuntime::throw_StackOverflowError_common(JavaThread* current, bool delayed) { 873 // We avoid using the normal exception construction in this case because 874 // it performs an upcall to Java, and we're already out of stack space. 875 JavaThread* THREAD = current; // For exception macros. 876 Klass* k = vmClasses::StackOverflowError_klass(); 877 oop exception_oop = InstanceKlass::cast(k)->allocate_instance(CHECK); 878 if (delayed) { 879 java_lang_Throwable::set_message(exception_oop, 880 Universe::delayed_stack_overflow_error_message()); 881 } 882 Handle exception (current, exception_oop); 883 if (StackTraceInThrowable) { 884 java_lang_Throwable::fill_in_stack_trace(exception); 885 } 886 // Remove the ScopedValue bindings in case we got a 887 // StackOverflowError while we were trying to remove ScopedValue 888 // bindings. 889 current->clear_scopedValueBindings(); 890 // Increment counter for hs_err file reporting 891 Atomic::inc(&Exceptions::_stack_overflow_errors); 892 throw_and_post_jvmti_exception(current, exception); 893 } 894 895 address SharedRuntime::continuation_for_implicit_exception(JavaThread* current, 896 address pc, 897 ImplicitExceptionKind exception_kind) 898 { 899 address target_pc = nullptr; 900 901 if (Interpreter::contains(pc)) { 902 switch (exception_kind) { 903 case IMPLICIT_NULL: return Interpreter::throw_NullPointerException_entry(); 904 case IMPLICIT_DIVIDE_BY_ZERO: return Interpreter::throw_ArithmeticException_entry(); 905 case STACK_OVERFLOW: return Interpreter::throw_StackOverflowError_entry(); 906 default: ShouldNotReachHere(); 907 } 908 } else { 909 switch (exception_kind) { 910 case STACK_OVERFLOW: { 911 // Stack overflow only occurs upon frame setup; the callee is 912 // going to be unwound. Dispatch to a shared runtime stub 913 // which will cause the StackOverflowError to be fabricated 914 // and processed. 915 // Stack overflow should never occur during deoptimization: 916 // the compiled method bangs the stack by as much as the 917 // interpreter would need in case of a deoptimization. The 918 // deoptimization blob and uncommon trap blob bang the stack 919 // in a debug VM to verify the correctness of the compiled 920 // method stack banging. 921 assert(current->deopt_mark() == nullptr, "no stack overflow from deopt blob/uncommon trap"); 922 Events::log_exception(current, "StackOverflowError at " INTPTR_FORMAT, p2i(pc)); 923 return SharedRuntime::throw_StackOverflowError_entry(); 924 } 925 926 case IMPLICIT_NULL: { 927 if (VtableStubs::contains(pc)) { 928 // We haven't yet entered the callee frame. Fabricate an 929 // exception and begin dispatching it in the caller. Since 930 // the caller was at a call site, it's safe to destroy all 931 // caller-saved registers, as these entry points do. 932 VtableStub* vt_stub = VtableStubs::stub_containing(pc); 933 934 // If vt_stub is null, then return null to signal handler to report the SEGV error. 935 if (vt_stub == nullptr) return nullptr; 936 937 if (vt_stub->is_abstract_method_error(pc)) { 938 assert(!vt_stub->is_vtable_stub(), "should never see AbstractMethodErrors from vtable-type VtableStubs"); 939 Events::log_exception(current, "AbstractMethodError at " INTPTR_FORMAT, p2i(pc)); 940 // Instead of throwing the abstract method error here directly, we re-resolve 941 // and will throw the AbstractMethodError during resolve. As a result, we'll 942 // get a more detailed error message. 943 return SharedRuntime::get_handle_wrong_method_stub(); 944 } else { 945 Events::log_exception(current, "NullPointerException at vtable entry " INTPTR_FORMAT, p2i(pc)); 946 // Assert that the signal comes from the expected location in stub code. 947 assert(vt_stub->is_null_pointer_exception(pc), 948 "obtained signal from unexpected location in stub code"); 949 return SharedRuntime::throw_NullPointerException_at_call_entry(); 950 } 951 } else { 952 CodeBlob* cb = CodeCache::find_blob(pc); 953 954 // If code blob is null, then return null to signal handler to report the SEGV error. 955 if (cb == nullptr) return nullptr; 956 957 // Exception happened in CodeCache. Must be either: 958 // 1. Inline-cache check in C2I handler blob, 959 // 2. Inline-cache check in nmethod, or 960 // 3. Implicit null exception in nmethod 961 962 if (!cb->is_nmethod()) { 963 bool is_in_blob = cb->is_adapter_blob() || cb->is_method_handles_adapter_blob(); 964 if (!is_in_blob) { 965 // Allow normal crash reporting to handle this 966 return nullptr; 967 } 968 Events::log_exception(current, "NullPointerException in code blob at " INTPTR_FORMAT, p2i(pc)); 969 // There is no handler here, so we will simply unwind. 970 return SharedRuntime::throw_NullPointerException_at_call_entry(); 971 } 972 973 // Otherwise, it's a compiled method. Consult its exception handlers. 974 nmethod* nm = cb->as_nmethod(); 975 if (nm->inlinecache_check_contains(pc)) { 976 // exception happened inside inline-cache check code 977 // => the nmethod is not yet active (i.e., the frame 978 // is not set up yet) => use return address pushed by 979 // caller => don't push another return address 980 Events::log_exception(current, "NullPointerException in IC check " INTPTR_FORMAT, p2i(pc)); 981 return SharedRuntime::throw_NullPointerException_at_call_entry(); 982 } 983 984 if (nm->method()->is_method_handle_intrinsic()) { 985 // exception happened inside MH dispatch code, similar to a vtable stub 986 Events::log_exception(current, "NullPointerException in MH adapter " INTPTR_FORMAT, p2i(pc)); 987 return SharedRuntime::throw_NullPointerException_at_call_entry(); 988 } 989 990 #ifndef PRODUCT 991 _implicit_null_throws++; 992 #endif 993 target_pc = nm->continuation_for_implicit_null_exception(pc); 994 // If there's an unexpected fault, target_pc might be null, 995 // in which case we want to fall through into the normal 996 // error handling code. 997 } 998 999 break; // fall through 1000 } 1001 1002 1003 case IMPLICIT_DIVIDE_BY_ZERO: { 1004 nmethod* nm = CodeCache::find_nmethod(pc); 1005 guarantee(nm != nullptr, "must have containing compiled method for implicit division-by-zero exceptions"); 1006 #ifndef PRODUCT 1007 _implicit_div0_throws++; 1008 #endif 1009 target_pc = nm->continuation_for_implicit_div0_exception(pc); 1010 // If there's an unexpected fault, target_pc might be null, 1011 // in which case we want to fall through into the normal 1012 // error handling code. 1013 break; // fall through 1014 } 1015 1016 default: ShouldNotReachHere(); 1017 } 1018 1019 assert(exception_kind == IMPLICIT_NULL || exception_kind == IMPLICIT_DIVIDE_BY_ZERO, "wrong implicit exception kind"); 1020 1021 if (exception_kind == IMPLICIT_NULL) { 1022 #ifndef PRODUCT 1023 // for AbortVMOnException flag 1024 Exceptions::debug_check_abort("java.lang.NullPointerException"); 1025 #endif //PRODUCT 1026 Events::log_exception(current, "Implicit null exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc)); 1027 } else { 1028 #ifndef PRODUCT 1029 // for AbortVMOnException flag 1030 Exceptions::debug_check_abort("java.lang.ArithmeticException"); 1031 #endif //PRODUCT 1032 Events::log_exception(current, "Implicit division by zero exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc)); 1033 } 1034 return target_pc; 1035 } 1036 1037 ShouldNotReachHere(); 1038 return nullptr; 1039 } 1040 1041 1042 /** 1043 * Throws an java/lang/UnsatisfiedLinkError. The address of this method is 1044 * installed in the native function entry of all native Java methods before 1045 * they get linked to their actual native methods. 1046 * 1047 * \note 1048 * This method actually never gets called! The reason is because 1049 * the interpreter's native entries call NativeLookup::lookup() which 1050 * throws the exception when the lookup fails. The exception is then 1051 * caught and forwarded on the return from NativeLookup::lookup() call 1052 * before the call to the native function. This might change in the future. 1053 */ 1054 JNI_ENTRY(void*, throw_unsatisfied_link_error(JNIEnv* env, ...)) 1055 { 1056 // We return a bad value here to make sure that the exception is 1057 // forwarded before we look at the return value. 1058 THROW_(vmSymbols::java_lang_UnsatisfiedLinkError(), (void*)badAddress); 1059 } 1060 JNI_END 1061 1062 address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() { 1063 return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error); 1064 } 1065 1066 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* current, oopDesc* obj)) 1067 #if INCLUDE_JVMCI 1068 if (!obj->klass()->has_finalizer()) { 1069 return; 1070 } 1071 #endif // INCLUDE_JVMCI 1072 assert(oopDesc::is_oop(obj), "must be a valid oop"); 1073 assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise"); 1074 InstanceKlass::register_finalizer(instanceOop(obj), CHECK); 1075 JRT_END 1076 1077 jlong SharedRuntime::get_java_tid(JavaThread* thread) { 1078 assert(thread != nullptr, "No thread"); 1079 if (thread == nullptr) { 1080 return 0; 1081 } 1082 guarantee(Thread::current() != thread || thread->is_oop_safe(), 1083 "current cannot touch oops after its GC barrier is detached."); 1084 oop obj = thread->threadObj(); 1085 return (obj == nullptr) ? 0 : java_lang_Thread::thread_id(obj); 1086 } 1087 1088 /** 1089 * This function ought to be a void function, but cannot be because 1090 * it gets turned into a tail-call on sparc, which runs into dtrace bug 1091 * 6254741. Once that is fixed we can remove the dummy return value. 1092 */ 1093 int SharedRuntime::dtrace_object_alloc(oopDesc* o) { 1094 return dtrace_object_alloc(JavaThread::current(), o, o->size()); 1095 } 1096 1097 int SharedRuntime::dtrace_object_alloc(JavaThread* thread, oopDesc* o) { 1098 return dtrace_object_alloc(thread, o, o->size()); 1099 } 1100 1101 int SharedRuntime::dtrace_object_alloc(JavaThread* thread, oopDesc* o, size_t size) { 1102 assert(DTraceAllocProbes, "wrong call"); 1103 Klass* klass = o->klass(); 1104 Symbol* name = klass->name(); 1105 HOTSPOT_OBJECT_ALLOC( 1106 get_java_tid(thread), 1107 (char *) name->bytes(), name->utf8_length(), size * HeapWordSize); 1108 return 0; 1109 } 1110 1111 JRT_LEAF(int, SharedRuntime::dtrace_method_entry( 1112 JavaThread* current, Method* method)) 1113 assert(current == JavaThread::current(), "pre-condition"); 1114 1115 assert(DTraceMethodProbes, "wrong call"); 1116 Symbol* kname = method->klass_name(); 1117 Symbol* name = method->name(); 1118 Symbol* sig = method->signature(); 1119 HOTSPOT_METHOD_ENTRY( 1120 get_java_tid(current), 1121 (char *) kname->bytes(), kname->utf8_length(), 1122 (char *) name->bytes(), name->utf8_length(), 1123 (char *) sig->bytes(), sig->utf8_length()); 1124 return 0; 1125 JRT_END 1126 1127 JRT_LEAF(int, SharedRuntime::dtrace_method_exit( 1128 JavaThread* current, Method* method)) 1129 assert(current == JavaThread::current(), "pre-condition"); 1130 assert(DTraceMethodProbes, "wrong call"); 1131 Symbol* kname = method->klass_name(); 1132 Symbol* name = method->name(); 1133 Symbol* sig = method->signature(); 1134 HOTSPOT_METHOD_RETURN( 1135 get_java_tid(current), 1136 (char *) kname->bytes(), kname->utf8_length(), 1137 (char *) name->bytes(), name->utf8_length(), 1138 (char *) sig->bytes(), sig->utf8_length()); 1139 return 0; 1140 JRT_END 1141 1142 1143 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode) 1144 // for a call current in progress, i.e., arguments has been pushed on stack 1145 // put callee has not been invoked yet. Used by: resolve virtual/static, 1146 // vtable updates, etc. Caller frame must be compiled. 1147 Handle SharedRuntime::find_callee_info(Bytecodes::Code& bc, CallInfo& callinfo, TRAPS) { 1148 JavaThread* current = THREAD; 1149 ResourceMark rm(current); 1150 1151 // last java frame on stack (which includes native call frames) 1152 vframeStream vfst(current, true); // Do not skip and javaCalls 1153 1154 return find_callee_info_helper(vfst, bc, callinfo, THREAD); 1155 } 1156 1157 Method* SharedRuntime::extract_attached_method(vframeStream& vfst) { 1158 nmethod* caller = vfst.nm(); 1159 1160 address pc = vfst.frame_pc(); 1161 { // Get call instruction under lock because another thread may be busy patching it. 1162 CompiledICLocker ic_locker(caller); 1163 return caller->attached_method_before_pc(pc); 1164 } 1165 return nullptr; 1166 } 1167 1168 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode 1169 // for a call current in progress, i.e., arguments has been pushed on stack 1170 // but callee has not been invoked yet. Caller frame must be compiled. 1171 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc, 1172 CallInfo& callinfo, TRAPS) { 1173 Handle receiver; 1174 Handle nullHandle; // create a handy null handle for exception returns 1175 JavaThread* current = THREAD; 1176 1177 assert(!vfst.at_end(), "Java frame must exist"); 1178 1179 // Find caller and bci from vframe 1180 methodHandle caller(current, vfst.method()); 1181 int bci = vfst.bci(); 1182 1183 if (caller->is_continuation_enter_intrinsic()) { 1184 bc = Bytecodes::_invokestatic; 1185 LinkResolver::resolve_continuation_enter(callinfo, CHECK_NH); 1186 return receiver; 1187 } 1188 1189 Bytecode_invoke bytecode(caller, bci); 1190 int bytecode_index = bytecode.index(); 1191 bc = bytecode.invoke_code(); 1192 1193 methodHandle attached_method(current, extract_attached_method(vfst)); 1194 if (attached_method.not_null()) { 1195 Method* callee = bytecode.static_target(CHECK_NH); 1196 vmIntrinsics::ID id = callee->intrinsic_id(); 1197 // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call, 1198 // it attaches statically resolved method to the call site. 1199 if (MethodHandles::is_signature_polymorphic(id) && 1200 MethodHandles::is_signature_polymorphic_intrinsic(id)) { 1201 bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id); 1202 1203 // Adjust invocation mode according to the attached method. 1204 switch (bc) { 1205 case Bytecodes::_invokevirtual: 1206 if (attached_method->method_holder()->is_interface()) { 1207 bc = Bytecodes::_invokeinterface; 1208 } 1209 break; 1210 case Bytecodes::_invokeinterface: 1211 if (!attached_method->method_holder()->is_interface()) { 1212 bc = Bytecodes::_invokevirtual; 1213 } 1214 break; 1215 case Bytecodes::_invokehandle: 1216 if (!MethodHandles::is_signature_polymorphic_method(attached_method())) { 1217 bc = attached_method->is_static() ? Bytecodes::_invokestatic 1218 : Bytecodes::_invokevirtual; 1219 } 1220 break; 1221 default: 1222 break; 1223 } 1224 } 1225 } 1226 1227 assert(bc != Bytecodes::_illegal, "not initialized"); 1228 1229 bool has_receiver = bc != Bytecodes::_invokestatic && 1230 bc != Bytecodes::_invokedynamic && 1231 bc != Bytecodes::_invokehandle; 1232 1233 // Find receiver for non-static call 1234 if (has_receiver) { 1235 // This register map must be update since we need to find the receiver for 1236 // compiled frames. The receiver might be in a register. 1237 RegisterMap reg_map2(current, 1238 RegisterMap::UpdateMap::include, 1239 RegisterMap::ProcessFrames::include, 1240 RegisterMap::WalkContinuation::skip); 1241 frame stubFrame = current->last_frame(); 1242 // Caller-frame is a compiled frame 1243 frame callerFrame = stubFrame.sender(®_map2); 1244 1245 if (attached_method.is_null()) { 1246 Method* callee = bytecode.static_target(CHECK_NH); 1247 if (callee == nullptr) { 1248 THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle); 1249 } 1250 } 1251 1252 // Retrieve from a compiled argument list 1253 receiver = Handle(current, callerFrame.retrieve_receiver(®_map2)); 1254 assert(oopDesc::is_oop_or_null(receiver()), ""); 1255 1256 if (receiver.is_null()) { 1257 THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle); 1258 } 1259 } 1260 1261 // Resolve method 1262 if (attached_method.not_null()) { 1263 // Parameterized by attached method. 1264 LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, CHECK_NH); 1265 } else { 1266 // Parameterized by bytecode. 1267 constantPoolHandle constants(current, caller->constants()); 1268 LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH); 1269 } 1270 1271 #ifdef ASSERT 1272 // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls 1273 if (has_receiver) { 1274 assert(receiver.not_null(), "should have thrown exception"); 1275 Klass* receiver_klass = receiver->klass(); 1276 Klass* rk = nullptr; 1277 if (attached_method.not_null()) { 1278 // In case there's resolved method attached, use its holder during the check. 1279 rk = attached_method->method_holder(); 1280 } else { 1281 // Klass is already loaded. 1282 constantPoolHandle constants(current, caller->constants()); 1283 rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH); 1284 } 1285 Klass* static_receiver_klass = rk; 1286 assert(receiver_klass->is_subtype_of(static_receiver_klass), 1287 "actual receiver must be subclass of static receiver klass"); 1288 if (receiver_klass->is_instance_klass()) { 1289 if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) { 1290 tty->print_cr("ERROR: Klass not yet initialized!!"); 1291 receiver_klass->print(); 1292 } 1293 assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized"); 1294 } 1295 } 1296 #endif 1297 1298 return receiver; 1299 } 1300 1301 methodHandle SharedRuntime::find_callee_method(TRAPS) { 1302 JavaThread* current = THREAD; 1303 ResourceMark rm(current); 1304 // We need first to check if any Java activations (compiled, interpreted) 1305 // exist on the stack since last JavaCall. If not, we need 1306 // to get the target method from the JavaCall wrapper. 1307 vframeStream vfst(current, true); // Do not skip any javaCalls 1308 methodHandle callee_method; 1309 if (vfst.at_end()) { 1310 // No Java frames were found on stack since we did the JavaCall. 1311 // Hence the stack can only contain an entry_frame. We need to 1312 // find the target method from the stub frame. 1313 RegisterMap reg_map(current, 1314 RegisterMap::UpdateMap::skip, 1315 RegisterMap::ProcessFrames::include, 1316 RegisterMap::WalkContinuation::skip); 1317 frame fr = current->last_frame(); 1318 assert(fr.is_runtime_frame(), "must be a runtimeStub"); 1319 fr = fr.sender(®_map); 1320 assert(fr.is_entry_frame(), "must be"); 1321 // fr is now pointing to the entry frame. 1322 callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method()); 1323 } else { 1324 Bytecodes::Code bc; 1325 CallInfo callinfo; 1326 find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle())); 1327 callee_method = methodHandle(current, callinfo.selected_method()); 1328 } 1329 assert(callee_method()->is_method(), "must be"); 1330 return callee_method; 1331 } 1332 1333 // Resolves a call. 1334 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, TRAPS) { 1335 JavaThread* current = THREAD; 1336 ResourceMark rm(current); 1337 RegisterMap cbl_map(current, 1338 RegisterMap::UpdateMap::skip, 1339 RegisterMap::ProcessFrames::include, 1340 RegisterMap::WalkContinuation::skip); 1341 frame caller_frame = current->last_frame().sender(&cbl_map); 1342 1343 CodeBlob* caller_cb = caller_frame.cb(); 1344 guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method"); 1345 nmethod* caller_nm = caller_cb->as_nmethod(); 1346 1347 // determine call info & receiver 1348 // note: a) receiver is null for static calls 1349 // b) an exception is thrown if receiver is null for non-static calls 1350 CallInfo call_info; 1351 Bytecodes::Code invoke_code = Bytecodes::_illegal; 1352 Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle())); 1353 1354 NoSafepointVerifier nsv; 1355 1356 methodHandle callee_method(current, call_info.selected_method()); 1357 1358 assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) || 1359 (!is_virtual && invoke_code == Bytecodes::_invokespecial) || 1360 (!is_virtual && invoke_code == Bytecodes::_invokehandle ) || 1361 (!is_virtual && invoke_code == Bytecodes::_invokedynamic) || 1362 ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode"); 1363 1364 assert(!caller_nm->is_unloading(), "It should not be unloading"); 1365 1366 #ifndef PRODUCT 1367 // tracing/debugging/statistics 1368 uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) : 1369 (is_virtual) ? (&_resolve_virtual_ctr) : 1370 (&_resolve_static_ctr); 1371 Atomic::inc(addr); 1372 1373 if (TraceCallFixup) { 1374 ResourceMark rm(current); 1375 tty->print("resolving %s%s (%s) call to", 1376 (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static", 1377 Bytecodes::name(invoke_code)); 1378 callee_method->print_short_name(tty); 1379 tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT, 1380 p2i(caller_frame.pc()), p2i(callee_method->code())); 1381 } 1382 #endif 1383 1384 if (invoke_code == Bytecodes::_invokestatic) { 1385 assert(callee_method->method_holder()->is_initialized() || 1386 callee_method->method_holder()->is_reentrant_initialization(current), 1387 "invalid class initialization state for invoke_static"); 1388 if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) { 1389 // In order to keep class initialization check, do not patch call 1390 // site for static call when the class is not fully initialized. 1391 // Proper check is enforced by call site re-resolution on every invocation. 1392 // 1393 // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true), 1394 // explicit class initialization check is put in nmethod entry (VEP). 1395 assert(callee_method->method_holder()->is_linked(), "must be"); 1396 return callee_method; 1397 } 1398 } 1399 1400 1401 // JSR 292 key invariant: 1402 // If the resolved method is a MethodHandle invoke target, the call 1403 // site must be a MethodHandle call site, because the lambda form might tail-call 1404 // leaving the stack in a state unknown to either caller or callee 1405 1406 // Compute entry points. The computation of the entry points is independent of 1407 // patching the call. 1408 1409 // Make sure the callee nmethod does not get deoptimized and removed before 1410 // we are done patching the code. 1411 1412 1413 CompiledICLocker ml(caller_nm); 1414 if (is_virtual && !is_optimized) { 1415 CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc()); 1416 inline_cache->update(&call_info, receiver->klass()); 1417 } else { 1418 // Callsite is a direct call - set it to the destination method 1419 CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc()); 1420 callsite->set(callee_method); 1421 } 1422 1423 return callee_method; 1424 } 1425 1426 // Inline caches exist only in compiled code 1427 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current)) 1428 #ifdef ASSERT 1429 RegisterMap reg_map(current, 1430 RegisterMap::UpdateMap::skip, 1431 RegisterMap::ProcessFrames::include, 1432 RegisterMap::WalkContinuation::skip); 1433 frame stub_frame = current->last_frame(); 1434 assert(stub_frame.is_runtime_frame(), "sanity check"); 1435 frame caller_frame = stub_frame.sender(®_map); 1436 assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame"); 1437 #endif /* ASSERT */ 1438 1439 methodHandle callee_method; 1440 JRT_BLOCK 1441 callee_method = SharedRuntime::handle_ic_miss_helper(CHECK_NULL); 1442 // Return Method* through TLS 1443 current->set_vm_result_2(callee_method()); 1444 JRT_BLOCK_END 1445 // return compiled code entry point after potential safepoints 1446 return get_resolved_entry(current, callee_method); 1447 JRT_END 1448 1449 1450 // Handle call site that has been made non-entrant 1451 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current)) 1452 // 6243940 We might end up in here if the callee is deoptimized 1453 // as we race to call it. We don't want to take a safepoint if 1454 // the caller was interpreted because the caller frame will look 1455 // interpreted to the stack walkers and arguments are now 1456 // "compiled" so it is much better to make this transition 1457 // invisible to the stack walking code. The i2c path will 1458 // place the callee method in the callee_target. It is stashed 1459 // there because if we try and find the callee by normal means a 1460 // safepoint is possible and have trouble gc'ing the compiled args. 1461 RegisterMap reg_map(current, 1462 RegisterMap::UpdateMap::skip, 1463 RegisterMap::ProcessFrames::include, 1464 RegisterMap::WalkContinuation::skip); 1465 frame stub_frame = current->last_frame(); 1466 assert(stub_frame.is_runtime_frame(), "sanity check"); 1467 frame caller_frame = stub_frame.sender(®_map); 1468 1469 if (caller_frame.is_interpreted_frame() || 1470 caller_frame.is_entry_frame() || 1471 caller_frame.is_upcall_stub_frame()) { 1472 Method* callee = current->callee_target(); 1473 guarantee(callee != nullptr && callee->is_method(), "bad handshake"); 1474 current->set_vm_result_2(callee); 1475 current->set_callee_target(nullptr); 1476 if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) { 1477 // Bypass class initialization checks in c2i when caller is in native. 1478 // JNI calls to static methods don't have class initialization checks. 1479 // Fast class initialization checks are present in c2i adapters and call into 1480 // SharedRuntime::handle_wrong_method() on the slow path. 1481 // 1482 // JVM upcalls may land here as well, but there's a proper check present in 1483 // LinkResolver::resolve_static_call (called from JavaCalls::call_static), 1484 // so bypassing it in c2i adapter is benign. 1485 return callee->get_c2i_no_clinit_check_entry(); 1486 } else { 1487 return callee->get_c2i_entry(); 1488 } 1489 } 1490 1491 // Must be compiled to compiled path which is safe to stackwalk 1492 methodHandle callee_method; 1493 JRT_BLOCK 1494 // Force resolving of caller (if we called from compiled frame) 1495 callee_method = SharedRuntime::reresolve_call_site(CHECK_NULL); 1496 current->set_vm_result_2(callee_method()); 1497 JRT_BLOCK_END 1498 // return compiled code entry point after potential safepoints 1499 return get_resolved_entry(current, callee_method); 1500 JRT_END 1501 1502 // Handle abstract method call 1503 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current)) 1504 // Verbose error message for AbstractMethodError. 1505 // Get the called method from the invoke bytecode. 1506 vframeStream vfst(current, true); 1507 assert(!vfst.at_end(), "Java frame must exist"); 1508 methodHandle caller(current, vfst.method()); 1509 Bytecode_invoke invoke(caller, vfst.bci()); 1510 DEBUG_ONLY( invoke.verify(); ) 1511 1512 // Find the compiled caller frame. 1513 RegisterMap reg_map(current, 1514 RegisterMap::UpdateMap::include, 1515 RegisterMap::ProcessFrames::include, 1516 RegisterMap::WalkContinuation::skip); 1517 frame stubFrame = current->last_frame(); 1518 assert(stubFrame.is_runtime_frame(), "must be"); 1519 frame callerFrame = stubFrame.sender(®_map); 1520 assert(callerFrame.is_compiled_frame(), "must be"); 1521 1522 // Install exception and return forward entry. 1523 address res = SharedRuntime::throw_AbstractMethodError_entry(); 1524 JRT_BLOCK 1525 methodHandle callee(current, invoke.static_target(current)); 1526 if (!callee.is_null()) { 1527 oop recv = callerFrame.retrieve_receiver(®_map); 1528 Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr; 1529 res = StubRoutines::forward_exception_entry(); 1530 LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res)); 1531 } 1532 JRT_BLOCK_END 1533 return res; 1534 JRT_END 1535 1536 // return verified_code_entry if interp_only_mode is not set for the current thread; 1537 // otherwise return c2i entry. 1538 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method) { 1539 if (current->is_interp_only_mode() && !callee_method->is_special_native_intrinsic()) { 1540 // In interp_only_mode we need to go to the interpreted entry 1541 // The c2i won't patch in this mode -- see fixup_callers_callsite 1542 return callee_method->get_c2i_entry(); 1543 } 1544 assert(callee_method->verified_code_entry() != nullptr, " Jump to zero!"); 1545 return callee_method->verified_code_entry(); 1546 } 1547 1548 // resolve a static call and patch code 1549 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current )) 1550 methodHandle callee_method; 1551 bool enter_special = false; 1552 JRT_BLOCK 1553 callee_method = SharedRuntime::resolve_helper(false, false, CHECK_NULL); 1554 current->set_vm_result_2(callee_method()); 1555 JRT_BLOCK_END 1556 // return compiled code entry point after potential safepoints 1557 return get_resolved_entry(current, callee_method); 1558 JRT_END 1559 1560 // resolve virtual call and update inline cache to monomorphic 1561 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current)) 1562 methodHandle callee_method; 1563 JRT_BLOCK 1564 callee_method = SharedRuntime::resolve_helper(true, false, CHECK_NULL); 1565 current->set_vm_result_2(callee_method()); 1566 JRT_BLOCK_END 1567 // return compiled code entry point after potential safepoints 1568 return get_resolved_entry(current, callee_method); 1569 JRT_END 1570 1571 1572 // Resolve a virtual call that can be statically bound (e.g., always 1573 // monomorphic, so it has no inline cache). Patch code to resolved target. 1574 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current)) 1575 methodHandle callee_method; 1576 JRT_BLOCK 1577 callee_method = SharedRuntime::resolve_helper(true, true, CHECK_NULL); 1578 current->set_vm_result_2(callee_method()); 1579 JRT_BLOCK_END 1580 // return compiled code entry point after potential safepoints 1581 return get_resolved_entry(current, callee_method); 1582 JRT_END 1583 1584 methodHandle SharedRuntime::handle_ic_miss_helper(TRAPS) { 1585 JavaThread* current = THREAD; 1586 ResourceMark rm(current); 1587 CallInfo call_info; 1588 Bytecodes::Code bc; 1589 1590 // receiver is null for static calls. An exception is thrown for null 1591 // receivers for non-static calls 1592 Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle())); 1593 1594 methodHandle callee_method(current, call_info.selected_method()); 1595 1596 #ifndef PRODUCT 1597 Atomic::inc(&_ic_miss_ctr); 1598 1599 // Statistics & Tracing 1600 if (TraceCallFixup) { 1601 ResourceMark rm(current); 1602 tty->print("IC miss (%s) call to", Bytecodes::name(bc)); 1603 callee_method->print_short_name(tty); 1604 tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code())); 1605 } 1606 1607 if (ICMissHistogram) { 1608 MutexLocker m(VMStatistic_lock); 1609 RegisterMap reg_map(current, 1610 RegisterMap::UpdateMap::skip, 1611 RegisterMap::ProcessFrames::include, 1612 RegisterMap::WalkContinuation::skip); 1613 frame f = current->last_frame().real_sender(®_map);// skip runtime stub 1614 // produce statistics under the lock 1615 trace_ic_miss(f.pc()); 1616 } 1617 #endif 1618 1619 // install an event collector so that when a vtable stub is created the 1620 // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The 1621 // event can't be posted when the stub is created as locks are held 1622 // - instead the event will be deferred until the event collector goes 1623 // out of scope. 1624 JvmtiDynamicCodeEventCollector event_collector; 1625 1626 // Update inline cache to megamorphic. Skip update if we are called from interpreted. 1627 RegisterMap reg_map(current, 1628 RegisterMap::UpdateMap::skip, 1629 RegisterMap::ProcessFrames::include, 1630 RegisterMap::WalkContinuation::skip); 1631 frame caller_frame = current->last_frame().sender(®_map); 1632 CodeBlob* cb = caller_frame.cb(); 1633 nmethod* caller_nm = cb->as_nmethod(); 1634 1635 CompiledICLocker ml(caller_nm); 1636 CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc()); 1637 inline_cache->update(&call_info, receiver()->klass()); 1638 1639 return callee_method; 1640 } 1641 1642 // 1643 // Resets a call-site in compiled code so it will get resolved again. 1644 // This routines handles both virtual call sites, optimized virtual call 1645 // sites, and static call sites. Typically used to change a call sites 1646 // destination from compiled to interpreted. 1647 // 1648 methodHandle SharedRuntime::reresolve_call_site(TRAPS) { 1649 JavaThread* current = THREAD; 1650 ResourceMark rm(current); 1651 RegisterMap reg_map(current, 1652 RegisterMap::UpdateMap::skip, 1653 RegisterMap::ProcessFrames::include, 1654 RegisterMap::WalkContinuation::skip); 1655 frame stub_frame = current->last_frame(); 1656 assert(stub_frame.is_runtime_frame(), "must be a runtimeStub"); 1657 frame caller = stub_frame.sender(®_map); 1658 1659 // Do nothing if the frame isn't a live compiled frame. 1660 // nmethod could be deoptimized by the time we get here 1661 // so no update to the caller is needed. 1662 1663 if ((caller.is_compiled_frame() && !caller.is_deoptimized_frame()) || 1664 (caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic())) { 1665 1666 address pc = caller.pc(); 1667 1668 nmethod* caller_nm = CodeCache::find_nmethod(pc); 1669 assert(caller_nm != nullptr, "did not find caller nmethod"); 1670 1671 // Default call_addr is the location of the "basic" call. 1672 // Determine the address of the call we a reresolving. With 1673 // Inline Caches we will always find a recognizable call. 1674 // With Inline Caches disabled we may or may not find a 1675 // recognizable call. We will always find a call for static 1676 // calls and for optimized virtual calls. For vanilla virtual 1677 // calls it depends on the state of the UseInlineCaches switch. 1678 // 1679 // With Inline Caches disabled we can get here for a virtual call 1680 // for two reasons: 1681 // 1 - calling an abstract method. The vtable for abstract methods 1682 // will run us thru handle_wrong_method and we will eventually 1683 // end up in the interpreter to throw the ame. 1684 // 2 - a racing deoptimization. We could be doing a vanilla vtable 1685 // call and between the time we fetch the entry address and 1686 // we jump to it the target gets deoptimized. Similar to 1 1687 // we will wind up in the interprter (thru a c2i with c2). 1688 // 1689 CompiledICLocker ml(caller_nm); 1690 address call_addr = caller_nm->call_instruction_address(pc); 1691 1692 if (call_addr != nullptr) { 1693 // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5 1694 // bytes back in the instruction stream so we must also check for reloc info. 1695 RelocIterator iter(caller_nm, call_addr, call_addr+1); 1696 bool ret = iter.next(); // Get item 1697 if (ret) { 1698 switch (iter.type()) { 1699 case relocInfo::static_call_type: 1700 case relocInfo::opt_virtual_call_type: { 1701 CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr); 1702 cdc->set_to_clean(); 1703 break; 1704 } 1705 1706 case relocInfo::virtual_call_type: { 1707 // compiled, dispatched call (which used to call an interpreted method) 1708 CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr); 1709 inline_cache->set_to_clean(); 1710 break; 1711 } 1712 default: 1713 break; 1714 } 1715 } 1716 } 1717 } 1718 1719 methodHandle callee_method = find_callee_method(CHECK_(methodHandle())); 1720 1721 1722 #ifndef PRODUCT 1723 Atomic::inc(&_wrong_method_ctr); 1724 1725 if (TraceCallFixup) { 1726 ResourceMark rm(current); 1727 tty->print("handle_wrong_method reresolving call to"); 1728 callee_method->print_short_name(tty); 1729 tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code())); 1730 } 1731 #endif 1732 1733 return callee_method; 1734 } 1735 1736 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) { 1737 // The faulting unsafe accesses should be changed to throw the error 1738 // synchronously instead. Meanwhile the faulting instruction will be 1739 // skipped over (effectively turning it into a no-op) and an 1740 // asynchronous exception will be raised which the thread will 1741 // handle at a later point. If the instruction is a load it will 1742 // return garbage. 1743 1744 // Request an async exception. 1745 thread->set_pending_unsafe_access_error(); 1746 1747 // Return address of next instruction to execute. 1748 return next_pc; 1749 } 1750 1751 #ifdef ASSERT 1752 void SharedRuntime::check_member_name_argument_is_last_argument(const methodHandle& method, 1753 const BasicType* sig_bt, 1754 const VMRegPair* regs) { 1755 ResourceMark rm; 1756 const int total_args_passed = method->size_of_parameters(); 1757 const VMRegPair* regs_with_member_name = regs; 1758 VMRegPair* regs_without_member_name = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed - 1); 1759 1760 const int member_arg_pos = total_args_passed - 1; 1761 assert(member_arg_pos >= 0 && member_arg_pos < total_args_passed, "oob"); 1762 assert(sig_bt[member_arg_pos] == T_OBJECT, "dispatch argument must be an object"); 1763 1764 java_calling_convention(sig_bt, regs_without_member_name, total_args_passed - 1); 1765 1766 for (int i = 0; i < member_arg_pos; i++) { 1767 VMReg a = regs_with_member_name[i].first(); 1768 VMReg b = regs_without_member_name[i].first(); 1769 assert(a->value() == b->value(), "register allocation mismatch: a= %d, b= %d", a->value(), b->value()); 1770 } 1771 assert(regs_with_member_name[member_arg_pos].first()->is_valid(), "bad member arg"); 1772 } 1773 #endif 1774 1775 // --------------------------------------------------------------------------- 1776 // We are calling the interpreter via a c2i. Normally this would mean that 1777 // we were called by a compiled method. However we could have lost a race 1778 // where we went int -> i2c -> c2i and so the caller could in fact be 1779 // interpreted. If the caller is compiled we attempt to patch the caller 1780 // so he no longer calls into the interpreter. 1781 JRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc)) 1782 AARCH64_PORT_ONLY(assert(pauth_ptr_is_raw(caller_pc), "should be raw")); 1783 1784 // It's possible that deoptimization can occur at a call site which hasn't 1785 // been resolved yet, in which case this function will be called from 1786 // an nmethod that has been patched for deopt and we can ignore the 1787 // request for a fixup. 1788 // Also it is possible that we lost a race in that from_compiled_entry 1789 // is now back to the i2c in that case we don't need to patch and if 1790 // we did we'd leap into space because the callsite needs to use 1791 // "to interpreter" stub in order to load up the Method*. Don't 1792 // ask me how I know this... 1793 1794 // Result from nmethod::is_unloading is not stable across safepoints. 1795 NoSafepointVerifier nsv; 1796 1797 nmethod* callee = method->code(); 1798 if (callee == nullptr) { 1799 return; 1800 } 1801 1802 // write lock needed because we might patch call site by set_to_clean() 1803 // and is_unloading() can modify nmethod's state 1804 MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, JavaThread::current())); 1805 1806 CodeBlob* cb = CodeCache::find_blob(caller_pc); 1807 if (cb == nullptr || !cb->is_nmethod() || !callee->is_in_use() || callee->is_unloading()) { 1808 return; 1809 } 1810 1811 // The check above makes sure this is an nmethod. 1812 nmethod* caller = cb->as_nmethod(); 1813 1814 // Get the return PC for the passed caller PC. 1815 address return_pc = caller_pc + frame::pc_return_offset; 1816 1817 if (!caller->is_in_use() || !NativeCall::is_call_before(return_pc)) { 1818 return; 1819 } 1820 1821 // Expect to find a native call there (unless it was no-inline cache vtable dispatch) 1822 CompiledICLocker ic_locker(caller); 1823 ResourceMark rm; 1824 1825 // If we got here through a static call or opt_virtual call, then we know where the 1826 // call address would be; let's peek at it 1827 address callsite_addr = (address)nativeCall_before(return_pc); 1828 RelocIterator iter(caller, callsite_addr, callsite_addr + 1); 1829 if (!iter.next()) { 1830 // No reloc entry found; not a static or optimized virtual call 1831 return; 1832 } 1833 1834 relocInfo::relocType type = iter.reloc()->type(); 1835 if (type != relocInfo::static_call_type && 1836 type != relocInfo::opt_virtual_call_type) { 1837 return; 1838 } 1839 1840 CompiledDirectCall* callsite = CompiledDirectCall::before(return_pc); 1841 callsite->set_to_clean(); 1842 JRT_END 1843 1844 1845 // same as JVM_Arraycopy, but called directly from compiled code 1846 JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src, jint src_pos, 1847 oopDesc* dest, jint dest_pos, 1848 jint length, 1849 JavaThread* current)) { 1850 #ifndef PRODUCT 1851 _slow_array_copy_ctr++; 1852 #endif 1853 // Check if we have null pointers 1854 if (src == nullptr || dest == nullptr) { 1855 THROW(vmSymbols::java_lang_NullPointerException()); 1856 } 1857 // Do the copy. The casts to arrayOop are necessary to the copy_array API, 1858 // even though the copy_array API also performs dynamic checks to ensure 1859 // that src and dest are truly arrays (and are conformable). 1860 // The copy_array mechanism is awkward and could be removed, but 1861 // the compilers don't call this function except as a last resort, 1862 // so it probably doesn't matter. 1863 src->klass()->copy_array((arrayOopDesc*)src, src_pos, 1864 (arrayOopDesc*)dest, dest_pos, 1865 length, current); 1866 } 1867 JRT_END 1868 1869 // The caller of generate_class_cast_message() (or one of its callers) 1870 // must use a ResourceMark in order to correctly free the result. 1871 char* SharedRuntime::generate_class_cast_message( 1872 JavaThread* thread, Klass* caster_klass) { 1873 1874 // Get target class name from the checkcast instruction 1875 vframeStream vfst(thread, true); 1876 assert(!vfst.at_end(), "Java frame must exist"); 1877 Bytecode_checkcast cc(vfst.method(), vfst.method()->bcp_from(vfst.bci())); 1878 constantPoolHandle cpool(thread, vfst.method()->constants()); 1879 Klass* target_klass = ConstantPool::klass_at_if_loaded(cpool, cc.index()); 1880 Symbol* target_klass_name = nullptr; 1881 if (target_klass == nullptr) { 1882 // This klass should be resolved, but just in case, get the name in the klass slot. 1883 target_klass_name = cpool->klass_name_at(cc.index()); 1884 } 1885 return generate_class_cast_message(caster_klass, target_klass, target_klass_name); 1886 } 1887 1888 1889 // The caller of generate_class_cast_message() (or one of its callers) 1890 // must use a ResourceMark in order to correctly free the result. 1891 char* SharedRuntime::generate_class_cast_message( 1892 Klass* caster_klass, Klass* target_klass, Symbol* target_klass_name) { 1893 const char* caster_name = caster_klass->external_name(); 1894 1895 assert(target_klass != nullptr || target_klass_name != nullptr, "one must be provided"); 1896 const char* target_name = target_klass == nullptr ? target_klass_name->as_klass_external_name() : 1897 target_klass->external_name(); 1898 1899 size_t msglen = strlen(caster_name) + strlen("class ") + strlen(" cannot be cast to class ") + strlen(target_name) + 1; 1900 1901 const char* caster_klass_description = ""; 1902 const char* target_klass_description = ""; 1903 const char* klass_separator = ""; 1904 if (target_klass != nullptr && caster_klass->module() == target_klass->module()) { 1905 caster_klass_description = caster_klass->joint_in_module_of_loader(target_klass); 1906 } else { 1907 caster_klass_description = caster_klass->class_in_module_of_loader(); 1908 target_klass_description = (target_klass != nullptr) ? target_klass->class_in_module_of_loader() : ""; 1909 klass_separator = (target_klass != nullptr) ? "; " : ""; 1910 } 1911 1912 // add 3 for parenthesis and preceding space 1913 msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3; 1914 1915 char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen); 1916 if (message == nullptr) { 1917 // Shouldn't happen, but don't cause even more problems if it does 1918 message = const_cast<char*>(caster_klass->external_name()); 1919 } else { 1920 jio_snprintf(message, 1921 msglen, 1922 "class %s cannot be cast to class %s (%s%s%s)", 1923 caster_name, 1924 target_name, 1925 caster_klass_description, 1926 klass_separator, 1927 target_klass_description 1928 ); 1929 } 1930 return message; 1931 } 1932 1933 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages()) 1934 (void) JavaThread::current()->stack_overflow_state()->reguard_stack(); 1935 JRT_END 1936 1937 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) { 1938 if (!SafepointSynchronize::is_synchronizing()) { 1939 // Only try quick_enter() if we're not trying to reach a safepoint 1940 // so that the calling thread reaches the safepoint more quickly. 1941 if (ObjectSynchronizer::quick_enter(obj, lock, current)) { 1942 return; 1943 } 1944 } 1945 // NO_ASYNC required because an async exception on the state transition destructor 1946 // would leave you with the lock held and it would never be released. 1947 // The normal monitorenter NullPointerException is thrown without acquiring a lock 1948 // and the model is that an exception implies the method failed. 1949 JRT_BLOCK_NO_ASYNC 1950 Handle h_obj(THREAD, obj); 1951 ObjectSynchronizer::enter(h_obj, lock, current); 1952 assert(!HAS_PENDING_EXCEPTION, "Should have no exception here"); 1953 JRT_BLOCK_END 1954 } 1955 1956 // Handles the uncommon case in locking, i.e., contention or an inflated lock. 1957 JRT_BLOCK_ENTRY(void, SharedRuntime::complete_monitor_locking_C(oopDesc* obj, BasicLock* lock, JavaThread* current)) 1958 SharedRuntime::monitor_enter_helper(obj, lock, current); 1959 JRT_END 1960 1961 void SharedRuntime::monitor_exit_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) { 1962 assert(JavaThread::current() == current, "invariant"); 1963 // Exit must be non-blocking, and therefore no exceptions can be thrown. 1964 ExceptionMark em(current); 1965 1966 // Check if C2_MacroAssembler::fast_unlock() or 1967 // C2_MacroAssembler::fast_unlock_lightweight() unlocked an inflated 1968 // monitor before going slow path. Since there is no safepoint 1969 // polling when calling into the VM, we can be sure that the monitor 1970 // hasn't been deallocated. 1971 ObjectMonitor* m = current->unlocked_inflated_monitor(); 1972 if (m != nullptr) { 1973 assert(!m->has_owner(current), "must be"); 1974 current->clear_unlocked_inflated_monitor(); 1975 1976 // We need to reacquire the lock before we can call ObjectSynchronizer::exit(). 1977 if (!m->try_enter(current, /*check_for_recursion*/ false)) { 1978 // Some other thread acquired the lock (or the monitor was 1979 // deflated). Either way we are done. 1980 current->dec_held_monitor_count(); 1981 return; 1982 } 1983 } 1984 1985 // The object could become unlocked through a JNI call, which we have no other checks for. 1986 // Give a fatal message if CheckJNICalls. Otherwise we ignore it. 1987 if (obj->is_unlocked()) { 1988 if (CheckJNICalls) { 1989 fatal("Object has been unlocked by JNI"); 1990 } 1991 return; 1992 } 1993 ObjectSynchronizer::exit(obj, lock, current); 1994 } 1995 1996 // Handles the uncommon cases of monitor unlocking in compiled code 1997 JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* obj, BasicLock* lock, JavaThread* current)) 1998 assert(current == JavaThread::current(), "pre-condition"); 1999 SharedRuntime::monitor_exit_helper(obj, lock, current); 2000 JRT_END 2001 2002 // This is only called when CheckJNICalls is true, and only 2003 // for virtual thread termination. 2004 JRT_LEAF(void, SharedRuntime::log_jni_monitor_still_held()) 2005 assert(CheckJNICalls, "Only call this when checking JNI usage"); 2006 if (log_is_enabled(Debug, jni)) { 2007 JavaThread* current = JavaThread::current(); 2008 int64_t vthread_id = java_lang_Thread::thread_id(current->vthread()); 2009 int64_t carrier_id = java_lang_Thread::thread_id(current->threadObj()); 2010 log_debug(jni)("VirtualThread (tid: " INT64_FORMAT ", carrier id: " INT64_FORMAT 2011 ") exiting with Objects still locked by JNI MonitorEnter.", 2012 vthread_id, carrier_id); 2013 } 2014 JRT_END 2015 2016 #ifndef PRODUCT 2017 2018 void SharedRuntime::print_statistics() { 2019 ttyLocker ttyl; 2020 if (xtty != nullptr) xtty->head("statistics type='SharedRuntime'"); 2021 2022 SharedRuntime::print_ic_miss_histogram(); 2023 2024 // Dump the JRT_ENTRY counters 2025 if (_new_instance_ctr) tty->print_cr("%5u new instance requires GC", _new_instance_ctr); 2026 if (_new_array_ctr) tty->print_cr("%5u new array requires GC", _new_array_ctr); 2027 if (_multi2_ctr) tty->print_cr("%5u multianewarray 2 dim", _multi2_ctr); 2028 if (_multi3_ctr) tty->print_cr("%5u multianewarray 3 dim", _multi3_ctr); 2029 if (_multi4_ctr) tty->print_cr("%5u multianewarray 4 dim", _multi4_ctr); 2030 if (_multi5_ctr) tty->print_cr("%5u multianewarray 5 dim", _multi5_ctr); 2031 2032 tty->print_cr("%5u inline cache miss in compiled", _ic_miss_ctr); 2033 tty->print_cr("%5u wrong method", _wrong_method_ctr); 2034 tty->print_cr("%5u unresolved static call site", _resolve_static_ctr); 2035 tty->print_cr("%5u unresolved virtual call site", _resolve_virtual_ctr); 2036 tty->print_cr("%5u unresolved opt virtual call site", _resolve_opt_virtual_ctr); 2037 2038 if (_mon_enter_stub_ctr) tty->print_cr("%5u monitor enter stub", _mon_enter_stub_ctr); 2039 if (_mon_exit_stub_ctr) tty->print_cr("%5u monitor exit stub", _mon_exit_stub_ctr); 2040 if (_mon_enter_ctr) tty->print_cr("%5u monitor enter slow", _mon_enter_ctr); 2041 if (_mon_exit_ctr) tty->print_cr("%5u monitor exit slow", _mon_exit_ctr); 2042 if (_partial_subtype_ctr) tty->print_cr("%5u slow partial subtype", _partial_subtype_ctr); 2043 if (_jbyte_array_copy_ctr) tty->print_cr("%5u byte array copies", _jbyte_array_copy_ctr); 2044 if (_jshort_array_copy_ctr) tty->print_cr("%5u short array copies", _jshort_array_copy_ctr); 2045 if (_jint_array_copy_ctr) tty->print_cr("%5u int array copies", _jint_array_copy_ctr); 2046 if (_jlong_array_copy_ctr) tty->print_cr("%5u long array copies", _jlong_array_copy_ctr); 2047 if (_oop_array_copy_ctr) tty->print_cr("%5u oop array copies", _oop_array_copy_ctr); 2048 if (_checkcast_array_copy_ctr) tty->print_cr("%5u checkcast array copies", _checkcast_array_copy_ctr); 2049 if (_unsafe_array_copy_ctr) tty->print_cr("%5u unsafe array copies", _unsafe_array_copy_ctr); 2050 if (_generic_array_copy_ctr) tty->print_cr("%5u generic array copies", _generic_array_copy_ctr); 2051 if (_slow_array_copy_ctr) tty->print_cr("%5u slow array copies", _slow_array_copy_ctr); 2052 if (_find_handler_ctr) tty->print_cr("%5u find exception handler", _find_handler_ctr); 2053 if (_rethrow_ctr) tty->print_cr("%5u rethrow handler", _rethrow_ctr); 2054 if (_unsafe_set_memory_ctr) tty->print_cr("%5u unsafe set memorys", _unsafe_set_memory_ctr); 2055 2056 AdapterHandlerLibrary::print_statistics(); 2057 2058 if (xtty != nullptr) xtty->tail("statistics"); 2059 } 2060 2061 inline double percent(int64_t x, int64_t y) { 2062 return 100.0 * (double)x / (double)MAX2(y, (int64_t)1); 2063 } 2064 2065 class MethodArityHistogram { 2066 public: 2067 enum { MAX_ARITY = 256 }; 2068 private: 2069 static uint64_t _arity_histogram[MAX_ARITY]; // histogram of #args 2070 static uint64_t _size_histogram[MAX_ARITY]; // histogram of arg size in words 2071 static uint64_t _total_compiled_calls; 2072 static uint64_t _max_compiled_calls_per_method; 2073 static int _max_arity; // max. arity seen 2074 static int _max_size; // max. arg size seen 2075 2076 static void add_method_to_histogram(nmethod* nm) { 2077 Method* method = (nm == nullptr) ? nullptr : nm->method(); 2078 if (method != nullptr) { 2079 ArgumentCount args(method->signature()); 2080 int arity = args.size() + (method->is_static() ? 0 : 1); 2081 int argsize = method->size_of_parameters(); 2082 arity = MIN2(arity, MAX_ARITY-1); 2083 argsize = MIN2(argsize, MAX_ARITY-1); 2084 uint64_t count = (uint64_t)method->compiled_invocation_count(); 2085 _max_compiled_calls_per_method = count > _max_compiled_calls_per_method ? count : _max_compiled_calls_per_method; 2086 _total_compiled_calls += count; 2087 _arity_histogram[arity] += count; 2088 _size_histogram[argsize] += count; 2089 _max_arity = MAX2(_max_arity, arity); 2090 _max_size = MAX2(_max_size, argsize); 2091 } 2092 } 2093 2094 void print_histogram_helper(int n, uint64_t* histo, const char* name) { 2095 const int N = MIN2(9, n); 2096 double sum = 0; 2097 double weighted_sum = 0; 2098 for (int i = 0; i <= n; i++) { sum += (double)histo[i]; weighted_sum += (double)(i*histo[i]); } 2099 if (sum >= 1) { // prevent divide by zero or divide overflow 2100 double rest = sum; 2101 double percent = sum / 100; 2102 for (int i = 0; i <= N; i++) { 2103 rest -= (double)histo[i]; 2104 tty->print_cr("%4d: " UINT64_FORMAT_W(12) " (%5.1f%%)", i, histo[i], (double)histo[i] / percent); 2105 } 2106 tty->print_cr("rest: " INT64_FORMAT_W(12) " (%5.1f%%)", (int64_t)rest, rest / percent); 2107 tty->print_cr("(avg. %s = %3.1f, max = %d)", name, weighted_sum / sum, n); 2108 tty->print_cr("(total # of compiled calls = " INT64_FORMAT_W(14) ")", _total_compiled_calls); 2109 tty->print_cr("(max # of compiled calls = " INT64_FORMAT_W(14) ")", _max_compiled_calls_per_method); 2110 } else { 2111 tty->print_cr("Histogram generation failed for %s. n = %d, sum = %7.5f", name, n, sum); 2112 } 2113 } 2114 2115 void print_histogram() { 2116 tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):"); 2117 print_histogram_helper(_max_arity, _arity_histogram, "arity"); 2118 tty->print_cr("\nHistogram of parameter block size (in words, incl. rcvr):"); 2119 print_histogram_helper(_max_size, _size_histogram, "size"); 2120 tty->cr(); 2121 } 2122 2123 public: 2124 MethodArityHistogram() { 2125 // Take the Compile_lock to protect against changes in the CodeBlob structures 2126 MutexLocker mu1(Compile_lock, Mutex::_safepoint_check_flag); 2127 // Take the CodeCache_lock to protect against changes in the CodeHeap structure 2128 MutexLocker mu2(CodeCache_lock, Mutex::_no_safepoint_check_flag); 2129 _max_arity = _max_size = 0; 2130 _total_compiled_calls = 0; 2131 _max_compiled_calls_per_method = 0; 2132 for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram[i] = 0; 2133 CodeCache::nmethods_do(add_method_to_histogram); 2134 print_histogram(); 2135 } 2136 }; 2137 2138 uint64_t MethodArityHistogram::_arity_histogram[MethodArityHistogram::MAX_ARITY]; 2139 uint64_t MethodArityHistogram::_size_histogram[MethodArityHistogram::MAX_ARITY]; 2140 uint64_t MethodArityHistogram::_total_compiled_calls; 2141 uint64_t MethodArityHistogram::_max_compiled_calls_per_method; 2142 int MethodArityHistogram::_max_arity; 2143 int MethodArityHistogram::_max_size; 2144 2145 void SharedRuntime::print_call_statistics(uint64_t comp_total) { 2146 tty->print_cr("Calls from compiled code:"); 2147 int64_t total = _nof_normal_calls + _nof_interface_calls + _nof_static_calls; 2148 int64_t mono_c = _nof_normal_calls - _nof_megamorphic_calls; 2149 int64_t mono_i = _nof_interface_calls; 2150 tty->print_cr("\t" INT64_FORMAT_W(12) " (100%%) total non-inlined ", total); 2151 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- virtual calls ", _nof_normal_calls, percent(_nof_normal_calls, total)); 2152 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_calls, percent(_nof_inlined_calls, _nof_normal_calls)); 2153 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- monomorphic ", mono_c, percent(mono_c, _nof_normal_calls)); 2154 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- megamorphic ", _nof_megamorphic_calls, percent(_nof_megamorphic_calls, _nof_normal_calls)); 2155 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- interface calls ", _nof_interface_calls, percent(_nof_interface_calls, total)); 2156 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_interface_calls, percent(_nof_inlined_interface_calls, _nof_interface_calls)); 2157 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- monomorphic ", mono_i, percent(mono_i, _nof_interface_calls)); 2158 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- static/special calls", _nof_static_calls, percent(_nof_static_calls, total)); 2159 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_static_calls, percent(_nof_inlined_static_calls, _nof_static_calls)); 2160 tty->cr(); 2161 tty->print_cr("Note 1: counter updates are not MT-safe."); 2162 tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;"); 2163 tty->print_cr(" %% in nested categories are relative to their category"); 2164 tty->print_cr(" (and thus add up to more than 100%% with inlining)"); 2165 tty->cr(); 2166 2167 MethodArityHistogram h; 2168 } 2169 #endif 2170 2171 #ifndef PRODUCT 2172 static int _lookups; // number of calls to lookup 2173 static int _equals; // number of buckets checked with matching hash 2174 static int _hits; // number of successful lookups 2175 static int _compact; // number of equals calls with compact signature 2176 #endif 2177 2178 // A simple wrapper class around the calling convention information 2179 // that allows sharing of adapters for the same calling convention. 2180 class AdapterFingerPrint : public CHeapObj<mtCode> { 2181 private: 2182 enum { 2183 _basic_type_bits = 4, 2184 _basic_type_mask = right_n_bits(_basic_type_bits), 2185 _basic_types_per_int = BitsPerInt / _basic_type_bits, 2186 _compact_int_count = 3 2187 }; 2188 // TO DO: Consider integrating this with a more global scheme for compressing signatures. 2189 // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive. 2190 2191 union { 2192 int _compact[_compact_int_count]; 2193 int* _fingerprint; 2194 } _value; 2195 int _length; // A negative length indicates the fingerprint is in the compact form, 2196 // Otherwise _value._fingerprint is the array. 2197 2198 // Remap BasicTypes that are handled equivalently by the adapters. 2199 // These are correct for the current system but someday it might be 2200 // necessary to make this mapping platform dependent. 2201 static int adapter_encoding(BasicType in) { 2202 switch (in) { 2203 case T_BOOLEAN: 2204 case T_BYTE: 2205 case T_SHORT: 2206 case T_CHAR: 2207 // There are all promoted to T_INT in the calling convention 2208 return T_INT; 2209 2210 case T_OBJECT: 2211 case T_ARRAY: 2212 // In other words, we assume that any register good enough for 2213 // an int or long is good enough for a managed pointer. 2214 #ifdef _LP64 2215 return T_LONG; 2216 #else 2217 return T_INT; 2218 #endif 2219 2220 case T_INT: 2221 case T_LONG: 2222 case T_FLOAT: 2223 case T_DOUBLE: 2224 case T_VOID: 2225 return in; 2226 2227 default: 2228 ShouldNotReachHere(); 2229 return T_CONFLICT; 2230 } 2231 } 2232 2233 public: 2234 AdapterFingerPrint(int total_args_passed, BasicType* sig_bt) { 2235 // The fingerprint is based on the BasicType signature encoded 2236 // into an array of ints with eight entries per int. 2237 int* ptr; 2238 int len = (total_args_passed + (_basic_types_per_int-1)) / _basic_types_per_int; 2239 if (len <= _compact_int_count) { 2240 assert(_compact_int_count == 3, "else change next line"); 2241 _value._compact[0] = _value._compact[1] = _value._compact[2] = 0; 2242 // Storing the signature encoded as signed chars hits about 98% 2243 // of the time. 2244 _length = -len; 2245 ptr = _value._compact; 2246 } else { 2247 _length = len; 2248 _value._fingerprint = NEW_C_HEAP_ARRAY(int, _length, mtCode); 2249 ptr = _value._fingerprint; 2250 } 2251 2252 // Now pack the BasicTypes with 8 per int 2253 int sig_index = 0; 2254 for (int index = 0; index < len; index++) { 2255 int value = 0; 2256 for (int byte = 0; sig_index < total_args_passed && byte < _basic_types_per_int; byte++) { 2257 int bt = adapter_encoding(sig_bt[sig_index++]); 2258 assert((bt & _basic_type_mask) == bt, "must fit in 4 bits"); 2259 value = (value << _basic_type_bits) | bt; 2260 } 2261 ptr[index] = value; 2262 } 2263 } 2264 2265 ~AdapterFingerPrint() { 2266 if (_length > 0) { 2267 FREE_C_HEAP_ARRAY(int, _value._fingerprint); 2268 } 2269 } 2270 2271 int value(int index) { 2272 if (_length < 0) { 2273 return _value._compact[index]; 2274 } 2275 return _value._fingerprint[index]; 2276 } 2277 int length() { 2278 if (_length < 0) return -_length; 2279 return _length; 2280 } 2281 2282 bool is_compact() { 2283 return _length <= 0; 2284 } 2285 2286 unsigned int compute_hash() { 2287 int hash = 0; 2288 for (int i = 0; i < length(); i++) { 2289 int v = value(i); 2290 hash = (hash << 8) ^ v ^ (hash >> 5); 2291 } 2292 return (unsigned int)hash; 2293 } 2294 2295 const char* as_string() { 2296 stringStream st; 2297 st.print("0x"); 2298 for (int i = 0; i < length(); i++) { 2299 st.print("%x", value(i)); 2300 } 2301 return st.as_string(); 2302 } 2303 2304 #ifndef PRODUCT 2305 // Reconstitutes the basic type arguments from the fingerprint, 2306 // producing strings like LIJDF 2307 const char* as_basic_args_string() { 2308 stringStream st; 2309 bool long_prev = false; 2310 for (int i = 0; i < length(); i++) { 2311 unsigned val = (unsigned)value(i); 2312 // args are packed so that first/lower arguments are in the highest 2313 // bits of each int value, so iterate from highest to the lowest 2314 for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) { 2315 unsigned v = (val >> j) & _basic_type_mask; 2316 if (v == 0) { 2317 assert(i == length() - 1, "Only expect zeroes in the last word"); 2318 continue; 2319 } 2320 if (long_prev) { 2321 long_prev = false; 2322 if (v == T_VOID) { 2323 st.print("J"); 2324 } else { 2325 st.print("L"); 2326 } 2327 } 2328 switch (v) { 2329 case T_INT: st.print("I"); break; 2330 case T_LONG: long_prev = true; break; 2331 case T_FLOAT: st.print("F"); break; 2332 case T_DOUBLE: st.print("D"); break; 2333 case T_VOID: break; 2334 default: ShouldNotReachHere(); 2335 } 2336 } 2337 } 2338 if (long_prev) { 2339 st.print("L"); 2340 } 2341 return st.as_string(); 2342 } 2343 #endif // !product 2344 2345 bool equals(AdapterFingerPrint* other) { 2346 if (other->_length != _length) { 2347 return false; 2348 } 2349 if (_length < 0) { 2350 assert(_compact_int_count == 3, "else change next line"); 2351 return _value._compact[0] == other->_value._compact[0] && 2352 _value._compact[1] == other->_value._compact[1] && 2353 _value._compact[2] == other->_value._compact[2]; 2354 } else { 2355 for (int i = 0; i < _length; i++) { 2356 if (_value._fingerprint[i] != other->_value._fingerprint[i]) { 2357 return false; 2358 } 2359 } 2360 } 2361 return true; 2362 } 2363 2364 static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) { 2365 NOT_PRODUCT(_equals++); 2366 return fp1->equals(fp2); 2367 } 2368 2369 static unsigned int compute_hash(AdapterFingerPrint* const& fp) { 2370 return fp->compute_hash(); 2371 } 2372 }; 2373 2374 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries 2375 using AdapterHandlerTable = ResourceHashtable<AdapterFingerPrint*, AdapterHandlerEntry*, 293, 2376 AnyObj::C_HEAP, mtCode, 2377 AdapterFingerPrint::compute_hash, 2378 AdapterFingerPrint::equals>; 2379 static AdapterHandlerTable* _adapter_handler_table; 2380 2381 // Find a entry with the same fingerprint if it exists 2382 static AdapterHandlerEntry* lookup(int total_args_passed, BasicType* sig_bt) { 2383 NOT_PRODUCT(_lookups++); 2384 assert_lock_strong(AdapterHandlerLibrary_lock); 2385 AdapterFingerPrint fp(total_args_passed, sig_bt); 2386 AdapterHandlerEntry** entry = _adapter_handler_table->get(&fp); 2387 if (entry != nullptr) { 2388 #ifndef PRODUCT 2389 if (fp.is_compact()) _compact++; 2390 _hits++; 2391 #endif 2392 return *entry; 2393 } 2394 return nullptr; 2395 } 2396 2397 #ifndef PRODUCT 2398 static void print_table_statistics() { 2399 auto size = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) { 2400 return sizeof(*key) + sizeof(*a); 2401 }; 2402 TableStatistics ts = _adapter_handler_table->statistics_calculate(size); 2403 ts.print(tty, "AdapterHandlerTable"); 2404 tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)", 2405 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries()); 2406 tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d compact %d", 2407 _lookups, _equals, _hits, _compact); 2408 } 2409 #endif 2410 2411 // --------------------------------------------------------------------------- 2412 // Implementation of AdapterHandlerLibrary 2413 AdapterHandlerEntry* AdapterHandlerLibrary::_abstract_method_handler = nullptr; 2414 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr; 2415 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr; 2416 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr; 2417 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr; 2418 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr; 2419 const int AdapterHandlerLibrary_size = 16*K; 2420 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr; 2421 2422 BufferBlob* AdapterHandlerLibrary::buffer_blob() { 2423 return _buffer; 2424 } 2425 2426 static void post_adapter_creation(const AdapterBlob* new_adapter, 2427 const AdapterHandlerEntry* entry) { 2428 if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) { 2429 char blob_id[256]; 2430 jio_snprintf(blob_id, 2431 sizeof(blob_id), 2432 "%s(%s)", 2433 new_adapter->name(), 2434 entry->fingerprint()->as_string()); 2435 if (Forte::is_enabled()) { 2436 Forte::register_stub(blob_id, new_adapter->content_begin(), new_adapter->content_end()); 2437 } 2438 2439 if (JvmtiExport::should_post_dynamic_code_generated()) { 2440 JvmtiExport::post_dynamic_code_generated(blob_id, new_adapter->content_begin(), new_adapter->content_end()); 2441 } 2442 } 2443 } 2444 2445 void AdapterHandlerLibrary::initialize() { 2446 ResourceMark rm; 2447 AdapterBlob* no_arg_blob = nullptr; 2448 AdapterBlob* int_arg_blob = nullptr; 2449 AdapterBlob* obj_arg_blob = nullptr; 2450 AdapterBlob* obj_int_arg_blob = nullptr; 2451 AdapterBlob* obj_obj_arg_blob = nullptr; 2452 { 2453 _adapter_handler_table = new (mtCode) AdapterHandlerTable(); 2454 MutexLocker mu(AdapterHandlerLibrary_lock); 2455 2456 // Create a special handler for abstract methods. Abstract methods 2457 // are never compiled so an i2c entry is somewhat meaningless, but 2458 // throw AbstractMethodError just in case. 2459 // Pass wrong_method_abstract for the c2i transitions to return 2460 // AbstractMethodError for invalid invocations. 2461 address wrong_method_abstract = SharedRuntime::get_handle_wrong_method_abstract_stub(); 2462 _abstract_method_handler = AdapterHandlerLibrary::new_entry(new AdapterFingerPrint(0, nullptr), 2463 SharedRuntime::throw_AbstractMethodError_entry(), 2464 wrong_method_abstract, wrong_method_abstract); 2465 2466 _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size); 2467 _no_arg_handler = create_adapter(no_arg_blob, 0, nullptr, true); 2468 2469 BasicType obj_args[] = { T_OBJECT }; 2470 _obj_arg_handler = create_adapter(obj_arg_blob, 1, obj_args, true); 2471 2472 BasicType int_args[] = { T_INT }; 2473 _int_arg_handler = create_adapter(int_arg_blob, 1, int_args, true); 2474 2475 BasicType obj_int_args[] = { T_OBJECT, T_INT }; 2476 _obj_int_arg_handler = create_adapter(obj_int_arg_blob, 2, obj_int_args, true); 2477 2478 BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT }; 2479 _obj_obj_arg_handler = create_adapter(obj_obj_arg_blob, 2, obj_obj_args, true); 2480 2481 assert(no_arg_blob != nullptr && 2482 obj_arg_blob != nullptr && 2483 int_arg_blob != nullptr && 2484 obj_int_arg_blob != nullptr && 2485 obj_obj_arg_blob != nullptr, "Initial adapters must be properly created"); 2486 } 2487 2488 // Outside of the lock 2489 post_adapter_creation(no_arg_blob, _no_arg_handler); 2490 post_adapter_creation(obj_arg_blob, _obj_arg_handler); 2491 post_adapter_creation(int_arg_blob, _int_arg_handler); 2492 post_adapter_creation(obj_int_arg_blob, _obj_int_arg_handler); 2493 post_adapter_creation(obj_obj_arg_blob, _obj_obj_arg_handler); 2494 } 2495 2496 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint, 2497 address i2c_entry, 2498 address c2i_entry, 2499 address c2i_unverified_entry, 2500 address c2i_no_clinit_check_entry) { 2501 // Insert an entry into the table 2502 return new AdapterHandlerEntry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry, 2503 c2i_no_clinit_check_entry); 2504 } 2505 2506 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) { 2507 if (method->is_abstract()) { 2508 return _abstract_method_handler; 2509 } 2510 int total_args_passed = method->size_of_parameters(); // All args on stack 2511 if (total_args_passed == 0) { 2512 return _no_arg_handler; 2513 } else if (total_args_passed == 1) { 2514 if (!method->is_static()) { 2515 return _obj_arg_handler; 2516 } 2517 switch (method->signature()->char_at(1)) { 2518 case JVM_SIGNATURE_CLASS: 2519 case JVM_SIGNATURE_ARRAY: 2520 return _obj_arg_handler; 2521 case JVM_SIGNATURE_INT: 2522 case JVM_SIGNATURE_BOOLEAN: 2523 case JVM_SIGNATURE_CHAR: 2524 case JVM_SIGNATURE_BYTE: 2525 case JVM_SIGNATURE_SHORT: 2526 return _int_arg_handler; 2527 } 2528 } else if (total_args_passed == 2 && 2529 !method->is_static()) { 2530 switch (method->signature()->char_at(1)) { 2531 case JVM_SIGNATURE_CLASS: 2532 case JVM_SIGNATURE_ARRAY: 2533 return _obj_obj_arg_handler; 2534 case JVM_SIGNATURE_INT: 2535 case JVM_SIGNATURE_BOOLEAN: 2536 case JVM_SIGNATURE_CHAR: 2537 case JVM_SIGNATURE_BYTE: 2538 case JVM_SIGNATURE_SHORT: 2539 return _obj_int_arg_handler; 2540 } 2541 } 2542 return nullptr; 2543 } 2544 2545 class AdapterSignatureIterator : public SignatureIterator { 2546 private: 2547 BasicType stack_sig_bt[16]; 2548 BasicType* sig_bt; 2549 int index; 2550 2551 public: 2552 AdapterSignatureIterator(Symbol* signature, 2553 fingerprint_t fingerprint, 2554 bool is_static, 2555 int total_args_passed) : 2556 SignatureIterator(signature, fingerprint), 2557 index(0) 2558 { 2559 sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed); 2560 if (!is_static) { // Pass in receiver first 2561 sig_bt[index++] = T_OBJECT; 2562 } 2563 do_parameters_on(this); 2564 } 2565 2566 BasicType* basic_types() { 2567 return sig_bt; 2568 } 2569 2570 #ifdef ASSERT 2571 int slots() { 2572 return index; 2573 } 2574 #endif 2575 2576 private: 2577 2578 friend class SignatureIterator; // so do_parameters_on can call do_type 2579 void do_type(BasicType type) { 2580 sig_bt[index++] = type; 2581 if (type == T_LONG || type == T_DOUBLE) { 2582 sig_bt[index++] = T_VOID; // Longs & doubles take 2 Java slots 2583 } 2584 } 2585 }; 2586 2587 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) { 2588 // Use customized signature handler. Need to lock around updates to 2589 // the _adapter_handler_table (it is not safe for concurrent readers 2590 // and a single writer: this could be fixed if it becomes a 2591 // problem). 2592 2593 // Fast-path for trivial adapters 2594 AdapterHandlerEntry* entry = get_simple_adapter(method); 2595 if (entry != nullptr) { 2596 return entry; 2597 } 2598 2599 ResourceMark rm; 2600 AdapterBlob* new_adapter = nullptr; 2601 2602 // Fill in the signature array, for the calling-convention call. 2603 int total_args_passed = method->size_of_parameters(); // All args on stack 2604 2605 AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(), 2606 method->is_static(), total_args_passed); 2607 assert(si.slots() == total_args_passed, ""); 2608 BasicType* sig_bt = si.basic_types(); 2609 { 2610 MutexLocker mu(AdapterHandlerLibrary_lock); 2611 2612 // Lookup method signature's fingerprint 2613 entry = lookup(total_args_passed, sig_bt); 2614 2615 if (entry != nullptr) { 2616 #ifdef ASSERT 2617 if (VerifyAdapterSharing) { 2618 AdapterBlob* comparison_blob = nullptr; 2619 AdapterHandlerEntry* comparison_entry = create_adapter(comparison_blob, total_args_passed, sig_bt, false); 2620 assert(comparison_blob == nullptr, "no blob should be created when creating an adapter for comparison"); 2621 assert(comparison_entry->compare_code(entry), "code must match"); 2622 // Release the one just created and return the original 2623 delete comparison_entry; 2624 } 2625 #endif 2626 return entry; 2627 } 2628 2629 entry = create_adapter(new_adapter, total_args_passed, sig_bt, /* allocate_code_blob */ true); 2630 } 2631 2632 // Outside of the lock 2633 if (new_adapter != nullptr) { 2634 post_adapter_creation(new_adapter, entry); 2635 } 2636 return entry; 2637 } 2638 2639 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(AdapterBlob*& new_adapter, 2640 int total_args_passed, 2641 BasicType* sig_bt, 2642 bool allocate_code_blob) { 2643 if (log_is_enabled(Info, perf, class, link)) { 2644 ClassLoader::perf_method_adapters_count()->inc(); 2645 } 2646 2647 // StubRoutines::_final_stubs_code is initialized after this function can be called. As a result, 2648 // VerifyAdapterCalls and VerifyAdapterSharing can fail if we re-use code that generated prior 2649 // to all StubRoutines::_final_stubs_code being set. Checks refer to runtime range checks generated 2650 // in an I2C stub that ensure that an I2C stub is called from an interpreter frame or stubs. 2651 bool contains_all_checks = StubRoutines::final_stubs_code() != nullptr; 2652 2653 VMRegPair stack_regs[16]; 2654 VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed); 2655 2656 // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage 2657 int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed); 2658 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache 2659 CodeBuffer buffer(buf); 2660 short buffer_locs[20]; 2661 buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs, 2662 sizeof(buffer_locs)/sizeof(relocInfo)); 2663 2664 // Make a C heap allocated version of the fingerprint to store in the adapter 2665 AdapterFingerPrint* fingerprint = new AdapterFingerPrint(total_args_passed, sig_bt); 2666 MacroAssembler _masm(&buffer); 2667 AdapterHandlerEntry* entry = SharedRuntime::generate_i2c2i_adapters(&_masm, 2668 total_args_passed, 2669 comp_args_on_stack, 2670 sig_bt, 2671 regs, 2672 fingerprint); 2673 2674 #ifdef ASSERT 2675 if (VerifyAdapterSharing) { 2676 entry->save_code(buf->code_begin(), buffer.insts_size()); 2677 if (!allocate_code_blob) { 2678 return entry; 2679 } 2680 } 2681 #endif 2682 2683 new_adapter = AdapterBlob::create(&buffer); 2684 NOT_PRODUCT(int insts_size = buffer.insts_size()); 2685 if (new_adapter == nullptr) { 2686 // CodeCache is full, disable compilation 2687 // Ought to log this but compile log is only per compile thread 2688 // and we're some non descript Java thread. 2689 return nullptr; 2690 } 2691 entry->relocate(new_adapter->content_begin()); 2692 #ifndef PRODUCT 2693 // debugging support 2694 if (PrintAdapterHandlers || PrintStubCode) { 2695 ttyLocker ttyl; 2696 entry->print_adapter_on(tty); 2697 tty->print_cr("i2c argument handler #%d for: %s %s (%d bytes generated)", 2698 _adapter_handler_table->number_of_entries(), fingerprint->as_basic_args_string(), 2699 fingerprint->as_string(), insts_size); 2700 tty->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(entry->get_c2i_entry())); 2701 if (Verbose || PrintStubCode) { 2702 address first_pc = entry->base_address(); 2703 if (first_pc != nullptr) { 2704 Disassembler::decode(first_pc, first_pc + insts_size, tty 2705 NOT_PRODUCT(COMMA &new_adapter->asm_remarks())); 2706 tty->cr(); 2707 } 2708 } 2709 } 2710 #endif 2711 2712 // Add the entry only if the entry contains all required checks (see sharedRuntime_xxx.cpp) 2713 // The checks are inserted only if -XX:+VerifyAdapterCalls is specified. 2714 if (contains_all_checks || !VerifyAdapterCalls) { 2715 assert_lock_strong(AdapterHandlerLibrary_lock); 2716 _adapter_handler_table->put(fingerprint, entry); 2717 } 2718 return entry; 2719 } 2720 2721 address AdapterHandlerEntry::base_address() { 2722 address base = _i2c_entry; 2723 if (base == nullptr) base = _c2i_entry; 2724 assert(base <= _c2i_entry || _c2i_entry == nullptr, ""); 2725 assert(base <= _c2i_unverified_entry || _c2i_unverified_entry == nullptr, ""); 2726 assert(base <= _c2i_no_clinit_check_entry || _c2i_no_clinit_check_entry == nullptr, ""); 2727 return base; 2728 } 2729 2730 void AdapterHandlerEntry::relocate(address new_base) { 2731 address old_base = base_address(); 2732 assert(old_base != nullptr, ""); 2733 ptrdiff_t delta = new_base - old_base; 2734 if (_i2c_entry != nullptr) 2735 _i2c_entry += delta; 2736 if (_c2i_entry != nullptr) 2737 _c2i_entry += delta; 2738 if (_c2i_unverified_entry != nullptr) 2739 _c2i_unverified_entry += delta; 2740 if (_c2i_no_clinit_check_entry != nullptr) 2741 _c2i_no_clinit_check_entry += delta; 2742 assert(base_address() == new_base, ""); 2743 } 2744 2745 2746 AdapterHandlerEntry::~AdapterHandlerEntry() { 2747 delete _fingerprint; 2748 #ifdef ASSERT 2749 FREE_C_HEAP_ARRAY(unsigned char, _saved_code); 2750 #endif 2751 } 2752 2753 2754 #ifdef ASSERT 2755 // Capture the code before relocation so that it can be compared 2756 // against other versions. If the code is captured after relocation 2757 // then relative instructions won't be equivalent. 2758 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) { 2759 _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode); 2760 _saved_code_length = length; 2761 memcpy(_saved_code, buffer, length); 2762 } 2763 2764 2765 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) { 2766 assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved"); 2767 2768 if (other->_saved_code_length != _saved_code_length) { 2769 return false; 2770 } 2771 2772 return memcmp(other->_saved_code, _saved_code, _saved_code_length) == 0; 2773 } 2774 #endif 2775 2776 2777 /** 2778 * Create a native wrapper for this native method. The wrapper converts the 2779 * Java-compiled calling convention to the native convention, handles 2780 * arguments, and transitions to native. On return from the native we transition 2781 * back to java blocking if a safepoint is in progress. 2782 */ 2783 void AdapterHandlerLibrary::create_native_wrapper(const methodHandle& method) { 2784 ResourceMark rm; 2785 nmethod* nm = nullptr; 2786 2787 // Check if memory should be freed before allocation 2788 CodeCache::gc_on_allocation(); 2789 2790 assert(method->is_native(), "must be native"); 2791 assert(method->is_special_native_intrinsic() || 2792 method->has_native_function(), "must have something valid to call!"); 2793 2794 { 2795 // Perform the work while holding the lock, but perform any printing outside the lock 2796 MutexLocker mu(AdapterHandlerLibrary_lock); 2797 // See if somebody beat us to it 2798 if (method->code() != nullptr) { 2799 return; 2800 } 2801 2802 const int compile_id = CompileBroker::assign_compile_id(method, CompileBroker::standard_entry_bci); 2803 assert(compile_id > 0, "Must generate native wrapper"); 2804 2805 2806 ResourceMark rm; 2807 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache 2808 if (buf != nullptr) { 2809 CodeBuffer buffer(buf); 2810 2811 if (method->is_continuation_enter_intrinsic()) { 2812 buffer.initialize_stubs_size(192); 2813 } 2814 2815 struct { double data[20]; } locs_buf; 2816 struct { double data[20]; } stubs_locs_buf; 2817 buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo)); 2818 #if defined(AARCH64) || defined(PPC64) 2819 // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be 2820 // in the constant pool to ensure ordering between the barrier and oops 2821 // accesses. For native_wrappers we need a constant. 2822 // On PPC64 the continuation enter intrinsic needs the constant pool for the compiled 2823 // static java call that is resolved in the runtime. 2824 if (PPC64_ONLY(method->is_continuation_enter_intrinsic() &&) true) { 2825 buffer.initialize_consts_size(8 PPC64_ONLY(+ 24)); 2826 } 2827 #endif 2828 buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo)); 2829 MacroAssembler _masm(&buffer); 2830 2831 // Fill in the signature array, for the calling-convention call. 2832 const int total_args_passed = method->size_of_parameters(); 2833 2834 VMRegPair stack_regs[16]; 2835 VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed); 2836 2837 AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(), 2838 method->is_static(), total_args_passed); 2839 BasicType* sig_bt = si.basic_types(); 2840 assert(si.slots() == total_args_passed, ""); 2841 BasicType ret_type = si.return_type(); 2842 2843 // Now get the compiled-Java arguments layout. 2844 SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed); 2845 2846 // Generate the compiled-to-native wrapper code 2847 nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type); 2848 2849 if (nm != nullptr) { 2850 { 2851 MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag); 2852 if (nm->make_in_use()) { 2853 method->set_code(method, nm); 2854 } 2855 } 2856 2857 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, CompileBroker::compiler(CompLevel_simple)); 2858 if (directive->PrintAssemblyOption) { 2859 nm->print_code(); 2860 } 2861 DirectivesStack::release(directive); 2862 } 2863 } 2864 } // Unlock AdapterHandlerLibrary_lock 2865 2866 2867 // Install the generated code. 2868 if (nm != nullptr) { 2869 const char *msg = method->is_static() ? "(static)" : ""; 2870 CompileTask::print_ul(nm, msg); 2871 if (PrintCompilation) { 2872 ttyLocker ttyl; 2873 CompileTask::print(tty, nm, msg); 2874 } 2875 nm->post_compiled_method_load_event(); 2876 } 2877 } 2878 2879 // ------------------------------------------------------------------------- 2880 // Java-Java calling convention 2881 // (what you use when Java calls Java) 2882 2883 //------------------------------name_for_receiver---------------------------------- 2884 // For a given signature, return the VMReg for parameter 0. 2885 VMReg SharedRuntime::name_for_receiver() { 2886 VMRegPair regs; 2887 BasicType sig_bt = T_OBJECT; 2888 (void) java_calling_convention(&sig_bt, ®s, 1); 2889 // Return argument 0 register. In the LP64 build pointers 2890 // take 2 registers, but the VM wants only the 'main' name. 2891 return regs.first(); 2892 } 2893 2894 VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, bool has_appendix, int* arg_size) { 2895 // This method is returning a data structure allocating as a 2896 // ResourceObject, so do not put any ResourceMarks in here. 2897 2898 BasicType *sig_bt = NEW_RESOURCE_ARRAY(BasicType, 256); 2899 VMRegPair *regs = NEW_RESOURCE_ARRAY(VMRegPair, 256); 2900 int cnt = 0; 2901 if (has_receiver) { 2902 sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature 2903 } 2904 2905 for (SignatureStream ss(sig); !ss.at_return_type(); ss.next()) { 2906 BasicType type = ss.type(); 2907 sig_bt[cnt++] = type; 2908 if (is_double_word_type(type)) 2909 sig_bt[cnt++] = T_VOID; 2910 } 2911 2912 if (has_appendix) { 2913 sig_bt[cnt++] = T_OBJECT; 2914 } 2915 2916 assert(cnt < 256, "grow table size"); 2917 2918 int comp_args_on_stack; 2919 comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt); 2920 2921 // the calling convention doesn't count out_preserve_stack_slots so 2922 // we must add that in to get "true" stack offsets. 2923 2924 if (comp_args_on_stack) { 2925 for (int i = 0; i < cnt; i++) { 2926 VMReg reg1 = regs[i].first(); 2927 if (reg1->is_stack()) { 2928 // Yuck 2929 reg1 = reg1->bias(out_preserve_stack_slots()); 2930 } 2931 VMReg reg2 = regs[i].second(); 2932 if (reg2->is_stack()) { 2933 // Yuck 2934 reg2 = reg2->bias(out_preserve_stack_slots()); 2935 } 2936 regs[i].set_pair(reg2, reg1); 2937 } 2938 } 2939 2940 // results 2941 *arg_size = cnt; 2942 return regs; 2943 } 2944 2945 // OSR Migration Code 2946 // 2947 // This code is used convert interpreter frames into compiled frames. It is 2948 // called from very start of a compiled OSR nmethod. A temp array is 2949 // allocated to hold the interesting bits of the interpreter frame. All 2950 // active locks are inflated to allow them to move. The displaced headers and 2951 // active interpreter locals are copied into the temp buffer. Then we return 2952 // back to the compiled code. The compiled code then pops the current 2953 // interpreter frame off the stack and pushes a new compiled frame. Then it 2954 // copies the interpreter locals and displaced headers where it wants. 2955 // Finally it calls back to free the temp buffer. 2956 // 2957 // All of this is done NOT at any Safepoint, nor is any safepoint or GC allowed. 2958 2959 JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *current) ) 2960 assert(current == JavaThread::current(), "pre-condition"); 2961 2962 // During OSR migration, we unwind the interpreted frame and replace it with a compiled 2963 // frame. The stack watermark code below ensures that the interpreted frame is processed 2964 // before it gets unwound. This is helpful as the size of the compiled frame could be 2965 // larger than the interpreted frame, which could result in the new frame not being 2966 // processed correctly. 2967 StackWatermarkSet::before_unwind(current); 2968 2969 // 2970 // This code is dependent on the memory layout of the interpreter local 2971 // array and the monitors. On all of our platforms the layout is identical 2972 // so this code is shared. If some platform lays the their arrays out 2973 // differently then this code could move to platform specific code or 2974 // the code here could be modified to copy items one at a time using 2975 // frame accessor methods and be platform independent. 2976 2977 frame fr = current->last_frame(); 2978 assert(fr.is_interpreted_frame(), ""); 2979 assert(fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks"); 2980 2981 // Figure out how many monitors are active. 2982 int active_monitor_count = 0; 2983 for (BasicObjectLock *kptr = fr.interpreter_frame_monitor_end(); 2984 kptr < fr.interpreter_frame_monitor_begin(); 2985 kptr = fr.next_monitor_in_interpreter_frame(kptr) ) { 2986 if (kptr->obj() != nullptr) active_monitor_count++; 2987 } 2988 2989 // QQQ we could place number of active monitors in the array so that compiled code 2990 // could double check it. 2991 2992 Method* moop = fr.interpreter_frame_method(); 2993 int max_locals = moop->max_locals(); 2994 // Allocate temp buffer, 1 word per local & 2 per active monitor 2995 int buf_size_words = max_locals + active_monitor_count * BasicObjectLock::size(); 2996 intptr_t *buf = NEW_C_HEAP_ARRAY(intptr_t,buf_size_words, mtCode); 2997 2998 // Copy the locals. Order is preserved so that loading of longs works. 2999 // Since there's no GC I can copy the oops blindly. 3000 assert(sizeof(HeapWord)==sizeof(intptr_t), "fix this code"); 3001 Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1), 3002 (HeapWord*)&buf[0], 3003 max_locals); 3004 3005 // Inflate locks. Copy the displaced headers. Be careful, there can be holes. 3006 int i = max_locals; 3007 for (BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end(); 3008 kptr2 < fr.interpreter_frame_monitor_begin(); 3009 kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) { 3010 if (kptr2->obj() != nullptr) { // Avoid 'holes' in the monitor array 3011 BasicLock *lock = kptr2->lock(); 3012 if (LockingMode == LM_LEGACY) { 3013 // Inflate so the object's header no longer refers to the BasicLock. 3014 if (lock->displaced_header().is_unlocked()) { 3015 // The object is locked and the resulting ObjectMonitor* will also be 3016 // locked so it can't be async deflated until ownership is dropped. 3017 // See the big comment in basicLock.cpp: BasicLock::move_to(). 3018 ObjectSynchronizer::inflate_helper(kptr2->obj()); 3019 } 3020 // Now the displaced header is free to move because the 3021 // object's header no longer refers to it. 3022 buf[i] = (intptr_t)lock->displaced_header().value(); 3023 } else if (UseObjectMonitorTable) { 3024 buf[i] = (intptr_t)lock->object_monitor_cache(); 3025 } 3026 #ifdef ASSERT 3027 else { 3028 buf[i] = badDispHeaderOSR; 3029 } 3030 #endif 3031 i++; 3032 buf[i++] = cast_from_oop<intptr_t>(kptr2->obj()); 3033 } 3034 } 3035 assert(i - max_locals == active_monitor_count*2, "found the expected number of monitors"); 3036 3037 RegisterMap map(current, 3038 RegisterMap::UpdateMap::skip, 3039 RegisterMap::ProcessFrames::include, 3040 RegisterMap::WalkContinuation::skip); 3041 frame sender = fr.sender(&map); 3042 if (sender.is_interpreted_frame()) { 3043 current->push_cont_fastpath(sender.sp()); 3044 } 3045 3046 return buf; 3047 JRT_END 3048 3049 JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) ) 3050 FREE_C_HEAP_ARRAY(intptr_t, buf); 3051 JRT_END 3052 3053 bool AdapterHandlerLibrary::contains(const CodeBlob* b) { 3054 bool found = false; 3055 auto findblob = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) { 3056 return (found = (b == CodeCache::find_blob(a->get_i2c_entry()))); 3057 }; 3058 assert_locked_or_safepoint(AdapterHandlerLibrary_lock); 3059 _adapter_handler_table->iterate(findblob); 3060 return found; 3061 } 3062 3063 void AdapterHandlerLibrary::print_handler_on(outputStream* st, const CodeBlob* b) { 3064 bool found = false; 3065 auto findblob = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) { 3066 if (b == CodeCache::find_blob(a->get_i2c_entry())) { 3067 found = true; 3068 st->print("Adapter for signature: "); 3069 a->print_adapter_on(st); 3070 return true; 3071 } else { 3072 return false; // keep looking 3073 } 3074 }; 3075 assert_locked_or_safepoint(AdapterHandlerLibrary_lock); 3076 _adapter_handler_table->iterate(findblob); 3077 assert(found, "Should have found handler"); 3078 } 3079 3080 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const { 3081 st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string()); 3082 if (get_i2c_entry() != nullptr) { 3083 st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry())); 3084 } 3085 if (get_c2i_entry() != nullptr) { 3086 st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry())); 3087 } 3088 if (get_c2i_unverified_entry() != nullptr) { 3089 st->print(" c2iUV: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry())); 3090 } 3091 if (get_c2i_no_clinit_check_entry() != nullptr) { 3092 st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry())); 3093 } 3094 st->cr(); 3095 } 3096 3097 #ifndef PRODUCT 3098 3099 void AdapterHandlerLibrary::print_statistics() { 3100 print_table_statistics(); 3101 } 3102 3103 #endif /* PRODUCT */ 3104 3105 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current)) 3106 assert(current == JavaThread::current(), "pre-condition"); 3107 StackOverflow* overflow_state = current->stack_overflow_state(); 3108 overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true); 3109 overflow_state->set_reserved_stack_activation(current->stack_base()); 3110 JRT_END 3111 3112 frame SharedRuntime::look_for_reserved_stack_annotated_method(JavaThread* current, frame fr) { 3113 ResourceMark rm(current); 3114 frame activation; 3115 nmethod* nm = nullptr; 3116 int count = 1; 3117 3118 assert(fr.is_java_frame(), "Must start on Java frame"); 3119 3120 RegisterMap map(JavaThread::current(), 3121 RegisterMap::UpdateMap::skip, 3122 RegisterMap::ProcessFrames::skip, 3123 RegisterMap::WalkContinuation::skip); // don't walk continuations 3124 for (; !fr.is_first_frame(); fr = fr.sender(&map)) { 3125 if (!fr.is_java_frame()) { 3126 continue; 3127 } 3128 3129 Method* method = nullptr; 3130 bool found = false; 3131 if (fr.is_interpreted_frame()) { 3132 method = fr.interpreter_frame_method(); 3133 if (method != nullptr && method->has_reserved_stack_access()) { 3134 found = true; 3135 } 3136 } else { 3137 CodeBlob* cb = fr.cb(); 3138 if (cb != nullptr && cb->is_nmethod()) { 3139 nm = cb->as_nmethod(); 3140 method = nm->method(); 3141 // scope_desc_near() must be used, instead of scope_desc_at() because on 3142 // SPARC, the pcDesc can be on the delay slot after the call instruction. 3143 for (ScopeDesc *sd = nm->scope_desc_near(fr.pc()); sd != nullptr; sd = sd->sender()) { 3144 method = sd->method(); 3145 if (method != nullptr && method->has_reserved_stack_access()) { 3146 found = true; 3147 } 3148 } 3149 } 3150 } 3151 if (found) { 3152 activation = fr; 3153 warning("Potentially dangerous stack overflow in " 3154 "ReservedStackAccess annotated method %s [%d]", 3155 method->name_and_sig_as_C_string(), count++); 3156 EventReservedStackActivation event; 3157 if (event.should_commit()) { 3158 event.set_method(method); 3159 event.commit(); 3160 } 3161 } 3162 } 3163 return activation; 3164 } 3165 3166 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) { 3167 // After any safepoint, just before going back to compiled code, 3168 // we inform the GC that we will be doing initializing writes to 3169 // this object in the future without emitting card-marks, so 3170 // GC may take any compensating steps. 3171 3172 oop new_obj = current->vm_result(); 3173 if (new_obj == nullptr) return; 3174 3175 BarrierSet *bs = BarrierSet::barrier_set(); 3176 bs->on_slowpath_allocation_exit(current, new_obj); 3177 } --- EOF ---