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