< prev index next >

src/hotspot/share/runtime/threads.cpp

Print this page

  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/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

 531     JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
 532     memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
 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   // must do this before set_active_handles
 546   main_thread->record_stack_base_and_size();
 547   main_thread->register_thread_stack_with_NMT();
 548   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
 549   MACOS_AARCH64_ONLY(main_thread->init_wx());
 550 


 551   // Set the lock_id now since we will run Java code before the Thread instance
 552   // is even created. The same value will be assigned to the Thread instance on init.
 553   main_thread->set_lock_id(ThreadIdentifier::next());
 554 
 555   if (!Thread::set_as_starting_thread(main_thread)) {
 556     vm_shutdown_during_initialization(
 557                                       "Failed necessary internal allocation. Out of swap space");
 558     main_thread->smr_delete();
 559     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 560     return JNI_ENOMEM;
 561   }
 562 
 563   JFR_ONLY(Jfr::initialize_main_thread(main_thread);)
 564 
 565   // Enable guard page *after* os::create_main_thread(), otherwise it would
 566   // crash Linux VM, see notes in os_linux.cpp.
 567   main_thread->stack_overflow_state()->create_stack_guard_pages();
 568 
 569   // Initialize Java-Level synchronization subsystem
 570   ObjectMonitor::Initialize();
 571   ObjectSynchronizer::initialize();
 572 



 573   // Initialize global modules
 574   jint status = init_globals();
 575   if (status != JNI_OK) {
 576     main_thread->smr_delete();
 577     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 578     return status;
 579   }



 580 
 581   // Create WatcherThread as soon as we can since we need it in case
 582   // of hangs during error reporting.
 583   WatcherThread::start();
 584 
 585   // Add main_thread to threads list to finish barrier setup with
 586   // on_thread_attach.  Should be before starting to build Java objects in
 587   // init_globals2, which invokes barriers.
 588   {
 589     MutexLocker mu(Threads_lock);
 590     Threads::add(main_thread);
 591   }
 592 
 593   status = init_globals2();
 594   if (status != JNI_OK) {
 595     Threads::remove(main_thread, false);
 596     // It is possible that we managed to fully initialize Universe but have then
 597     // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
 598     // will want to report it, so we can't delete the main thread.
 599     if (!main_thread->has_pending_exception()) {

 704     if (StartAttachListener || AttachListener::init_at_startup()) {
 705       AttachListener::init();
 706     }
 707   }
 708 
 709   // Launch -Xrun agents if EagerXrunInit is not set.
 710   if (!EagerXrunInit) {
 711     JvmtiAgentList::load_xrun_agents();
 712   }
 713 
 714   Arena::start_chunk_pool_cleaner_task();
 715 
 716   // Start the service thread
 717   // The service thread enqueues JVMTI deferred events and does various hashtable
 718   // and other cleanups.  Needs to start before the compilers start posting events.
 719   ServiceThread::initialize();
 720 
 721   // Start the monitor deflation thread:
 722   MonitorDeflationThread::initialize();
 723 
 724   // initialize compiler(s)
 725 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
 726   bool init_compilation = true;
 727 #if INCLUDE_JVMCI
 728   bool force_JVMCI_initialization = false;
 729   if (EnableJVMCI) {
 730     // Initialize JVMCI eagerly when it is explicitly requested.
 731     // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
 732     force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
 733     if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
 734       // Force initialization of jarjvmci otherwise requests for blocking
 735       // compilations will not actually block until jarjvmci is initialized.
 736       force_JVMCI_initialization = true;
 737     }
 738     if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
 739       // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
 740       // so compilation should be disabled. This prevents dumping or
 741       // printing from happening more than once.
 742       init_compilation = false;
 743     }
 744   }
 745 #endif
 746   if (init_compilation) {
 747     CompileBroker::compilation_init(CHECK_JNI_ERR);
 748   }
 749 #endif
 750 


 751   if (CDSConfig::is_using_aot_linked_classes()) {
 752     AOTLinkedClassBulkLoader::finish_loading_javabase_classes(CHECK_JNI_ERR);
 753     SystemDictionary::restore_archived_method_handle_intrinsics();
 754   }
 755 
 756   // Start string deduplication thread if requested.
 757   if (StringDedup::is_enabled()) {
 758     StringDedup::start();
 759   }
 760 
 761   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 762   // It is done after compilers are initialized, because otherwise compilations of
 763   // signature polymorphic MH intrinsics can be missed
 764   // (see SystemDictionary::find_method_handle_intrinsic).
 765   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 766 
 767   // This will initialize the module system.  Only java.base classes can be
 768   // loaded until phase 2 completes
 769   call_initPhase2(CHECK_JNI_ERR);
 770 
 771   if (CDSConfig::is_using_aot_linked_classes()) {
 772     AOTLinkedClassBulkLoader::load_non_javabase_classes(THREAD);
 773   }
 774 #ifndef PRODUCT
 775   HeapShared::initialize_test_class_from_archive(THREAD);
 776 #endif
 777 
 778   JFR_ONLY(Jfr::on_create_vm_2();)
 779 
 780   // Always call even when there are not JVMTI environments yet, since environments
 781   // may be attached late and JVMTI must track phases of VM execution
 782   JvmtiExport::enter_start_phase();
 783 
 784   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
 785   JvmtiExport::post_vm_start();
 786 
 787   // Final system initialization including security manager and system class loader
 788   call_initPhase3(CHECK_JNI_ERR);
 789 
 790   // cache the system and platform class loaders
 791   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
 792 





 793   if (Continuations::enabled()) {
 794     // Initialize Continuation class now so that failure to create enterSpecial/doYield
 795     // special nmethods due to limited CodeCache size can be treated as a fatal error at
 796     // startup with the proper message that CodeCache size is too small.
 797     initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
 798   }
 799 
 800 #if INCLUDE_CDS
 801   // capture the module path info from the ModuleEntryTable
 802   ClassLoader::initialize_module_path(THREAD);
 803   if (HAS_PENDING_EXCEPTION) {
 804     java_lang_Throwable::print(PENDING_EXCEPTION, tty);
 805     vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly");
 806   }
 807 #endif
 808 
 809 #if INCLUDE_JVMCI
 810   if (force_JVMCI_initialization) {
 811     JVMCI::initialize_compiler(CHECK_JNI_ERR);
 812   }
 813 #endif
 814 














 815   if (NativeHeapTrimmer::enabled()) {
 816     NativeHeapTrimmer::initialize();
 817   }
 818 
 819   // Always call even when there are not JVMTI environments yet, since environments
 820   // may be attached late and JVMTI must track phases of VM execution
 821   JvmtiExport::enter_live_phase();
 822 
 823   // Make perfmemory accessible
 824   PerfMemory::set_accessible(true);
 825 
 826   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
 827   JvmtiExport::post_vm_initialized();
 828 
 829   JFR_ONLY(Jfr::on_create_vm_3();)
 830 
 831 #if INCLUDE_MANAGEMENT
 832   Management::initialize(THREAD);
 833 
 834   if (HAS_PENDING_EXCEPTION) {

 843   if (CheckJNICalls)                  JniPeriodicChecker::engage();
 844 
 845   call_postVMInitHook(THREAD);
 846   // The Java side of PostVMInitHook.run must deal with all
 847   // exceptions and provide means of diagnosis.
 848   if (HAS_PENDING_EXCEPTION) {
 849     CLEAR_PENDING_EXCEPTION;
 850   }
 851 
 852   // Let WatcherThread run all registered periodic tasks now.
 853   // NOTE:  All PeriodicTasks should be registered by now. If they
 854   //   aren't, late joiners might appear to start slowly (we might
 855   //   take a while to process their first tick).
 856   WatcherThread::run_all_tasks();
 857 
 858   create_vm_timer.end();
 859 #ifdef ASSERT
 860   _vm_complete = true;
 861 #endif
 862 
 863   if (CDSConfig::is_dumping_static_archive()) {






 864     MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);

 865   }
 866 
 867   if (log_is_enabled(Info, perf, class, link)) {
 868     LogStreamHandle(Info, perf, class, link) log;
 869     log.print_cr("At VM initialization completion:");
 870     ClassLoader::print_counters(&log);












 871   }
 872 
 873   return JNI_OK;
 874 }
 875 
 876 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
 877 // the program falls off the end of main(). Another VM exit path is through
 878 // vm_exit(), when the program calls System.exit() to return a value, or when
 879 // there is a serious error in VM.
 880 // These two separate shutdown paths are not exactly the same, but they share
 881 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
 882 //
 883 // Shutdown sequence:
 884 //   + Shutdown native memory tracking if it is on
 885 //   + Wait until we are the last non-daemon thread to execute
 886 //     <-- every thing is still working at this moment -->
 887 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
 888 //        shutdown hooks
 889 //   + Call before_exit(), prepare for VM exit
 890 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),

  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/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

 597     JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
 598     memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
 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   // must do this before set_active_handles
 612   main_thread->record_stack_base_and_size();
 613   main_thread->register_thread_stack_with_NMT();
 614   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
 615   MACOS_AARCH64_ONLY(main_thread->init_wx());
 616 
 617   MutexLockerImpl::init_counters(); // depends on mutex_init(), perfMemory_init(), and Thread::initialize_thread_current().
 618 
 619   // Set the lock_id now since we will run Java code before the Thread instance
 620   // is even created. The same value will be assigned to the Thread instance on init.
 621   main_thread->set_lock_id(ThreadIdentifier::next());
 622 
 623   if (!Thread::set_as_starting_thread(main_thread)) {
 624     vm_shutdown_during_initialization(
 625                                       "Failed necessary internal allocation. Out of swap space");
 626     main_thread->smr_delete();
 627     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 628     return JNI_ENOMEM;
 629   }
 630 
 631   JFR_ONLY(Jfr::initialize_main_thread(main_thread);)
 632 
 633   // Enable guard page *after* os::create_main_thread(), otherwise it would
 634   // crash Linux VM, see notes in os_linux.cpp.
 635   main_thread->stack_overflow_state()->create_stack_guard_pages();
 636 
 637   // Initialize Java-Level synchronization subsystem
 638   ObjectMonitor::Initialize();
 639   ObjectSynchronizer::initialize();
 640 
 641   Deoptimization::init_counters();
 642   VMThread::init_counters();
 643 
 644   // Initialize global modules
 645   jint status = init_globals();
 646   if (status != JNI_OK) {
 647     main_thread->smr_delete();
 648     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 649     return status;
 650   }
 651   if (xtty != nullptr)
 652     xtty->elem("vm_main_thread thread='" UINTX_FORMAT "'",
 653                (uintx) main_thread->osthread()->thread_id());
 654 
 655   // Create WatcherThread as soon as we can since we need it in case
 656   // of hangs during error reporting.
 657   WatcherThread::start();
 658 
 659   // Add main_thread to threads list to finish barrier setup with
 660   // on_thread_attach.  Should be before starting to build Java objects in
 661   // init_globals2, which invokes barriers.
 662   {
 663     MutexLocker mu(Threads_lock);
 664     Threads::add(main_thread);
 665   }
 666 
 667   status = init_globals2();
 668   if (status != JNI_OK) {
 669     Threads::remove(main_thread, false);
 670     // It is possible that we managed to fully initialize Universe but have then
 671     // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
 672     // will want to report it, so we can't delete the main thread.
 673     if (!main_thread->has_pending_exception()) {

 778     if (StartAttachListener || AttachListener::init_at_startup()) {
 779       AttachListener::init();
 780     }
 781   }
 782 
 783   // Launch -Xrun agents if EagerXrunInit is not set.
 784   if (!EagerXrunInit) {
 785     JvmtiAgentList::load_xrun_agents();
 786   }
 787 
 788   Arena::start_chunk_pool_cleaner_task();
 789 
 790   // Start the service thread
 791   // The service thread enqueues JVMTI deferred events and does various hashtable
 792   // and other cleanups.  Needs to start before the compilers start posting events.
 793   ServiceThread::initialize();
 794 
 795   // Start the monitor deflation thread:
 796   MonitorDeflationThread::initialize();
 797 
 798 #if INCLUDE_CDS
 799   // Start the method sampler
 800   MethodProfiler::initialize();






















 801 #endif
 802 
 803   bool force_JVMCI_initialization = initialize_compilation(CHECK_JNI_ERR);
 804 
 805   if (CDSConfig::is_using_aot_linked_classes()) {
 806     AOTLinkedClassBulkLoader::finish_loading_javabase_classes(CHECK_JNI_ERR);
 807     SystemDictionary::restore_archived_method_handle_intrinsics();
 808   }
 809 
 810   // Start string deduplication thread if requested.
 811   if (StringDedup::is_enabled()) {
 812     StringDedup::start();
 813   }
 814 
 815   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 816   // It is done after compilers are initialized, because otherwise compilations of
 817   // signature polymorphic MH intrinsics can be missed
 818   // (see SystemDictionary::find_method_handle_intrinsic).
 819   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 820 
 821   // This will initialize the module system.  Only java.base classes can be
 822   // loaded until phase 2 completes
 823   call_initPhase2(CHECK_JNI_ERR);
 824 
 825   if (CDSConfig::is_using_aot_linked_classes() && !CDSConfig::is_dumping_final_static_archive()) {
 826     AOTLinkedClassBulkLoader::load_non_javabase_classes(THREAD);
 827   }
 828 #ifndef PRODUCT
 829   HeapShared::initialize_test_class_from_archive(THREAD);
 830 #endif
 831 
 832   JFR_ONLY(Jfr::on_create_vm_2();)
 833 
 834   // Always call even when there are not JVMTI environments yet, since environments
 835   // may be attached late and JVMTI must track phases of VM execution
 836   JvmtiExport::enter_start_phase();
 837 
 838   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
 839   JvmtiExport::post_vm_start();
 840 
 841   // Final system initialization including security manager and system class loader
 842   call_initPhase3(CHECK_JNI_ERR);
 843 
 844   // cache the system and platform class loaders
 845   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
 846 
 847   // Initiate replay training processing once preloading is over.
 848   CompileBroker::init_training_replay();
 849 
 850   AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
 851 
 852   if (Continuations::enabled()) {
 853     // Initialize Continuation class now so that failure to create enterSpecial/doYield
 854     // special nmethods due to limited CodeCache size can be treated as a fatal error at
 855     // startup with the proper message that CodeCache size is too small.
 856     initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
 857   }
 858 
 859 #if INCLUDE_CDS
 860   // capture the module path info from the ModuleEntryTable
 861   ClassLoader::initialize_module_path(THREAD);
 862   if (HAS_PENDING_EXCEPTION) {
 863     java_lang_Throwable::print(PENDING_EXCEPTION, tty);
 864     vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly");
 865   }
 866 #endif
 867 
 868 #if INCLUDE_JVMCI
 869   if (force_JVMCI_initialization) {
 870     JVMCI::initialize_compiler(CHECK_JNI_ERR);
 871   }
 872 #endif
 873 
 874   if (PrecompileCode) {
 875     Precompiler::compile_cached_code(CHECK_JNI_ERR);
 876     if (PrecompileOnlyAndExit) {
 877       SCCache::close();
 878       log_vm_init_stats();
 879       vm_direct_exit(0, "Code precompiation is over");
 880     }
 881   }
 882 
 883 #if defined(COMPILER2)
 884   // Pre-load cached compiled methods
 885   SCCache::preload_code(CHECK_JNI_ERR);
 886 #endif
 887 
 888   if (NativeHeapTrimmer::enabled()) {
 889     NativeHeapTrimmer::initialize();
 890   }
 891 
 892   // Always call even when there are not JVMTI environments yet, since environments
 893   // may be attached late and JVMTI must track phases of VM execution
 894   JvmtiExport::enter_live_phase();
 895 
 896   // Make perfmemory accessible
 897   PerfMemory::set_accessible(true);
 898 
 899   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
 900   JvmtiExport::post_vm_initialized();
 901 
 902   JFR_ONLY(Jfr::on_create_vm_3();)
 903 
 904 #if INCLUDE_MANAGEMENT
 905   Management::initialize(THREAD);
 906 
 907   if (HAS_PENDING_EXCEPTION) {

 916   if (CheckJNICalls)                  JniPeriodicChecker::engage();
 917 
 918   call_postVMInitHook(THREAD);
 919   // The Java side of PostVMInitHook.run must deal with all
 920   // exceptions and provide means of diagnosis.
 921   if (HAS_PENDING_EXCEPTION) {
 922     CLEAR_PENDING_EXCEPTION;
 923   }
 924 
 925   // Let WatcherThread run all registered periodic tasks now.
 926   // NOTE:  All PeriodicTasks should be registered by now. If they
 927   //   aren't, late joiners might appear to start slowly (we might
 928   //   take a while to process their first tick).
 929   WatcherThread::run_all_tasks();
 930 
 931   create_vm_timer.end();
 932 #ifdef ASSERT
 933   _vm_complete = true;
 934 #endif
 935 
 936   if (CDSConfig::is_dumping_classic_static_archive()) {
 937     // Classic -Xshare:dump, aka "old workflow"
 938     MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
 939   } else if (CDSConfig::is_dumping_final_static_archive()) {
 940     // TODO: copy the verification and loader constraints from preimage to final image
 941     // TODO: load archived classes for custom loaders as well.
 942     log_info(cds)("Dumping final image of CacheDataStore %s", CacheDataStore);
 943     MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
 944     vm_direct_exit(0, "CacheDataStore dumping is complete");
 945   }
 946 
 947   log_info(init)("At VM initialization completion:");
 948   log_vm_init_stats();
 949 
 950   if (UsePerfData) {
 951     if (ProfileVMLocks) {
 952       main_thread->set_profile_vm_locks(true);
 953     }
 954     if (ProfileVMCalls) {
 955       main_thread->set_profile_vm_calls(true);
 956     }
 957     if (ProfileRuntimeCalls) {
 958       main_thread->set_profile_rt_calls(true);
 959     }
 960     if (ProfileVMOps) {
 961       main_thread->set_profile_vm_ops(true);
 962     }
 963   }
 964 
 965   return JNI_OK;
 966 }
 967 
 968 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
 969 // the program falls off the end of main(). Another VM exit path is through
 970 // vm_exit(), when the program calls System.exit() to return a value, or when
 971 // there is a serious error in VM.
 972 // These two separate shutdown paths are not exactly the same, but they share
 973 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
 974 //
 975 // Shutdown sequence:
 976 //   + Shutdown native memory tracking if it is on
 977 //   + Wait until we are the last non-daemon thread to execute
 978 //     <-- every thing is still working at this moment -->
 979 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
 980 //        shutdown hooks
 981 //   + Call before_exit(), prepare for VM exit
 982 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),
< prev index next >