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