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