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