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