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