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