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