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(),
309 // enable the startup code to use lambda and other language features in this
310 // phase and onward.
311 //
312 // After phase 2, The VM will begin search classes from -Xbootclasspath/a.
313 static void call_initPhase2(TRAPS) {
314 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
315
316 Klass* klass = vmClasses::System_klass();
317
318 JavaValue result(T_INT);
319 JavaCallArguments args;
320 args.push_int(DisplayVMOutputToStderr);
321 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
322 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
323 vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
324 if (result.get_jint() != JNI_OK) {
325 vm_exit_during_initialization(); // no message or exception
326 }
327
328 universe_post_module_init();
329 }
330
331 // Phase 3. final setup - set security manager, system class loader and TCCL
332 //
333 // This will instantiate and set the security manager, set the system class
334 // loader as well as the thread context class loader. The security manager
335 // and system class loader may be a custom class loaded from -Xbootclasspath/a,
336 // other modules or the application's classpath.
337 static void call_initPhase3(TRAPS) {
338 Klass* klass = vmClasses::System_klass();
339 JavaValue result(T_VOID);
340 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
341 vmSymbols::void_method_signature(), CHECK);
342 }
343
344 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
345 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
346
347 initialize_class(vmSymbols::java_lang_String(), CHECK);
348
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
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(),
319 // enable the startup code to use lambda and other language features in this
320 // phase and onward.
321 //
322 // After phase 2, The VM will begin search classes from -Xbootclasspath/a.
323 static void call_initPhase2(TRAPS) {
324 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
325
326 Klass* klass = vmClasses::System_klass();
327
328 JavaValue result(T_INT);
329 JavaCallArguments args;
330 args.push_int(DisplayVMOutputToStderr);
331 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
332 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
333 vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
334 if (result.get_jint() != JNI_OK) {
335 vm_exit_during_initialization(); // no message or exception
336 }
337
338 universe_post_module_init();
339
340 #if 0
341 if (CDSConfig::is_using_aot_linked_classes()) {
342 AOTLinkedClassBulkLoader::load_non_javabase_boot_classes(THREAD);
343 if (CDSConfig::is_using_full_module_graph()) {
344 assert(SystemDictionary::java_platform_loader() != nullptr, "must be");
345 assert(SystemDictionary::java_system_loader() != nullptr, "must be");
346 AOTLinkedClassBulkLoader::load_platform_classes(THREAD);
347 AOTLinkedClassBulkLoader::load_app_classes(THREAD);
348 } else {
349 // Special case -- we assume that the final archive has the same module graph
350 // as the training run.
351 // AOTLinkedClassBulkLoader will be called for the platform/system loaders
352 // inside SystemDictionary::compute_java_loaders().
353 assert(CDSConfig::is_dumping_final_static_archive(), "must be");
354 assert(SystemDictionary::java_platform_loader() == nullptr, "must be");
355 assert(SystemDictionary::java_system_loader() == nullptr, "must be");
356 }
357 }
358
359 #ifndef PRODUCT
360 HeapShared::initialize_test_class_from_archive(THREAD);
361 #endif
362 #endif
363 }
364
365 // Phase 3. final setup - set security manager, system class loader and TCCL
366 //
367 // This will instantiate and set the security manager, set the system class
368 // loader as well as the thread context class loader. The security manager
369 // and system class loader may be a custom class loaded from -Xbootclasspath/a,
370 // other modules or the application's classpath.
371 static void call_initPhase3(TRAPS) {
372 Klass* klass = vmClasses::System_klass();
373 JavaValue result(T_VOID);
374 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
375 vmSymbols::void_method_signature(), CHECK);
376 }
377
378 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
379 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
380
381 initialize_class(vmSymbols::java_lang_String(), CHECK);
382
429 JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
430
431 JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
432
433 JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
434 }
435
436 // an instance of OutOfMemory exception has been allocated earlier
437 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
438 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
439 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
440 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
441 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
442 initialize_class(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), CHECK);
443 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
444 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
445 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
446 initialize_class(vmSymbols::java_lang_InternalError(), CHECK);
447 }
448
449 bool Threads::initialize_compilation(TRAPS) {
450 // initialize compiler(s)
451 bool force_JVMCI_initialization = false;
452
453 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
454 bool init_compilation = true;
455 #if INCLUDE_JVMCI
456 if (EnableJVMCI) {
457 // Initialize JVMCI eagerly when it is explicitly requested.
458 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
459 force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
460 if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
461 // Force initialization of jarjvmci otherwise requests for blocking
462 // compilations will not actually block until jarjvmci is initialized.
463 force_JVMCI_initialization = true;
464 }
465 if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
466 // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
467 // so compilation should be disabled. This prevents dumping or
468 // printing from happening more than once.
469 init_compilation = false;
470 }
471 }
472 #endif
473 if (init_compilation) {
474 CompileBroker::compilation_init(CHECK_false);
475 }
476 #endif
477
478 return force_JVMCI_initialization;
479 }
480
481 void Threads::initialize_jsr292_core_classes(TRAPS) {
482 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
483
484 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
485 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
486 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
487 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
488
489 if (UseSharedSpaces) {
490 HeapShared::initialize_java_lang_invoke(CHECK);
491 }
492 }
493
494 // One-shot PeriodicTask subclass for reading the release file
495 class ReadReleaseFileTask : public PeriodicTask {
496 public:
497 ReadReleaseFileTask() : PeriodicTask(100) {}
498
499 virtual void task() {
500 os::read_image_release_file();
615 } else {
616 JavaThread::_jvmci_old_thread_counters = nullptr;
617 }
618 #endif // INCLUDE_JVMCI
619
620 // Initialize OopStorage for threadObj
621 JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
622
623 // Attach the main thread to this os thread
624 JavaThread* main_thread = new JavaThread();
625 main_thread->set_thread_state(_thread_in_vm);
626 main_thread->initialize_thread_current();
627 // Once mutexes and main_thread are ready, we can use NmtVirtualMemoryLocker.
628 MemTracker::NmtVirtualMemoryLocker::set_safe_to_use();
629 // must do this before set_active_handles
630 main_thread->record_stack_base_and_size();
631 main_thread->register_thread_stack_with_NMT();
632 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
633 MACOS_AARCH64_ONLY(main_thread->init_wx());
634
635 MutexLockerImpl::init_counters(); // depends on mutex_init(), perfMemory_init(), and Thread::initialize_thread_current().
636
637 // Set the _monitor_owner_id now since we will run Java code before the Thread instance
638 // is even created. The same value will be assigned to the Thread instance on init.
639 main_thread->set_monitor_owner_id(ThreadIdentifier::next());
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 // Add main_thread to threads list to finish barrier setup with
682 // on_thread_attach. Should be before starting to build Java objects in
683 // init_globals2, which invokes barriers.
684 {
685 MutexLocker mu(Threads_lock);
686 Threads::add(main_thread);
687 }
688
689 status = init_globals2();
690 if (status != JNI_OK) {
691 Threads::remove(main_thread, false);
800 if (StartAttachListener || AttachListener::init_at_startup()) {
801 AttachListener::init();
802 }
803 }
804
805 // Launch -Xrun agents if EagerXrunInit is not set.
806 if (!EagerXrunInit) {
807 JvmtiAgentList::load_xrun_agents();
808 }
809
810 Arena::start_chunk_pool_cleaner_task();
811
812 // Start the service thread
813 // The service thread enqueues JVMTI deferred events and does various hashtable
814 // and other cleanups. Needs to start before the compilers start posting events.
815 ServiceThread::initialize();
816
817 // Start the monitor deflation thread:
818 MonitorDeflationThread::initialize();
819
820 #if INCLUDE_CDS
821 // Start the method sampler
822 MethodProfiler::initialize();
823 #endif
824
825 bool force_JVMCI_initialization = initialize_compilation(CHECK_JNI_ERR);
826
827 if (CDSConfig::is_using_aot_linked_classes()) {
828 AOTLinkedClassBulkLoader::finish_loading_javabase_classes(CHECK_JNI_ERR);
829 SystemDictionary::restore_archived_method_handle_intrinsics();
830 }
831
832 // Start string deduplication thread if requested.
833 if (StringDedup::is_enabled()) {
834 StringDedup::start();
835 }
836
837 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
838 // It is done after compilers are initialized, because otherwise compilations of
839 // signature polymorphic MH intrinsics can be missed
840 // (see SystemDictionary::find_method_handle_intrinsic).
841 initialize_jsr292_core_classes(CHECK_JNI_ERR);
842
843 // This will initialize the module system. Only java.base classes can be
844 // loaded until phase 2 completes
845 call_initPhase2(CHECK_JNI_ERR);
846
847 if (CDSConfig::is_using_aot_linked_classes() && !CDSConfig::is_dumping_final_static_archive()) {
848 AOTLinkedClassBulkLoader::load_non_javabase_classes(THREAD);
849 }
850 #ifndef PRODUCT
851 HeapShared::initialize_test_class_from_archive(THREAD);
852 #endif
853
854 JFR_ONLY(Jfr::on_create_vm_2();)
855
856 // Always call even when there are not JVMTI environments yet, since environments
857 // may be attached late and JVMTI must track phases of VM execution
858 JvmtiExport::enter_start_phase();
859
860 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
861 JvmtiExport::post_vm_start();
862
863 // Final system initialization including security manager and system class loader
864 call_initPhase3(CHECK_JNI_ERR);
865
866 // cache the system and platform class loaders
867 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
868
869 // Initiate replay training processing once preloading is over.
870 CompileBroker::init_training_replay();
871
872 AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
873
874 if (Continuations::enabled()) {
875 // Initialize Continuation class now so that failure to create enterSpecial/doYield
876 // special nmethods due to limited CodeCache size can be treated as a fatal error at
877 // startup with the proper message that CodeCache size is too small.
878 initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
879 }
880
881 #if INCLUDE_CDS
882 if (PrecompileCode) {
883 Precompiler::compile_cached_code(CHECK_JNI_ERR);
884 if (PrecompileOnlyAndExit) {
885 AOTCodeCache::close();
886 log_vm_init_stats();
887 vm_direct_exit(0, "Code precompiation is over");
888 }
889 }
890 #endif
891
892 #if defined(COMPILER2)
893 // Pre-load cached compiled methods
894 AOTCodeCache::preload_code(CHECK_JNI_ERR);
895 #endif
896
897 if (NativeHeapTrimmer::enabled()) {
898 NativeHeapTrimmer::initialize();
899 }
900
901 // Always call even when there are not JVMTI environments yet, since environments
902 // may be attached late and JVMTI must track phases of VM execution
903 JvmtiExport::enter_live_phase();
904
905 // Make perfmemory accessible
906 PerfMemory::set_accessible(true);
907
908 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
909 JvmtiExport::post_vm_initialized();
910
911 #if INCLUDE_JVMCI
912 if (force_JVMCI_initialization) {
913 JVMCI::initialize_compiler_in_create_vm(CHECK_JNI_ERR);
914 }
915 #endif
916
935 // exceptions and provide means of diagnosis.
936 if (HAS_PENDING_EXCEPTION) {
937 CLEAR_PENDING_EXCEPTION;
938 }
939
940 // Let WatcherThread run all registered periodic tasks now.
941 // NOTE: All PeriodicTasks should be registered by now. If they
942 // aren't, late joiners might appear to start slowly (we might
943 // take a while to process their first tick).
944 WatcherThread::run_all_tasks();
945
946 create_vm_timer.end();
947 #ifdef ASSERT
948 _vm_complete = true;
949 #endif
950
951 if (CDSConfig::is_dumping_classic_static_archive()) {
952 // Classic -Xshare:dump, aka "old workflow"
953 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
954 } else if (CDSConfig::is_dumping_final_static_archive()) {
955 if (CDSConfig::is_experimental_leyden_workflow()) {
956 // TODO: copy the verification and loader constraints from preimage to final image
957 // TODO: load archived classes for custom loaders as well.
958 log_info(cds)("Dumping final image of CacheDataStore %s", CacheDataStore);
959 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
960 vm_direct_exit(0, "CacheDataStore dumping is complete");
961 } else {
962 tty->print_cr("Reading AOTConfiguration %s and writing AOTCache %s", AOTConfiguration, AOTCache);
963 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
964 }
965 }
966
967 log_info(init)("At VM initialization completion:");
968 log_vm_init_stats();
969
970 if (UsePerfData) {
971 if (ProfileVMLocks) {
972 main_thread->set_profile_vm_locks(true);
973 }
974 if (ProfileVMCalls) {
975 main_thread->set_profile_vm_calls(true);
976 }
977 if (ProfileRuntimeCalls) {
978 main_thread->set_profile_rt_calls(true);
979 }
980 if (ProfileVMOps) {
981 main_thread->set_profile_vm_ops(true);
982 }
983 }
984
985 return JNI_OK;
986 }
987
988 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
989 // the program falls off the end of main(). Another VM exit path is through
990 // vm_exit(), when the program calls System.exit() to return a value, or when
991 // there is a serious error in VM.
992 // These two separate shutdown paths are not exactly the same, but they share
993 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
994 //
995 // Shutdown sequence:
996 // + Shutdown native memory tracking if it is on
997 // + Wait until we are the last non-daemon thread to execute
998 // <-- every thing is still working at this moment -->
999 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
1000 // shutdown hooks
1001 // + Call before_exit(), prepare for VM exit
1002 // > run VM level shutdown hooks (they are registered through JVM_OnExit(),
|