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