< prev index next >

src/hotspot/share/runtime/threads.cpp

Print this page

  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "cds/aotLinkedClassBulkLoader.hpp"
  28 #include "cds/aotMetaspace.hpp"
  29 #include "cds/cds_globals.hpp"
  30 #include "cds/cdsConfig.hpp"
  31 #include "cds/heapShared.hpp"

  32 #include "classfile/classLoader.hpp"
  33 #include "classfile/javaClasses.hpp"
  34 #include "classfile/javaThreadStatus.hpp"
  35 #include "classfile/symbolTable.hpp"
  36 #include "classfile/systemDictionary.hpp"

  37 #include "classfile/vmClasses.hpp"
  38 #include "classfile/vmSymbols.hpp"


  39 #include "compiler/compileBroker.hpp"
  40 #include "compiler/compilerThread.hpp"
  41 #include "compiler/compileTask.hpp"

  42 #include "gc/shared/barrierSet.hpp"
  43 #include "gc/shared/barrierSetNMethod.hpp"
  44 #include "gc/shared/gcVMOperations.hpp"
  45 #include "gc/shared/oopStorage.hpp"
  46 #include "gc/shared/oopStorageSet.hpp"
  47 #include "gc/shared/stringdedup/stringDedup.hpp"

  48 #include "jfr/jfrEvents.hpp"
  49 #include "jvm.h"
  50 #include "jvmtifiles/jvmtiEnv.hpp"
  51 #include "logging/log.hpp"
  52 #include "logging/logAsyncWriter.hpp"
  53 #include "logging/logConfiguration.hpp"
  54 #include "memory/allocation.inline.hpp"
  55 #include "memory/iterator.hpp"
  56 #include "memory/oopFactory.hpp"
  57 #include "memory/resourceArea.hpp"
  58 #include "memory/universe.hpp"
  59 #include "nmt/memTracker.hpp"
  60 #include "oops/instanceKlass.hpp"
  61 #include "oops/klass.inline.hpp"
  62 #include "oops/oop.inline.hpp"
  63 #include "oops/symbol.hpp"
  64 #include "prims/jvm_misc.hpp"
  65 #include "prims/jvmtiAgentList.hpp"
  66 #include "prims/jvmtiEnvBase.hpp"
  67 #include "runtime/arguments.hpp"

  93 #include "runtime/thread.inline.hpp"
  94 #include "runtime/threads.hpp"
  95 #include "runtime/threadSMR.inline.hpp"
  96 #include "runtime/timer.hpp"
  97 #include "runtime/timerTrace.hpp"
  98 #include "runtime/trimNativeHeap.hpp"
  99 #include "runtime/vm_version.hpp"
 100 #include "runtime/vmOperations.hpp"
 101 #include "services/attachListener.hpp"
 102 #include "services/management.hpp"
 103 #include "services/threadIdTable.hpp"
 104 #include "services/threadService.hpp"
 105 #include "utilities/dtrace.hpp"
 106 #include "utilities/events.hpp"
 107 #include "utilities/macros.hpp"
 108 #include "utilities/vmError.hpp"
 109 #if INCLUDE_JVMCI
 110 #include "jvmci/jvmci.hpp"
 111 #include "jvmci/jvmciEnv.hpp"
 112 #endif



 113 #ifdef COMPILER2
 114 #include "opto/idealGraphPrinter.hpp"

 115 #endif
 116 #if INCLUDE_JFR
 117 #include "jfr/jfr.hpp"
 118 #endif
 119 
 120 // Initialization after module runtime initialization
 121 void universe_post_module_init();  // must happen after call_initPhase2
 122 
 123 
 124 static void initialize_class(Symbol* class_name, TRAPS) {
 125   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
 126   InstanceKlass::cast(klass)->initialize(CHECK);
 127 }
 128 
 129 
 130 // Creates the initial ThreadGroup
 131 static Handle create_initial_thread_group(TRAPS) {
 132   Handle system_instance = JavaCalls::construct_new_instance(
 133                             vmClasses::ThreadGroup_klass(),
 134                             vmSymbols::void_method_signature(),

 361   create_initial_thread(thread_group, main_thread, CHECK);
 362 
 363   HeapShared::init_box_classes(CHECK);
 364 
 365   // The VM creates objects of this class.
 366   initialize_class(vmSymbols::java_lang_Module(), CHECK);
 367 
 368 #ifdef ASSERT
 369   InstanceKlass *k = vmClasses::UnsafeConstants_klass();
 370   assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
 371 #endif
 372 
 373   // initialize the hardware-specific constants needed by Unsafe
 374   initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
 375   jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
 376 
 377   // The VM preresolves methods to these classes. Make sure that they get initialized
 378   initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
 379   initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
 380 









 381   // Phase 1 of the system initialization in the library, java.lang.System class initialization
 382   call_initPhase1(CHECK);
 383 
 384   // Get the Java runtime name, version, and vendor info after java.lang.System is initialized.
 385   // Some values are actually configure-time constants but some can be set via the jlink tool and
 386   // so must be read dynamically. We treat them all the same.
 387   InstanceKlass* ik = SystemDictionary::find_instance_klass(THREAD, vmSymbols::java_lang_VersionProps(),
 388                                                             Handle());
 389   {
 390     ResourceMark rm(main_thread);
 391     JDK_Version::set_java_version(get_java_version_info(ik, vmSymbols::java_version_name()));
 392 
 393     JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name()));
 394 
 395     JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
 396 
 397     JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
 398 
 399     JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
 400   }
 401 
 402   // an instance of OutOfMemory exception has been allocated earlier
 403   initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
 404   initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
 405   initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
 406   initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
 407   initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
 408   initialize_class(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), CHECK);
 409   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
 410   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
 411   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
 412   initialize_class(vmSymbols::java_lang_InternalError(), CHECK);
 413 }
 414 
































 415 void Threads::initialize_jsr292_core_classes(TRAPS) {
 416   TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
 417 
 418   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
 419   initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
 420   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
 421   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
 422 
 423   if (UseSharedSpaces) {
 424     HeapShared::initialize_java_lang_invoke(CHECK);
 425   }
 426 }
 427 
 428 // One-shot PeriodicTask subclass for reading the release file
 429 class ReadReleaseFileTask : public PeriodicTask {
 430  public:
 431   ReadReleaseFileTask() : PeriodicTask(100) {}
 432 
 433   virtual void task() {
 434     os::read_image_release_file();

 549   } else {
 550     JavaThread::_jvmci_old_thread_counters = nullptr;
 551   }
 552 #endif // INCLUDE_JVMCI
 553 
 554   // Initialize OopStorage for threadObj
 555   JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
 556 
 557   // Attach the main thread to this os thread
 558   JavaThread* main_thread = new JavaThread();
 559   main_thread->set_thread_state(_thread_in_vm);
 560   main_thread->initialize_thread_current();
 561   // Once mutexes and main_thread are ready, we can use NmtVirtualMemoryLocker.
 562   MemTracker::NmtVirtualMemoryLocker::set_safe_to_use();
 563   // must do this before set_active_handles
 564   main_thread->record_stack_base_and_size();
 565   main_thread->register_thread_stack_with_NMT();
 566   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
 567   MACOS_AARCH64_ONLY(main_thread->init_wx());
 568 


 569   // Set the _monitor_owner_id now since we will run Java code before the Thread instance
 570   // is even created. The same value will be assigned to the Thread instance on init.
 571   main_thread->set_monitor_owner_id(ThreadIdentifier::next());
 572 
 573   if (!Thread::set_as_starting_thread(main_thread)) {
 574     vm_shutdown_during_initialization(
 575                                       "Failed necessary internal allocation. Out of swap space");
 576     main_thread->smr_delete();
 577     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 578     return JNI_ENOMEM;
 579   }
 580 
 581   JFR_ONLY(Jfr::initialize_main_thread(main_thread);)
 582 
 583   // Enable guard page *after* os::create_main_thread(), otherwise it would
 584   // crash Linux VM, see notes in os_linux.cpp.
 585   main_thread->stack_overflow_state()->create_stack_guard_pages();
 586 
 587   // Initialize Java-Level synchronization subsystem
 588   ObjectMonitor::Initialize();
 589   ObjectSynchronizer::initialize();
 590 



 591   // Initialize global modules
 592   jint status = init_globals();
 593   if (status != JNI_OK) {
 594     main_thread->smr_delete();
 595     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 596     return status;
 597   }



 598 
 599   // Have the WatcherThread read the release file in the background.
 600   ReadReleaseFileTask* read_task = new ReadReleaseFileTask();
 601   read_task->enroll();
 602 
 603   // Create WatcherThread as soon as we can since we need it in case
 604   // of hangs during error reporting.
 605   WatcherThread::start();
 606 
 607   // Add main_thread to threads list to finish barrier setup with
 608   // on_thread_attach.  Should be before starting to build Java objects in
 609   // init_globals2, which invokes barriers.
 610   {
 611     MutexLocker mu(Threads_lock);
 612     Threads::add(main_thread);
 613   }
 614 
 615   status = init_globals2();
 616   if (status != JNI_OK) {
 617     Threads::remove(main_thread, false);

 726     if (StartAttachListener || AttachListener::init_at_startup()) {
 727       AttachListener::init();
 728     }
 729   }
 730 
 731   // Launch -Xrun agents if EagerXrunInit is not set.
 732   if (!EagerXrunInit) {
 733     JvmtiAgentList::load_xrun_agents();
 734   }
 735 
 736   Arena::start_chunk_pool_cleaner_task();
 737 
 738   // Start the service thread
 739   // The service thread enqueues JVMTI deferred events and does various hashtable
 740   // and other cleanups.  Needs to start before the compilers start posting events.
 741   ServiceThread::initialize();
 742 
 743   // Start the monitor deflation thread:
 744   MonitorDeflationThread::initialize();
 745 
 746   // initialize compiler(s)
 747 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
 748   bool init_compilation = true;
 749 #if INCLUDE_JVMCI
 750   bool force_JVMCI_initialization = false;
 751   if (EnableJVMCI) {
 752     // Initialize JVMCI eagerly when it is explicitly requested.
 753     // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
 754     force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
 755     if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
 756       // Force initialization of jarjvmci otherwise requests for blocking
 757       // compilations will not actually block until jarjvmci is initialized.
 758       force_JVMCI_initialization = true;
 759     }
 760     if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
 761       // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
 762       // so compilation should be disabled. This prevents dumping or
 763       // printing from happening more than once.
 764       init_compilation = false;
 765     }
 766   }
 767 #endif
 768   if (init_compilation) {
 769     CompileBroker::compilation_init(CHECK_JNI_ERR);
 770   }
 771 #endif
 772 


 773   if (CDSConfig::is_using_aot_linked_classes()) {
 774     SystemDictionary::restore_archived_method_handle_intrinsics();
 775     AOTLinkedClassBulkLoader::finish_loading_javabase_classes(CHECK_JNI_ERR);
 776   }
 777 
 778   // Start string deduplication thread if requested.
 779   if (StringDedup::is_enabled()) {
 780     StringDedup::start();
 781   }
 782 
 783   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 784   // It is done after compilers are initialized, because otherwise compilations of
 785   // signature polymorphic MH intrinsics can be missed
 786   // (see SystemDictionary::find_method_handle_intrinsic).
 787   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 788 
 789   // This will initialize the module system.  Only java.base classes can be
 790   // loaded until phase 2 completes
 791   call_initPhase2(CHECK_JNI_ERR);
 792 
 793   if (CDSConfig::is_using_aot_linked_classes()) {
 794     AOTLinkedClassBulkLoader::load_non_javabase_classes(THREAD);
 795   }
 796 #ifndef PRODUCT
 797   HeapShared::initialize_test_class_from_archive(THREAD);
 798 #endif
 799 
 800   JFR_ONLY(Jfr::on_create_vm_2();)
 801 
 802   // Always call even when there are not JVMTI environments yet, since environments
 803   // may be attached late and JVMTI must track phases of VM execution
 804   JvmtiExport::enter_start_phase();
 805 
 806   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
 807   JvmtiExport::post_vm_start();
 808 
 809   // Final system initialization including security manager and system class loader
 810   call_initPhase3(CHECK_JNI_ERR);
 811 
 812   // cache the system and platform class loaders
 813   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
 814 
 815   // Initiate replay training processing once preloading is over.
 816   CompileBroker::init_training_replay();
 817 
 818   AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
 819 
 820   if (Continuations::enabled()) {
 821     // Initialize Continuation class now so that failure to create enterSpecial/doYield
 822     // special nmethods due to limited CodeCache size can be treated as a fatal error at
 823     // startup with the proper message that CodeCache size is too small.
 824     initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
 825   }
 826 
















 827   if (NativeHeapTrimmer::enabled()) {
 828     NativeHeapTrimmer::initialize();
 829   }
 830 
 831   // Always call even when there are not JVMTI environments yet, since environments
 832   // may be attached late and JVMTI must track phases of VM execution
 833   JvmtiExport::enter_live_phase();
 834 
 835   // Make perfmemory accessible
 836   PerfMemory::set_accessible(true);
 837 
 838   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
 839   JvmtiExport::post_vm_initialized();
 840 
 841 #if INCLUDE_JVMCI
 842   if (force_JVMCI_initialization) {
 843     JVMCI::initialize_compiler_in_create_vm(CHECK_JNI_ERR);
 844   }
 845 #endif
 846 

 878 
 879   // Let WatcherThread run all registered periodic tasks now.
 880   // NOTE:  All PeriodicTasks should be registered by now. If they
 881   //   aren't, late joiners might appear to start slowly (we might
 882   //   take a while to process their first tick).
 883   WatcherThread::run_all_tasks();
 884 
 885   create_vm_timer.end();
 886 #ifdef ASSERT
 887   _vm_complete = true;
 888 #endif
 889 
 890   if (CDSConfig::is_dumping_classic_static_archive()) {
 891     // Classic -Xshare:dump, aka "old workflow"
 892     AOTMetaspace::preload_and_dump(CHECK_JNI_ERR);
 893   } else if (CDSConfig::is_dumping_final_static_archive()) {
 894     tty->print_cr("Reading AOTConfiguration %s and writing AOTCache %s", AOTConfiguration, AOTCache);
 895     AOTMetaspace::preload_and_dump(CHECK_JNI_ERR);
 896   }
 897 
 898   if (log_is_enabled(Info, perf, class, link)) {
 899     LogStreamHandle(Info, perf, class, link) log;
 900     log.print_cr("At VM initialization completion:");
 901     ClassLoader::print_counters(&log);












 902   }
 903 
 904   return JNI_OK;
 905 }
 906 
 907 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
 908 // the program falls off the end of main(). Another VM exit path is through
 909 // vm_exit(), when the program calls System.exit() to return a value, or when
 910 // there is a serious error in VM.
 911 // These two separate shutdown paths are not exactly the same, but they share
 912 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
 913 //
 914 // Shutdown sequence:
 915 //   + Shutdown native memory tracking if it is on
 916 //   + Wait until we are the last non-daemon thread to execute
 917 //     <-- every thing is still working at this moment -->
 918 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
 919 //        shutdown hooks
 920 //   + Call before_exit(), prepare for VM exit
 921 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),

 994     // queue until after the vm thread is dead. After this point,
 995     // we'll never emerge out of the safepoint before the VM exits.
 996     // Assert that the thread is terminated so that acquiring the
 997     // Heap_lock doesn't cause the terminated thread to participate in
 998     // the safepoint protocol.
 999 
1000     assert(thread->is_terminated(), "must be terminated here");
1001     MutexLocker ml(Heap_lock);
1002 
1003     VMThread::wait_for_vm_thread_exit();
1004     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
1005     VMThread::destroy();
1006   }
1007 
1008   // Now, all Java threads are gone except daemon threads. Daemon threads
1009   // running Java code or in VM are stopped by the Safepoint. However,
1010   // daemon threads executing native code are still running.  But they
1011   // will be stopped at native=>Java/VM barriers. Note that we can't
1012   // simply kill or suspend them, as it is inherently deadlock-prone.
1013 






1014   VM_Exit::set_vm_exited();
1015 
1016   // Clean up ideal graph printers after the VMThread has started
1017   // the final safepoint which will block all the Compiler threads.
1018   // Note that this Thread has already logically exited so the
1019   // clean_up() function's use of a JavaThreadIteratorWithHandle
1020   // would be a problem except set_vm_exited() has remembered the
1021   // shutdown thread which is granted a policy exception.
1022 #if defined(COMPILER2) && !defined(PRODUCT)
1023   IdealGraphPrinter::clean_up();
1024 #endif
1025 
1026   notify_vm_shutdown();
1027 
1028   // exit_globals() will delete tty
1029   exit_globals();
1030 
1031   // Deleting the shutdown thread here is safe. See comment on
1032   // wait_until_not_protected() above.
1033   delete thread;

  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "cds/aotLinkedClassBulkLoader.hpp"
  28 #include "cds/aotMetaspace.hpp"
  29 #include "cds/cds_globals.hpp"
  30 #include "cds/cdsConfig.hpp"
  31 #include "cds/heapShared.hpp"
  32 #include "cds/methodProfiler.hpp"
  33 #include "classfile/classLoader.hpp"
  34 #include "classfile/javaClasses.hpp"
  35 #include "classfile/javaThreadStatus.hpp"
  36 #include "classfile/symbolTable.hpp"
  37 #include "classfile/systemDictionary.hpp"
  38 #include "classfile/systemDictionaryShared.hpp"
  39 #include "classfile/vmClasses.hpp"
  40 #include "classfile/vmSymbols.hpp"
  41 #include "code/aotCodeCache.hpp"
  42 #include "compiler/compilationPolicy.hpp"
  43 #include "compiler/compileBroker.hpp"
  44 #include "compiler/compilerThread.hpp"
  45 #include "compiler/compileTask.hpp"
  46 #include "compiler/precompiler.hpp"
  47 #include "gc/shared/barrierSet.hpp"
  48 #include "gc/shared/barrierSetNMethod.hpp"
  49 #include "gc/shared/gcVMOperations.hpp"
  50 #include "gc/shared/oopStorage.hpp"
  51 #include "gc/shared/oopStorageSet.hpp"
  52 #include "gc/shared/stringdedup/stringDedup.hpp"
  53 #include "interpreter/interpreterRuntime.hpp"
  54 #include "jfr/jfrEvents.hpp"
  55 #include "jvm.h"
  56 #include "jvmtifiles/jvmtiEnv.hpp"
  57 #include "logging/log.hpp"
  58 #include "logging/logAsyncWriter.hpp"
  59 #include "logging/logConfiguration.hpp"
  60 #include "memory/allocation.inline.hpp"
  61 #include "memory/iterator.hpp"
  62 #include "memory/oopFactory.hpp"
  63 #include "memory/resourceArea.hpp"
  64 #include "memory/universe.hpp"
  65 #include "nmt/memTracker.hpp"
  66 #include "oops/instanceKlass.hpp"
  67 #include "oops/klass.inline.hpp"
  68 #include "oops/oop.inline.hpp"
  69 #include "oops/symbol.hpp"
  70 #include "prims/jvm_misc.hpp"
  71 #include "prims/jvmtiAgentList.hpp"
  72 #include "prims/jvmtiEnvBase.hpp"
  73 #include "runtime/arguments.hpp"

  99 #include "runtime/thread.inline.hpp"
 100 #include "runtime/threads.hpp"
 101 #include "runtime/threadSMR.inline.hpp"
 102 #include "runtime/timer.hpp"
 103 #include "runtime/timerTrace.hpp"
 104 #include "runtime/trimNativeHeap.hpp"
 105 #include "runtime/vm_version.hpp"
 106 #include "runtime/vmOperations.hpp"
 107 #include "services/attachListener.hpp"
 108 #include "services/management.hpp"
 109 #include "services/threadIdTable.hpp"
 110 #include "services/threadService.hpp"
 111 #include "utilities/dtrace.hpp"
 112 #include "utilities/events.hpp"
 113 #include "utilities/macros.hpp"
 114 #include "utilities/vmError.hpp"
 115 #if INCLUDE_JVMCI
 116 #include "jvmci/jvmci.hpp"
 117 #include "jvmci/jvmciEnv.hpp"
 118 #endif
 119 #ifdef COMPILER1
 120 #include "c1/c1_Runtime1.hpp"
 121 #endif
 122 #ifdef COMPILER2
 123 #include "opto/idealGraphPrinter.hpp"
 124 #include "opto/runtime.hpp"
 125 #endif
 126 #if INCLUDE_JFR
 127 #include "jfr/jfr.hpp"
 128 #endif
 129 
 130 // Initialization after module runtime initialization
 131 void universe_post_module_init();  // must happen after call_initPhase2
 132 
 133 
 134 static void initialize_class(Symbol* class_name, TRAPS) {
 135   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
 136   InstanceKlass::cast(klass)->initialize(CHECK);
 137 }
 138 
 139 
 140 // Creates the initial ThreadGroup
 141 static Handle create_initial_thread_group(TRAPS) {
 142   Handle system_instance = JavaCalls::construct_new_instance(
 143                             vmClasses::ThreadGroup_klass(),
 144                             vmSymbols::void_method_signature(),

 371   create_initial_thread(thread_group, main_thread, CHECK);
 372 
 373   HeapShared::init_box_classes(CHECK);
 374 
 375   // The VM creates objects of this class.
 376   initialize_class(vmSymbols::java_lang_Module(), CHECK);
 377 
 378 #ifdef ASSERT
 379   InstanceKlass *k = vmClasses::UnsafeConstants_klass();
 380   assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
 381 #endif
 382 
 383   // initialize the hardware-specific constants needed by Unsafe
 384   initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
 385   jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
 386 
 387   // The VM preresolves methods to these classes. Make sure that they get initialized
 388   initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
 389   initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
 390 
 391   if (CDSConfig::is_using_aot_linked_classes()) {
 392     // This is necessary for reflection to work in early core lib bootstrap code.
 393     vmClasses::reflect_AccessibleObject_klass()->link_class(CHECK);
 394     vmClasses::reflect_Field_klass()->link_class(CHECK);
 395     vmClasses::reflect_Parameter_klass()->link_class(CHECK);
 396     vmClasses::reflect_Method_klass()->link_class(CHECK);
 397     vmClasses::reflect_Constructor_klass()->link_class(CHECK);
 398   }
 399 
 400   // Phase 1 of the system initialization in the library, java.lang.System class initialization
 401   call_initPhase1(CHECK);
 402 
 403   // Get the Java runtime name, version, and vendor info after java.lang.System is initialized.
 404   // Some values are actually configure-time constants but some can be set via the jlink tool and
 405   // so must be read dynamically. We treat them all the same.
 406   InstanceKlass* ik = SystemDictionary::find_instance_klass(THREAD, vmSymbols::java_lang_VersionProps(),
 407                                                             Handle());
 408   {
 409     ResourceMark rm(main_thread);
 410     JDK_Version::set_java_version(get_java_version_info(ik, vmSymbols::java_version_name()));
 411 
 412     JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name()));
 413 
 414     JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
 415 
 416     JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
 417 
 418     JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
 419   }
 420 
 421   // an instance of OutOfMemory exception has been allocated earlier
 422   initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
 423   initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
 424   initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
 425   initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
 426   initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
 427   initialize_class(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), CHECK);
 428   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
 429   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
 430   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
 431   initialize_class(vmSymbols::java_lang_InternalError(), CHECK);
 432 }
 433 
 434 bool Threads::initialize_compilation(TRAPS) {
 435   // initialize compiler(s)
 436   bool force_JVMCI_initialization = false;
 437 
 438 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
 439   bool init_compilation = true;
 440 #if INCLUDE_JVMCI
 441   if (EnableJVMCI) {
 442     // Initialize JVMCI eagerly when it is explicitly requested.
 443     // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
 444     force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
 445     if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
 446       // Force initialization of jarjvmci otherwise requests for blocking
 447       // compilations will not actually block until jarjvmci is initialized.
 448       force_JVMCI_initialization = true;
 449     }
 450     if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
 451       // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
 452       // so compilation should be disabled. This prevents dumping or
 453       // printing from happening more than once.
 454       init_compilation = false;
 455     }
 456   }
 457 #endif
 458   if (init_compilation) {
 459     CompileBroker::compilation_init(CHECK_false);
 460   }
 461 #endif
 462 
 463   return force_JVMCI_initialization;
 464 }
 465 
 466 void Threads::initialize_jsr292_core_classes(TRAPS) {
 467   TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
 468 
 469   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
 470   initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
 471   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
 472   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
 473 
 474   if (UseSharedSpaces) {
 475     HeapShared::initialize_java_lang_invoke(CHECK);
 476   }
 477 }
 478 
 479 // One-shot PeriodicTask subclass for reading the release file
 480 class ReadReleaseFileTask : public PeriodicTask {
 481  public:
 482   ReadReleaseFileTask() : PeriodicTask(100) {}
 483 
 484   virtual void task() {
 485     os::read_image_release_file();

 600   } else {
 601     JavaThread::_jvmci_old_thread_counters = nullptr;
 602   }
 603 #endif // INCLUDE_JVMCI
 604 
 605   // Initialize OopStorage for threadObj
 606   JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
 607 
 608   // Attach the main thread to this os thread
 609   JavaThread* main_thread = new JavaThread();
 610   main_thread->set_thread_state(_thread_in_vm);
 611   main_thread->initialize_thread_current();
 612   // Once mutexes and main_thread are ready, we can use NmtVirtualMemoryLocker.
 613   MemTracker::NmtVirtualMemoryLocker::set_safe_to_use();
 614   // must do this before set_active_handles
 615   main_thread->record_stack_base_and_size();
 616   main_thread->register_thread_stack_with_NMT();
 617   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
 618   MACOS_AARCH64_ONLY(main_thread->init_wx());
 619 
 620   MutexLockerImpl::init_counters(); // depends on mutex_init(), perfMemory_init(), and Thread::initialize_thread_current().
 621 
 622   // Set the _monitor_owner_id now since we will run Java code before the Thread instance
 623   // is even created. The same value will be assigned to the Thread instance on init.
 624   main_thread->set_monitor_owner_id(ThreadIdentifier::next());
 625 
 626   if (!Thread::set_as_starting_thread(main_thread)) {
 627     vm_shutdown_during_initialization(
 628                                       "Failed necessary internal allocation. Out of swap space");
 629     main_thread->smr_delete();
 630     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 631     return JNI_ENOMEM;
 632   }
 633 
 634   JFR_ONLY(Jfr::initialize_main_thread(main_thread);)
 635 
 636   // Enable guard page *after* os::create_main_thread(), otherwise it would
 637   // crash Linux VM, see notes in os_linux.cpp.
 638   main_thread->stack_overflow_state()->create_stack_guard_pages();
 639 
 640   // Initialize Java-Level synchronization subsystem
 641   ObjectMonitor::Initialize();
 642   ObjectSynchronizer::initialize();
 643 
 644   Deoptimization::init_counters();
 645   VMThread::init_counters();
 646 
 647   // Initialize global modules
 648   jint status = init_globals();
 649   if (status != JNI_OK) {
 650     main_thread->smr_delete();
 651     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 652     return status;
 653   }
 654   if (xtty != nullptr)
 655     xtty->elem("vm_main_thread thread='%zu'",
 656                (uintx) main_thread->osthread()->thread_id());
 657 
 658   // Have the WatcherThread read the release file in the background.
 659   ReadReleaseFileTask* read_task = new ReadReleaseFileTask();
 660   read_task->enroll();
 661 
 662   // Create WatcherThread as soon as we can since we need it in case
 663   // of hangs during error reporting.
 664   WatcherThread::start();
 665 
 666   // Add main_thread to threads list to finish barrier setup with
 667   // on_thread_attach.  Should be before starting to build Java objects in
 668   // init_globals2, which invokes barriers.
 669   {
 670     MutexLocker mu(Threads_lock);
 671     Threads::add(main_thread);
 672   }
 673 
 674   status = init_globals2();
 675   if (status != JNI_OK) {
 676     Threads::remove(main_thread, false);

 785     if (StartAttachListener || AttachListener::init_at_startup()) {
 786       AttachListener::init();
 787     }
 788   }
 789 
 790   // Launch -Xrun agents if EagerXrunInit is not set.
 791   if (!EagerXrunInit) {
 792     JvmtiAgentList::load_xrun_agents();
 793   }
 794 
 795   Arena::start_chunk_pool_cleaner_task();
 796 
 797   // Start the service thread
 798   // The service thread enqueues JVMTI deferred events and does various hashtable
 799   // and other cleanups.  Needs to start before the compilers start posting events.
 800   ServiceThread::initialize();
 801 
 802   // Start the monitor deflation thread:
 803   MonitorDeflationThread::initialize();
 804 
 805 #if INCLUDE_CDS
 806   // Start the method sampler
 807   MethodProfiler::initialize();






















 808 #endif
 809 
 810   bool force_JVMCI_initialization = initialize_compilation(CHECK_JNI_ERR);
 811 
 812   if (CDSConfig::is_using_aot_linked_classes()) {
 813     SystemDictionary::restore_archived_method_handle_intrinsics();
 814     AOTLinkedClassBulkLoader::finish_loading_javabase_classes(CHECK_JNI_ERR);
 815   }
 816 
 817   // Start string deduplication thread if requested.
 818   if (StringDedup::is_enabled()) {
 819     StringDedup::start();
 820   }
 821 
 822   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 823   // It is done after compilers are initialized, because otherwise compilations of
 824   // signature polymorphic MH intrinsics can be missed
 825   // (see SystemDictionary::find_method_handle_intrinsic).
 826   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 827 
 828   // This will initialize the module system.  Only java.base classes can be
 829   // loaded until phase 2 completes
 830   call_initPhase2(CHECK_JNI_ERR);
 831 
 832   if (CDSConfig::is_using_aot_linked_classes() && !CDSConfig::is_dumping_final_static_archive()) {
 833     AOTLinkedClassBulkLoader::load_non_javabase_classes(THREAD);
 834   }
 835 #ifndef PRODUCT
 836   HeapShared::initialize_test_class_from_archive(THREAD);
 837 #endif
 838 
 839   JFR_ONLY(Jfr::on_create_vm_2();)
 840 
 841   // Always call even when there are not JVMTI environments yet, since environments
 842   // may be attached late and JVMTI must track phases of VM execution
 843   JvmtiExport::enter_start_phase();
 844 
 845   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
 846   JvmtiExport::post_vm_start();
 847 
 848   // Final system initialization including security manager and system class loader
 849   call_initPhase3(CHECK_JNI_ERR);
 850 
 851   // cache the system and platform class loaders
 852   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
 853 
 854   // Initiate replay training processing once preloading is over.
 855   CompileBroker::init_training_replay();
 856 
 857   AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
 858 
 859   if (Continuations::enabled()) {
 860     // Initialize Continuation class now so that failure to create enterSpecial/doYield
 861     // special nmethods due to limited CodeCache size can be treated as a fatal error at
 862     // startup with the proper message that CodeCache size is too small.
 863     initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
 864   }
 865 
 866 #if INCLUDE_CDS
 867   if (PrecompileCode) {
 868     Precompiler::compile_aot_code(CHECK_JNI_ERR);
 869     if (PrecompileOnlyAndExit) {
 870       AOTCodeCache::close();
 871       log_vm_init_stats();
 872       vm_direct_exit(0, "Code precompiation is over");
 873     }
 874   }
 875 #endif
 876 
 877 #if defined(COMPILER2)
 878   // Pre-load cached compiled methods
 879   AOTCodeCache::preload_code(CHECK_JNI_ERR);
 880 #endif
 881 
 882   if (NativeHeapTrimmer::enabled()) {
 883     NativeHeapTrimmer::initialize();
 884   }
 885 
 886   // Always call even when there are not JVMTI environments yet, since environments
 887   // may be attached late and JVMTI must track phases of VM execution
 888   JvmtiExport::enter_live_phase();
 889 
 890   // Make perfmemory accessible
 891   PerfMemory::set_accessible(true);
 892 
 893   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
 894   JvmtiExport::post_vm_initialized();
 895 
 896 #if INCLUDE_JVMCI
 897   if (force_JVMCI_initialization) {
 898     JVMCI::initialize_compiler_in_create_vm(CHECK_JNI_ERR);
 899   }
 900 #endif
 901 

 933 
 934   // Let WatcherThread run all registered periodic tasks now.
 935   // NOTE:  All PeriodicTasks should be registered by now. If they
 936   //   aren't, late joiners might appear to start slowly (we might
 937   //   take a while to process their first tick).
 938   WatcherThread::run_all_tasks();
 939 
 940   create_vm_timer.end();
 941 #ifdef ASSERT
 942   _vm_complete = true;
 943 #endif
 944 
 945   if (CDSConfig::is_dumping_classic_static_archive()) {
 946     // Classic -Xshare:dump, aka "old workflow"
 947     AOTMetaspace::preload_and_dump(CHECK_JNI_ERR);
 948   } else if (CDSConfig::is_dumping_final_static_archive()) {
 949     tty->print_cr("Reading AOTConfiguration %s and writing AOTCache %s", AOTConfiguration, AOTCache);
 950     AOTMetaspace::preload_and_dump(CHECK_JNI_ERR);
 951   }
 952 
 953   log_info(init)("At VM initialization completion:");
 954   log_vm_init_stats();
 955 
 956   if (UsePerfData) {
 957     if (ProfileVMLocks) {
 958       main_thread->set_profile_vm_locks(true);
 959     }
 960     if (ProfileVMCalls) {
 961       main_thread->set_profile_vm_calls(true);
 962     }
 963     if (ProfileRuntimeCalls) {
 964       main_thread->set_profile_rt_calls(true);
 965     }
 966     if (ProfileVMOps) {
 967       main_thread->set_profile_vm_ops(true);
 968     }
 969   }
 970 
 971   return JNI_OK;
 972 }
 973 
 974 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
 975 // the program falls off the end of main(). Another VM exit path is through
 976 // vm_exit(), when the program calls System.exit() to return a value, or when
 977 // there is a serious error in VM.
 978 // These two separate shutdown paths are not exactly the same, but they share
 979 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
 980 //
 981 // Shutdown sequence:
 982 //   + Shutdown native memory tracking if it is on
 983 //   + Wait until we are the last non-daemon thread to execute
 984 //     <-- every thing is still working at this moment -->
 985 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
 986 //        shutdown hooks
 987 //   + Call before_exit(), prepare for VM exit
 988 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),

1061     // queue until after the vm thread is dead. After this point,
1062     // we'll never emerge out of the safepoint before the VM exits.
1063     // Assert that the thread is terminated so that acquiring the
1064     // Heap_lock doesn't cause the terminated thread to participate in
1065     // the safepoint protocol.
1066 
1067     assert(thread->is_terminated(), "must be terminated here");
1068     MutexLocker ml(Heap_lock);
1069 
1070     VMThread::wait_for_vm_thread_exit();
1071     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
1072     VMThread::destroy();
1073   }
1074 
1075   // Now, all Java threads are gone except daemon threads. Daemon threads
1076   // running Java code or in VM are stopped by the Safepoint. However,
1077   // daemon threads executing native code are still running.  But they
1078   // will be stopped at native=>Java/VM barriers. Note that we can't
1079   // simply kill or suspend them, as it is inherently deadlock-prone.
1080 
1081   #if INCLUDE_CDS
1082   if (AOTVerifyTrainingData) {
1083     TrainingData::verify();
1084   }
1085   #endif
1086 
1087   VM_Exit::set_vm_exited();
1088 
1089   // Clean up ideal graph printers after the VMThread has started
1090   // the final safepoint which will block all the Compiler threads.
1091   // Note that this Thread has already logically exited so the
1092   // clean_up() function's use of a JavaThreadIteratorWithHandle
1093   // would be a problem except set_vm_exited() has remembered the
1094   // shutdown thread which is granted a policy exception.
1095 #if defined(COMPILER2) && !defined(PRODUCT)
1096   IdealGraphPrinter::clean_up();
1097 #endif
1098 
1099   notify_vm_shutdown();
1100 
1101   // exit_globals() will delete tty
1102   exit_globals();
1103 
1104   // Deleting the shutdown thread here is safe. See comment on
1105   // wait_until_not_protected() above.
1106   delete thread;
< prev index next >