< prev index next >

src/hotspot/share/runtime/threads.cpp

Print this page

  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 "cds/aotLinkedClassBulkLoader.hpp"
  27 #include "cds/aotMetaspace.hpp"
  28 #include "cds/cds_globals.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/heapShared.hpp"

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

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


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

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

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

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



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

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

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









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
































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

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


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



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



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

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


 775   if (CDSConfig::is_using_aot_linked_classes()) {
 776     SystemDictionary::restore_archived_method_handle_intrinsics();
 777     AOTLinkedClassBulkLoader::link_or_init_javabase_classes(THREAD);
 778   }
 779 
 780   // Start string deduplication thread if requested.
 781   if (StringDedup::is_enabled()) {
 782     StringDedup::start();
 783   }
 784 
 785   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 786   // It is done after compilers are initialized, because otherwise compilations of
 787   // signature polymorphic MH intrinsics can be missed
 788   // (see SystemDictionary::find_method_handle_intrinsic).
 789   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 790 
 791   // This will initialize the module system.  Only java.base classes can be
 792   // loaded until phase 2 completes
 793   call_initPhase2(CHECK_JNI_ERR);
 794 

 809   JvmtiExport::post_vm_start();
 810 
 811   // Final system initialization including security manager and system class loader
 812   call_initPhase3(CHECK_JNI_ERR);
 813 
 814   // cache the system and platform class loaders
 815   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
 816 
 817   // Initiate replay training processing once preloading is over.
 818   CompileBroker::init_training_replay();
 819 
 820   AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
 821 
 822   if (Continuations::enabled()) {
 823     // Initialize Continuation class now so that failure to create enterSpecial/doYield
 824     // special nmethods due to limited CodeCache size can be treated as a fatal error at
 825     // startup with the proper message that CodeCache size is too small.
 826     initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
 827   }
 828 
















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

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












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

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






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

  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 "cds/aotLinkedClassBulkLoader.hpp"
  27 #include "cds/aotMetaspace.hpp"
  28 #include "cds/cds_globals.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/heapShared.hpp"
  31 #include "cds/methodProfiler.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/systemDictionaryShared.hpp"
  38 #include "classfile/vmClasses.hpp"
  39 #include "classfile/vmSymbols.hpp"
  40 #include "code/aotCodeCache.hpp"
  41 #include "compiler/compilationPolicy.hpp"
  42 #include "compiler/compileBroker.hpp"
  43 #include "compiler/compilerThread.hpp"
  44 #include "compiler/compileTask.hpp"
  45 #include "compiler/precompiler.hpp"
  46 #include "gc/shared/barrierSet.hpp"
  47 #include "gc/shared/barrierSetNMethod.hpp"
  48 #include "gc/shared/gcVMOperations.hpp"
  49 #include "gc/shared/oopStorage.hpp"
  50 #include "gc/shared/oopStorageSet.hpp"
  51 #include "gc/shared/stringdedup/stringDedup.hpp"
  52 #include "interpreter/interpreterRuntime.hpp"
  53 #include "jfr/jfrEvents.hpp"
  54 #include "jvm.h"
  55 #include "jvmtifiles/jvmtiEnv.hpp"
  56 #include "logging/log.hpp"
  57 #include "logging/logAsyncWriter.hpp"
  58 #include "logging/logConfiguration.hpp"
  59 #include "memory/allocation.inline.hpp"
  60 #include "memory/iterator.hpp"
  61 #include "memory/oopFactory.hpp"
  62 #include "memory/resourceArea.hpp"
  63 #include "memory/universe.hpp"
  64 #include "nmt/memTracker.hpp"
  65 #include "oops/instanceKlass.hpp"
  66 #include "oops/klass.inline.hpp"
  67 #include "oops/oop.inline.hpp"
  68 #include "oops/symbol.hpp"
  69 #include "prims/jvm_misc.hpp"
  70 #include "prims/jvmtiAgentList.hpp"
  71 #include "prims/jvmtiEnvBase.hpp"
  72 #include "runtime/arguments.hpp"

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

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

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

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






















 810 #endif
 811 
 812   bool force_JVMCI_initialization = initialize_compilation(CHECK_JNI_ERR);
 813 
 814   if (CDSConfig::is_using_aot_linked_classes()) {
 815     SystemDictionary::restore_archived_method_handle_intrinsics();
 816     AOTLinkedClassBulkLoader::link_or_init_javabase_classes(THREAD);
 817   }
 818 
 819   // Start string deduplication thread if requested.
 820   if (StringDedup::is_enabled()) {
 821     StringDedup::start();
 822   }
 823 
 824   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 825   // It is done after compilers are initialized, because otherwise compilations of
 826   // signature polymorphic MH intrinsics can be missed
 827   // (see SystemDictionary::find_method_handle_intrinsic).
 828   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 829 
 830   // This will initialize the module system.  Only java.base classes can be
 831   // loaded until phase 2 completes
 832   call_initPhase2(CHECK_JNI_ERR);
 833 

 848   JvmtiExport::post_vm_start();
 849 
 850   // Final system initialization including security manager and system class loader
 851   call_initPhase3(CHECK_JNI_ERR);
 852 
 853   // cache the system and platform class loaders
 854   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
 855 
 856   // Initiate replay training processing once preloading is over.
 857   CompileBroker::init_training_replay();
 858 
 859   AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
 860 
 861   if (Continuations::enabled()) {
 862     // Initialize Continuation class now so that failure to create enterSpecial/doYield
 863     // special nmethods due to limited CodeCache size can be treated as a fatal error at
 864     // startup with the proper message that CodeCache size is too small.
 865     initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
 866   }
 867 
 868 #if INCLUDE_CDS
 869   if (PrecompileCode) {
 870     Precompiler::compile_aot_code(CHECK_JNI_ERR);
 871     if (PrecompileOnlyAndExit) {
 872       AOTCodeCache::close();
 873       log_vm_init_stats();
 874       vm_direct_exit(0, "Code precompiation is over");
 875     }
 876   }
 877 #endif
 878 
 879 #if defined(COMPILER2)
 880   // Pre-load cached compiled methods
 881   AOTCodeCache::preload_code(CHECK_JNI_ERR);
 882 #endif
 883 
 884   if (NativeHeapTrimmer::enabled()) {
 885     NativeHeapTrimmer::initialize();
 886   }
 887 
 888   // Always call even when there are not JVMTI environments yet, since environments
 889   // may be attached late and JVMTI must track phases of VM execution
 890   JvmtiExport::enter_live_phase();
 891 
 892   // Make perfmemory accessible
 893   PerfMemory::set_accessible(true);
 894 
 895   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
 896   JvmtiExport::post_vm_initialized();
 897 
 898 #if INCLUDE_JVMCI
 899   if (force_JVMCI_initialization) {
 900     JVMCI::initialize_compiler_in_create_vm(CHECK_JNI_ERR);
 901   }
 902 #endif
 903 

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

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