7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26 #include "precompiled.hpp"
27 #include "cds/cds_globals.hpp"
28 #include "cds/cdsConfig.hpp"
29 #include "cds/metaspaceShared.hpp"
30 #include "classfile/classLoader.hpp"
31 #include "classfile/javaClasses.hpp"
32 #include "classfile/javaThreadStatus.hpp"
33 #include "classfile/systemDictionary.hpp"
34 #include "classfile/vmClasses.hpp"
35 #include "classfile/vmSymbols.hpp"
36 #include "compiler/compileBroker.hpp"
37 #include "compiler/compileTask.hpp"
38 #include "compiler/compilerThread.hpp"
39 #include "gc/shared/barrierSet.hpp"
40 #include "gc/shared/barrierSetNMethod.hpp"
41 #include "gc/shared/gcVMOperations.hpp"
42 #include "gc/shared/oopStorage.hpp"
43 #include "gc/shared/oopStorageSet.hpp"
44 #include "gc/shared/stringdedup/stringDedup.hpp"
45 #include "jfr/jfrEvents.hpp"
46 #include "jvm.h"
47 #include "jvmtifiles/jvmtiEnv.hpp"
48 #include "logging/log.hpp"
49 #include "logging/logAsyncWriter.hpp"
50 #include "logging/logConfiguration.hpp"
51 #include "memory/allocation.inline.hpp"
52 #include "memory/iterator.hpp"
53 #include "memory/oopFactory.hpp"
54 #include "memory/resourceArea.hpp"
55 #include "memory/universe.hpp"
56 #include "nmt/memTracker.hpp"
57 #include "oops/instanceKlass.hpp"
58 #include "oops/klass.inline.hpp"
59 #include "oops/oop.inline.hpp"
60 #include "oops/symbol.hpp"
61 #include "prims/jvm_misc.hpp"
62 #include "prims/jvmtiAgentList.hpp"
63 #include "prims/jvmtiEnvBase.hpp"
64 #include "runtime/arguments.hpp"
65 #include "runtime/fieldDescriptor.inline.hpp"
66 #include "runtime/flags/jvmFlagLimit.hpp"
67 #include "runtime/globals.hpp"
68 #include "runtime/handles.inline.hpp"
69 #include "runtime/interfaceSupport.inline.hpp"
70 #include "runtime/java.hpp"
71 #include "runtime/javaCalls.hpp"
72 #include "runtime/javaThread.inline.hpp"
73 #include "runtime/jniHandles.inline.hpp"
74 #include "runtime/jniPeriodicChecker.hpp"
75 #include "runtime/lockStack.inline.hpp"
76 #include "runtime/monitorDeflationThread.hpp"
77 #include "runtime/mutexLocker.hpp"
78 #include "runtime/nonJavaThread.hpp"
79 #include "runtime/objectMonitor.inline.hpp"
300 // enable the startup code to use lambda and other language features in this
301 // phase and onward.
302 //
303 // After phase 2, The VM will begin search classes from -Xbootclasspath/a.
304 static void call_initPhase2(TRAPS) {
305 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
306
307 Klass* klass = vmClasses::System_klass();
308
309 JavaValue result(T_INT);
310 JavaCallArguments args;
311 args.push_int(DisplayVMOutputToStderr);
312 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
313 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
314 vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
315 if (result.get_jint() != JNI_OK) {
316 vm_exit_during_initialization(); // no message or exception
317 }
318
319 universe_post_module_init();
320 }
321
322 // Phase 3. final setup - set security manager, system class loader and TCCL
323 //
324 // This will instantiate and set the security manager, set the system class
325 // loader as well as the thread context class loader. The security manager
326 // and system class loader may be a custom class loaded from -Xbootclasspath/a,
327 // other modules or the application's classpath.
328 static void call_initPhase3(TRAPS) {
329 Klass* klass = vmClasses::System_klass();
330 JavaValue result(T_VOID);
331 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
332 vmSymbols::void_method_signature(), CHECK);
333 }
334
335 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
336 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
337
338 initialize_class(vmSymbols::java_lang_String(), CHECK);
339
340 // Inject CompactStrings value after the static initializers for String ran.
341 java_lang_String::set_compact_strings(CompactStrings);
342
343 // Initialize java_lang.System (needed before creating the thread)
344 initialize_class(vmSymbols::java_lang_System(), CHECK);
345 // The VM creates & returns objects of this class. Make sure it's initialized.
346 initialize_class(vmSymbols::java_lang_Class(), CHECK);
347 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
348 Handle thread_group = create_initial_thread_group(CHECK);
349 Universe::set_main_thread_group(thread_group());
350 initialize_class(vmSymbols::java_lang_Thread(), CHECK);
351 create_initial_thread(thread_group, main_thread, CHECK);
352
353 // The VM creates objects of this class.
354 initialize_class(vmSymbols::java_lang_Module(), CHECK);
355
356 #ifdef ASSERT
357 InstanceKlass *k = vmClasses::UnsafeConstants_klass();
358 assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
359 #endif
360
361 // initialize the hardware-specific constants needed by Unsafe
362 initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
363 jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
364
365 // The VM preresolves methods to these classes. Make sure that they get initialized
366 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
367 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
368
369 // Phase 1 of the system initialization in the library, java.lang.System class initialization
370 call_initPhase1(CHECK);
371
372 // Get the Java runtime name, version, and vendor info after java.lang.System is initialized.
381 JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name()));
382
383 JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
384
385 JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
386
387 JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
388 }
389
390 // an instance of OutOfMemory exception has been allocated earlier
391 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
392 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
393 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
394 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
395 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
396 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
397 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
398 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
399 }
400
401 void Threads::initialize_jsr292_core_classes(TRAPS) {
402 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
403
404 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
405 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
406 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
407 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
408 }
409
410 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
411 extern void JDK_Version_init();
412
413 // Preinitialize version info.
414 VM_Version::early_initialize();
415
416 // Check version
417 if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
418
419 // Initialize library-based TLS
420 ThreadLocalStorage::init();
421
422 // Initialize the output stream module
423 ostream_init();
424
425 // Process java launcher properties.
426 Arguments::process_sun_java_launcher_properties(args);
427
513 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
514 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
515 } else {
516 JavaThread::_jvmci_old_thread_counters = nullptr;
517 }
518 #endif // INCLUDE_JVMCI
519
520 // Initialize OopStorage for threadObj
521 JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
522
523 // Attach the main thread to this os thread
524 JavaThread* main_thread = new JavaThread();
525 main_thread->set_thread_state(_thread_in_vm);
526 main_thread->initialize_thread_current();
527 // must do this before set_active_handles
528 main_thread->record_stack_base_and_size();
529 main_thread->register_thread_stack_with_NMT();
530 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
531 MACOS_AARCH64_ONLY(main_thread->init_wx());
532
533 if (!main_thread->set_as_starting_thread()) {
534 vm_shutdown_during_initialization(
535 "Failed necessary internal allocation. Out of swap space");
536 main_thread->smr_delete();
537 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
538 return JNI_ENOMEM;
539 }
540
541 // Enable guard page *after* os::create_main_thread(), otherwise it would
542 // crash Linux VM, see notes in os_linux.cpp.
543 main_thread->stack_overflow_state()->create_stack_guard_pages();
544
545 // Initialize Java-Level synchronization subsystem
546 ObjectMonitor::Initialize();
547 ObjectSynchronizer::initialize();
548
549 // Initialize global modules
550 jint status = init_globals();
551 if (status != JNI_OK) {
552 main_thread->smr_delete();
553 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
554 return status;
555 }
556
557 // Create WatcherThread as soon as we can since we need it in case
558 // of hangs during error reporting.
559 WatcherThread::start();
560
561 // Add main_thread to threads list to finish barrier setup with
562 // on_thread_attach. Should be before starting to build Java objects in
563 // init_globals2, which invokes barriers.
564 {
565 MutexLocker mu(Threads_lock);
566 Threads::add(main_thread);
567 }
568
569 status = init_globals2();
570 if (status != JNI_OK) {
571 Threads::remove(main_thread, false);
572 // It is possible that we managed to fully initialize Universe but have then
573 // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
574 // will want to report it, so we can't delete the main thread.
575 if (!main_thread->has_pending_exception()) {
673 if (StartAttachListener || AttachListener::init_at_startup()) {
674 AttachListener::init();
675 }
676 }
677
678 // Launch -Xrun agents if EagerXrunInit is not set.
679 if (!EagerXrunInit) {
680 JvmtiAgentList::load_xrun_agents();
681 }
682
683 Arena::start_chunk_pool_cleaner_task();
684
685 // Start the service thread
686 // The service thread enqueues JVMTI deferred events and does various hashtable
687 // and other cleanups. Needs to start before the compilers start posting events.
688 ServiceThread::initialize();
689
690 // Start the monitor deflation thread:
691 MonitorDeflationThread::initialize();
692
693 // initialize compiler(s)
694 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
695 bool init_compilation = true;
696 #if INCLUDE_JVMCI
697 bool force_JVMCI_initialization = false;
698 if (EnableJVMCI) {
699 // Initialize JVMCI eagerly when it is explicitly requested.
700 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
701 force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
702 if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
703 // Force initialization of jarjvmci otherwise requests for blocking
704 // compilations will not actually block until jarjvmci is initialized.
705 force_JVMCI_initialization = true;
706 }
707 if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
708 // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
709 // so compilation should be disabled. This prevents dumping or
710 // printing from happening more than once.
711 init_compilation = false;
712 }
713 }
714 #endif
715 if (init_compilation) {
716 CompileBroker::compilation_init(CHECK_JNI_ERR);
717 }
718 #endif
719
720 // Start string deduplication thread if requested.
721 if (StringDedup::is_enabled()) {
722 StringDedup::start();
723 }
724
725 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
726 // It is done after compilers are initialized, because otherwise compilations of
727 // signature polymorphic MH intrinsics can be missed
728 // (see SystemDictionary::find_method_handle_intrinsic).
729 initialize_jsr292_core_classes(CHECK_JNI_ERR);
730
731 // This will initialize the module system. Only java.base classes can be
732 // loaded until phase 2 completes
733 call_initPhase2(CHECK_JNI_ERR);
734
735 JFR_ONLY(Jfr::on_create_vm_2();)
736
737 // Always call even when there are not JVMTI environments yet, since environments
738 // may be attached late and JVMTI must track phases of VM execution
739 JvmtiExport::enter_start_phase();
740
741 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
742 JvmtiExport::post_vm_start();
743
744 // Final system initialization including security manager and system class loader
745 call_initPhase3(CHECK_JNI_ERR);
746
747 // cache the system and platform class loaders
748 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
749
750 if (Continuations::enabled()) {
751 // Initialize Continuation class now so that failure to create enterSpecial/doYield
752 // special nmethods due to limited CodeCache size can be treated as a fatal error at
753 // startup with the proper message that CodeCache size is too small.
754 initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
755 }
756
757 #if INCLUDE_CDS
758 // capture the module path info from the ModuleEntryTable
759 ClassLoader::initialize_module_path(THREAD);
760 if (HAS_PENDING_EXCEPTION) {
761 java_lang_Throwable::print(PENDING_EXCEPTION, tty);
762 vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly");
763 }
764 #endif
765
766 #if INCLUDE_JVMCI
767 if (force_JVMCI_initialization) {
768 JVMCI::initialize_compiler(CHECK_JNI_ERR);
769 }
770 #endif
771
772 if (NativeHeapTrimmer::enabled()) {
773 NativeHeapTrimmer::initialize();
774 }
775
776 // Always call even when there are not JVMTI environments yet, since environments
777 // may be attached late and JVMTI must track phases of VM execution
778 JvmtiExport::enter_live_phase();
779
780 // Make perfmemory accessible
781 PerfMemory::set_accessible(true);
782
783 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
784 JvmtiExport::post_vm_initialized();
785
786 JFR_ONLY(Jfr::on_create_vm_3();)
787
788 #if INCLUDE_MANAGEMENT
789 Management::initialize(THREAD);
790
791 if (HAS_PENDING_EXCEPTION) {
800 if (CheckJNICalls) JniPeriodicChecker::engage();
801
802 call_postVMInitHook(THREAD);
803 // The Java side of PostVMInitHook.run must deal with all
804 // exceptions and provide means of diagnosis.
805 if (HAS_PENDING_EXCEPTION) {
806 CLEAR_PENDING_EXCEPTION;
807 }
808
809 // Let WatcherThread run all registered periodic tasks now.
810 // NOTE: All PeriodicTasks should be registered by now. If they
811 // aren't, late joiners might appear to start slowly (we might
812 // take a while to process their first tick).
813 WatcherThread::run_all_tasks();
814
815 create_vm_timer.end();
816 #ifdef ASSERT
817 _vm_complete = true;
818 #endif
819
820 if (CDSConfig::is_dumping_static_archive()) {
821 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
822 }
823
824 if (log_is_enabled(Info, perf, class, link)) {
825 LogStreamHandle(Info, perf, class, link) log;
826 log.print_cr("At VM initialization completion:");
827 ClassLoader::print_counters(&log);
828 }
829
830 return JNI_OK;
831 }
832
833 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
834 // the program falls off the end of main(). Another VM exit path is through
835 // vm_exit(), when the program calls System.exit() to return a value, or when
836 // there is a serious error in VM.
837 // These two separate shutdown paths are not exactly the same, but they share
838 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
839 //
840 // Shutdown sequence:
841 // + Shutdown native memory tracking if it is on
842 // + Wait until we are the last non-daemon thread to execute
843 // <-- every thing is still working at this moment -->
844 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
845 // shutdown hooks
846 // + Call before_exit(), prepare for VM exit
847 // > run VM level shutdown hooks (they are registered through JVM_OnExit(),
|
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26 #include "precompiled.hpp"
27 #include "c1/c1_Runtime1.hpp"
28 #include "cds/cds_globals.hpp"
29 #include "cds/cdsConfig.hpp"
30 #include "cds/classPreloader.hpp"
31 #include "cds/heapShared.hpp"
32 #include "cds/metaspaceShared.hpp"
33 #include "cds/methodProfiler.hpp"
34 #include "classfile/classLoader.hpp"
35 #include "classfile/javaClasses.hpp"
36 #include "classfile/javaThreadStatus.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 "opto/runtime.hpp"
70 #include "oops/symbol.hpp"
71 #include "prims/jvm_misc.hpp"
72 #include "prims/jvmtiAgentList.hpp"
73 #include "prims/jvmtiEnvBase.hpp"
74 #include "runtime/arguments.hpp"
75 #include "runtime/fieldDescriptor.inline.hpp"
76 #include "runtime/flags/jvmFlagLimit.hpp"
77 #include "runtime/globals.hpp"
78 #include "runtime/handles.inline.hpp"
79 #include "runtime/interfaceSupport.inline.hpp"
80 #include "runtime/java.hpp"
81 #include "runtime/javaCalls.hpp"
82 #include "runtime/javaThread.inline.hpp"
83 #include "runtime/jniHandles.inline.hpp"
84 #include "runtime/jniPeriodicChecker.hpp"
85 #include "runtime/lockStack.inline.hpp"
86 #include "runtime/monitorDeflationThread.hpp"
87 #include "runtime/mutexLocker.hpp"
88 #include "runtime/nonJavaThread.hpp"
89 #include "runtime/objectMonitor.inline.hpp"
310 // enable the startup code to use lambda and other language features in this
311 // phase and onward.
312 //
313 // After phase 2, The VM will begin search classes from -Xbootclasspath/a.
314 static void call_initPhase2(TRAPS) {
315 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
316
317 Klass* klass = vmClasses::System_klass();
318
319 JavaValue result(T_INT);
320 JavaCallArguments args;
321 args.push_int(DisplayVMOutputToStderr);
322 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
323 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
324 vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
325 if (result.get_jint() != JNI_OK) {
326 vm_exit_during_initialization(); // no message or exception
327 }
328
329 universe_post_module_init();
330
331 // Preload all boot classes outside of java.base module
332 ClassPreloader::runtime_preload(THREAD, Handle());
333 if (CDSConfig::is_using_full_module_graph()) {
334 // SystemDictionary::java_{platform,system}_loader are already assigned. We can spin
335 // this up a little quicker.
336 assert(SystemDictionary::java_platform_loader() != nullptr, "must be");
337 assert(SystemDictionary::java_system_loader() != nullptr, "must be");
338 ClassPreloader::runtime_preload(THREAD, Handle(THREAD, SystemDictionary::java_platform_loader()));
339 ClassPreloader::runtime_preload(THREAD, Handle(THREAD, SystemDictionary::java_system_loader()));
340 }
341 }
342
343 // Phase 3. final setup - set security manager, system class loader and TCCL
344 //
345 // This will instantiate and set the security manager, set the system class
346 // loader as well as the thread context class loader. The security manager
347 // and system class loader may be a custom class loaded from -Xbootclasspath/a,
348 // other modules or the application's classpath.
349 static void call_initPhase3(TRAPS) {
350 Klass* klass = vmClasses::System_klass();
351 JavaValue result(T_VOID);
352 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
353 vmSymbols::void_method_signature(), CHECK);
354 }
355
356 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
357 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
358
359 initialize_class(vmSymbols::java_lang_String(), CHECK);
360
361 // Inject CompactStrings value after the static initializers for String ran.
362 java_lang_String::set_compact_strings(CompactStrings);
363
364 // Initialize java_lang.System (needed before creating the thread)
365 initialize_class(vmSymbols::java_lang_System(), CHECK);
366 // The VM creates & returns objects of this class. Make sure it's initialized.
367 initialize_class(vmSymbols::java_lang_Class(), CHECK);
368 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
369 Handle thread_group = create_initial_thread_group(CHECK);
370 Universe::set_main_thread_group(thread_group());
371 initialize_class(vmSymbols::java_lang_Thread(), CHECK);
372 create_initial_thread(thread_group, main_thread, CHECK);
373
374 HeapShared::init_box_classes(CHECK);
375
376 // The VM creates objects of this class.
377 initialize_class(vmSymbols::java_lang_Module(), CHECK);
378
379 #ifdef ASSERT
380 InstanceKlass *k = vmClasses::UnsafeConstants_klass();
381 assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
382 #endif
383
384 // initialize the hardware-specific constants needed by Unsafe
385 initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
386 jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
387
388 // The VM preresolves methods to these classes. Make sure that they get initialized
389 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
390 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
391
392 // Phase 1 of the system initialization in the library, java.lang.System class initialization
393 call_initPhase1(CHECK);
394
395 // Get the Java runtime name, version, and vendor info after java.lang.System is initialized.
404 JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name()));
405
406 JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
407
408 JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
409
410 JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
411 }
412
413 // an instance of OutOfMemory exception has been allocated earlier
414 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
415 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
416 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
417 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
418 initialize_class(vmSymbols::java_lang_ArithmeticException(), 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 }
423
424 bool Threads::initialize_compilation(TRAPS) {
425 // initialize compiler(s)
426 bool force_JVMCI_initialization = false;
427
428 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
429 bool init_compilation = true;
430 #if INCLUDE_JVMCI
431 if (EnableJVMCI) {
432 // Initialize JVMCI eagerly when it is explicitly requested.
433 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
434 force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
435 if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
436 // Force initialization of jarjvmci otherwise requests for blocking
437 // compilations will not actually block until jarjvmci is initialized.
438 force_JVMCI_initialization = true;
439 }
440 if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
441 // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
442 // so compilation should be disabled. This prevents dumping or
443 // printing from happening more than once.
444 init_compilation = false;
445 }
446 }
447 #endif
448 if (init_compilation) {
449 CompileBroker::compilation_init(CHECK_false);
450 }
451 #endif
452
453 return force_JVMCI_initialization;
454 }
455
456 void Threads::initialize_jsr292_core_classes(TRAPS) {
457 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
458
459 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
460 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
461 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
462 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
463
464 if (UseSharedSpaces) {
465 HeapShared::initialize_java_lang_invoke(CHECK);
466 }
467 }
468
469 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
470 extern void JDK_Version_init();
471
472 // Preinitialize version info.
473 VM_Version::early_initialize();
474
475 // Check version
476 if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
477
478 // Initialize library-based TLS
479 ThreadLocalStorage::init();
480
481 // Initialize the output stream module
482 ostream_init();
483
484 // Process java launcher properties.
485 Arguments::process_sun_java_launcher_properties(args);
486
572 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
573 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
574 } else {
575 JavaThread::_jvmci_old_thread_counters = nullptr;
576 }
577 #endif // INCLUDE_JVMCI
578
579 // Initialize OopStorage for threadObj
580 JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
581
582 // Attach the main thread to this os thread
583 JavaThread* main_thread = new JavaThread();
584 main_thread->set_thread_state(_thread_in_vm);
585 main_thread->initialize_thread_current();
586 // must do this before set_active_handles
587 main_thread->record_stack_base_and_size();
588 main_thread->register_thread_stack_with_NMT();
589 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
590 MACOS_AARCH64_ONLY(main_thread->init_wx());
591
592 MutexLockerImpl::init_counters(); // depends on mutex_init(), perfMemory_init(), and Thread::initialize_thread_current().
593
594 if (!main_thread->set_as_starting_thread()) {
595 vm_shutdown_during_initialization(
596 "Failed necessary internal allocation. Out of swap space");
597 main_thread->smr_delete();
598 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
599 return JNI_ENOMEM;
600 }
601
602 // Enable guard page *after* os::create_main_thread(), otherwise it would
603 // crash Linux VM, see notes in os_linux.cpp.
604 main_thread->stack_overflow_state()->create_stack_guard_pages();
605
606 // Initialize Java-Level synchronization subsystem
607 ObjectMonitor::Initialize();
608 ObjectSynchronizer::initialize();
609
610 Deoptimization::init_counters();
611 VMThread::init_counters();
612
613 // Initialize global modules
614 jint status = init_globals();
615 if (status != JNI_OK) {
616 main_thread->smr_delete();
617 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
618 return status;
619 }
620 if (xtty != nullptr)
621 xtty->elem("vm_main_thread thread='" UINTX_FORMAT "'",
622 (uintx) main_thread->osthread()->thread_id());
623
624 // Create WatcherThread as soon as we can since we need it in case
625 // of hangs during error reporting.
626 WatcherThread::start();
627
628 // Add main_thread to threads list to finish barrier setup with
629 // on_thread_attach. Should be before starting to build Java objects in
630 // init_globals2, which invokes barriers.
631 {
632 MutexLocker mu(Threads_lock);
633 Threads::add(main_thread);
634 }
635
636 status = init_globals2();
637 if (status != JNI_OK) {
638 Threads::remove(main_thread, false);
639 // It is possible that we managed to fully initialize Universe but have then
640 // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
641 // will want to report it, so we can't delete the main thread.
642 if (!main_thread->has_pending_exception()) {
740 if (StartAttachListener || AttachListener::init_at_startup()) {
741 AttachListener::init();
742 }
743 }
744
745 // Launch -Xrun agents if EagerXrunInit is not set.
746 if (!EagerXrunInit) {
747 JvmtiAgentList::load_xrun_agents();
748 }
749
750 Arena::start_chunk_pool_cleaner_task();
751
752 // Start the service thread
753 // The service thread enqueues JVMTI deferred events and does various hashtable
754 // and other cleanups. Needs to start before the compilers start posting events.
755 ServiceThread::initialize();
756
757 // Start the monitor deflation thread:
758 MonitorDeflationThread::initialize();
759
760 // Start the method sampler
761 MethodProfiler::initialize();
762
763 bool force_JVMCI_initialization = initialize_compilation(CHECK_JNI_ERR);
764
765 ClassPreloader::init_javabase_preloaded_classes(CHECK_JNI_ERR);
766
767 // Start string deduplication thread if requested.
768 if (StringDedup::is_enabled()) {
769 StringDedup::start();
770 }
771
772 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
773 // It is done after compilers are initialized, because otherwise compilations of
774 // signature polymorphic MH intrinsics can be missed
775 // (see SystemDictionary::find_method_handle_intrinsic).
776 initialize_jsr292_core_classes(CHECK_JNI_ERR);
777
778 // This will initialize the module system. Only java.base classes can be
779 // loaded until phase 2 completes
780 call_initPhase2(CHECK_JNI_ERR);
781
782 JFR_ONLY(Jfr::on_create_vm_2();)
783
784 // Always call even when there are not JVMTI environments yet, since environments
785 // may be attached late and JVMTI must track phases of VM execution
786 JvmtiExport::enter_start_phase();
787
788 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
789 JvmtiExport::post_vm_start();
790
791 // Final system initialization including security manager and system class loader
792 call_initPhase3(CHECK_JNI_ERR);
793
794 // cache the system and platform class loaders
795 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
796
797 // Initiate replay training processing once preloading is over.
798 CompileBroker::init_training_replay();
799
800 ClassPreloader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
801
802 if (Continuations::enabled()) {
803 // Initialize Continuation class now so that failure to create enterSpecial/doYield
804 // special nmethods due to limited CodeCache size can be treated as a fatal error at
805 // startup with the proper message that CodeCache size is too small.
806 initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
807 }
808
809 #if INCLUDE_CDS
810 // capture the module path info from the ModuleEntryTable
811 ClassLoader::initialize_module_path(THREAD);
812 if (HAS_PENDING_EXCEPTION) {
813 java_lang_Throwable::print(PENDING_EXCEPTION, tty);
814 vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly");
815 }
816 #endif
817
818 #if INCLUDE_JVMCI
819 if (force_JVMCI_initialization) {
820 JVMCI::initialize_compiler(CHECK_JNI_ERR);
821 }
822 #endif
823
824 if (PrecompileCode) {
825 Precompiler::compile_cached_code(CHECK_JNI_ERR);
826 if (PrecompileOnlyAndExit) {
827 SCCache::close();
828 log_vm_init_stats(true /* use_tty */);
829 vm_direct_exit(0, "Code precompiation is over");
830 }
831 }
832
833 #if defined(COMPILER2)
834 // Pre-load cached compiled methods
835 SCCache::preload_code(CHECK_JNI_ERR);
836 #endif
837
838 if (NativeHeapTrimmer::enabled()) {
839 NativeHeapTrimmer::initialize();
840 }
841
842 // Always call even when there are not JVMTI environments yet, since environments
843 // may be attached late and JVMTI must track phases of VM execution
844 JvmtiExport::enter_live_phase();
845
846 // Make perfmemory accessible
847 PerfMemory::set_accessible(true);
848
849 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
850 JvmtiExport::post_vm_initialized();
851
852 JFR_ONLY(Jfr::on_create_vm_3();)
853
854 #if INCLUDE_MANAGEMENT
855 Management::initialize(THREAD);
856
857 if (HAS_PENDING_EXCEPTION) {
866 if (CheckJNICalls) JniPeriodicChecker::engage();
867
868 call_postVMInitHook(THREAD);
869 // The Java side of PostVMInitHook.run must deal with all
870 // exceptions and provide means of diagnosis.
871 if (HAS_PENDING_EXCEPTION) {
872 CLEAR_PENDING_EXCEPTION;
873 }
874
875 // Let WatcherThread run all registered periodic tasks now.
876 // NOTE: All PeriodicTasks should be registered by now. If they
877 // aren't, late joiners might appear to start slowly (we might
878 // take a while to process their first tick).
879 WatcherThread::run_all_tasks();
880
881 create_vm_timer.end();
882 #ifdef ASSERT
883 _vm_complete = true;
884 #endif
885
886 if (CDSConfig::is_dumping_classic_static_archive()) {
887 // Classic -Xshare:dump, aka "old workflow"
888 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
889 } else if (CDSConfig::is_dumping_final_static_archive()) {
890 // TODO: copy the verification and loader constraints from preimage to final image
891 // TODO: load archived classes for custom loaders as well.
892 log_info(cds)("Dumping final image of CacheDataStore %s", CacheDataStore);
893 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
894 vm_direct_exit(0, "CacheDataStore dumping is complete");
895 }
896
897 log_info(init)("At VM initialization completion:");
898 log_vm_init_stats(false /* use_tty */);
899
900 if (UsePerfData) {
901 if (ProfileVMLocks) {
902 main_thread->set_profile_vm_locks(true);
903 }
904 if (ProfileVMCalls) {
905 main_thread->set_profile_vm_calls(true);
906 }
907 if (ProfileRuntimeCalls) {
908 main_thread->set_profile_rt_calls(true);
909 }
910 if (ProfileVMOps) {
911 main_thread->set_profile_vm_ops(true);
912 }
913 }
914
915 return JNI_OK;
916 }
917
918 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
919 // the program falls off the end of main(). Another VM exit path is through
920 // vm_exit(), when the program calls System.exit() to return a value, or when
921 // there is a serious error in VM.
922 // These two separate shutdown paths are not exactly the same, but they share
923 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
924 //
925 // Shutdown sequence:
926 // + Shutdown native memory tracking if it is on
927 // + Wait until we are the last non-daemon thread to execute
928 // <-- every thing is still working at this moment -->
929 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
930 // shutdown hooks
931 // + Call before_exit(), prepare for VM exit
932 // > run VM level shutdown hooks (they are registered through JVM_OnExit(),
|