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