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