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 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
429 extern void JDK_Version_init();
430
431 // Preinitialize version info.
432 VM_Version::early_initialize();
433
434 // Check version
533 } else {
534 JavaThread::_jvmci_old_thread_counters = nullptr;
535 }
536 #endif // INCLUDE_JVMCI
537
538 // Initialize OopStorage for threadObj
539 JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
540
541 // Attach the main thread to this os thread
542 JavaThread* main_thread = new JavaThread();
543 main_thread->set_thread_state(_thread_in_vm);
544 main_thread->initialize_thread_current();
545 // Once mutexes and main_thread are ready, we can use NmtVirtualMemoryLocker.
546 MemTracker::NmtVirtualMemoryLocker::set_safe_to_use();
547 // must do this before set_active_handles
548 main_thread->record_stack_base_and_size();
549 main_thread->register_thread_stack_with_NMT();
550 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
551 MACOS_AARCH64_ONLY(main_thread->init_wx());
552
553 // Set the _monitor_owner_id now since we will run Java code before the Thread instance
554 // is even created. The same value will be assigned to the Thread instance on init.
555 main_thread->set_monitor_owner_id(ThreadIdentifier::next());
556
557 if (!Thread::set_as_starting_thread(main_thread)) {
558 vm_shutdown_during_initialization(
559 "Failed necessary internal allocation. Out of swap space");
560 main_thread->smr_delete();
561 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
562 return JNI_ENOMEM;
563 }
564
565 JFR_ONLY(Jfr::initialize_main_thread(main_thread);)
566
567 // Enable guard page *after* os::create_main_thread(), otherwise it would
568 // crash Linux VM, see notes in os_linux.cpp.
569 main_thread->stack_overflow_state()->create_stack_guard_pages();
570
571 // Initialize Java-Level synchronization subsystem
572 ObjectMonitor::Initialize();
573 ObjectSynchronizer::initialize();
574
575 // Initialize global modules
576 jint status = init_globals();
577 if (status != JNI_OK) {
578 main_thread->smr_delete();
579 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
580 return status;
581 }
582
583 // Create WatcherThread as soon as we can since we need it in case
584 // of hangs during error reporting.
585 WatcherThread::start();
586
587 // Add main_thread to threads list to finish barrier setup with
588 // on_thread_attach. Should be before starting to build Java objects in
589 // init_globals2, which invokes barriers.
590 {
591 MutexLocker mu(Threads_lock);
592 Threads::add(main_thread);
593 }
594
595 status = init_globals2();
596 if (status != JNI_OK) {
597 Threads::remove(main_thread, false);
598 // It is possible that we managed to fully initialize Universe but have then
599 // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
600 // will want to report it, so we can't delete the main thread.
601 if (!main_thread->has_pending_exception()) {
706 if (StartAttachListener || AttachListener::init_at_startup()) {
707 AttachListener::init();
708 }
709 }
710
711 // Launch -Xrun agents if EagerXrunInit is not set.
712 if (!EagerXrunInit) {
713 JvmtiAgentList::load_xrun_agents();
714 }
715
716 Arena::start_chunk_pool_cleaner_task();
717
718 // Start the service thread
719 // The service thread enqueues JVMTI deferred events and does various hashtable
720 // and other cleanups. Needs to start before the compilers start posting events.
721 ServiceThread::initialize();
722
723 // Start the monitor deflation thread:
724 MonitorDeflationThread::initialize();
725
726 // initialize compiler(s)
727 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
728 bool init_compilation = true;
729 #if INCLUDE_JVMCI
730 bool force_JVMCI_initialization = false;
731 if (EnableJVMCI) {
732 // Initialize JVMCI eagerly when it is explicitly requested.
733 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
734 force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
735 if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
736 // Force initialization of jarjvmci otherwise requests for blocking
737 // compilations will not actually block until jarjvmci is initialized.
738 force_JVMCI_initialization = true;
739 }
740 if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
741 // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
742 // so compilation should be disabled. This prevents dumping or
743 // printing from happening more than once.
744 init_compilation = false;
745 }
746 }
747 #endif
748 if (init_compilation) {
749 CompileBroker::compilation_init(CHECK_JNI_ERR);
750 }
751 #endif
752
753 if (CDSConfig::is_using_aot_linked_classes()) {
754 AOTLinkedClassBulkLoader::finish_loading_javabase_classes(CHECK_JNI_ERR);
755 SystemDictionary::restore_archived_method_handle_intrinsics();
756 }
757
758 // Start string deduplication thread if requested.
759 if (StringDedup::is_enabled()) {
760 StringDedup::start();
761 }
762
763 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
764 // It is done after compilers are initialized, because otherwise compilations of
765 // signature polymorphic MH intrinsics can be missed
766 // (see SystemDictionary::find_method_handle_intrinsic).
767 initialize_jsr292_core_classes(CHECK_JNI_ERR);
768
769 // This will initialize the module system. Only java.base classes can be
770 // loaded until phase 2 completes
771 call_initPhase2(CHECK_JNI_ERR);
772
773 if (CDSConfig::is_using_aot_linked_classes()) {
774 AOTLinkedClassBulkLoader::load_non_javabase_classes(THREAD);
775 }
776 #ifndef PRODUCT
777 HeapShared::initialize_test_class_from_archive(THREAD);
778 #endif
779
780 JFR_ONLY(Jfr::on_create_vm_2();)
781
782 // Always call even when there are not JVMTI environments yet, since environments
783 // may be attached late and JVMTI must track phases of VM execution
784 JvmtiExport::enter_start_phase();
785
786 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
787 JvmtiExport::post_vm_start();
788
789 // Final system initialization including security manager and system class loader
790 call_initPhase3(CHECK_JNI_ERR);
791
792 // cache the system and platform class loaders
793 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
794
795 if (Continuations::enabled()) {
796 // Initialize Continuation class now so that failure to create enterSpecial/doYield
797 // special nmethods due to limited CodeCache size can be treated as a fatal error at
798 // startup with the proper message that CodeCache size is too small.
799 initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
800 }
801
802 #if INCLUDE_CDS
803 // capture the module path info from the ModuleEntryTable
804 ClassLoader::initialize_module_path(THREAD);
805 if (HAS_PENDING_EXCEPTION) {
806 java_lang_Throwable::print(PENDING_EXCEPTION, tty);
807 vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly");
808 }
809 #endif
810
811 if (NativeHeapTrimmer::enabled()) {
812 NativeHeapTrimmer::initialize();
813 }
814
815 // Always call even when there are not JVMTI environments yet, since environments
816 // may be attached late and JVMTI must track phases of VM execution
817 JvmtiExport::enter_live_phase();
818
819 // Make perfmemory accessible
820 PerfMemory::set_accessible(true);
821
822 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
823 JvmtiExport::post_vm_initialized();
824
825 #if INCLUDE_JVMCI
826 if (force_JVMCI_initialization) {
827 JVMCI::initialize_compiler(CHECK_JNI_ERR);
828 }
829 #endif
830
845 if (CheckJNICalls) JniPeriodicChecker::engage();
846
847 call_postVMInitHook(THREAD);
848 // The Java side of PostVMInitHook.run must deal with all
849 // exceptions and provide means of diagnosis.
850 if (HAS_PENDING_EXCEPTION) {
851 CLEAR_PENDING_EXCEPTION;
852 }
853
854 // Let WatcherThread run all registered periodic tasks now.
855 // NOTE: All PeriodicTasks should be registered by now. If they
856 // aren't, late joiners might appear to start slowly (we might
857 // take a while to process their first tick).
858 WatcherThread::run_all_tasks();
859
860 create_vm_timer.end();
861 #ifdef ASSERT
862 _vm_complete = true;
863 #endif
864
865 if (CDSConfig::is_dumping_static_archive()) {
866 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
867 }
868
869 if (log_is_enabled(Info, perf, class, link)) {
870 LogStreamHandle(Info, perf, class, link) log;
871 log.print_cr("At VM initialization completion:");
872 ClassLoader::print_counters(&log);
873 }
874
875 return JNI_OK;
876 }
877
878 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
879 // the program falls off the end of main(). Another VM exit path is through
880 // vm_exit(), when the program calls System.exit() to return a value, or when
881 // there is a serious error in VM.
882 // These two separate shutdown paths are not exactly the same, but they share
883 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
884 //
885 // Shutdown sequence:
886 // + Shutdown native memory tracking if it is on
887 // + Wait until we are the last non-daemon thread to execute
888 // <-- every thing is still working at this moment -->
889 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
890 // shutdown hooks
891 // + Call before_exit(), prepare for VM exit
892 // > 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/SCCache.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 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
495 extern void JDK_Version_init();
496
497 // Preinitialize version info.
498 VM_Version::early_initialize();
499
500 // Check version
599 } else {
600 JavaThread::_jvmci_old_thread_counters = nullptr;
601 }
602 #endif // INCLUDE_JVMCI
603
604 // Initialize OopStorage for threadObj
605 JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
606
607 // Attach the main thread to this os thread
608 JavaThread* main_thread = new JavaThread();
609 main_thread->set_thread_state(_thread_in_vm);
610 main_thread->initialize_thread_current();
611 // Once mutexes and main_thread are ready, we can use NmtVirtualMemoryLocker.
612 MemTracker::NmtVirtualMemoryLocker::set_safe_to_use();
613 // must do this before set_active_handles
614 main_thread->record_stack_base_and_size();
615 main_thread->register_thread_stack_with_NMT();
616 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
617 MACOS_AARCH64_ONLY(main_thread->init_wx());
618
619 MutexLockerImpl::init_counters(); // depends on mutex_init(), perfMemory_init(), and Thread::initialize_thread_current().
620
621 // Set the _monitor_owner_id now since we will run Java code before the Thread instance
622 // is even created. The same value will be assigned to the Thread instance on init.
623 main_thread->set_monitor_owner_id(ThreadIdentifier::next());
624
625 if (!Thread::set_as_starting_thread(main_thread)) {
626 vm_shutdown_during_initialization(
627 "Failed necessary internal allocation. Out of swap space");
628 main_thread->smr_delete();
629 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
630 return JNI_ENOMEM;
631 }
632
633 JFR_ONLY(Jfr::initialize_main_thread(main_thread);)
634
635 // Enable guard page *after* os::create_main_thread(), otherwise it would
636 // crash Linux VM, see notes in os_linux.cpp.
637 main_thread->stack_overflow_state()->create_stack_guard_pages();
638
639 // Initialize Java-Level synchronization subsystem
640 ObjectMonitor::Initialize();
641 ObjectSynchronizer::initialize();
642
643 Deoptimization::init_counters();
644 VMThread::init_counters();
645
646 // Initialize global modules
647 jint status = init_globals();
648 if (status != JNI_OK) {
649 main_thread->smr_delete();
650 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
651 return status;
652 }
653 if (xtty != nullptr)
654 xtty->elem("vm_main_thread thread='%zu'",
655 (uintx) main_thread->osthread()->thread_id());
656
657 // Create WatcherThread as soon as we can since we need it in case
658 // of hangs during error reporting.
659 WatcherThread::start();
660
661 // Add main_thread to threads list to finish barrier setup with
662 // on_thread_attach. Should be before starting to build Java objects in
663 // init_globals2, which invokes barriers.
664 {
665 MutexLocker mu(Threads_lock);
666 Threads::add(main_thread);
667 }
668
669 status = init_globals2();
670 if (status != JNI_OK) {
671 Threads::remove(main_thread, false);
672 // It is possible that we managed to fully initialize Universe but have then
673 // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
674 // will want to report it, so we can't delete the main thread.
675 if (!main_thread->has_pending_exception()) {
780 if (StartAttachListener || AttachListener::init_at_startup()) {
781 AttachListener::init();
782 }
783 }
784
785 // Launch -Xrun agents if EagerXrunInit is not set.
786 if (!EagerXrunInit) {
787 JvmtiAgentList::load_xrun_agents();
788 }
789
790 Arena::start_chunk_pool_cleaner_task();
791
792 // Start the service thread
793 // The service thread enqueues JVMTI deferred events and does various hashtable
794 // and other cleanups. Needs to start before the compilers start posting events.
795 ServiceThread::initialize();
796
797 // Start the monitor deflation thread:
798 MonitorDeflationThread::initialize();
799
800 #if INCLUDE_CDS
801 // Start the method sampler
802 MethodProfiler::initialize();
803 #endif
804
805 bool force_JVMCI_initialization = initialize_compilation(CHECK_JNI_ERR);
806
807 if (CDSConfig::is_using_aot_linked_classes()) {
808 AOTLinkedClassBulkLoader::finish_loading_javabase_classes(CHECK_JNI_ERR);
809 SystemDictionary::restore_archived_method_handle_intrinsics();
810 }
811
812 // Start string deduplication thread if requested.
813 if (StringDedup::is_enabled()) {
814 StringDedup::start();
815 }
816
817 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
818 // It is done after compilers are initialized, because otherwise compilations of
819 // signature polymorphic MH intrinsics can be missed
820 // (see SystemDictionary::find_method_handle_intrinsic).
821 initialize_jsr292_core_classes(CHECK_JNI_ERR);
822
823 // This will initialize the module system. Only java.base classes can be
824 // loaded until phase 2 completes
825 call_initPhase2(CHECK_JNI_ERR);
826
827 if (CDSConfig::is_using_aot_linked_classes() && !CDSConfig::is_dumping_final_static_archive()) {
828 AOTLinkedClassBulkLoader::load_non_javabase_classes(THREAD);
829 }
830 #ifndef PRODUCT
831 HeapShared::initialize_test_class_from_archive(THREAD);
832 #endif
833
834 JFR_ONLY(Jfr::on_create_vm_2();)
835
836 // Always call even when there are not JVMTI environments yet, since environments
837 // may be attached late and JVMTI must track phases of VM execution
838 JvmtiExport::enter_start_phase();
839
840 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
841 JvmtiExport::post_vm_start();
842
843 // Final system initialization including security manager and system class loader
844 call_initPhase3(CHECK_JNI_ERR);
845
846 // cache the system and platform class loaders
847 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
848
849 // Initiate replay training processing once preloading is over.
850 CompileBroker::init_training_replay();
851
852 AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
853
854 if (Continuations::enabled()) {
855 // Initialize Continuation class now so that failure to create enterSpecial/doYield
856 // special nmethods due to limited CodeCache size can be treated as a fatal error at
857 // startup with the proper message that CodeCache size is too small.
858 initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
859 }
860
861 #if INCLUDE_CDS
862 // capture the module path info from the ModuleEntryTable
863 ClassLoader::initialize_module_path(THREAD);
864 if (HAS_PENDING_EXCEPTION) {
865 java_lang_Throwable::print(PENDING_EXCEPTION, tty);
866 vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly");
867 }
868 #endif
869
870 if (PrecompileCode) {
871 Precompiler::compile_cached_code(CHECK_JNI_ERR);
872 if (PrecompileOnlyAndExit) {
873 SCCache::close();
874 log_vm_init_stats();
875 vm_direct_exit(0, "Code precompiation is over");
876 }
877 }
878
879 #if defined(COMPILER2)
880 // Pre-load cached compiled methods
881 SCCache::preload_code(CHECK_JNI_ERR);
882 #endif
883
884 if (NativeHeapTrimmer::enabled()) {
885 NativeHeapTrimmer::initialize();
886 }
887
888 // Always call even when there are not JVMTI environments yet, since environments
889 // may be attached late and JVMTI must track phases of VM execution
890 JvmtiExport::enter_live_phase();
891
892 // Make perfmemory accessible
893 PerfMemory::set_accessible(true);
894
895 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
896 JvmtiExport::post_vm_initialized();
897
898 #if INCLUDE_JVMCI
899 if (force_JVMCI_initialization) {
900 JVMCI::initialize_compiler(CHECK_JNI_ERR);
901 }
902 #endif
903
918 if (CheckJNICalls) JniPeriodicChecker::engage();
919
920 call_postVMInitHook(THREAD);
921 // The Java side of PostVMInitHook.run must deal with all
922 // exceptions and provide means of diagnosis.
923 if (HAS_PENDING_EXCEPTION) {
924 CLEAR_PENDING_EXCEPTION;
925 }
926
927 // Let WatcherThread run all registered periodic tasks now.
928 // NOTE: All PeriodicTasks should be registered by now. If they
929 // aren't, late joiners might appear to start slowly (we might
930 // take a while to process their first tick).
931 WatcherThread::run_all_tasks();
932
933 create_vm_timer.end();
934 #ifdef ASSERT
935 _vm_complete = true;
936 #endif
937
938 if (CDSConfig::is_dumping_classic_static_archive()) {
939 // Classic -Xshare:dump, aka "old workflow"
940 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
941 } else if (CDSConfig::is_dumping_final_static_archive()) {
942 // TODO: copy the verification and loader constraints from preimage to final image
943 // TODO: load archived classes for custom loaders as well.
944 log_info(cds)("Dumping final image of CacheDataStore %s", CacheDataStore);
945 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
946 vm_direct_exit(0, "CacheDataStore dumping is complete");
947 }
948
949 log_info(init)("At VM initialization completion:");
950 log_vm_init_stats();
951
952 if (UsePerfData) {
953 if (ProfileVMLocks) {
954 main_thread->set_profile_vm_locks(true);
955 }
956 if (ProfileVMCalls) {
957 main_thread->set_profile_vm_calls(true);
958 }
959 if (ProfileRuntimeCalls) {
960 main_thread->set_profile_rt_calls(true);
961 }
962 if (ProfileVMOps) {
963 main_thread->set_profile_vm_ops(true);
964 }
965 }
966
967 return JNI_OK;
968 }
969
970 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
971 // the program falls off the end of main(). Another VM exit path is through
972 // vm_exit(), when the program calls System.exit() to return a value, or when
973 // there is a serious error in VM.
974 // These two separate shutdown paths are not exactly the same, but they share
975 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
976 //
977 // Shutdown sequence:
978 // + Shutdown native memory tracking if it is on
979 // + Wait until we are the last non-daemon thread to execute
980 // <-- every thing is still working at this moment -->
981 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
982 // shutdown hooks
983 // + Call before_exit(), prepare for VM exit
984 // > run VM level shutdown hooks (they are registered through JVM_OnExit(),
|