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