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/cds_globals.hpp"
29 #include "cds/cdsConfig.hpp"
30 #include "cds/heapShared.hpp"
31 #include "cds/metaspaceShared.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/compileTask.hpp"
41 #include "compiler/compilerThread.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/threadSMR.inline.hpp"
95 #include "runtime/threads.hpp"
96 #include "runtime/timer.hpp"
97 #include "runtime/timerTrace.hpp"
98 #include "runtime/trimNativeHeap.hpp"
99 #include "runtime/vmOperations.hpp"
100 #include "runtime/vm_version.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(),
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 AOTLinkedClassBulkLoader::finish_loading_javabase_classes(CHECK_JNI_ERR);
775 SystemDictionary::restore_archived_method_handle_intrinsics();
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
847 JFR_ONLY(Jfr::on_create_vm_3();)
848
849 #if INCLUDE_MANAGEMENT
850 Management::initialize(THREAD);
851
852 if (HAS_PENDING_EXCEPTION) {
853 // management agent fails to start possibly due to
854 // configuration problem and is responsible for printing
855 // stack trace if appropriate. Simply exit VM.
856 vm_exit(1);
857 }
858 #endif // INCLUDE_MANAGEMENT
859
860 if (UsePerfData) PerfDataManager::create_misc_perfdata();
861 if (CheckJNICalls) JniPeriodicChecker::engage();
862
863 call_postVMInitHook(THREAD);
864 // The Java side of PostVMInitHook.run must deal with all
865 // exceptions and provide means of diagnosis.
866 if (HAS_PENDING_EXCEPTION) {
867 CLEAR_PENDING_EXCEPTION;
868 }
869
870 // Let WatcherThread run all registered periodic tasks now.
871 // NOTE: All PeriodicTasks should be registered by now. If they
872 // aren't, late joiners might appear to start slowly (we might
873 // take a while to process their first tick).
874 WatcherThread::run_all_tasks();
875
876 create_vm_timer.end();
877 #ifdef ASSERT
878 _vm_complete = true;
879 #endif
880
881 if (CDSConfig::is_dumping_classic_static_archive()) {
882 // Classic -Xshare:dump, aka "old workflow"
883 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
884 } else if (CDSConfig::is_dumping_final_static_archive()) {
885 tty->print_cr("Reading AOTConfiguration %s and writing AOTCache %s", AOTConfiguration, AOTCache);
886 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
887 }
888
889 if (log_is_enabled(Info, perf, class, link)) {
890 LogStreamHandle(Info, perf, class, link) log;
891 log.print_cr("At VM initialization completion:");
892 ClassLoader::print_counters(&log);
893 }
894
895 return JNI_OK;
896 }
897
898 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
899 // the program falls off the end of main(). Another VM exit path is through
900 // vm_exit(), when the program calls System.exit() to return a value, or when
901 // there is a serious error in VM.
902 // These two separate shutdown paths are not exactly the same, but they share
903 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
904 //
905 // Shutdown sequence:
906 // + Shutdown native memory tracking if it is on
907 // + Wait until we are the last non-daemon thread to execute
908 // <-- every thing is still working at this moment -->
909 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
910 // shutdown hooks
911 // + Call before_exit(), prepare for VM exit
912 // > run VM level shutdown hooks (they are registered through JVM_OnExit(),
|
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/cds_globals.hpp"
29 #include "cds/cdsConfig.hpp"
30 #include "cds/heapShared.hpp"
31 #include "cds/metaspaceShared.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/compileTask.hpp"
45 #include "compiler/compilerThread.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/threadSMR.inline.hpp"
101 #include "runtime/threads.hpp"
102 #include "runtime/timer.hpp"
103 #include "runtime/timerTrace.hpp"
104 #include "runtime/trimNativeHeap.hpp"
105 #include "runtime/vmOperations.hpp"
106 #include "runtime/vm_version.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(),
405 JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
406
407 JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
408
409 JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
410 }
411
412 // an instance of OutOfMemory exception has been allocated earlier
413 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
414 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
415 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
416 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
417 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
418 initialize_class(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), CHECK);
419 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
420 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
421 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
422 initialize_class(vmSymbols::java_lang_InternalError(), CHECK);
423 }
424
425 bool Threads::initialize_compilation(TRAPS) {
426 // initialize compiler(s)
427 bool force_JVMCI_initialization = false;
428
429 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
430 bool init_compilation = true;
431 #if INCLUDE_JVMCI
432 if (EnableJVMCI) {
433 // Initialize JVMCI eagerly when it is explicitly requested.
434 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
435 force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
436 if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
437 // Force initialization of jarjvmci otherwise requests for blocking
438 // compilations will not actually block until jarjvmci is initialized.
439 force_JVMCI_initialization = true;
440 }
441 if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
442 // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
443 // so compilation should be disabled. This prevents dumping or
444 // printing from happening more than once.
445 init_compilation = false;
446 }
447 }
448 #endif
449 if (init_compilation) {
450 CompileBroker::compilation_init(CHECK_false);
451 }
452 #endif
453
454 return force_JVMCI_initialization;
455 }
456
457 void Threads::initialize_jsr292_core_classes(TRAPS) {
458 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
459
460 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
461 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
462 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
463 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
464
465 if (UseSharedSpaces) {
466 HeapShared::initialize_java_lang_invoke(CHECK);
467 }
468 }
469
470 // One-shot PeriodicTask subclass for reading the release file
471 class ReadReleaseFileTask : public PeriodicTask {
472 public:
473 ReadReleaseFileTask() : PeriodicTask(100) {}
474
475 virtual void task() {
476 os::read_image_release_file();
591 } else {
592 JavaThread::_jvmci_old_thread_counters = nullptr;
593 }
594 #endif // INCLUDE_JVMCI
595
596 // Initialize OopStorage for threadObj
597 JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
598
599 // Attach the main thread to this os thread
600 JavaThread* main_thread = new JavaThread();
601 main_thread->set_thread_state(_thread_in_vm);
602 main_thread->initialize_thread_current();
603 // Once mutexes and main_thread are ready, we can use NmtVirtualMemoryLocker.
604 MemTracker::NmtVirtualMemoryLocker::set_safe_to_use();
605 // must do this before set_active_handles
606 main_thread->record_stack_base_and_size();
607 main_thread->register_thread_stack_with_NMT();
608 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
609 MACOS_AARCH64_ONLY(main_thread->init_wx());
610
611 MutexLockerImpl::init_counters(); // depends on mutex_init(), perfMemory_init(), and Thread::initialize_thread_current().
612
613 // Set the _monitor_owner_id now since we will run Java code before the Thread instance
614 // is even created. The same value will be assigned to the Thread instance on init.
615 main_thread->set_monitor_owner_id(ThreadIdentifier::next());
616
617 if (!Thread::set_as_starting_thread(main_thread)) {
618 vm_shutdown_during_initialization(
619 "Failed necessary internal allocation. Out of swap space");
620 main_thread->smr_delete();
621 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
622 return JNI_ENOMEM;
623 }
624
625 JFR_ONLY(Jfr::initialize_main_thread(main_thread);)
626
627 // Enable guard page *after* os::create_main_thread(), otherwise it would
628 // crash Linux VM, see notes in os_linux.cpp.
629 main_thread->stack_overflow_state()->create_stack_guard_pages();
630
631 // Initialize Java-Level synchronization subsystem
632 ObjectMonitor::Initialize();
633 ObjectSynchronizer::initialize();
634
635 Deoptimization::init_counters();
636 VMThread::init_counters();
637
638 // Initialize global modules
639 jint status = init_globals();
640 if (status != JNI_OK) {
641 main_thread->smr_delete();
642 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
643 return status;
644 }
645 if (xtty != nullptr)
646 xtty->elem("vm_main_thread thread='%zu'",
647 (uintx) main_thread->osthread()->thread_id());
648
649 // Have the WatcherThread read the release file in the background.
650 ReadReleaseFileTask* read_task = new ReadReleaseFileTask();
651 read_task->enroll();
652
653 // Create WatcherThread as soon as we can since we need it in case
654 // of hangs during error reporting.
655 WatcherThread::start();
656
657 // Add main_thread to threads list to finish barrier setup with
658 // on_thread_attach. Should be before starting to build Java objects in
659 // init_globals2, which invokes barriers.
660 {
661 MutexLocker mu(Threads_lock);
662 Threads::add(main_thread);
663 }
664
665 status = init_globals2();
666 if (status != JNI_OK) {
667 Threads::remove(main_thread, false);
776 if (StartAttachListener || AttachListener::init_at_startup()) {
777 AttachListener::init();
778 }
779 }
780
781 // Launch -Xrun agents if EagerXrunInit is not set.
782 if (!EagerXrunInit) {
783 JvmtiAgentList::load_xrun_agents();
784 }
785
786 Arena::start_chunk_pool_cleaner_task();
787
788 // Start the service thread
789 // The service thread enqueues JVMTI deferred events and does various hashtable
790 // and other cleanups. Needs to start before the compilers start posting events.
791 ServiceThread::initialize();
792
793 // Start the monitor deflation thread:
794 MonitorDeflationThread::initialize();
795
796 #if INCLUDE_CDS
797 // Start the method sampler
798 MethodProfiler::initialize();
799 #endif
800
801 bool force_JVMCI_initialization = initialize_compilation(CHECK_JNI_ERR);
802
803 if (CDSConfig::is_using_aot_linked_classes()) {
804 SystemDictionary::restore_archived_method_handle_intrinsics();
805 AOTLinkedClassBulkLoader::finish_loading_javabase_classes(CHECK_JNI_ERR);
806 }
807
808 // Start string deduplication thread if requested.
809 if (StringDedup::is_enabled()) {
810 StringDedup::start();
811 }
812
813 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
814 // It is done after compilers are initialized, because otherwise compilations of
815 // signature polymorphic MH intrinsics can be missed
816 // (see SystemDictionary::find_method_handle_intrinsic).
817 initialize_jsr292_core_classes(CHECK_JNI_ERR);
818
819 // This will initialize the module system. Only java.base classes can be
820 // loaded until phase 2 completes
821 call_initPhase2(CHECK_JNI_ERR);
822
823 if (CDSConfig::is_using_aot_linked_classes() && !CDSConfig::is_dumping_final_static_archive()) {
824 AOTLinkedClassBulkLoader::load_non_javabase_classes(THREAD);
825 }
826 #ifndef PRODUCT
827 HeapShared::initialize_test_class_from_archive(THREAD);
828 #endif
829
830 JFR_ONLY(Jfr::on_create_vm_2();)
831
832 // Always call even when there are not JVMTI environments yet, since environments
833 // may be attached late and JVMTI must track phases of VM execution
834 JvmtiExport::enter_start_phase();
835
836 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
837 JvmtiExport::post_vm_start();
838
839 // Final system initialization including security manager and system class loader
840 call_initPhase3(CHECK_JNI_ERR);
841
842 // cache the system and platform class loaders
843 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
844
845 // Initiate replay training processing once preloading is over.
846 CompileBroker::init_training_replay();
847
848 AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
849
850 if (Continuations::enabled()) {
851 // Initialize Continuation class now so that failure to create enterSpecial/doYield
852 // special nmethods due to limited CodeCache size can be treated as a fatal error at
853 // startup with the proper message that CodeCache size is too small.
854 initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
855 }
856
857 #if INCLUDE_CDS
858 if (PrecompileCode) {
859 Precompiler::compile_cached_code(CHECK_JNI_ERR);
860 if (PrecompileOnlyAndExit) {
861 AOTCodeCache::close();
862 log_vm_init_stats();
863 vm_direct_exit(0, "Code precompiation is over");
864 }
865 }
866 #endif
867
868 #if defined(COMPILER2)
869 // Pre-load cached compiled methods
870 AOTCodeCache::preload_code(CHECK_JNI_ERR);
871 #endif
872
873 if (NativeHeapTrimmer::enabled()) {
874 NativeHeapTrimmer::initialize();
875 }
876
877 // Always call even when there are not JVMTI environments yet, since environments
878 // may be attached late and JVMTI must track phases of VM execution
879 JvmtiExport::enter_live_phase();
880
881 // Make perfmemory accessible
882 PerfMemory::set_accessible(true);
883
884 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
885 JvmtiExport::post_vm_initialized();
886
887 #if INCLUDE_JVMCI
888 if (force_JVMCI_initialization) {
889 JVMCI::initialize_compiler_in_create_vm(CHECK_JNI_ERR);
890 }
891 #endif
892
893 JFR_ONLY(Jfr::on_create_vm_3();)
894
895 #if INCLUDE_MANAGEMENT
896 bool start_agent = true;
897 #if INCLUDE_CDS
898 start_agent = !CDSConfig::is_dumping_final_static_archive();
899 if (!start_agent) {
900 log_info(aot)("Not starting management agent during creation of AOT cache.");
901 }
902 #endif // INCLUDE_CDS
903 if (start_agent) {
904 Management::initialize(THREAD);
905
906 if (HAS_PENDING_EXCEPTION) {
907 // management agent fails to start possibly due to
908 // configuration problem and is responsible for printing
909 // stack trace if appropriate. Simply exit VM.
910 vm_exit(1);
911 }
912 }
913 #endif // INCLUDE_MANAGEMENT
914
915 if (UsePerfData) PerfDataManager::create_misc_perfdata();
916 if (CheckJNICalls) JniPeriodicChecker::engage();
917
918 call_postVMInitHook(THREAD);
919 // The Java side of PostVMInitHook.run must deal with all
920 // exceptions and provide means of diagnosis.
921 if (HAS_PENDING_EXCEPTION) {
922 CLEAR_PENDING_EXCEPTION;
923 }
924
925 // Let WatcherThread run all registered periodic tasks now.
926 // NOTE: All PeriodicTasks should be registered by now. If they
927 // aren't, late joiners might appear to start slowly (we might
928 // take a while to process their first tick).
929 WatcherThread::run_all_tasks();
930
931 create_vm_timer.end();
932 #ifdef ASSERT
933 _vm_complete = true;
934 #endif
935
936 if (CDSConfig::is_dumping_classic_static_archive()) {
937 // Classic -Xshare:dump, aka "old workflow"
938 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
939 } else if (CDSConfig::is_dumping_final_static_archive()) {
940 tty->print_cr("Reading AOTConfiguration %s and writing AOTCache %s", AOTConfiguration, AOTCache);
941 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
942 }
943
944 log_info(init)("At VM initialization completion:");
945 log_vm_init_stats();
946
947 if (UsePerfData) {
948 if (ProfileVMLocks) {
949 main_thread->set_profile_vm_locks(true);
950 }
951 if (ProfileVMCalls) {
952 main_thread->set_profile_vm_calls(true);
953 }
954 if (ProfileRuntimeCalls) {
955 main_thread->set_profile_rt_calls(true);
956 }
957 if (ProfileVMOps) {
958 main_thread->set_profile_vm_ops(true);
959 }
960 }
961
962 return JNI_OK;
963 }
964
965 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
966 // the program falls off the end of main(). Another VM exit path is through
967 // vm_exit(), when the program calls System.exit() to return a value, or when
968 // there is a serious error in VM.
969 // These two separate shutdown paths are not exactly the same, but they share
970 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
971 //
972 // Shutdown sequence:
973 // + Shutdown native memory tracking if it is on
974 // + Wait until we are the last non-daemon thread to execute
975 // <-- every thing is still working at this moment -->
976 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
977 // shutdown hooks
978 // + Call before_exit(), prepare for VM exit
979 // > run VM level shutdown hooks (they are registered through JVM_OnExit(),
|