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