1 /* 2 * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. 3 * Copyright (c) 2021, Azul Systems, Inc. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 * 24 */ 25 26 #include "precompiled.hpp" 27 #include "cds/cds_globals.hpp" 28 #include "cds/cdsConfig.hpp" 29 #include "cds/metaspaceShared.hpp" 30 #include "classfile/classLoader.hpp" 31 #include "classfile/javaClasses.hpp" 32 #include "classfile/javaThreadStatus.hpp" 33 #include "classfile/systemDictionary.hpp" 34 #include "classfile/vmClasses.hpp" 35 #include "classfile/vmSymbols.hpp" 36 #include "compiler/compileBroker.hpp" 37 #include "compiler/compileTask.hpp" 38 #include "compiler/compilerThread.hpp" 39 #include "gc/shared/barrierSet.hpp" 40 #include "gc/shared/barrierSetNMethod.hpp" 41 #include "gc/shared/gcVMOperations.hpp" 42 #include "gc/shared/oopStorage.hpp" 43 #include "gc/shared/oopStorageSet.hpp" 44 #include "gc/shared/stringdedup/stringDedup.hpp" 45 #include "jfr/jfrEvents.hpp" 46 #include "jvm.h" 47 #include "jvmtifiles/jvmtiEnv.hpp" 48 #include "logging/log.hpp" 49 #include "logging/logAsyncWriter.hpp" 50 #include "logging/logConfiguration.hpp" 51 #include "memory/allocation.inline.hpp" 52 #include "memory/iterator.hpp" 53 #include "memory/oopFactory.hpp" 54 #include "memory/resourceArea.hpp" 55 #include "memory/universe.hpp" 56 #include "nmt/memTracker.hpp" 57 #include "oops/instanceKlass.hpp" 58 #include "oops/klass.inline.hpp" 59 #include "oops/oop.inline.hpp" 60 #include "oops/symbol.hpp" 61 #include "prims/jvm_misc.hpp" 62 #include "prims/jvmtiAgentList.hpp" 63 #include "prims/jvmtiEnvBase.hpp" 64 #include "runtime/arguments.hpp" 65 #include "runtime/fieldDescriptor.inline.hpp" 66 #include "runtime/flags/jvmFlagLimit.hpp" 67 #include "runtime/globals.hpp" 68 #include "runtime/handles.inline.hpp" 69 #include "runtime/interfaceSupport.inline.hpp" 70 #include "runtime/java.hpp" 71 #include "runtime/javaCalls.hpp" 72 #include "runtime/javaThread.inline.hpp" 73 #include "runtime/jniHandles.inline.hpp" 74 #include "runtime/jniPeriodicChecker.hpp" 75 #include "runtime/lockStack.inline.hpp" 76 #include "runtime/monitorDeflationThread.hpp" 77 #include "runtime/mutexLocker.hpp" 78 #include "runtime/nonJavaThread.hpp" 79 #include "runtime/objectMonitor.inline.hpp" 80 #include "runtime/osThread.hpp" 81 #include "runtime/safepoint.hpp" 82 #include "runtime/safepointMechanism.inline.hpp" 83 #include "runtime/safepointVerifiers.hpp" 84 #include "runtime/serviceThread.hpp" 85 #include "runtime/sharedRuntime.hpp" 86 #include "runtime/stackWatermarkSet.inline.hpp" 87 #include "runtime/statSampler.hpp" 88 #include "runtime/stubCodeGenerator.hpp" 89 #include "runtime/thread.inline.hpp" 90 #include "runtime/threadSMR.inline.hpp" 91 #include "runtime/threads.hpp" 92 #include "runtime/timer.hpp" 93 #include "runtime/timerTrace.hpp" 94 #include "runtime/trimNativeHeap.hpp" 95 #include "runtime/vmOperations.hpp" 96 #include "runtime/vm_version.hpp" 97 #include "services/attachListener.hpp" 98 #include "services/management.hpp" 99 #include "services/threadIdTable.hpp" 100 #include "services/threadService.hpp" 101 #include "utilities/dtrace.hpp" 102 #include "utilities/events.hpp" 103 #include "utilities/macros.hpp" 104 #include "utilities/vmError.hpp" 105 #if INCLUDE_JVMCI 106 #include "jvmci/jvmci.hpp" 107 #include "jvmci/jvmciEnv.hpp" 108 #endif 109 #ifdef COMPILER2 110 #include "opto/idealGraphPrinter.hpp" 111 #endif 112 #if INCLUDE_RTM_OPT 113 #include "runtime/rtmLocking.hpp" 114 #endif 115 #if INCLUDE_JFR 116 #include "jfr/jfr.hpp" 117 #endif 118 119 // Initialization after module runtime initialization 120 void universe_post_module_init(); // must happen after call_initPhase2 121 122 123 static void initialize_class(Symbol* class_name, TRAPS) { 124 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK); 125 InstanceKlass::cast(klass)->initialize(CHECK); 126 } 127 128 129 // Creates the initial ThreadGroup 130 static Handle create_initial_thread_group(TRAPS) { 131 Handle system_instance = JavaCalls::construct_new_instance( 132 vmClasses::ThreadGroup_klass(), 133 vmSymbols::void_method_signature(), 134 CHECK_NH); 135 Universe::set_system_thread_group(system_instance()); 136 137 Handle string = java_lang_String::create_from_str("main", CHECK_NH); 138 Handle main_instance = JavaCalls::construct_new_instance( 139 vmClasses::ThreadGroup_klass(), 140 vmSymbols::threadgroup_string_void_signature(), 141 system_instance, 142 string, 143 CHECK_NH); 144 return main_instance; 145 } 146 147 // Creates the initial Thread, and sets it to running. 148 static void create_initial_thread(Handle thread_group, JavaThread* thread, 149 TRAPS) { 150 InstanceKlass* ik = vmClasses::Thread_klass(); 151 assert(ik->is_initialized(), "must be"); 152 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK); 153 154 // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread 155 // constructor calls Thread.current(), which must be set here for the 156 // initial thread. 157 java_lang_Thread::set_thread(thread_oop(), thread); 158 thread->set_threadOopHandles(thread_oop()); 159 160 Handle string = java_lang_String::create_from_str("main", CHECK); 161 162 JavaValue result(T_VOID); 163 JavaCalls::call_special(&result, thread_oop, 164 ik, 165 vmSymbols::object_initializer_name(), 166 vmSymbols::threadgroup_string_void_signature(), 167 thread_group, 168 string, 169 CHECK); 170 171 assert(thread->lock_id() == ThreadIdentifier::initial(), "invariant"); 172 173 // Set thread status to running since main thread has 174 // been started and running. 175 java_lang_Thread::set_thread_status(thread_oop(), 176 JavaThreadStatus::RUNNABLE); 177 } 178 179 // Extract version and vendor specific information from 180 // java.lang.VersionProps fields. 181 // Returned char* is allocated in the thread's resource area 182 // so must be copied for permanency. 183 static const char* get_java_version_info(InstanceKlass* ik, 184 Symbol* field_name) { 185 fieldDescriptor fd; 186 bool found = ik != nullptr && 187 ik->find_local_field(field_name, 188 vmSymbols::string_signature(), &fd); 189 if (found) { 190 oop name_oop = ik->java_mirror()->obj_field(fd.offset()); 191 if (name_oop == nullptr) { 192 return nullptr; 193 } 194 const char* name = java_lang_String::as_utf8_string(name_oop); 195 return name; 196 } else { 197 return nullptr; 198 } 199 } 200 201 // ======= Threads ======== 202 203 // The Threads class links together all active threads, and provides 204 // operations over all threads. It is protected by the Threads_lock, 205 // which is also used in other global contexts like safepointing. 206 // ThreadsListHandles are used to safely perform operations on one 207 // or more threads without the risk of the thread exiting during the 208 // operation. 209 // 210 // Note: The Threads_lock is currently more widely used than we 211 // would like. We are actively migrating Threads_lock uses to other 212 // mechanisms in order to reduce Threads_lock contention. 213 214 int Threads::_number_of_threads = 0; 215 int Threads::_number_of_non_daemon_threads = 0; 216 int Threads::_return_code = 0; 217 uintx Threads::_thread_claim_token = 1; // Never zero. 218 219 #ifdef ASSERT 220 bool Threads::_vm_complete = false; 221 #endif 222 223 // General purpose hook into Java code, run once when the VM is initialized. 224 // The Java library method itself may be changed independently from the VM. 225 static void call_postVMInitHook(TRAPS) { 226 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD); 227 if (klass != nullptr) { 228 JavaValue result(T_VOID); 229 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(), 230 vmSymbols::void_method_signature(), 231 CHECK); 232 } 233 } 234 235 // All NonJavaThreads (i.e., every non-JavaThread in the system). 236 void Threads::non_java_threads_do(ThreadClosure* tc) { 237 NoSafepointVerifier nsv; 238 for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) { 239 tc->do_thread(njti.current()); 240 } 241 } 242 243 // All JavaThreads 244 #define ALL_JAVA_THREADS(X) \ 245 for (JavaThread* X : *ThreadsSMRSupport::get_java_thread_list()) 246 247 // All JavaThreads 248 void Threads::java_threads_do(ThreadClosure* tc) { 249 assert_locked_or_safepoint(Threads_lock); 250 // ALL_JAVA_THREADS iterates through all JavaThreads. 251 ALL_JAVA_THREADS(p) { 252 tc->do_thread(p); 253 } 254 } 255 256 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system). 257 void Threads::threads_do(ThreadClosure* tc) { 258 assert_locked_or_safepoint(Threads_lock); 259 java_threads_do(tc); 260 non_java_threads_do(tc); 261 } 262 263 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) { 264 assert_at_safepoint(); 265 266 uintx claim_token = Threads::thread_claim_token(); 267 ALL_JAVA_THREADS(p) { 268 if (p->claim_threads_do(is_par, claim_token)) { 269 tc->do_thread(p); 270 } 271 } 272 for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) { 273 Thread* current = njti.current(); 274 if (current->claim_threads_do(is_par, claim_token)) { 275 tc->do_thread(current); 276 } 277 } 278 } 279 280 // The system initialization in the library has three phases. 281 // 282 // Phase 1: java.lang.System class initialization 283 // java.lang.System is a primordial class loaded and initialized 284 // by the VM early during startup. java.lang.System.<clinit> 285 // only does registerNatives and keeps the rest of the class 286 // initialization work later until thread initialization completes. 287 // 288 // System.initPhase1 initializes the system properties, the static 289 // fields in, out, and err. Set up java signal handlers, OS-specific 290 // system settings, and thread group of the main thread. 291 static void call_initPhase1(TRAPS) { 292 Klass* klass = vmClasses::System_klass(); 293 JavaValue result(T_VOID); 294 JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(), 295 vmSymbols::void_method_signature(), CHECK); 296 } 297 298 // Phase 2. Module system initialization 299 // This will initialize the module system. Only java.base classes 300 // can be loaded until phase 2 completes. 301 // 302 // Call System.initPhase2 after the compiler initialization and jsr292 303 // classes get initialized because module initialization runs a lot of java 304 // code, that for performance reasons, should be compiled. Also, this will 305 // enable the startup code to use lambda and other language features in this 306 // phase and onward. 307 // 308 // After phase 2, The VM will begin search classes from -Xbootclasspath/a. 309 static void call_initPhase2(TRAPS) { 310 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime)); 311 312 Klass* klass = vmClasses::System_klass(); 313 314 JavaValue result(T_INT); 315 JavaCallArguments args; 316 args.push_int(DisplayVMOutputToStderr); 317 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown 318 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(), 319 vmSymbols::boolean_boolean_int_signature(), &args, CHECK); 320 if (result.get_jint() != JNI_OK) { 321 vm_exit_during_initialization(); // no message or exception 322 } 323 324 universe_post_module_init(); 325 } 326 327 // Phase 3. final setup - set security manager, system class loader and TCCL 328 // 329 // This will instantiate and set the security manager, set the system class 330 // loader as well as the thread context class loader. The security manager 331 // and system class loader may be a custom class loaded from -Xbootclasspath/a, 332 // other modules or the application's classpath. 333 static void call_initPhase3(TRAPS) { 334 Klass* klass = vmClasses::System_klass(); 335 JavaValue result(T_VOID); 336 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(), 337 vmSymbols::void_method_signature(), CHECK); 338 } 339 340 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) { 341 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime)); 342 343 initialize_class(vmSymbols::java_lang_String(), CHECK); 344 345 // Inject CompactStrings value after the static initializers for String ran. 346 java_lang_String::set_compact_strings(CompactStrings); 347 348 // Initialize java_lang.System (needed before creating the thread) 349 initialize_class(vmSymbols::java_lang_System(), CHECK); 350 // The VM creates & returns objects of this class. Make sure it's initialized. 351 initialize_class(vmSymbols::java_lang_Class(), CHECK); 352 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK); 353 Handle thread_group = create_initial_thread_group(CHECK); 354 Universe::set_main_thread_group(thread_group()); 355 initialize_class(vmSymbols::java_lang_Thread(), CHECK); 356 create_initial_thread(thread_group, main_thread, CHECK); 357 358 // The VM creates objects of this class. 359 initialize_class(vmSymbols::java_lang_Module(), CHECK); 360 361 #ifdef ASSERT 362 InstanceKlass *k = vmClasses::UnsafeConstants_klass(); 363 assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized"); 364 #endif 365 366 // initialize the hardware-specific constants needed by Unsafe 367 initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK); 368 jdk_internal_misc_UnsafeConstants::set_unsafe_constants(); 369 370 // The VM preresolves methods to these classes. Make sure that they get initialized 371 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK); 372 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK); 373 374 // Phase 1 of the system initialization in the library, java.lang.System class initialization 375 call_initPhase1(CHECK); 376 377 // Get the Java runtime name, version, and vendor info after java.lang.System is initialized. 378 // Some values are actually configure-time constants but some can be set via the jlink tool and 379 // so must be read dynamically. We treat them all the same. 380 InstanceKlass* ik = SystemDictionary::find_instance_klass(THREAD, vmSymbols::java_lang_VersionProps(), 381 Handle(), Handle()); 382 { 383 ResourceMark rm(main_thread); 384 JDK_Version::set_java_version(get_java_version_info(ik, vmSymbols::java_version_name())); 385 386 JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name())); 387 388 JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name())); 389 390 JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name())); 391 392 JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name())); 393 } 394 395 // an instance of OutOfMemory exception has been allocated earlier 396 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK); 397 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK); 398 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK); 399 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK); 400 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK); 401 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK); 402 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK); 403 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK); 404 } 405 406 void Threads::initialize_jsr292_core_classes(TRAPS) { 407 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime)); 408 409 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK); 410 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK); 411 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK); 412 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK); 413 } 414 415 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { 416 extern void JDK_Version_init(); 417 418 // Preinitialize version info. 419 VM_Version::early_initialize(); 420 421 // Check version 422 if (!is_supported_jni_version(args->version)) return JNI_EVERSION; 423 424 // Initialize library-based TLS 425 ThreadLocalStorage::init(); 426 427 // Initialize the output stream module 428 ostream_init(); 429 430 // Process java launcher properties. 431 Arguments::process_sun_java_launcher_properties(args); 432 433 // Initialize the os module 434 os::init(); 435 436 MACOS_AARCH64_ONLY(os::current_thread_enable_wx(WXWrite)); 437 438 // Record VM creation timing statistics 439 TraceVmCreationTime create_vm_timer; 440 create_vm_timer.start(); 441 442 // Initialize system properties. 443 Arguments::init_system_properties(); 444 445 // So that JDK version can be used as a discriminator when parsing arguments 446 JDK_Version_init(); 447 448 // Update/Initialize System properties after JDK version number is known 449 Arguments::init_version_specific_system_properties(); 450 451 // Make sure to initialize log configuration *before* parsing arguments 452 LogConfiguration::initialize(create_vm_timer.begin_time()); 453 454 // Parse arguments 455 // Note: this internally calls os::init_container_support() 456 jint parse_result = Arguments::parse(args); 457 if (parse_result != JNI_OK) return parse_result; 458 459 // Initialize NMT right after argument parsing to keep the pre-NMT-init window small. 460 MemTracker::initialize(); 461 462 os::init_before_ergo(); 463 464 jint ergo_result = Arguments::apply_ergo(); 465 if (ergo_result != JNI_OK) return ergo_result; 466 467 // Final check of all ranges after ergonomics which may change values. 468 if (!JVMFlagLimit::check_all_ranges()) { 469 return JNI_EINVAL; 470 } 471 472 // Final check of all 'AfterErgo' constraints after ergonomics which may change values. 473 bool constraint_result = JVMFlagLimit::check_all_constraints(JVMFlagConstraintPhase::AfterErgo); 474 if (!constraint_result) { 475 return JNI_EINVAL; 476 } 477 478 if (PauseAtStartup) { 479 os::pause(); 480 } 481 482 HOTSPOT_VM_INIT_BEGIN(); 483 484 // Timing (must come after argument parsing) 485 TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime)); 486 487 // Initialize the os module after parsing the args 488 jint os_init_2_result = os::init_2(); 489 if (os_init_2_result != JNI_OK) return os_init_2_result; 490 491 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT 492 // Initialize assert poison page mechanism. 493 if (ShowRegistersOnAssert) { 494 initialize_assert_poison(); 495 } 496 #endif // CAN_SHOW_REGISTERS_ON_ASSERT 497 498 SafepointMechanism::initialize(); 499 500 jint adjust_after_os_result = Arguments::adjust_after_os(); 501 if (adjust_after_os_result != JNI_OK) return adjust_after_os_result; 502 503 // Initialize output stream logging 504 ostream_init_log(); 505 506 // Launch -agentlib/-agentpath and converted -Xrun agents 507 JvmtiAgentList::load_agents(); 508 509 // Initialize Threads state 510 _number_of_threads = 0; 511 _number_of_non_daemon_threads = 0; 512 513 // Initialize global data structures and create system classes in heap 514 vm_init_globals(); 515 516 #if INCLUDE_JVMCI 517 if (JVMCICounterSize > 0) { 518 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI); 519 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize); 520 } else { 521 JavaThread::_jvmci_old_thread_counters = nullptr; 522 } 523 #endif // INCLUDE_JVMCI 524 525 // Initialize OopStorage for threadObj 526 JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread); 527 528 // Attach the main thread to this os thread 529 JavaThread* main_thread = new JavaThread(); 530 main_thread->set_thread_state(_thread_in_vm); 531 main_thread->initialize_thread_current(); 532 // must do this before set_active_handles 533 main_thread->record_stack_base_and_size(); 534 main_thread->register_thread_stack_with_NMT(); 535 main_thread->set_active_handles(JNIHandleBlock::allocate_block()); 536 MACOS_AARCH64_ONLY(main_thread->init_wx()); 537 538 // Set the lock_id now since we will run Java code before the Thread instance 539 // is even created. The same value will be assigned to the Thread instance on init. 540 main_thread->set_lock_id(ThreadIdentifier::next()); 541 assert(main_thread->lock_id() == ThreadIdentifier::initial(), "invariant"); 542 543 if (!main_thread->set_as_starting_thread()) { 544 vm_shutdown_during_initialization( 545 "Failed necessary internal allocation. Out of swap space"); 546 main_thread->smr_delete(); 547 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 548 return JNI_ENOMEM; 549 } 550 551 // Enable guard page *after* os::create_main_thread(), otherwise it would 552 // crash Linux VM, see notes in os_linux.cpp. 553 main_thread->stack_overflow_state()->create_stack_guard_pages(); 554 555 // Initialize Java-Level synchronization subsystem 556 ObjectMonitor::Initialize(); 557 ObjectSynchronizer::initialize(); 558 559 // Initialize global modules 560 jint status = init_globals(); 561 if (status != JNI_OK) { 562 main_thread->smr_delete(); 563 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 564 return status; 565 } 566 567 // Create WatcherThread as soon as we can since we need it in case 568 // of hangs during error reporting. 569 WatcherThread::start(); 570 571 // Add main_thread to threads list to finish barrier setup with 572 // on_thread_attach. Should be before starting to build Java objects in 573 // init_globals2, which invokes barriers. 574 { 575 MutexLocker mu(Threads_lock); 576 Threads::add(main_thread); 577 } 578 579 status = init_globals2(); 580 if (status != JNI_OK) { 581 Threads::remove(main_thread, false); 582 // It is possible that we managed to fully initialize Universe but have then 583 // failed by throwing an exception. In that case our caller JNI_CreateJavaVM 584 // will want to report it, so we can't delete the main thread. 585 if (!main_thread->has_pending_exception()) { 586 main_thread->smr_delete(); 587 } 588 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 589 return status; 590 } 591 592 ObjectMonitor::Initialize2(); 593 594 JFR_ONLY(Jfr::on_create_vm_1();) 595 596 // Should be done after the heap is fully created 597 main_thread->cache_global_variables(); 598 599 // Any JVMTI raw monitors entered in onload will transition into 600 // real raw monitor. VM is setup enough here for raw monitor enter. 601 JvmtiExport::transition_pending_onload_raw_monitors(); 602 603 // Create the VMThread 604 { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime)); 605 606 VMThread::create(); 607 VMThread* vmthread = VMThread::vm_thread(); 608 609 if (!os::create_thread(vmthread, os::vm_thread)) { 610 vm_exit_during_initialization("Cannot create VM thread. " 611 "Out of system resources."); 612 } 613 614 // Wait for the VM thread to become ready, and VMThread::run to initialize 615 // Monitors can have spurious returns, must always check another state flag 616 { 617 MonitorLocker ml(Notify_lock); 618 os::start_thread(vmthread); 619 while (!vmthread->is_running()) { 620 ml.wait(); 621 } 622 } 623 } 624 625 assert(Universe::is_fully_initialized(), "not initialized"); 626 if (VerifyDuringStartup) { 627 // Make sure we're starting with a clean slate. 628 VM_Verify verify_op; 629 VMThread::execute(&verify_op); 630 } 631 632 // We need this to update the java.vm.info property in case any flags used 633 // to initially define it have been changed. This is needed for both CDS 634 // since UseSharedSpaces may be changed after java.vm.info 635 // is initially computed. See Abstract_VM_Version::vm_info_string(). 636 // This update must happen before we initialize the java classes, but 637 // after any initialization logic that might modify the flags. 638 Arguments::update_vm_info_property(VM_Version::vm_info_string()); 639 640 JavaThread* THREAD = JavaThread::current(); // For exception macros. 641 HandleMark hm(THREAD); 642 643 // Always call even when there are not JVMTI environments yet, since environments 644 // may be attached late and JVMTI must track phases of VM execution 645 JvmtiExport::enter_early_start_phase(); 646 647 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 648 JvmtiExport::post_early_vm_start(); 649 650 // Launch -Xrun agents early if EagerXrunInit is set 651 if (EagerXrunInit) { 652 JvmtiAgentList::load_xrun_agents(); 653 } 654 655 initialize_java_lang_classes(main_thread, CHECK_JNI_ERR); 656 657 quicken_jni_functions(); 658 659 // No more stub generation allowed after that point. 660 StubCodeDesc::freeze(); 661 662 // Set flag that basic initialization has completed. Used by exceptions and various 663 // debug stuff, that does not work until all basic classes have been initialized. 664 set_init_completed(); 665 666 LogConfiguration::post_initialize(); 667 Metaspace::post_initialize(); 668 MutexLockerImpl::post_initialize(); 669 670 HOTSPOT_VM_INIT_END(); 671 672 // record VM initialization completion time 673 #if INCLUDE_MANAGEMENT 674 Management::record_vm_init_completed(); 675 #endif // INCLUDE_MANAGEMENT 676 677 log_info(os)("Initialized VM with process ID %d", os::current_process_id()); 678 679 // Signal Dispatcher needs to be started before VMInit event is posted 680 os::initialize_jdk_signal_support(CHECK_JNI_ERR); 681 682 // Start Attach Listener if +StartAttachListener or it can't be started lazily 683 if (!DisableAttachMechanism) { 684 AttachListener::vm_start(); 685 if (StartAttachListener || AttachListener::init_at_startup()) { 686 AttachListener::init(); 687 } 688 } 689 690 // Launch -Xrun agents if EagerXrunInit is not set. 691 if (!EagerXrunInit) { 692 JvmtiAgentList::load_xrun_agents(); 693 } 694 695 Arena::start_chunk_pool_cleaner_task(); 696 697 // Start the service thread 698 // The service thread enqueues JVMTI deferred events and does various hashtable 699 // and other cleanups. Needs to start before the compilers start posting events. 700 ServiceThread::initialize(); 701 702 // Start the monitor deflation thread: 703 MonitorDeflationThread::initialize(); 704 705 // initialize compiler(s) 706 #if defined(COMPILER1) || COMPILER2_OR_JVMCI 707 bool init_compilation = true; 708 #if INCLUDE_JVMCI 709 bool force_JVMCI_initialization = false; 710 if (EnableJVMCI) { 711 // Initialize JVMCI eagerly when it is explicitly requested. 712 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled. 713 force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig; 714 if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) { 715 // Force initialization of jarjvmci otherwise requests for blocking 716 // compilations will not actually block until jarjvmci is initialized. 717 force_JVMCI_initialization = true; 718 } 719 if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) { 720 // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM 721 // so compilation should be disabled. This prevents dumping or 722 // printing from happening more than once. 723 init_compilation = false; 724 } 725 } 726 #endif 727 if (init_compilation) { 728 CompileBroker::compilation_init(CHECK_JNI_ERR); 729 } 730 #endif 731 732 // Start string deduplication thread if requested. 733 if (StringDedup::is_enabled()) { 734 StringDedup::start(); 735 } 736 737 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading. 738 // It is done after compilers are initialized, because otherwise compilations of 739 // signature polymorphic MH intrinsics can be missed 740 // (see SystemDictionary::find_method_handle_intrinsic). 741 initialize_jsr292_core_classes(CHECK_JNI_ERR); 742 743 // This will initialize the module system. Only java.base classes can be 744 // loaded until phase 2 completes 745 call_initPhase2(CHECK_JNI_ERR); 746 747 JFR_ONLY(Jfr::on_create_vm_2();) 748 749 // Always call even when there are not JVMTI environments yet, since environments 750 // may be attached late and JVMTI must track phases of VM execution 751 JvmtiExport::enter_start_phase(); 752 753 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 754 JvmtiExport::post_vm_start(); 755 756 // Final system initialization including security manager and system class loader 757 call_initPhase3(CHECK_JNI_ERR); 758 759 // cache the system and platform class loaders 760 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR); 761 762 if (Continuations::enabled()) { 763 // Initialize Continuation class now so that failure to create enterSpecial/doYield 764 // special nmethods due to limited CodeCache size can be treated as a fatal error at 765 // startup with the proper message that CodeCache size is too small. 766 initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR); 767 } 768 769 #if INCLUDE_CDS 770 // capture the module path info from the ModuleEntryTable 771 ClassLoader::initialize_module_path(THREAD); 772 if (HAS_PENDING_EXCEPTION) { 773 java_lang_Throwable::print(PENDING_EXCEPTION, tty); 774 vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly"); 775 } 776 #endif 777 778 #if INCLUDE_JVMCI 779 if (force_JVMCI_initialization) { 780 JVMCI::initialize_compiler(CHECK_JNI_ERR); 781 } 782 #endif 783 784 if (NativeHeapTrimmer::enabled()) { 785 NativeHeapTrimmer::initialize(); 786 } 787 788 // Always call even when there are not JVMTI environments yet, since environments 789 // may be attached late and JVMTI must track phases of VM execution 790 JvmtiExport::enter_live_phase(); 791 792 // Make perfmemory accessible 793 PerfMemory::set_accessible(true); 794 795 // Notify JVMTI agents that VM initialization is complete - nop if no agents. 796 JvmtiExport::post_vm_initialized(); 797 798 JFR_ONLY(Jfr::on_create_vm_3();) 799 800 #if INCLUDE_MANAGEMENT 801 Management::initialize(THREAD); 802 803 if (HAS_PENDING_EXCEPTION) { 804 // management agent fails to start possibly due to 805 // configuration problem and is responsible for printing 806 // stack trace if appropriate. Simply exit VM. 807 vm_exit(1); 808 } 809 #endif // INCLUDE_MANAGEMENT 810 811 StatSampler::engage(); 812 if (CheckJNICalls) JniPeriodicChecker::engage(); 813 814 #if INCLUDE_RTM_OPT 815 RTMLockingCounters::init(); 816 #endif 817 818 call_postVMInitHook(THREAD); 819 // The Java side of PostVMInitHook.run must deal with all 820 // exceptions and provide means of diagnosis. 821 if (HAS_PENDING_EXCEPTION) { 822 CLEAR_PENDING_EXCEPTION; 823 } 824 825 // Let WatcherThread run all registered periodic tasks now. 826 // NOTE: All PeriodicTasks should be registered by now. If they 827 // aren't, late joiners might appear to start slowly (we might 828 // take a while to process their first tick). 829 WatcherThread::run_all_tasks(); 830 831 create_vm_timer.end(); 832 #ifdef ASSERT 833 _vm_complete = true; 834 #endif 835 836 if (CDSConfig::is_dumping_static_archive()) { 837 MetaspaceShared::preload_and_dump(); 838 } 839 840 return JNI_OK; 841 } 842 843 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when 844 // the program falls off the end of main(). Another VM exit path is through 845 // vm_exit(), when the program calls System.exit() to return a value, or when 846 // there is a serious error in VM. 847 // These two separate shutdown paths are not exactly the same, but they share 848 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level. 849 // 850 // Shutdown sequence: 851 // + Shutdown native memory tracking if it is on 852 // + Wait until we are the last non-daemon thread to execute 853 // <-- every thing is still working at this moment --> 854 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level 855 // shutdown hooks 856 // + Call before_exit(), prepare for VM exit 857 // > run VM level shutdown hooks (they are registered through JVM_OnExit(), 858 // currently the only user of this mechanism is File.deleteOnExit()) 859 // > stop StatSampler, watcher thread, 860 // post thread end and vm death events to JVMTI, 861 // stop signal thread 862 // + Call JavaThread::exit(), it will: 863 // > release JNI handle blocks, remove stack guard pages 864 // > remove this thread from Threads list 865 // <-- no more Java code from this thread after this point --> 866 // + Stop VM thread, it will bring the remaining VM to a safepoint and stop 867 // the compiler threads at safepoint 868 // <-- do not use anything that could get blocked by Safepoint --> 869 // + Disable tracing at JNI/JVM barriers 870 // + Set _vm_exited flag for threads that are still running native code 871 // + Call exit_globals() 872 // > deletes tty 873 // > deletes PerfMemory resources 874 // + Delete this thread 875 // + Return to caller 876 877 void Threads::destroy_vm() { 878 JavaThread* thread = JavaThread::current(); 879 880 #ifdef ASSERT 881 _vm_complete = false; 882 #endif 883 // Wait until we are the last non-daemon thread to execute, or 884 // if we are a daemon then wait until the last non-daemon thread has 885 // executed. 886 bool daemon = java_lang_Thread::is_daemon(thread->threadObj()); 887 int expected = daemon ? 0 : 1; 888 { 889 MonitorLocker nu(Threads_lock); 890 while (Threads::number_of_non_daemon_threads() > expected) 891 // This wait should make safepoint checks, wait without a timeout. 892 nu.wait(0); 893 } 894 895 EventShutdown e; 896 if (e.should_commit()) { 897 e.set_reason("No remaining non-daemon Java threads"); 898 e.commit(); 899 } 900 901 // Hang forever on exit if we are reporting an error. 902 if (ShowMessageBoxOnError && VMError::is_error_reported()) { 903 os::infinite_sleep(); 904 } 905 os::wait_for_keypress_at_exit(); 906 907 // run Java level shutdown hooks 908 thread->invoke_shutdown_hooks(); 909 910 before_exit(thread); 911 912 thread->exit(true); 913 914 // We are no longer on the main thread list but could still be in a 915 // secondary list where another thread may try to interact with us. 916 // So wait until all such interactions are complete before we bring 917 // the VM to the termination safepoint. Normally this would be done 918 // using thread->smr_delete() below where we delete the thread, but 919 // we can't call that after the termination safepoint is active as 920 // we will deadlock on the Threads_lock. Once all interactions are 921 // complete it is safe to directly delete the thread at any time. 922 ThreadsSMRSupport::wait_until_not_protected(thread); 923 924 // Stop VM thread. 925 { 926 // 4945125 The vm thread comes to a safepoint during exit. 927 // GC vm_operations can get caught at the safepoint, and the 928 // heap is unparseable if they are caught. Grab the Heap_lock 929 // to prevent this. The GC vm_operations will not be able to 930 // queue until after the vm thread is dead. After this point, 931 // we'll never emerge out of the safepoint before the VM exits. 932 // Assert that the thread is terminated so that acquiring the 933 // Heap_lock doesn't cause the terminated thread to participate in 934 // the safepoint protocol. 935 936 assert(thread->is_terminated(), "must be terminated here"); 937 MutexLocker ml(Heap_lock); 938 939 VMThread::wait_for_vm_thread_exit(); 940 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint"); 941 VMThread::destroy(); 942 } 943 944 // Now, all Java threads are gone except daemon threads. Daemon threads 945 // running Java code or in VM are stopped by the Safepoint. However, 946 // daemon threads executing native code are still running. But they 947 // will be stopped at native=>Java/VM barriers. Note that we can't 948 // simply kill or suspend them, as it is inherently deadlock-prone. 949 950 VM_Exit::set_vm_exited(); 951 952 // Clean up ideal graph printers after the VMThread has started 953 // the final safepoint which will block all the Compiler threads. 954 // Note that this Thread has already logically exited so the 955 // clean_up() function's use of a JavaThreadIteratorWithHandle 956 // would be a problem except set_vm_exited() has remembered the 957 // shutdown thread which is granted a policy exception. 958 #if defined(COMPILER2) && !defined(PRODUCT) 959 IdealGraphPrinter::clean_up(); 960 #endif 961 962 notify_vm_shutdown(); 963 964 // exit_globals() will delete tty 965 exit_globals(); 966 967 // Deleting the shutdown thread here is safe. See comment on 968 // wait_until_not_protected() above. 969 delete thread; 970 971 #if INCLUDE_JVMCI 972 if (JVMCICounterSize > 0) { 973 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters); 974 } 975 #endif 976 977 LogConfiguration::finalize(); 978 } 979 980 981 jboolean Threads::is_supported_jni_version_including_1_1(jint version) { 982 if (version == JNI_VERSION_1_1) return JNI_TRUE; 983 return is_supported_jni_version(version); 984 } 985 986 987 jboolean Threads::is_supported_jni_version(jint version) { 988 if (version == JNI_VERSION_1_2) return JNI_TRUE; 989 if (version == JNI_VERSION_1_4) return JNI_TRUE; 990 if (version == JNI_VERSION_1_6) return JNI_TRUE; 991 if (version == JNI_VERSION_1_8) return JNI_TRUE; 992 if (version == JNI_VERSION_9) return JNI_TRUE; 993 if (version == JNI_VERSION_10) return JNI_TRUE; 994 if (version == JNI_VERSION_19) return JNI_TRUE; 995 if (version == JNI_VERSION_20) return JNI_TRUE; 996 if (version == JNI_VERSION_21) return JNI_TRUE; 997 return JNI_FALSE; 998 } 999 1000 void Threads::add(JavaThread* p, bool force_daemon) { 1001 // The threads lock must be owned at this point 1002 assert(Threads_lock->owned_by_self(), "must have threads lock"); 1003 1004 BarrierSet::barrier_set()->on_thread_attach(p); 1005 1006 // Once a JavaThread is added to the Threads list, smr_delete() has 1007 // to be used to delete it. Otherwise we can just delete it directly. 1008 p->set_on_thread_list(); 1009 1010 _number_of_threads++; 1011 oop threadObj = p->threadObj(); 1012 bool daemon = true; 1013 // Bootstrapping problem: threadObj can be null for initial 1014 // JavaThread (or for threads attached via JNI) 1015 if (!force_daemon && 1016 (threadObj == nullptr || !java_lang_Thread::is_daemon(threadObj))) { 1017 _number_of_non_daemon_threads++; 1018 daemon = false; 1019 } 1020 1021 ThreadService::add_thread(p, daemon); 1022 1023 // Maintain fast thread list 1024 ThreadsSMRSupport::add_thread(p); 1025 1026 // Increase the ObjectMonitor ceiling for the new thread. 1027 ObjectSynchronizer::inc_in_use_list_ceiling(); 1028 1029 // Possible GC point. 1030 Events::log(Thread::current(), "Thread added: " INTPTR_FORMAT, p2i(p)); 1031 1032 // Make new thread known to active EscapeBarrier 1033 EscapeBarrier::thread_added(p); 1034 } 1035 1036 void Threads::remove(JavaThread* p, bool is_daemon) { 1037 // Extra scope needed for Thread_lock, so we can check 1038 // that we do not remove thread without safepoint code notice 1039 { MonitorLocker ml(Threads_lock); 1040 1041 if (ThreadIdTable::is_initialized()) { 1042 // This cleanup must be done before the current thread's GC barrier 1043 // is detached since we need to touch the threadObj oop. 1044 jlong tid = SharedRuntime::get_java_tid(p); 1045 ThreadIdTable::remove_thread(tid); 1046 } 1047 1048 // BarrierSet state must be destroyed after the last thread transition 1049 // before the thread terminates. Thread transitions result in calls to 1050 // StackWatermarkSet::on_safepoint(), which performs GC processing, 1051 // requiring the GC state to be alive. 1052 BarrierSet::barrier_set()->on_thread_detach(p); 1053 if (p->is_exiting()) { 1054 // If we got here via JavaThread::exit(), then we remember that the 1055 // thread's GC barrier has been detached. We don't do this when we get 1056 // here from another path, e.g., cleanup_failed_attach_current_thread(). 1057 p->set_terminated(JavaThread::_thread_gc_barrier_detached); 1058 } 1059 1060 assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present"); 1061 1062 // Maintain fast thread list 1063 ThreadsSMRSupport::remove_thread(p); 1064 1065 _number_of_threads--; 1066 if (!is_daemon) { 1067 _number_of_non_daemon_threads--; 1068 1069 // If this is the last non-daemon thread then we need to do 1070 // a notify on the Threads_lock so a thread waiting 1071 // on destroy_vm will wake up. But that thread could be a daemon 1072 // or non-daemon, so we notify for both the 0 and 1 case. 1073 if (number_of_non_daemon_threads() <= 1) { 1074 ml.notify_all(); 1075 } 1076 } 1077 ThreadService::remove_thread(p, is_daemon); 1078 1079 // Make sure that safepoint code disregard this thread. This is needed since 1080 // the thread might mess around with locks after this point. This can cause it 1081 // to do callbacks into the safepoint code. However, the safepoint code is not aware 1082 // of this thread since it is removed from the queue. 1083 p->set_terminated(JavaThread::_thread_terminated); 1084 1085 // Notify threads waiting in EscapeBarriers 1086 EscapeBarrier::thread_removed(p); 1087 } // unlock Threads_lock 1088 1089 // Reduce the ObjectMonitor ceiling for the exiting thread. 1090 ObjectSynchronizer::dec_in_use_list_ceiling(); 1091 1092 // Since Events::log uses a lock, we grab it outside the Threads_lock 1093 Events::log(Thread::current(), "Thread exited: " INTPTR_FORMAT, p2i(p)); 1094 } 1095 1096 // Operations on the Threads list for GC. These are not explicitly locked, 1097 // but the garbage collector must provide a safe context for them to run. 1098 // In particular, these things should never be called when the Threads_lock 1099 // is held by some other thread. (Note: the Safepoint abstraction also 1100 // uses the Threads_lock to guarantee this property. It also makes sure that 1101 // all threads gets blocked when exiting or starting). 1102 1103 void Threads::oops_do(OopClosure* f, NMethodClosure* cf) { 1104 ALL_JAVA_THREADS(p) { 1105 p->oops_do(f, cf); 1106 } 1107 VMThread::vm_thread()->oops_do(f, cf); 1108 } 1109 1110 void Threads::change_thread_claim_token() { 1111 if (++_thread_claim_token == 0) { 1112 // On overflow of the token counter, there is a risk of future 1113 // collisions between a new global token value and a stale token 1114 // for a thread, because not all iterations visit all threads. 1115 // (Though it's pretty much a theoretical concern for non-trivial 1116 // token counter sizes.) To deal with the possibility, reset all 1117 // the thread tokens to zero on global token overflow. 1118 struct ResetClaims : public ThreadClosure { 1119 virtual void do_thread(Thread* t) { 1120 t->claim_threads_do(false, 0); 1121 } 1122 } reset_claims; 1123 Threads::threads_do(&reset_claims); 1124 // On overflow, update the global token to non-zero, to 1125 // avoid the special "never claimed" initial thread value. 1126 _thread_claim_token = 1; 1127 } 1128 } 1129 1130 #ifdef ASSERT 1131 static void assert_thread_claimed(const char* kind, Thread* t, uintx expected) { 1132 const uintx token = t->threads_do_token(); 1133 assert(token == expected, 1134 "%s " PTR_FORMAT " has incorrect value " UINTX_FORMAT " != " 1135 UINTX_FORMAT, kind, p2i(t), token, expected); 1136 } 1137 1138 void Threads::assert_all_threads_claimed() { 1139 ALL_JAVA_THREADS(p) { 1140 assert_thread_claimed("JavaThread", p, _thread_claim_token); 1141 } 1142 1143 struct NJTClaimedVerifierClosure : public ThreadClosure { 1144 uintx _thread_claim_token; 1145 1146 NJTClaimedVerifierClosure(uintx thread_claim_token) : ThreadClosure(), _thread_claim_token(thread_claim_token) { } 1147 1148 virtual void do_thread(Thread* thread) override { 1149 assert_thread_claimed("Non-JavaThread", VMThread::vm_thread(), _thread_claim_token); 1150 } 1151 } tc(_thread_claim_token); 1152 1153 non_java_threads_do(&tc); 1154 } 1155 #endif // ASSERT 1156 1157 class ParallelOopsDoThreadClosure : public ThreadClosure { 1158 private: 1159 OopClosure* _f; 1160 NMethodClosure* _cf; 1161 public: 1162 ParallelOopsDoThreadClosure(OopClosure* f, NMethodClosure* cf) : _f(f), _cf(cf) {} 1163 void do_thread(Thread* t) { 1164 t->oops_do(_f, _cf); 1165 } 1166 }; 1167 1168 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, NMethodClosure* cf) { 1169 ParallelOopsDoThreadClosure tc(f, cf); 1170 possibly_parallel_threads_do(is_par, &tc); 1171 } 1172 1173 void Threads::metadata_do(MetadataClosure* f) { 1174 ALL_JAVA_THREADS(p) { 1175 p->metadata_do(f); 1176 } 1177 } 1178 1179 class ThreadHandlesClosure : public ThreadClosure { 1180 void (*_f)(Metadata*); 1181 public: 1182 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {} 1183 virtual void do_thread(Thread* thread) { 1184 thread->metadata_handles_do(_f); 1185 } 1186 }; 1187 1188 void Threads::metadata_handles_do(void f(Metadata*)) { 1189 // Only walk the Handles in Thread. 1190 ThreadHandlesClosure handles_closure(f); 1191 threads_do(&handles_closure); 1192 } 1193 1194 #if INCLUDE_JVMTI 1195 // Get count of Java threads that are waiting to enter or re-enter the specified monitor. 1196 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list, 1197 int count, 1198 address monitor) { 1199 assert(Thread::current()->is_VM_thread(), "Must be the VM thread"); 1200 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count); 1201 1202 int i = 0; 1203 for (JavaThread* p : *t_list) { 1204 if (!p->can_call_java()) continue; 1205 1206 // The first stage of async deflation does not affect any field 1207 // used by this comparison so the ObjectMonitor* is usable here. 1208 address pending = (address)p->current_pending_monitor(); 1209 address waiting = (address)p->current_waiting_monitor(); 1210 oop thread_oop = JvmtiEnvBase::get_vthread_or_thread_oop(p); 1211 bool is_virtual = java_lang_VirtualThread::is_instance(thread_oop); 1212 jint state = is_virtual ? JvmtiEnvBase::get_vthread_state(thread_oop, p) 1213 : JvmtiEnvBase::get_thread_state(thread_oop, p); 1214 if (pending == monitor || (waiting == monitor && 1215 (state & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER)) 1216 ) { // found a match 1217 if (i < count) result->append(p); // save the first count matches 1218 i++; 1219 } 1220 } 1221 1222 return result; 1223 } 1224 #endif // INCLUDE_JVMTI 1225 1226 JavaThread *Threads::owning_thread_from_stacklock(ThreadsList * t_list, address basicLock) { 1227 assert(LockingMode == LM_LEGACY, "Not with new lightweight locking"); 1228 1229 JavaThread* the_owner = nullptr; 1230 for (JavaThread* q : *t_list) { 1231 if (q->is_lock_owned(basicLock)) { 1232 the_owner = q; 1233 break; 1234 } 1235 } 1236 return the_owner; 1237 } 1238 1239 JavaThread* Threads::owning_thread_from_object(ThreadsList * t_list, oop obj) { 1240 assert(LockingMode == LM_LIGHTWEIGHT, "Only with new lightweight locking"); 1241 for (JavaThread* q : *t_list) { 1242 // Need to start processing before accessing oops in the thread. 1243 StackWatermark* watermark = StackWatermarkSet::get(q, StackWatermarkKind::gc); 1244 if (watermark != nullptr) { 1245 watermark->start_processing(); 1246 } 1247 1248 if (q->lock_stack().contains(obj)) { 1249 return q; 1250 } 1251 } 1252 return nullptr; 1253 } 1254 1255 JavaThread* Threads::owning_thread_from_monitor(ThreadsList* t_list, ObjectMonitor* monitor) { 1256 if (monitor->is_owner_anonymous()) { 1257 if (LockingMode == LM_LIGHTWEIGHT) { 1258 return owning_thread_from_object(t_list, monitor->object()); 1259 } else { 1260 assert(LockingMode == LM_LEGACY, "invariant"); 1261 return owning_thread_from_stacklock(t_list, (address)monitor->stack_locker()); 1262 } 1263 } else { 1264 JavaThread* the_owner = nullptr; 1265 int64_t owner_tid = (int64_t)monitor->owner(); 1266 for (JavaThread* q : *t_list) { 1267 if (monitor->is_owner(q)) { 1268 the_owner = q; 1269 break; 1270 } 1271 } 1272 return the_owner; 1273 } 1274 } 1275 1276 class PrintOnClosure : public ThreadClosure { 1277 private: 1278 outputStream* _st; 1279 1280 public: 1281 PrintOnClosure(outputStream* st) : 1282 _st(st) {} 1283 1284 virtual void do_thread(Thread* thread) { 1285 if (thread != nullptr) { 1286 thread->print_on(_st); 1287 _st->cr(); 1288 } 1289 } 1290 }; 1291 1292 // Threads::print_on() is called at safepoint by VM_PrintThreads operation. 1293 void Threads::print_on(outputStream* st, bool print_stacks, 1294 bool internal_format, bool print_concurrent_locks, 1295 bool print_extended_info) { 1296 char buf[32]; 1297 st->print_raw_cr(os::local_time_string(buf, sizeof(buf))); 1298 1299 st->print_cr("Full thread dump %s (%s %s):", 1300 VM_Version::vm_name(), 1301 VM_Version::vm_release(), 1302 VM_Version::vm_info_string()); 1303 st->cr(); 1304 1305 #if INCLUDE_SERVICES 1306 // Dump concurrent locks 1307 ConcurrentLocksDump concurrent_locks; 1308 if (print_concurrent_locks) { 1309 concurrent_locks.dump_at_safepoint(); 1310 } 1311 #endif // INCLUDE_SERVICES 1312 1313 ThreadsSMRSupport::print_info_on(st); 1314 st->cr(); 1315 1316 ALL_JAVA_THREADS(p) { 1317 ResourceMark rm; 1318 p->print_on(st, print_extended_info); 1319 if (print_stacks) { 1320 if (internal_format) { 1321 p->trace_stack(); 1322 } else { 1323 p->print_stack_on(st); 1324 } 1325 } 1326 st->cr(); 1327 #if INCLUDE_SERVICES 1328 if (print_concurrent_locks) { 1329 concurrent_locks.print_locks_on(p, st); 1330 } 1331 #endif // INCLUDE_SERVICES 1332 } 1333 1334 PrintOnClosure cl(st); 1335 non_java_threads_do(&cl); 1336 1337 st->flush(); 1338 } 1339 1340 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf, 1341 int buflen, bool* found_current) { 1342 if (this_thread != nullptr) { 1343 bool is_current = (current == this_thread); 1344 *found_current = *found_current || is_current; 1345 st->print("%s", is_current ? "=>" : " "); 1346 1347 st->print(PTR_FORMAT, p2i(this_thread)); 1348 st->print(" "); 1349 this_thread->print_on_error(st, buf, buflen); 1350 st->cr(); 1351 } 1352 } 1353 1354 class PrintOnErrorClosure : public ThreadClosure { 1355 outputStream* _st; 1356 Thread* _current; 1357 char* _buf; 1358 int _buflen; 1359 bool* _found_current; 1360 unsigned _num_printed; 1361 public: 1362 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf, 1363 int buflen, bool* found_current) : 1364 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current), 1365 _num_printed(0) {} 1366 1367 virtual void do_thread(Thread* thread) { 1368 _num_printed++; 1369 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current); 1370 } 1371 1372 unsigned num_printed() const { return _num_printed; } 1373 }; 1374 1375 // Threads::print_on_error() is called by fatal error handler. It's possible 1376 // that VM is not at safepoint and/or current thread is inside signal handler. 1377 // Don't print stack trace, as the stack may not be walkable. Don't allocate 1378 // memory (even in resource area), it might deadlock the error handler. 1379 void Threads::print_on_error(outputStream* st, Thread* current, char* buf, 1380 int buflen) { 1381 ThreadsSMRSupport::print_info_on(st); 1382 st->cr(); 1383 1384 bool found_current = false; 1385 st->print_cr("Java Threads: ( => current thread )"); 1386 unsigned num_java = 0; 1387 ALL_JAVA_THREADS(thread) { 1388 print_on_error(thread, st, current, buf, buflen, &found_current); 1389 num_java++; 1390 } 1391 st->print_cr("Total: %u", num_java); 1392 st->cr(); 1393 1394 st->print_cr("Other Threads:"); 1395 unsigned num_other = ((VMThread::vm_thread() != nullptr) ? 1 : 0) + 1396 ((WatcherThread::watcher_thread() != nullptr) ? 1 : 0) + 1397 ((AsyncLogWriter::instance() != nullptr) ? 1 : 0); 1398 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current); 1399 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current); 1400 print_on_error(AsyncLogWriter::instance(), st, current, buf, buflen, &found_current); 1401 1402 if (Universe::heap() != nullptr) { 1403 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current); 1404 Universe::heap()->gc_threads_do(&print_closure); 1405 num_other += print_closure.num_printed(); 1406 } 1407 1408 if (!found_current) { 1409 st->cr(); 1410 st->print("=>" PTR_FORMAT " (exited) ", p2i(current)); 1411 current->print_on_error(st, buf, buflen); 1412 num_other++; 1413 st->cr(); 1414 } 1415 st->print_cr("Total: %u", num_other); 1416 st->cr(); 1417 1418 st->print_cr("Threads with active compile tasks:"); 1419 unsigned num = print_threads_compiling(st, buf, buflen); 1420 st->print_cr("Total: %u", num); 1421 } 1422 1423 unsigned Threads::print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form) { 1424 unsigned num = 0; 1425 ALL_JAVA_THREADS(thread) { 1426 if (thread->is_Compiler_thread()) { 1427 CompilerThread* ct = (CompilerThread*) thread; 1428 1429 // Keep task in local variable for null check. 1430 // ct->_task might be set to null by concurring compiler thread 1431 // because it completed the compilation. The task is never freed, 1432 // though, just returned to a free list. 1433 CompileTask* task = ct->task(); 1434 if (task != nullptr) { 1435 thread->print_name_on_error(st, buf, buflen); 1436 st->print(" "); 1437 task->print(st, nullptr, short_form, true); 1438 num++; 1439 } 1440 } 1441 } 1442 return num; 1443 } 1444 1445 void Threads::verify() { 1446 ALL_JAVA_THREADS(p) { 1447 p->verify(); 1448 } 1449 VMThread* thread = VMThread::vm_thread(); 1450 if (thread != nullptr) thread->verify(); 1451 }