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