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