< 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.inline.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"

  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 "sanitizers/address.hpp"
 101 #include "services/attachListener.hpp"
 102 #include "services/management.hpp"
 103 #include "services/threadIdTable.hpp"
 104 #include "services/threadService.hpp"
 105 #include "utilities/debug.hpp"
 106 #include "utilities/dtrace.hpp"
 107 #include "utilities/events.hpp"
 108 #include "utilities/macros.hpp"
 109 #include "utilities/vmError.hpp"
 110 #if INCLUDE_JVMCI
 111 #include "jvmci/jvmci.hpp"
 112 #include "jvmci/jvmciEnv.hpp"
 113 #endif



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

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

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









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
































 424 void Threads::initialize_jsr292_core_classes(TRAPS) {
 425   TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
 426 
 427   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
 428   initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
 429   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
 430   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
 431 
 432   if (UseSharedSpaces) {
 433     HeapShared::initialize_java_lang_invoke(CHECK);
 434   }
 435 }
 436 
 437 // One-shot PeriodicTask subclass for reading the release file
 438 class ReadReleaseFileTask : public PeriodicTask {
 439  public:
 440   ReadReleaseFileTask() : PeriodicTask(100) {}
 441 
 442   virtual void task() {
 443     os::read_image_release_file();

 562     JavaThread::_jvmci_old_thread_counters = nullptr;
 563   }
 564 #endif // INCLUDE_JVMCI
 565 
 566   // Initialize OopStorage for threadObj
 567   JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
 568 
 569   // Attach the main thread to this os thread. It is added to the threads list inside
 570   // universe_init(), within init_globals().
 571   JavaThread* main_thread = new JavaThread();
 572   main_thread->set_thread_state(_thread_in_vm);
 573   main_thread->initialize_thread_current();
 574   // Once mutexes and main_thread are ready, we can use NmtVirtualMemoryLocker.
 575   MemTracker::NmtVirtualMemoryLocker::set_safe_to_use();
 576   // must do this before set_active_handles
 577   main_thread->record_stack_base_and_size();
 578   main_thread->register_thread_stack_with_NMT();
 579   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
 580   MACOS_AARCH64_ONLY(main_thread->init_wx());
 581 


 582   // Set the _monitor_owner_id now since we will run Java code before the Thread instance
 583   // is even created. The same value will be assigned to the Thread instance on init.
 584   const int64_t main_thread_tid = ThreadIdentifier::next();
 585   guarantee(main_thread_tid == 3, "Must equal the PRIMORDIAL_TID used in Threads.java");
 586   main_thread->set_monitor_owner_id(main_thread_tid);
 587 
 588   if (!Thread::set_as_starting_thread(main_thread)) {
 589     vm_shutdown_during_initialization(
 590                                       "Failed necessary internal allocation. Out of swap space");
 591     main_thread->smr_delete();
 592     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 593     return JNI_ENOMEM;
 594   }
 595 
 596   JFR_ONLY(Jfr::initialize_main_thread(main_thread);)
 597 
 598   // Enable guard page *after* os::create_main_thread(), otherwise it would
 599   // crash Linux VM, see notes in os_linux.cpp.
 600   main_thread->stack_overflow_state()->create_stack_guard_pages();
 601 
 602   // Initialize Java-Level synchronization subsystem
 603   ObjectMonitor::Initialize();
 604   ObjectSynchronizer::initialize();
 605 



 606   // Initialize global modules
 607   jint status = init_globals();
 608   if (status != JNI_OK) {
 609     main_thread->smr_delete();
 610     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 611     return status;
 612   }



 613 
 614   // Have the WatcherThread read the release file in the background.
 615   ReadReleaseFileTask* read_task = new ReadReleaseFileTask();
 616   read_task->enroll();
 617 
 618   // Create WatcherThread as soon as we can since we need it in case
 619   // of hangs during error reporting.
 620   WatcherThread::start();
 621 
 622   status = init_globals2();
 623   if (status != JNI_OK) {
 624     Threads::remove(main_thread, false);
 625     // It is possible that we managed to fully initialize Universe but have then
 626     // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
 627     // will want to report it, so we can't delete the main thread.
 628     if (!main_thread->has_pending_exception()) {
 629       main_thread->smr_delete();
 630     }
 631     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 632     return status;

 744 
 745   // Launch -Xrun agents if EagerXrunInit is not set.
 746   if (!EagerXrunInit) {
 747     JvmtiAgentList::load_xrun_agents();
 748   }
 749 
 750   Arena::start_chunk_pool_cleaner_task();
 751 
 752   // Start the service thread
 753   // The service thread enqueues JVMTI deferred events and does various hashtable
 754   // and other cleanups.  Needs to start before the compilers start posting events.
 755   ServiceThread::initialize();
 756 
 757   if (CDSConfig::is_using_aot_linked_classes()) {
 758     nmethod::post_delayed_compiled_method_load_events();
 759   }
 760 
 761   // Start the monitor deflation thread:
 762   MonitorDeflationThread::initialize();
 763 
 764   // initialize compiler(s)
 765 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
 766   bool init_compilation = true;
 767 #if INCLUDE_JVMCI
 768   bool force_JVMCI_initialization = false;
 769   if (EnableJVMCI) {
 770     // Initialize JVMCI eagerly when it is explicitly requested.
 771     // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
 772     force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
 773     if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
 774       // Force initialization of jarjvmci otherwise requests for blocking
 775       // compilations will not actually block until jarjvmci is initialized.
 776       force_JVMCI_initialization = true;
 777     }
 778     if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
 779       // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
 780       // so compilation should be disabled. This prevents dumping or
 781       // printing from happening more than once.
 782       init_compilation = false;
 783     }
 784   }
 785 #endif
 786   if (init_compilation) {
 787     CompileBroker::compilation_init(CHECK_JNI_ERR);
 788   }
 789 #endif
 790 


 791   if (CDSConfig::is_using_aot_linked_classes()) {
 792     SystemDictionary::restore_archived_method_handle_intrinsics();
 793     AOTLinkedClassBulkLoader::init_javabase_classes(THREAD);
 794   }
 795 
 796   // Start string deduplication thread if requested.
 797   if (StringDedup::is_enabled()) {
 798     StringDedup::start();
 799   }
 800 
 801   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 802   // It is done after compilers are initialized, because otherwise compilations of
 803   // signature polymorphic MH intrinsics can be missed
 804   // (see SystemDictionary::find_method_handle_intrinsic).
 805   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 806 
 807   // This will initialize the module system.  Only java.base classes can be
 808   // loaded until phase 2 completes
 809   call_initPhase2(CHECK_JNI_ERR);
 810 

 825   JvmtiExport::post_vm_start();
 826 
 827   // Final system initialization including security manager and system class loader
 828   call_initPhase3(CHECK_JNI_ERR);
 829 
 830   // cache the system and platform class loaders
 831   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
 832 
 833   // Initiate replay training processing once preloading is over.
 834   CompileBroker::init_training_replay();
 835 
 836   AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
 837 
 838   if (Continuations::enabled()) {
 839     // Initialize Continuation class now so that failure to create enterSpecial/doYield
 840     // special nmethods due to limited CodeCache size can be treated as a fatal error at
 841     // startup with the proper message that CodeCache size is too small.
 842     initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
 843   }
 844 
















 845   if (NativeHeapTrimmer::enabled()) {
 846     NativeHeapTrimmer::initialize();
 847   }
 848 
 849   // Always call even when there are not JVMTI environments yet, since environments
 850   // may be attached late and JVMTI must track phases of VM execution
 851   JvmtiExport::enter_live_phase();
 852 
 853   // Make perfmemory accessible
 854   PerfMemory::set_accessible(true);
 855 
 856   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
 857   JvmtiExport::post_vm_initialized();
 858 
 859 #if INCLUDE_JVMCI
 860   if (force_JVMCI_initialization) {
 861     JVMCI::initialize_compiler_in_create_vm(CHECK_JNI_ERR);
 862   }
 863 #endif
 864 

 899   //   aren't, late joiners might appear to start slowly (we might
 900   //   take a while to process their first tick).
 901   WatcherThread::run_all_tasks();
 902 
 903   // Finish materializing AOT objects
 904   HeapShared::finish_materialize_objects();
 905 
 906   create_vm_timer.end();
 907 #ifdef ASSERT
 908   _vm_complete = true;
 909 #endif
 910 
 911   if (CDSConfig::is_dumping_classic_static_archive()) {
 912     // Classic -Xshare:dump, aka "old workflow"
 913     AOTMetaspace::dump_static_archive(CHECK_JNI_ERR);
 914   } else if (CDSConfig::is_dumping_final_static_archive()) {
 915     tty->print_cr("Reading AOTConfiguration %s and writing AOTCache %s", AOTConfiguration, AOTCache);
 916     AOTMetaspace::dump_static_archive(CHECK_JNI_ERR);
 917   }
 918 
 919   if (log_is_enabled(Info, perf, class, link)) {
 920     LogStreamHandle(Info, perf, class, link) log;
 921     log.print_cr("At VM initialization completion:");
 922     ClassLoader::print_counters(&log);












 923   }
 924 
 925   return JNI_OK;
 926 }
 927 
 928 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
 929 // the program falls off the end of main(). Another VM exit path is through
 930 // vm_exit(), when the program calls System.exit() to return a value, or when
 931 // there is a serious error in VM.
 932 // These two separate shutdown paths are not exactly the same, but they share
 933 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
 934 //
 935 // Shutdown sequence:
 936 //   + Shutdown native memory tracking if it is on
 937 //   + Wait until we are the last non-daemon thread to execute
 938 //     <-- every thing is still working at this moment -->
 939 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
 940 //        shutdown hooks
 941 //   + Call before_exit(), prepare for VM exit
 942 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),

1015     // queue until after the vm thread is dead. After this point,
1016     // we'll never emerge out of the safepoint before the VM exits.
1017     // Assert that the thread is terminated so that acquiring the
1018     // Heap_lock doesn't cause the terminated thread to participate in
1019     // the safepoint protocol.
1020 
1021     assert(thread->is_terminated(), "must be terminated here");
1022     MutexLocker ml(Heap_lock);
1023 
1024     VMThread::wait_for_vm_thread_exit();
1025     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
1026     VMThread::destroy();
1027   }
1028 
1029   // Now, all Java threads are gone except daemon threads. Daemon threads
1030   // running Java code or in VM are stopped by the Safepoint. However,
1031   // daemon threads executing native code are still running.  But they
1032   // will be stopped at native=>Java/VM barriers. Note that we can't
1033   // simply kill or suspend them, as it is inherently deadlock-prone.
1034 






1035   VM_Exit::set_vm_exited();
1036 
1037   // Clean up ideal graph printers after the VMThread has started
1038   // the final safepoint which will block all the Compiler threads.
1039   // Note that this Thread has already logically exited so the
1040   // clean_up() function's use of a JavaThreadIteratorWithHandle
1041   // would be a problem except set_vm_exited() has remembered the
1042   // shutdown thread which is granted a policy exception.
1043 #if defined(COMPILER2) && !defined(PRODUCT)
1044   IdealGraphPrinter::clean_up();
1045 #endif
1046 
1047   notify_vm_shutdown();
1048 
1049   // exit_globals() will delete tty
1050   exit_globals();
1051 
1052   // Deleting the shutdown thread here is safe. See comment on
1053   // wait_until_not_protected() above.
1054   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.inline.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"

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

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

 613     JavaThread::_jvmci_old_thread_counters = nullptr;
 614   }
 615 #endif // INCLUDE_JVMCI
 616 
 617   // Initialize OopStorage for threadObj
 618   JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
 619 
 620   // Attach the main thread to this os thread. It is added to the threads list inside
 621   // universe_init(), within init_globals().
 622   JavaThread* main_thread = new JavaThread();
 623   main_thread->set_thread_state(_thread_in_vm);
 624   main_thread->initialize_thread_current();
 625   // Once mutexes and main_thread are ready, we can use NmtVirtualMemoryLocker.
 626   MemTracker::NmtVirtualMemoryLocker::set_safe_to_use();
 627   // must do this before set_active_handles
 628   main_thread->record_stack_base_and_size();
 629   main_thread->register_thread_stack_with_NMT();
 630   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
 631   MACOS_AARCH64_ONLY(main_thread->init_wx());
 632 
 633   MutexLockerImpl::init_counters(); // depends on mutex_init(), perfMemory_init(), and Thread::initialize_thread_current().
 634 
 635   // Set the _monitor_owner_id now since we will run Java code before the Thread instance
 636   // is even created. The same value will be assigned to the Thread instance on init.
 637   const int64_t main_thread_tid = ThreadIdentifier::next();
 638   guarantee(main_thread_tid == 3, "Must equal the PRIMORDIAL_TID used in Threads.java");
 639   main_thread->set_monitor_owner_id(main_thread_tid);
 640 
 641   if (!Thread::set_as_starting_thread(main_thread)) {
 642     vm_shutdown_during_initialization(
 643                                       "Failed necessary internal allocation. Out of swap space");
 644     main_thread->smr_delete();
 645     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 646     return JNI_ENOMEM;
 647   }
 648 
 649   JFR_ONLY(Jfr::initialize_main_thread(main_thread);)
 650 
 651   // Enable guard page *after* os::create_main_thread(), otherwise it would
 652   // crash Linux VM, see notes in os_linux.cpp.
 653   main_thread->stack_overflow_state()->create_stack_guard_pages();
 654 
 655   // Initialize Java-Level synchronization subsystem
 656   ObjectMonitor::Initialize();
 657   ObjectSynchronizer::initialize();
 658 
 659   Deoptimization::init_counters();
 660   VMThread::init_counters();
 661 
 662   // Initialize global modules
 663   jint status = init_globals();
 664   if (status != JNI_OK) {
 665     main_thread->smr_delete();
 666     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 667     return status;
 668   }
 669   if (xtty != nullptr)
 670     xtty->elem("vm_main_thread thread='%zu'",
 671                (uintx) main_thread->osthread()->thread_id());
 672 
 673   // Have the WatcherThread read the release file in the background.
 674   ReadReleaseFileTask* read_task = new ReadReleaseFileTask();
 675   read_task->enroll();
 676 
 677   // Create WatcherThread as soon as we can since we need it in case
 678   // of hangs during error reporting.
 679   WatcherThread::start();
 680 
 681   status = init_globals2();
 682   if (status != JNI_OK) {
 683     Threads::remove(main_thread, false);
 684     // It is possible that we managed to fully initialize Universe but have then
 685     // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
 686     // will want to report it, so we can't delete the main thread.
 687     if (!main_thread->has_pending_exception()) {
 688       main_thread->smr_delete();
 689     }
 690     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 691     return status;

 803 
 804   // Launch -Xrun agents if EagerXrunInit is not set.
 805   if (!EagerXrunInit) {
 806     JvmtiAgentList::load_xrun_agents();
 807   }
 808 
 809   Arena::start_chunk_pool_cleaner_task();
 810 
 811   // Start the service thread
 812   // The service thread enqueues JVMTI deferred events and does various hashtable
 813   // and other cleanups.  Needs to start before the compilers start posting events.
 814   ServiceThread::initialize();
 815 
 816   if (CDSConfig::is_using_aot_linked_classes()) {
 817     nmethod::post_delayed_compiled_method_load_events();
 818   }
 819 
 820   // Start the monitor deflation thread:
 821   MonitorDeflationThread::initialize();
 822 
 823 #if INCLUDE_CDS
 824   // Start the method sampler
 825   MethodProfiler::initialize();






















 826 #endif
 827 
 828   bool force_JVMCI_initialization = initialize_compilation(CHECK_JNI_ERR);
 829 
 830   if (CDSConfig::is_using_aot_linked_classes()) {
 831     SystemDictionary::restore_archived_method_handle_intrinsics();
 832     AOTLinkedClassBulkLoader::init_javabase_classes(THREAD);
 833   }
 834 
 835   // Start string deduplication thread if requested.
 836   if (StringDedup::is_enabled()) {
 837     StringDedup::start();
 838   }
 839 
 840   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 841   // It is done after compilers are initialized, because otherwise compilations of
 842   // signature polymorphic MH intrinsics can be missed
 843   // (see SystemDictionary::find_method_handle_intrinsic).
 844   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 845 
 846   // This will initialize the module system.  Only java.base classes can be
 847   // loaded until phase 2 completes
 848   call_initPhase2(CHECK_JNI_ERR);
 849 

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

 954   //   aren't, late joiners might appear to start slowly (we might
 955   //   take a while to process their first tick).
 956   WatcherThread::run_all_tasks();
 957 
 958   // Finish materializing AOT objects
 959   HeapShared::finish_materialize_objects();
 960 
 961   create_vm_timer.end();
 962 #ifdef ASSERT
 963   _vm_complete = true;
 964 #endif
 965 
 966   if (CDSConfig::is_dumping_classic_static_archive()) {
 967     // Classic -Xshare:dump, aka "old workflow"
 968     AOTMetaspace::dump_static_archive(CHECK_JNI_ERR);
 969   } else if (CDSConfig::is_dumping_final_static_archive()) {
 970     tty->print_cr("Reading AOTConfiguration %s and writing AOTCache %s", AOTConfiguration, AOTCache);
 971     AOTMetaspace::dump_static_archive(CHECK_JNI_ERR);
 972   }
 973 
 974   log_info(init)("At VM initialization completion:");
 975   log_vm_init_stats();
 976 
 977   if (UsePerfData) {
 978     if (ProfileVMLocks) {
 979       main_thread->set_profile_vm_locks(true);
 980     }
 981     if (ProfileVMCalls) {
 982       main_thread->set_profile_vm_calls(true);
 983     }
 984     if (ProfileRuntimeCalls) {
 985       main_thread->set_profile_rt_calls(true);
 986     }
 987     if (ProfileVMOps) {
 988       main_thread->set_profile_vm_ops(true);
 989     }
 990   }
 991 
 992   return JNI_OK;
 993 }
 994 
 995 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
 996 // the program falls off the end of main(). Another VM exit path is through
 997 // vm_exit(), when the program calls System.exit() to return a value, or when
 998 // there is a serious error in VM.
 999 // These two separate shutdown paths are not exactly the same, but they share
1000 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
1001 //
1002 // Shutdown sequence:
1003 //   + Shutdown native memory tracking if it is on
1004 //   + Wait until we are the last non-daemon thread to execute
1005 //     <-- every thing is still working at this moment -->
1006 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
1007 //        shutdown hooks
1008 //   + Call before_exit(), prepare for VM exit
1009 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),

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