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