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