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