1 /*
   2  * Copyright (c) 1997, 2022, 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 "jvm.h"
  28 #include "cds/cds_globals.hpp"
  29 #include "cds/metaspaceShared.hpp"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/javaClasses.hpp"
  32 #include "classfile/javaThreadStatus.hpp"
  33 #include "classfile/systemDictionary.hpp"
  34 #include "classfile/vmClasses.hpp"
  35 #include "classfile/vmSymbols.hpp"
  36 #include "compiler/compileBroker.hpp"
  37 #include "compiler/compileTask.hpp"
  38 #include "compiler/compilerThread.hpp"
  39 #include "gc/shared/barrierSet.hpp"
  40 #include "gc/shared/barrierSetNMethod.hpp"
  41 #include "gc/shared/gcVMOperations.hpp"
  42 #include "gc/shared/oopStorage.hpp"
  43 #include "gc/shared/oopStorageSet.hpp"
  44 #include "gc/shared/stringdedup/stringDedup.hpp"
  45 #include "jfr/jfrEvents.hpp"
  46 #include "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/monitorDeflationThread.hpp"
  72 #include "runtime/mutexLocker.hpp"
  73 #include "runtime/nonJavaThread.hpp"
  74 #include "runtime/objectMonitor.hpp"
  75 #include "runtime/osThread.hpp"
  76 #include "runtime/safepoint.hpp"
  77 #include "runtime/safepointMechanism.inline.hpp"
  78 #include "runtime/safepointVerifiers.hpp"
  79 #include "runtime/serviceThread.hpp"
  80 #include "runtime/sharedRuntime.hpp"
  81 #include "runtime/statSampler.hpp"
  82 #include "runtime/stubCodeGenerator.hpp"
  83 #include "runtime/thread.inline.hpp"
  84 #include "runtime/threads.hpp"
  85 #include "runtime/threadSMR.inline.hpp"
  86 #include "runtime/timer.hpp"
  87 #include "runtime/timerTrace.hpp"
  88 #include "runtime/vmOperations.hpp"
  89 #include "runtime/vm_version.hpp"
  90 #include "services/attachListener.hpp"
  91 #include "services/management.hpp"
  92 #include "services/memTracker.hpp"
  93 #include "services/threadIdTable.hpp"
  94 #include "services/threadService.hpp"
  95 #include "utilities/dtrace.hpp"
  96 #include "utilities/events.hpp"
  97 #include "utilities/macros.hpp"
  98 #include "utilities/systemMemoryBarrier.hpp"
  99 #include "utilities/vmError.hpp"
 100 #if INCLUDE_JVMCI
 101 #include "jvmci/jvmci.hpp"
 102 #include "jvmci/jvmciEnv.hpp"
 103 #endif
 104 #ifdef COMPILER2
 105 #include "opto/idealGraphPrinter.hpp"
 106 #endif
 107 #if INCLUDE_RTM_OPT
 108 #include "runtime/rtmLocking.hpp"
 109 #endif
 110 #if INCLUDE_JFR
 111 #include "jfr/jfr.hpp"
 112 #endif
 113 
 114 // Initialization after module runtime initialization
 115 void universe_post_module_init();  // must happen after call_initPhase2
 116 
 117 
 118 static void initialize_class(Symbol* class_name, TRAPS) {
 119   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
 120   InstanceKlass::cast(klass)->initialize(CHECK);
 121 }
 122 
 123 
 124 // Creates the initial ThreadGroup
 125 static Handle create_initial_thread_group(TRAPS) {
 126   Handle system_instance = JavaCalls::construct_new_instance(
 127                             vmClasses::ThreadGroup_klass(),
 128                             vmSymbols::void_method_signature(),
 129                             CHECK_NH);
 130   Universe::set_system_thread_group(system_instance());
 131 
 132   Handle string = java_lang_String::create_from_str("main", CHECK_NH);
 133   Handle main_instance = JavaCalls::construct_new_instance(
 134                             vmClasses::ThreadGroup_klass(),
 135                             vmSymbols::threadgroup_string_void_signature(),
 136                             system_instance,
 137                             string,
 138                             CHECK_NH);
 139   return main_instance;
 140 }
 141 
 142 // Creates the initial Thread, and sets it to running.
 143 static void create_initial_thread(Handle thread_group, JavaThread* thread,
 144                                  TRAPS) {
 145   InstanceKlass* ik = vmClasses::Thread_klass();
 146   assert(ik->is_initialized(), "must be");
 147   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 148 
 149   // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread
 150   // constructor calls Thread.current(), which must be set here for the
 151   // initial thread.
 152   java_lang_Thread::set_thread(thread_oop(), thread);
 153   thread->set_threadOopHandles(thread_oop());
 154 
 155   Handle string = java_lang_String::create_from_str("main", CHECK);
 156 
 157   JavaValue result(T_VOID);
 158   JavaCalls::call_special(&result, thread_oop,
 159                           ik,
 160                           vmSymbols::object_initializer_name(),
 161                           vmSymbols::threadgroup_string_void_signature(),
 162                           thread_group,
 163                           string,
 164                           CHECK);
 165 
 166   // Set thread status to running since main thread has
 167   // been started and running.
 168   java_lang_Thread::set_thread_status(thread_oop(),
 169                                       JavaThreadStatus::RUNNABLE);
 170 }
 171 
 172 // Extract version and vendor specific information from
 173 // java.lang.VersionProps fields.
 174 // Returned char* is allocated in the thread's resource area
 175 // so must be copied for permanency.
 176 static const char* get_java_version_info(InstanceKlass* ik,
 177                                          Symbol* field_name) {
 178   fieldDescriptor fd;
 179   bool found = ik != NULL &&
 180                ik->find_local_field(field_name,
 181                                     vmSymbols::string_signature(), &fd);
 182   if (found) {
 183     oop name_oop = ik->java_mirror()->obj_field(fd.offset());
 184     if (name_oop == NULL) {
 185       return NULL;
 186     }
 187     const char* name = java_lang_String::as_utf8_string(name_oop);
 188     return name;
 189   } else {
 190     return NULL;
 191   }
 192 }
 193 
 194 // ======= Threads ========
 195 
 196 // The Threads class links together all active threads, and provides
 197 // operations over all threads. It is protected by the Threads_lock,
 198 // which is also used in other global contexts like safepointing.
 199 // ThreadsListHandles are used to safely perform operations on one
 200 // or more threads without the risk of the thread exiting during the
 201 // operation.
 202 //
 203 // Note: The Threads_lock is currently more widely used than we
 204 // would like. We are actively migrating Threads_lock uses to other
 205 // mechanisms in order to reduce Threads_lock contention.
 206 
 207 int         Threads::_number_of_threads = 0;
 208 int         Threads::_number_of_non_daemon_threads = 0;
 209 int         Threads::_return_code = 0;
 210 uintx       Threads::_thread_claim_token = 1; // Never zero.
 211 
 212 #ifdef ASSERT
 213 bool        Threads::_vm_complete = false;
 214 #endif
 215 
 216 // General purpose hook into Java code, run once when the VM is initialized.
 217 // The Java library method itself may be changed independently from the VM.
 218 static void call_postVMInitHook(TRAPS) {
 219   Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD);
 220   if (klass != NULL) {
 221     JavaValue result(T_VOID);
 222     JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
 223                            vmSymbols::void_method_signature(),
 224                            CHECK);
 225   }
 226 }
 227 
 228 // All NonJavaThreads (i.e., every non-JavaThread in the system).
 229 void Threads::non_java_threads_do(ThreadClosure* tc) {
 230   NoSafepointVerifier nsv;
 231   for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) {
 232     tc->do_thread(njti.current());
 233   }
 234 }
 235 
 236 // All JavaThreads
 237 #define ALL_JAVA_THREADS(X) \
 238   for (JavaThread* X : *ThreadsSMRSupport::get_java_thread_list())
 239 
 240 // All JavaThreads
 241 void Threads::java_threads_do(ThreadClosure* tc) {
 242   assert_locked_or_safepoint(Threads_lock);
 243   // ALL_JAVA_THREADS iterates through all JavaThreads.
 244   ALL_JAVA_THREADS(p) {
 245     tc->do_thread(p);
 246   }
 247 }
 248 
 249 void Threads::java_threads_and_vm_thread_do(ThreadClosure* tc) {
 250   assert_locked_or_safepoint(Threads_lock);
 251   java_threads_do(tc);
 252   tc->do_thread(VMThread::vm_thread());
 253 }
 254 
 255 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system).
 256 void Threads::threads_do(ThreadClosure* tc) {
 257   assert_locked_or_safepoint(Threads_lock);
 258   java_threads_do(tc);
 259   non_java_threads_do(tc);
 260 }
 261 
 262 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) {
 263   uintx claim_token = Threads::thread_claim_token();
 264   ALL_JAVA_THREADS(p) {
 265     if (p->claim_threads_do(is_par, claim_token)) {
 266       tc->do_thread(p);
 267     }
 268   }
 269   VMThread* vmt = VMThread::vm_thread();
 270   if (vmt->claim_threads_do(is_par, claim_token)) {
 271     tc->do_thread(vmt);
 272   }
 273 }
 274 
 275 // The system initialization in the library has three phases.
 276 //
 277 // Phase 1: java.lang.System class initialization
 278 //     java.lang.System is a primordial class loaded and initialized
 279 //     by the VM early during startup.  java.lang.System.<clinit>
 280 //     only does registerNatives and keeps the rest of the class
 281 //     initialization work later until thread initialization completes.
 282 //
 283 //     System.initPhase1 initializes the system properties, the static
 284 //     fields in, out, and err. Set up java signal handlers, OS-specific
 285 //     system settings, and thread group of the main thread.
 286 static void call_initPhase1(TRAPS) {
 287   Klass* klass = vmClasses::System_klass();
 288   JavaValue result(T_VOID);
 289   JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(),
 290                                          vmSymbols::void_method_signature(), CHECK);
 291 }
 292 
 293 // Phase 2. Module system initialization
 294 //     This will initialize the module system.  Only java.base classes
 295 //     can be loaded until phase 2 completes.
 296 //
 297 //     Call System.initPhase2 after the compiler initialization and jsr292
 298 //     classes get initialized because module initialization runs a lot of java
 299 //     code, that for performance reasons, should be compiled.  Also, this will
 300 //     enable the startup code to use lambda and other language features in this
 301 //     phase and onward.
 302 //
 303 //     After phase 2, The VM will begin search classes from -Xbootclasspath/a.
 304 static void call_initPhase2(TRAPS) {
 305   TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
 306 
 307   Klass* klass = vmClasses::System_klass();
 308 
 309   JavaValue result(T_INT);
 310   JavaCallArguments args;
 311   args.push_int(DisplayVMOutputToStderr);
 312   args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
 313   JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
 314                                          vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
 315   if (result.get_jint() != JNI_OK) {
 316     vm_exit_during_initialization(); // no message or exception
 317   }
 318 
 319   universe_post_module_init();
 320 }
 321 
 322 // Phase 3. final setup - set security manager, system class loader and TCCL
 323 //
 324 //     This will instantiate and set the security manager, set the system class
 325 //     loader as well as the thread context class loader.  The security manager
 326 //     and system class loader may be a custom class loaded from -Xbootclasspath/a,
 327 //     other modules or the application's classpath.
 328 static void call_initPhase3(TRAPS) {
 329   Klass* klass = vmClasses::System_klass();
 330   JavaValue result(T_VOID);
 331   JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
 332                                          vmSymbols::void_method_signature(), CHECK);
 333 }
 334 
 335 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
 336   TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
 337 
 338   if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
 339     create_vm_init_libraries();
 340   }
 341 
 342   initialize_class(vmSymbols::java_lang_String(), CHECK);
 343 
 344   // Inject CompactStrings value after the static initializers for String ran.
 345   java_lang_String::set_compact_strings(CompactStrings);
 346 
 347   // Initialize java_lang.System (needed before creating the thread)
 348   initialize_class(vmSymbols::java_lang_System(), CHECK);
 349   // The VM creates & returns objects of this class. Make sure it's initialized.
 350   initialize_class(vmSymbols::java_lang_Class(), CHECK);
 351   initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
 352   Handle thread_group = create_initial_thread_group(CHECK);
 353   Universe::set_main_thread_group(thread_group());
 354   initialize_class(vmSymbols::java_lang_Thread(), CHECK);
 355   create_initial_thread(thread_group, main_thread, CHECK);
 356 
 357   // The VM creates objects of this class.
 358   initialize_class(vmSymbols::java_lang_Module(), CHECK);
 359 
 360 #ifdef ASSERT
 361   InstanceKlass *k = vmClasses::UnsafeConstants_klass();
 362   assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
 363 #endif
 364 
 365   // initialize the hardware-specific constants needed by Unsafe
 366   initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
 367   jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
 368 
 369   // The VM preresolves methods to these classes. Make sure that they get initialized
 370   initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
 371   initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
 372 
 373   // Phase 1 of the system initialization in the library, java.lang.System class initialization
 374   call_initPhase1(CHECK);
 375 
 376   // Get the Java runtime name, version, and vendor info after java.lang.System is initialized.
 377   // Some values are actually configure-time constants but some can be set via the jlink tool and
 378   // so must be read dynamically. We treat them all the same.
 379   InstanceKlass* ik = SystemDictionary::find_instance_klass(THREAD, vmSymbols::java_lang_VersionProps(),
 380                                                             Handle(), Handle());
 381   {
 382     ResourceMark rm(main_thread);
 383     JDK_Version::set_java_version(get_java_version_info(ik, vmSymbols::java_version_name()));
 384 
 385     JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name()));
 386 
 387     JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
 388 
 389     JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
 390 
 391     JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
 392   }
 393 
 394   // an instance of OutOfMemory exception has been allocated earlier
 395   initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
 396   initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
 397   initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
 398   initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
 399   initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
 400   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
 401   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
 402   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
 403 }
 404 
 405 void Threads::initialize_jsr292_core_classes(TRAPS) {
 406   TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
 407 
 408   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
 409   initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
 410   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
 411   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
 412 }
 413 
 414 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
 415   extern void JDK_Version_init();
 416 
 417   // Preinitialize version info.
 418   VM_Version::early_initialize();
 419 
 420   // Check version
 421   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
 422 
 423   // Initialize library-based TLS
 424   ThreadLocalStorage::init();
 425 
 426   // Initialize the output stream module
 427   ostream_init();
 428 
 429   // Process java launcher properties.
 430   Arguments::process_sun_java_launcher_properties(args);
 431 
 432   // Initialize the os module
 433   os::init();
 434 
 435   MACOS_AARCH64_ONLY(os::current_thread_enable_wx(WXWrite));
 436 
 437   // Record VM creation timing statistics
 438   TraceVmCreationTime create_vm_timer;
 439   create_vm_timer.start();
 440 
 441   // Initialize system properties.
 442   Arguments::init_system_properties();
 443 
 444   // So that JDK version can be used as a discriminator when parsing arguments
 445   JDK_Version_init();
 446 
 447   // Update/Initialize System properties after JDK version number is known
 448   Arguments::init_version_specific_system_properties();
 449 
 450   // Make sure to initialize log configuration *before* parsing arguments
 451   LogConfiguration::initialize(create_vm_timer.begin_time());
 452 
 453   // Parse arguments
 454   // Note: this internally calls os::init_container_support()
 455   jint parse_result = Arguments::parse(args);
 456   if (parse_result != JNI_OK) return parse_result;
 457 
 458   // Initialize NMT right after argument parsing to keep the pre-NMT-init window small.
 459   MemTracker::initialize();
 460 
 461   os::init_before_ergo();
 462 
 463   jint ergo_result = Arguments::apply_ergo();
 464   if (ergo_result != JNI_OK) return ergo_result;
 465 
 466   // Final check of all ranges after ergonomics which may change values.
 467   if (!JVMFlagLimit::check_all_ranges()) {
 468     return JNI_EINVAL;
 469   }
 470 
 471   // Final check of all 'AfterErgo' constraints after ergonomics which may change values.
 472   bool constraint_result = JVMFlagLimit::check_all_constraints(JVMFlagConstraintPhase::AfterErgo);
 473   if (!constraint_result) {
 474     return JNI_EINVAL;
 475   }
 476 
 477   if (PauseAtStartup) {
 478     os::pause();
 479   }
 480 
 481   HOTSPOT_VM_INIT_BEGIN();
 482 
 483   // Timing (must come after argument parsing)
 484   TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime));
 485 
 486   // Initialize the os module after parsing the args
 487   jint os_init_2_result = os::init_2();
 488   if (os_init_2_result != JNI_OK) return os_init_2_result;
 489 
 490 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
 491   // Initialize assert poison page mechanism.
 492   if (ShowRegistersOnAssert) {
 493     initialize_assert_poison();
 494   }
 495 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
 496 
 497   SafepointMechanism::initialize();
 498 
 499   jint adjust_after_os_result = Arguments::adjust_after_os();
 500   if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
 501 
 502   // Initialize output stream logging
 503   ostream_init_log();
 504 
 505   // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
 506   // Must be before create_vm_init_agents()
 507   if (Arguments::init_libraries_at_startup()) {
 508     convert_vm_init_libraries_to_agents();
 509   }
 510 
 511   // Launch -agentlib/-agentpath and converted -Xrun agents
 512   if (Arguments::init_agents_at_startup()) {
 513     create_vm_init_agents();
 514   }
 515 
 516   // Initialize Threads state
 517   _number_of_threads = 0;
 518   _number_of_non_daemon_threads = 0;
 519 
 520   // Initialize global data structures and create system classes in heap
 521   vm_init_globals();
 522 
 523 #if INCLUDE_JVMCI
 524   if (JVMCICounterSize > 0) {
 525     JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
 526     memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
 527   } else {
 528     JavaThread::_jvmci_old_thread_counters = NULL;
 529   }
 530 #endif // INCLUDE_JVMCI
 531 
 532   // Initialize OopStorage for threadObj
 533   JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
 534 
 535   // Attach the main thread to this os thread
 536   JavaThread* main_thread = new JavaThread();
 537   main_thread->set_thread_state(_thread_in_vm);
 538   main_thread->initialize_thread_current();
 539   // must do this before set_active_handles
 540   main_thread->record_stack_base_and_size();
 541   main_thread->register_thread_stack_with_NMT();
 542   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
 543   MACOS_AARCH64_ONLY(main_thread->init_wx());
 544 
 545   if (!main_thread->set_as_starting_thread()) {
 546     vm_shutdown_during_initialization(
 547                                       "Failed necessary internal allocation. Out of swap space");
 548     main_thread->smr_delete();
 549     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 550     return JNI_ENOMEM;
 551   }
 552 
 553   // Enable guard page *after* os::create_main_thread(), otherwise it would
 554   // crash Linux VM, see notes in os_linux.cpp.
 555   main_thread->stack_overflow_state()->create_stack_guard_pages();
 556 
 557   if (UseSystemMemoryBarrier) {
 558     if (!SystemMemoryBarrier::initialize()) {
 559       vm_shutdown_during_initialization("Failed to initialize the requested system memory barrier synchronization.");
 560       return JNI_EINVAL;
 561     }
 562     log_debug(os)("Using experimental system memory barrier synchronization");
 563   }
 564 
 565   // Initialize Java-Level synchronization subsystem
 566   ObjectMonitor::Initialize();
 567   ObjectSynchronizer::initialize();
 568 
 569   // Initialize global modules
 570   jint status = init_globals();
 571   if (status != JNI_OK) {
 572     main_thread->smr_delete();
 573     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 574     return status;
 575   }
 576 
 577   JFR_ONLY(Jfr::on_create_vm_1();)
 578 
 579   // Should be done after the heap is fully created
 580   main_thread->cache_global_variables();
 581 
 582   { MutexLocker mu(Threads_lock);
 583     Threads::add(main_thread);
 584   }
 585 
 586   // Any JVMTI raw monitors entered in onload will transition into
 587   // real raw monitor. VM is setup enough here for raw monitor enter.
 588   JvmtiExport::transition_pending_onload_raw_monitors();
 589 
 590   // Create the VMThread
 591   { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime));
 592 
 593     VMThread::create();
 594     VMThread* vmthread = VMThread::vm_thread();
 595 
 596     if (!os::create_thread(vmthread, os::vm_thread)) {
 597       vm_exit_during_initialization("Cannot create VM thread. "
 598                                     "Out of system resources.");
 599     }
 600 
 601     // Wait for the VM thread to become ready, and VMThread::run to initialize
 602     // Monitors can have spurious returns, must always check another state flag
 603     {
 604       MonitorLocker ml(Notify_lock);
 605       os::start_thread(vmthread);
 606       while (!vmthread->is_running()) {
 607         ml.wait();
 608       }
 609     }
 610   }
 611 
 612   assert(Universe::is_fully_initialized(), "not initialized");
 613   if (VerifyDuringStartup) {
 614     // Make sure we're starting with a clean slate.
 615     VM_Verify verify_op;
 616     VMThread::execute(&verify_op);
 617   }
 618 
 619   // We need this to update the java.vm.info property in case any flags used
 620   // to initially define it have been changed. This is needed for both CDS
 621   // since UseSharedSpaces may be changed after java.vm.info
 622   // is initially computed. See Abstract_VM_Version::vm_info_string().
 623   // This update must happen before we initialize the java classes, but
 624   // after any initialization logic that might modify the flags.
 625   Arguments::update_vm_info_property(VM_Version::vm_info_string());
 626 
 627   JavaThread* THREAD = JavaThread::current(); // For exception macros.
 628   HandleMark hm(THREAD);
 629 
 630   // Always call even when there are not JVMTI environments yet, since environments
 631   // may be attached late and JVMTI must track phases of VM execution
 632   JvmtiExport::enter_early_start_phase();
 633 
 634   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
 635   JvmtiExport::post_early_vm_start();
 636 
 637   initialize_java_lang_classes(main_thread, CHECK_JNI_ERR);
 638 
 639   quicken_jni_functions();
 640 
 641   // No more stub generation allowed after that point.
 642   StubCodeDesc::freeze();
 643 
 644   // Set flag that basic initialization has completed. Used by exceptions and various
 645   // debug stuff, that does not work until all basic classes have been initialized.
 646   set_init_completed();
 647 
 648   LogConfiguration::post_initialize();
 649   Metaspace::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 = NULL;
 826   void *library = NULL;
 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 == NULL) {
 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, NULL);
 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 == NULL) { // 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 == NULL) {
 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, NULL);
 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 != NULL; 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 == NULL) {
 916       on_load_entry = lookup_agent_on_load(agent);
 917       if (on_load_entry != NULL) {
 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 != NULL; 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 != NULL) {
 952       // Invoke the Agent_OnLoad function
 953       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
 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 != NULL; 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 != NULL) {
 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 != NULL; agent = agent->next()) {
1000     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
1001 
1002     if (on_load_entry != NULL) {
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(), NULL);
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("Thread", p, _thread_claim_token);
1314   }
1315   assert_thread_claimed("VMThread", VMThread::vm_thread(), _thread_claim_token);
1316 }
1317 #endif // ASSERT
1318 
1319 class ParallelOopsDoThreadClosure : public ThreadClosure {
1320 private:
1321   OopClosure* _f;
1322   CodeBlobClosure* _cf;
1323 public:
1324   ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {}
1325   void do_thread(Thread* t) {
1326     t->oops_do(_f, _cf);
1327   }
1328 };
1329 
1330 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) {
1331   ParallelOopsDoThreadClosure tc(f, cf);
1332   possibly_parallel_threads_do(is_par, &tc);
1333 }
1334 
1335 void Threads::metadata_do(MetadataClosure* f) {
1336   ALL_JAVA_THREADS(p) {
1337     p->metadata_do(f);
1338   }
1339 }
1340 
1341 class ThreadHandlesClosure : public ThreadClosure {
1342   void (*_f)(Metadata*);
1343  public:
1344   ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
1345   virtual void do_thread(Thread* thread) {
1346     thread->metadata_handles_do(_f);
1347   }
1348 };
1349 
1350 void Threads::metadata_handles_do(void f(Metadata*)) {
1351   // Only walk the Handles in Thread.
1352   ThreadHandlesClosure handles_closure(f);
1353   threads_do(&handles_closure);
1354 }
1355 
1356 // Get count Java threads that are waiting to enter the specified monitor.
1357 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list,
1358                                                          int count,
1359                                                          address monitor) {
1360   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
1361 
1362   int i = 0;
1363   for (JavaThread* p : *t_list) {
1364     if (!p->can_call_java()) continue;
1365 
1366     // The first stage of async deflation does not affect any field
1367     // used by this comparison so the ObjectMonitor* is usable here.
1368     address pending = (address)p->current_pending_monitor();
1369     if (pending == monitor) {             // found a match
1370       if (i < count) result->append(p);   // save the first count matches
1371       i++;
1372     }
1373   }
1374 
1375   return result;
1376 }
1377 
1378 
1379 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list,
1380                                                       address owner) {
1381   // NULL owner means not locked so we can skip the search
1382   if (owner == NULL) return NULL;
1383 
1384   for (JavaThread* p : *t_list) {
1385     // first, see if owner is the address of a Java thread
1386     if (owner == (address)p) return p;
1387   }
1388 
1389   // Cannot assert on lack of success here since this function may be
1390   // used by code that is trying to report useful problem information
1391   // like deadlock detection.
1392   if (UseHeavyMonitors) return NULL;
1393 
1394   // If we didn't find a matching Java thread and we didn't force use of
1395   // heavyweight monitors, then the owner is the stack address of the
1396   // Lock Word in the owning Java thread's stack.
1397   //
1398   JavaThread* the_owner = NULL;
1399   for (JavaThread* q : *t_list) {
1400     if (q->is_lock_owned(owner)) {
1401       the_owner = q;
1402       break;
1403     }
1404   }
1405 
1406   // cannot assert on lack of success here; see above comment
1407   return the_owner;
1408 }
1409 
1410 class PrintOnClosure : public ThreadClosure {
1411 private:
1412   outputStream* _st;
1413 
1414 public:
1415   PrintOnClosure(outputStream* st) :
1416       _st(st) {}
1417 
1418   virtual void do_thread(Thread* thread) {
1419     if (thread != NULL) {
1420       thread->print_on(_st);
1421       _st->cr();
1422     }
1423   }
1424 };
1425 
1426 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
1427 void Threads::print_on(outputStream* st, bool print_stacks,
1428                        bool internal_format, bool print_concurrent_locks,
1429                        bool print_extended_info) {
1430   char buf[32];
1431   st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
1432 
1433   st->print_cr("Full thread dump %s (%s %s):",
1434                VM_Version::vm_name(),
1435                VM_Version::vm_release(),
1436                VM_Version::vm_info_string());
1437   st->cr();
1438 
1439 #if INCLUDE_SERVICES
1440   // Dump concurrent locks
1441   ConcurrentLocksDump concurrent_locks;
1442   if (print_concurrent_locks) {
1443     concurrent_locks.dump_at_safepoint();
1444   }
1445 #endif // INCLUDE_SERVICES
1446 
1447   ThreadsSMRSupport::print_info_on(st);
1448   st->cr();
1449 
1450   ALL_JAVA_THREADS(p) {
1451     ResourceMark rm;
1452     p->print_on(st, print_extended_info);
1453     if (print_stacks) {
1454       if (internal_format) {
1455         p->trace_stack();
1456       } else {
1457         p->print_stack_on(st);
1458       }
1459     }
1460     st->cr();
1461 #if INCLUDE_SERVICES
1462     if (print_concurrent_locks) {
1463       concurrent_locks.print_locks_on(p, st);
1464     }
1465 #endif // INCLUDE_SERVICES
1466   }
1467 
1468   PrintOnClosure cl(st);
1469   cl.do_thread(VMThread::vm_thread());
1470   Universe::heap()->gc_threads_do(&cl);
1471   if (StringDedup::is_enabled()) {
1472     StringDedup::threads_do(&cl);
1473   }
1474   cl.do_thread(WatcherThread::watcher_thread());
1475   cl.do_thread(AsyncLogWriter::instance());
1476 
1477   st->flush();
1478 }
1479 
1480 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
1481                              int buflen, bool* found_current) {
1482   if (this_thread != NULL) {
1483     bool is_current = (current == this_thread);
1484     *found_current = *found_current || is_current;
1485     st->print("%s", is_current ? "=>" : "  ");
1486 
1487     st->print(PTR_FORMAT, p2i(this_thread));
1488     st->print(" ");
1489     this_thread->print_on_error(st, buf, buflen);
1490     st->cr();
1491   }
1492 }
1493 
1494 class PrintOnErrorClosure : public ThreadClosure {
1495   outputStream* _st;
1496   Thread* _current;
1497   char* _buf;
1498   int _buflen;
1499   bool* _found_current;
1500  public:
1501   PrintOnErrorClosure(outputStream* st, Thread* current, char* buf,
1502                       int buflen, bool* found_current) :
1503    _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {}
1504 
1505   virtual void do_thread(Thread* thread) {
1506     Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current);
1507   }
1508 };
1509 
1510 // Threads::print_on_error() is called by fatal error handler. It's possible
1511 // that VM is not at safepoint and/or current thread is inside signal handler.
1512 // Don't print stack trace, as the stack may not be walkable. Don't allocate
1513 // memory (even in resource area), it might deadlock the error handler.
1514 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
1515                              int buflen) {
1516   ThreadsSMRSupport::print_info_on(st);
1517   st->cr();
1518 
1519   bool found_current = false;
1520   st->print_cr("Java Threads: ( => current thread )");
1521   ALL_JAVA_THREADS(thread) {
1522     print_on_error(thread, st, current, buf, buflen, &found_current);
1523   }
1524   st->cr();
1525 
1526   st->print_cr("Other Threads:");
1527   print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current);
1528   print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current);
1529   print_on_error(AsyncLogWriter::instance(), st, current, buf, buflen, &found_current);
1530 
1531   if (Universe::heap() != NULL) {
1532     PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
1533     Universe::heap()->gc_threads_do(&print_closure);
1534   }
1535 
1536   if (StringDedup::is_enabled()) {
1537     PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
1538     StringDedup::threads_do(&print_closure);
1539   }
1540 
1541   if (!found_current) {
1542     st->cr();
1543     st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
1544     current->print_on_error(st, buf, buflen);
1545     st->cr();
1546   }
1547   st->cr();
1548 
1549   st->print_cr("Threads with active compile tasks:");
1550   print_threads_compiling(st, buf, buflen);
1551 }
1552 
1553 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form) {
1554   ALL_JAVA_THREADS(thread) {
1555     if (thread->is_Compiler_thread()) {
1556       CompilerThread* ct = (CompilerThread*) thread;
1557 
1558       // Keep task in local variable for NULL check.
1559       // ct->_task might be set to NULL by concurring compiler thread
1560       // because it completed the compilation. The task is never freed,
1561       // though, just returned to a free list.
1562       CompileTask* task = ct->task();
1563       if (task != NULL) {
1564         thread->print_name_on_error(st, buf, buflen);
1565         st->print("  ");
1566         task->print(st, NULL, short_form, true);
1567       }
1568     }
1569   }
1570 }
1571 
1572 void Threads::verify() {
1573   ALL_JAVA_THREADS(p) {
1574     p->verify();
1575   }
1576   VMThread* thread = VMThread::vm_thread();
1577   if (thread != NULL) thread->verify();
1578 }