< prev index next >

src/hotspot/share/runtime/threads.cpp

Print this page

   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"

 303 //     enable the startup code to use lambda and other language features in this
 304 //     phase and onward.
 305 //
 306 //     After phase 2, The VM will begin search classes from -Xbootclasspath/a.
 307 static void call_initPhase2(TRAPS) {
 308   TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
 309 
 310   Klass* klass = vmClasses::System_klass();
 311 
 312   JavaValue result(T_INT);
 313   JavaCallArguments args;
 314   args.push_int(DisplayVMOutputToStderr);
 315   args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
 316   JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
 317                                          vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
 318   if (result.get_jint() != JNI_OK) {
 319     vm_exit_during_initialization(); // no message or exception
 320   }
 321 
 322   universe_post_module_init();











 323 }
 324 
 325 // Phase 3. final setup - set security manager, system class loader and TCCL
 326 //
 327 //     This will instantiate and set the security manager, set the system class
 328 //     loader as well as the thread context class loader.  The security manager
 329 //     and system class loader may be a custom class loaded from -Xbootclasspath/a,
 330 //     other modules or the application's classpath.
 331 static void call_initPhase3(TRAPS) {
 332   Klass* klass = vmClasses::System_klass();
 333   JavaValue result(T_VOID);
 334   JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
 335                                          vmSymbols::void_method_signature(), CHECK);
 336 }
 337 
 338 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
 339   TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
 340 
 341   initialize_class(vmSymbols::java_lang_String(), CHECK);
 342 
 343   // Inject CompactStrings value after the static initializers for String ran.
 344   java_lang_String::set_compact_strings(CompactStrings);
 345 
 346   // Initialize java_lang.System (needed before creating the thread)
 347   initialize_class(vmSymbols::java_lang_System(), CHECK);
 348   // The VM creates & returns objects of this class. Make sure it's initialized.
 349   initialize_class(vmSymbols::java_lang_Class(), CHECK);
 350   initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
 351   Handle thread_group = create_initial_thread_group(CHECK);
 352   Universe::set_main_thread_group(thread_group());
 353   initialize_class(vmSymbols::java_lang_Thread(), CHECK);
 354   create_initial_thread(thread_group, main_thread, CHECK);
 355 


 356   // The VM creates objects of this class.
 357   initialize_class(vmSymbols::java_lang_Module(), CHECK);
 358 
 359 #ifdef ASSERT
 360   InstanceKlass *k = vmClasses::UnsafeConstants_klass();
 361   assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
 362 #endif
 363 
 364   // initialize the hardware-specific constants needed by Unsafe
 365   initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
 366   jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
 367 
 368   // The VM preresolves methods to these classes. Make sure that they get initialized
 369   initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
 370   initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
 371 
 372   // Phase 1 of the system initialization in the library, java.lang.System class initialization
 373   call_initPhase1(CHECK);
 374 
 375   // Get the Java runtime name, version, and vendor info after java.lang.System is initialized.

 384     JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name()));
 385 
 386     JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
 387 
 388     JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
 389 
 390     JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
 391   }
 392 
 393   // an instance of OutOfMemory exception has been allocated earlier
 394   initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
 395   initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
 396   initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
 397   initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
 398   initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
 399   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
 400   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
 401   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
 402 }
 403 
































 404 void Threads::initialize_jsr292_core_classes(TRAPS) {
 405   TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
 406 
 407   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
 408   initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
 409   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
 410   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);




 411 }
 412 
 413 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
 414   extern void JDK_Version_init();
 415 
 416   // Preinitialize version info.
 417   VM_Version::early_initialize();
 418 
 419   // Check version
 420   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
 421 
 422   // Initialize library-based TLS
 423   ThreadLocalStorage::init();
 424 
 425   // Initialize the output stream module
 426   ostream_init();
 427 
 428   // Process java launcher properties.
 429   Arguments::process_sun_java_launcher_properties(args);
 430 

 516     JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
 517     memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
 518   } else {
 519     JavaThread::_jvmci_old_thread_counters = nullptr;
 520   }
 521 #endif // INCLUDE_JVMCI
 522 
 523   // Initialize OopStorage for threadObj
 524   JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
 525 
 526   // Attach the main thread to this os thread
 527   JavaThread* main_thread = new JavaThread();
 528   main_thread->set_thread_state(_thread_in_vm);
 529   main_thread->initialize_thread_current();
 530   // must do this before set_active_handles
 531   main_thread->record_stack_base_and_size();
 532   main_thread->register_thread_stack_with_NMT();
 533   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
 534   MACOS_AARCH64_ONLY(main_thread->init_wx());
 535 


 536   if (!main_thread->set_as_starting_thread()) {
 537     vm_shutdown_during_initialization(
 538                                       "Failed necessary internal allocation. Out of swap space");
 539     main_thread->smr_delete();
 540     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 541     return JNI_ENOMEM;
 542   }
 543 
 544   // Enable guard page *after* os::create_main_thread(), otherwise it would
 545   // crash Linux VM, see notes in os_linux.cpp.
 546   main_thread->stack_overflow_state()->create_stack_guard_pages();
 547 
 548   // Initialize Java-Level synchronization subsystem
 549   ObjectMonitor::Initialize();
 550   ObjectSynchronizer::initialize();
 551 



 552   // Initialize global modules
 553   jint status = init_globals();
 554   if (status != JNI_OK) {
 555     main_thread->smr_delete();
 556     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 557     return status;
 558   }



 559 
 560   // Create WatcherThread as soon as we can since we need it in case
 561   // of hangs during error reporting.
 562   WatcherThread::start();
 563 
 564   // Add main_thread to threads list to finish barrier setup with
 565   // on_thread_attach.  Should be before starting to build Java objects in
 566   // init_globals2, which invokes barriers.
 567   {
 568     MutexLocker mu(Threads_lock);
 569     Threads::add(main_thread);
 570   }
 571 
 572   status = init_globals2();
 573   if (status != JNI_OK) {
 574     Threads::remove(main_thread, false);
 575     // It is possible that we managed to fully initialize Universe but have then
 576     // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
 577     // will want to report it, so we can't delete the main thread.
 578     if (!main_thread->has_pending_exception()) {

 676     if (StartAttachListener || AttachListener::init_at_startup()) {
 677       AttachListener::init();
 678     }
 679   }
 680 
 681   // Launch -Xrun agents if EagerXrunInit is not set.
 682   if (!EagerXrunInit) {
 683     JvmtiAgentList::load_xrun_agents();
 684   }
 685 
 686   Arena::start_chunk_pool_cleaner_task();
 687 
 688   // Start the service thread
 689   // The service thread enqueues JVMTI deferred events and does various hashtable
 690   // and other cleanups.  Needs to start before the compilers start posting events.
 691   ServiceThread::initialize();
 692 
 693   // Start the monitor deflation thread:
 694   MonitorDeflationThread::initialize();
 695 
 696   // initialize compiler(s)
 697 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
 698   bool init_compilation = true;
 699 #if INCLUDE_JVMCI
 700   bool force_JVMCI_initialization = false;
 701   if (EnableJVMCI) {
 702     // Initialize JVMCI eagerly when it is explicitly requested.
 703     // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
 704     force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
 705     if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
 706       // Force initialization of jarjvmci otherwise requests for blocking
 707       // compilations will not actually block until jarjvmci is initialized.
 708       force_JVMCI_initialization = true;
 709     }
 710     if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
 711       // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
 712       // so compilation should be disabled. This prevents dumping or
 713       // printing from happening more than once.
 714       init_compilation = false;
 715     }
 716   }
 717 #endif
 718   if (init_compilation) {
 719     CompileBroker::compilation_init(CHECK_JNI_ERR);
 720   }
 721 #endif
 722 
 723   // Start string deduplication thread if requested.
 724   if (StringDedup::is_enabled()) {
 725     StringDedup::start();
 726   }
 727 
 728   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 729   // It is done after compilers are initialized, because otherwise compilations of
 730   // signature polymorphic MH intrinsics can be missed
 731   // (see SystemDictionary::find_method_handle_intrinsic).
 732   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 733 
 734   // This will initialize the module system.  Only java.base classes can be
 735   // loaded until phase 2 completes
 736   call_initPhase2(CHECK_JNI_ERR);
 737 
 738   JFR_ONLY(Jfr::on_create_vm_2();)
 739 
 740   // Always call even when there are not JVMTI environments yet, since environments
 741   // may be attached late and JVMTI must track phases of VM execution
 742   JvmtiExport::enter_start_phase();
 743 
 744   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
 745   JvmtiExport::post_vm_start();
 746 
 747   // Final system initialization including security manager and system class loader
 748   call_initPhase3(CHECK_JNI_ERR);
 749 
 750   // cache the system and platform class loaders
 751   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
 752 





 753   if (Continuations::enabled()) {
 754     // Initialize Continuation class now so that failure to create enterSpecial/doYield
 755     // special nmethods due to limited CodeCache size can be treated as a fatal error at
 756     // startup with the proper message that CodeCache size is too small.
 757     initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
 758   }
 759 
 760 #if INCLUDE_CDS
 761   // capture the module path info from the ModuleEntryTable
 762   ClassLoader::initialize_module_path(THREAD);
 763   if (HAS_PENDING_EXCEPTION) {
 764     java_lang_Throwable::print(PENDING_EXCEPTION, tty);
 765     vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly");
 766   }
 767 #endif
 768 
 769 #if INCLUDE_JVMCI
 770   if (force_JVMCI_initialization) {
 771     JVMCI::initialize_compiler(CHECK_JNI_ERR);
 772   }
 773 #endif
 774 














 775   if (NativeHeapTrimmer::enabled()) {
 776     NativeHeapTrimmer::initialize();
 777   }
 778 
 779   // Always call even when there are not JVMTI environments yet, since environments
 780   // may be attached late and JVMTI must track phases of VM execution
 781   JvmtiExport::enter_live_phase();
 782 
 783   // Make perfmemory accessible
 784   PerfMemory::set_accessible(true);
 785 
 786   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
 787   JvmtiExport::post_vm_initialized();
 788 
 789   JFR_ONLY(Jfr::on_create_vm_3();)
 790 
 791 #if INCLUDE_MANAGEMENT
 792   Management::initialize(THREAD);
 793 
 794   if (HAS_PENDING_EXCEPTION) {

 807 #endif
 808 
 809   call_postVMInitHook(THREAD);
 810   // The Java side of PostVMInitHook.run must deal with all
 811   // exceptions and provide means of diagnosis.
 812   if (HAS_PENDING_EXCEPTION) {
 813     CLEAR_PENDING_EXCEPTION;
 814   }
 815 
 816   // Let WatcherThread run all registered periodic tasks now.
 817   // NOTE:  All PeriodicTasks should be registered by now. If they
 818   //   aren't, late joiners might appear to start slowly (we might
 819   //   take a while to process their first tick).
 820   WatcherThread::run_all_tasks();
 821 
 822   create_vm_timer.end();
 823 #ifdef ASSERT
 824   _vm_complete = true;
 825 #endif
 826 
 827   if (CDSConfig::is_dumping_static_archive()) {






 828     MetaspaceShared::preload_and_dump();



















 829   }
 830 
 831   return JNI_OK;
 832 }
 833 
 834 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
 835 // the program falls off the end of main(). Another VM exit path is through
 836 // vm_exit(), when the program calls System.exit() to return a value, or when
 837 // there is a serious error in VM.
 838 // These two separate shutdown paths are not exactly the same, but they share
 839 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
 840 //
 841 // Shutdown sequence:
 842 //   + Shutdown native memory tracking if it is on
 843 //   + Wait until we are the last non-daemon thread to execute
 844 //     <-- every thing is still working at this moment -->
 845 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
 846 //        shutdown hooks
 847 //   + Call before_exit(), prepare for VM exit
 848 //      > 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"

 313 //     enable the startup code to use lambda and other language features in this
 314 //     phase and onward.
 315 //
 316 //     After phase 2, The VM will begin search classes from -Xbootclasspath/a.
 317 static void call_initPhase2(TRAPS) {
 318   TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
 319 
 320   Klass* klass = vmClasses::System_klass();
 321 
 322   JavaValue result(T_INT);
 323   JavaCallArguments args;
 324   args.push_int(DisplayVMOutputToStderr);
 325   args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
 326   JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
 327                                          vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
 328   if (result.get_jint() != JNI_OK) {
 329     vm_exit_during_initialization(); // no message or exception
 330   }
 331 
 332   universe_post_module_init();
 333 
 334   // Preload all boot classes outside of java.base module
 335   ClassPreloader::runtime_preload(THREAD, Handle());
 336   if (CDSConfig::is_using_full_module_graph()) {
 337     // SystemDictionary::java_{platform,system}_loader are already assigned. We can spin
 338     // this up a little quicker.
 339     assert(SystemDictionary::java_platform_loader() != nullptr, "must be");
 340     assert(SystemDictionary::java_system_loader() != nullptr,   "must be");
 341     ClassPreloader::runtime_preload(THREAD, Handle(THREAD, SystemDictionary::java_platform_loader()));
 342     ClassPreloader::runtime_preload(THREAD, Handle(THREAD, SystemDictionary::java_system_loader()));
 343   }
 344 }
 345 
 346 // Phase 3. final setup - set security manager, system class loader and TCCL
 347 //
 348 //     This will instantiate and set the security manager, set the system class
 349 //     loader as well as the thread context class loader.  The security manager
 350 //     and system class loader may be a custom class loaded from -Xbootclasspath/a,
 351 //     other modules or the application's classpath.
 352 static void call_initPhase3(TRAPS) {
 353   Klass* klass = vmClasses::System_klass();
 354   JavaValue result(T_VOID);
 355   JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
 356                                          vmSymbols::void_method_signature(), CHECK);
 357 }
 358 
 359 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
 360   TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
 361 
 362   initialize_class(vmSymbols::java_lang_String(), CHECK);
 363 
 364   // Inject CompactStrings value after the static initializers for String ran.
 365   java_lang_String::set_compact_strings(CompactStrings);
 366 
 367   // Initialize java_lang.System (needed before creating the thread)
 368   initialize_class(vmSymbols::java_lang_System(), CHECK);
 369   // The VM creates & returns objects of this class. Make sure it's initialized.
 370   initialize_class(vmSymbols::java_lang_Class(), CHECK);
 371   initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
 372   Handle thread_group = create_initial_thread_group(CHECK);
 373   Universe::set_main_thread_group(thread_group());
 374   initialize_class(vmSymbols::java_lang_Thread(), CHECK);
 375   create_initial_thread(thread_group, main_thread, CHECK);
 376 
 377   HeapShared::init_box_classes(CHECK);
 378 
 379   // The VM creates objects of this class.
 380   initialize_class(vmSymbols::java_lang_Module(), CHECK);
 381 
 382 #ifdef ASSERT
 383   InstanceKlass *k = vmClasses::UnsafeConstants_klass();
 384   assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
 385 #endif
 386 
 387   // initialize the hardware-specific constants needed by Unsafe
 388   initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
 389   jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
 390 
 391   // The VM preresolves methods to these classes. Make sure that they get initialized
 392   initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
 393   initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
 394 
 395   // Phase 1 of the system initialization in the library, java.lang.System class initialization
 396   call_initPhase1(CHECK);
 397 
 398   // Get the Java runtime name, version, and vendor info after java.lang.System is initialized.

 407     JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name()));
 408 
 409     JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
 410 
 411     JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
 412 
 413     JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
 414   }
 415 
 416   // an instance of OutOfMemory exception has been allocated earlier
 417   initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
 418   initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
 419   initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
 420   initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
 421   initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
 422   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
 423   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
 424   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
 425 }
 426 
 427 bool Threads::initialize_compilation(TRAPS) {
 428   // initialize compiler(s)
 429   bool force_JVMCI_initialization = false;
 430 
 431 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
 432   bool init_compilation = true;
 433 #if INCLUDE_JVMCI
 434   if (EnableJVMCI) {
 435     // Initialize JVMCI eagerly when it is explicitly requested.
 436     // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
 437     force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
 438     if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
 439       // Force initialization of jarjvmci otherwise requests for blocking
 440       // compilations will not actually block until jarjvmci is initialized.
 441       force_JVMCI_initialization = true;
 442     }
 443     if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
 444       // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
 445       // so compilation should be disabled. This prevents dumping or
 446       // printing from happening more than once.
 447       init_compilation = false;
 448     }
 449   }
 450 #endif
 451   if (init_compilation) {
 452     CompileBroker::compilation_init(CHECK_false);
 453   }
 454 #endif
 455 
 456   return force_JVMCI_initialization;
 457 }
 458 
 459 void Threads::initialize_jsr292_core_classes(TRAPS) {
 460   TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
 461 
 462   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
 463   initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
 464   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
 465   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
 466 
 467   if (UseSharedSpaces) {
 468     HeapShared::initialize_java_lang_invoke(CHECK);
 469   }
 470 }
 471 
 472 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
 473   extern void JDK_Version_init();
 474 
 475   // Preinitialize version info.
 476   VM_Version::early_initialize();
 477 
 478   // Check version
 479   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
 480 
 481   // Initialize library-based TLS
 482   ThreadLocalStorage::init();
 483 
 484   // Initialize the output stream module
 485   ostream_init();
 486 
 487   // Process java launcher properties.
 488   Arguments::process_sun_java_launcher_properties(args);
 489 

 575     JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
 576     memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
 577   } else {
 578     JavaThread::_jvmci_old_thread_counters = nullptr;
 579   }
 580 #endif // INCLUDE_JVMCI
 581 
 582   // Initialize OopStorage for threadObj
 583   JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
 584 
 585   // Attach the main thread to this os thread
 586   JavaThread* main_thread = new JavaThread();
 587   main_thread->set_thread_state(_thread_in_vm);
 588   main_thread->initialize_thread_current();
 589   // must do this before set_active_handles
 590   main_thread->record_stack_base_and_size();
 591   main_thread->register_thread_stack_with_NMT();
 592   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
 593   MACOS_AARCH64_ONLY(main_thread->init_wx());
 594 
 595   MutexLockerImpl::init_counters(); // depends on mutex_init(), perfMemory_init(), and Thread::initialize_thread_current().
 596 
 597   if (!main_thread->set_as_starting_thread()) {
 598     vm_shutdown_during_initialization(
 599                                       "Failed necessary internal allocation. Out of swap space");
 600     main_thread->smr_delete();
 601     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 602     return JNI_ENOMEM;
 603   }
 604 
 605   // Enable guard page *after* os::create_main_thread(), otherwise it would
 606   // crash Linux VM, see notes in os_linux.cpp.
 607   main_thread->stack_overflow_state()->create_stack_guard_pages();
 608 
 609   // Initialize Java-Level synchronization subsystem
 610   ObjectMonitor::Initialize();
 611   ObjectSynchronizer::initialize();
 612 
 613   Deoptimization::init_counters();
 614   VMThread::init_counters();
 615 
 616   // Initialize global modules
 617   jint status = init_globals();
 618   if (status != JNI_OK) {
 619     main_thread->smr_delete();
 620     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
 621     return status;
 622   }
 623   if (xtty != nullptr)
 624     xtty->elem("vm_main_thread thread='" UINTX_FORMAT "'",
 625                (uintx) main_thread->osthread()->thread_id());
 626 
 627   // Create WatcherThread as soon as we can since we need it in case
 628   // of hangs during error reporting.
 629   WatcherThread::start();
 630 
 631   // Add main_thread to threads list to finish barrier setup with
 632   // on_thread_attach.  Should be before starting to build Java objects in
 633   // init_globals2, which invokes barriers.
 634   {
 635     MutexLocker mu(Threads_lock);
 636     Threads::add(main_thread);
 637   }
 638 
 639   status = init_globals2();
 640   if (status != JNI_OK) {
 641     Threads::remove(main_thread, false);
 642     // It is possible that we managed to fully initialize Universe but have then
 643     // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
 644     // will want to report it, so we can't delete the main thread.
 645     if (!main_thread->has_pending_exception()) {

 743     if (StartAttachListener || AttachListener::init_at_startup()) {
 744       AttachListener::init();
 745     }
 746   }
 747 
 748   // Launch -Xrun agents if EagerXrunInit is not set.
 749   if (!EagerXrunInit) {
 750     JvmtiAgentList::load_xrun_agents();
 751   }
 752 
 753   Arena::start_chunk_pool_cleaner_task();
 754 
 755   // Start the service thread
 756   // The service thread enqueues JVMTI deferred events and does various hashtable
 757   // and other cleanups.  Needs to start before the compilers start posting events.
 758   ServiceThread::initialize();
 759 
 760   // Start the monitor deflation thread:
 761   MonitorDeflationThread::initialize();
 762 
 763   // Start the method sampler
 764   MethodProfiler::initialize();
 765 
 766   bool force_JVMCI_initialization = initialize_compilation(CHECK_JNI_ERR);
 767 
 768   ClassPreloader::init_javabase_preloaded_classes(CHECK_JNI_ERR);




















 769 
 770   // Start string deduplication thread if requested.
 771   if (StringDedup::is_enabled()) {
 772     StringDedup::start();
 773   }
 774 
 775   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 776   // It is done after compilers are initialized, because otherwise compilations of
 777   // signature polymorphic MH intrinsics can be missed
 778   // (see SystemDictionary::find_method_handle_intrinsic).
 779   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 780 
 781   // This will initialize the module system.  Only java.base classes can be
 782   // loaded until phase 2 completes
 783   call_initPhase2(CHECK_JNI_ERR);
 784 
 785   JFR_ONLY(Jfr::on_create_vm_2();)
 786 
 787   // Always call even when there are not JVMTI environments yet, since environments
 788   // may be attached late and JVMTI must track phases of VM execution
 789   JvmtiExport::enter_start_phase();
 790 
 791   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
 792   JvmtiExport::post_vm_start();
 793 
 794   // Final system initialization including security manager and system class loader
 795   call_initPhase3(CHECK_JNI_ERR);
 796 
 797   // cache the system and platform class loaders
 798   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
 799 
 800   // Initiate replay training processing once preloading is over.
 801   CompileBroker::init_training_replay();
 802 
 803   ClassPreloader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
 804 
 805   if (Continuations::enabled()) {
 806     // Initialize Continuation class now so that failure to create enterSpecial/doYield
 807     // special nmethods due to limited CodeCache size can be treated as a fatal error at
 808     // startup with the proper message that CodeCache size is too small.
 809     initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
 810   }
 811 
 812 #if INCLUDE_CDS
 813   // capture the module path info from the ModuleEntryTable
 814   ClassLoader::initialize_module_path(THREAD);
 815   if (HAS_PENDING_EXCEPTION) {
 816     java_lang_Throwable::print(PENDING_EXCEPTION, tty);
 817     vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly");
 818   }
 819 #endif
 820 
 821 #if INCLUDE_JVMCI
 822   if (force_JVMCI_initialization) {
 823     JVMCI::initialize_compiler(CHECK_JNI_ERR);
 824   }
 825 #endif
 826 
 827   if (PrecompileCode) {
 828     Precompiler::compile_cached_code(CHECK_JNI_ERR);
 829     if (PrecompileOnlyAndExit) {
 830       SCCache::close();
 831       log_vm_init_stats();
 832       vm_direct_exit(0, "Code precompiation is over");
 833     }
 834   }
 835 
 836 #if defined(COMPILER2)
 837   // Pre-load cached compiled methods
 838   SCCache::preload_code(CHECK_JNI_ERR);
 839 #endif
 840 
 841   if (NativeHeapTrimmer::enabled()) {
 842     NativeHeapTrimmer::initialize();
 843   }
 844 
 845   // Always call even when there are not JVMTI environments yet, since environments
 846   // may be attached late and JVMTI must track phases of VM execution
 847   JvmtiExport::enter_live_phase();
 848 
 849   // Make perfmemory accessible
 850   PerfMemory::set_accessible(true);
 851 
 852   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
 853   JvmtiExport::post_vm_initialized();
 854 
 855   JFR_ONLY(Jfr::on_create_vm_3();)
 856 
 857 #if INCLUDE_MANAGEMENT
 858   Management::initialize(THREAD);
 859 
 860   if (HAS_PENDING_EXCEPTION) {

 873 #endif
 874 
 875   call_postVMInitHook(THREAD);
 876   // The Java side of PostVMInitHook.run must deal with all
 877   // exceptions and provide means of diagnosis.
 878   if (HAS_PENDING_EXCEPTION) {
 879     CLEAR_PENDING_EXCEPTION;
 880   }
 881 
 882   // Let WatcherThread run all registered periodic tasks now.
 883   // NOTE:  All PeriodicTasks should be registered by now. If they
 884   //   aren't, late joiners might appear to start slowly (we might
 885   //   take a while to process their first tick).
 886   WatcherThread::run_all_tasks();
 887 
 888   create_vm_timer.end();
 889 #ifdef ASSERT
 890   _vm_complete = true;
 891 #endif
 892 
 893   if (CDSConfig::is_dumping_classic_static_archive()) {
 894     // Classic -Xshare:dump, aka "old workflow"
 895     MetaspaceShared::preload_and_dump();
 896   } else if (CDSConfig::is_dumping_final_static_archive()) {
 897     // TODO: copy the verification and loader constraints from preimage to final image
 898     // TODO: load archived classes for custom loaders as well.
 899     log_info(cds)("Dumping final image of CacheDataStore %s", CacheDataStore);
 900     MetaspaceShared::preload_and_dump();
 901     vm_direct_exit(0, "CacheDataStore dumping is complete");
 902   }
 903 
 904   log_info(init)("Before main:");
 905   log_vm_init_stats();
 906 
 907   if (UsePerfData) {
 908     if (ProfileVMLocks) {
 909       main_thread->set_profile_vm_locks(true);
 910     }
 911     if (ProfileVMCalls) {
 912       main_thread->set_profile_vm_calls(true);
 913     }
 914     if (ProfileRuntimeCalls) {
 915       main_thread->set_profile_rt_calls(true);
 916     }
 917     if (ProfileVMOps) {
 918       main_thread->set_profile_vm_ops(true);
 919     }
 920   }
 921 
 922   return JNI_OK;
 923 }
 924 
 925 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
 926 // the program falls off the end of main(). Another VM exit path is through
 927 // vm_exit(), when the program calls System.exit() to return a value, or when
 928 // there is a serious error in VM.
 929 // These two separate shutdown paths are not exactly the same, but they share
 930 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
 931 //
 932 // Shutdown sequence:
 933 //   + Shutdown native memory tracking if it is on
 934 //   + Wait until we are the last non-daemon thread to execute
 935 //     <-- every thing is still working at this moment -->
 936 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
 937 //        shutdown hooks
 938 //   + Call before_exit(), prepare for VM exit
 939 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),
< prev index next >