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