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

  89 #include "runtime/thread.inline.hpp"
  90 #include "runtime/threadSMR.inline.hpp"
  91 #include "runtime/threads.hpp"
  92 #include "runtime/timer.hpp"
  93 #include "runtime/timerTrace.hpp"
  94 #include "runtime/trimNativeHeap.hpp"
  95 #include "runtime/vmOperations.hpp"
  96 #include "runtime/vm_version.hpp"
  97 #include "services/attachListener.hpp"
  98 #include "services/management.hpp"
  99 #include "services/threadIdTable.hpp"
 100 #include "services/threadService.hpp"
 101 #include "utilities/dtrace.hpp"
 102 #include "utilities/events.hpp"
 103 #include "utilities/macros.hpp"
 104 #include "utilities/vmError.hpp"
 105 #if INCLUDE_JVMCI
 106 #include "jvmci/jvmci.hpp"
 107 #include "jvmci/jvmciEnv.hpp"
 108 #endif



 109 #ifdef COMPILER2
 110 #include "opto/idealGraphPrinter.hpp"

 111 #endif
 112 #if INCLUDE_JFR
 113 #include "jfr/jfr.hpp"
 114 #endif
 115 
 116 // Initialization after module runtime initialization
 117 void universe_post_module_init();  // must happen after call_initPhase2
 118 
 119 
 120 static void initialize_class(Symbol* class_name, TRAPS) {
 121   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
 122   InstanceKlass::cast(klass)->initialize(CHECK);
 123 }
 124 
 125 
 126 // Creates the initial ThreadGroup
 127 static Handle create_initial_thread_group(TRAPS) {
 128   Handle system_instance = JavaCalls::construct_new_instance(
 129                             vmClasses::ThreadGroup_klass(),
 130                             vmSymbols::void_method_signature(),

 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.

 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_ArrayIndexOutOfBoundsException(), CHECK);
 397   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
 398   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
 399   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
 400 }
 401 
































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




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

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


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



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



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

 674     if (StartAttachListener || AttachListener::init_at_startup()) {
 675       AttachListener::init();
 676     }
 677   }
 678 
 679   // Launch -Xrun agents if EagerXrunInit is not set.
 680   if (!EagerXrunInit) {
 681     JvmtiAgentList::load_xrun_agents();
 682   }
 683 
 684   Arena::start_chunk_pool_cleaner_task();
 685 
 686   // Start the service thread
 687   // The service thread enqueues JVMTI deferred events and does various hashtable
 688   // and other cleanups.  Needs to start before the compilers start posting events.
 689   ServiceThread::initialize();
 690 
 691   // Start the monitor deflation thread:
 692   MonitorDeflationThread::initialize();
 693 
 694   // initialize compiler(s)
 695 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
 696   bool init_compilation = true;
 697 #if INCLUDE_JVMCI
 698   bool force_JVMCI_initialization = false;
 699   if (EnableJVMCI) {
 700     // Initialize JVMCI eagerly when it is explicitly requested.
 701     // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
 702     force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
 703     if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
 704       // Force initialization of jarjvmci otherwise requests for blocking
 705       // compilations will not actually block until jarjvmci is initialized.
 706       force_JVMCI_initialization = true;
 707     }
 708     if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
 709       // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
 710       // so compilation should be disabled. This prevents dumping or
 711       // printing from happening more than once.
 712       init_compilation = false;
 713     }
 714   }
 715 #endif
 716   if (init_compilation) {
 717     CompileBroker::compilation_init(CHECK_JNI_ERR);
 718   }
 719 #endif
 720 




 721   // Start string deduplication thread if requested.
 722   if (StringDedup::is_enabled()) {
 723     StringDedup::start();
 724   }
 725 
 726   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
 727   // It is done after compilers are initialized, because otherwise compilations of
 728   // signature polymorphic MH intrinsics can be missed
 729   // (see SystemDictionary::find_method_handle_intrinsic).
 730   initialize_jsr292_core_classes(CHECK_JNI_ERR);
 731 
 732   // This will initialize the module system.  Only java.base classes can be
 733   // loaded until phase 2 completes
 734   call_initPhase2(CHECK_JNI_ERR);
 735 
 736   JFR_ONLY(Jfr::on_create_vm_2();)
 737 
 738   // Always call even when there are not JVMTI environments yet, since environments
 739   // may be attached late and JVMTI must track phases of VM execution
 740   JvmtiExport::enter_start_phase();
 741 
 742   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
 743   JvmtiExport::post_vm_start();
 744 
 745   // Final system initialization including security manager and system class loader
 746   call_initPhase3(CHECK_JNI_ERR);
 747 
 748   // cache the system and platform class loaders
 749   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
 750 





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














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

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






 822     MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);

 823   }
 824 
 825   if (log_is_enabled(Info, perf, class, link)) {
 826     LogStreamHandle(Info, perf, class, link) log;
 827     log.print_cr("At VM initialization completion:");
 828     ClassLoader::print_counters(&log);












 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 "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/systemDictionary.hpp"
  37 #include "classfile/systemDictionaryShared.hpp"
  38 #include "classfile/vmClasses.hpp"
  39 #include "classfile/vmSymbols.hpp"
  40 #include "code/SCCache.hpp"
  41 #include "compiler/compilationPolicy.hpp"
  42 #include "compiler/compileBroker.hpp"
  43 #include "compiler/compileTask.hpp"
  44 #include "compiler/compilerThread.hpp"
  45 #include "compiler/precompiler.hpp"
  46 #include "gc/shared/barrierSet.hpp"
  47 #include "gc/shared/barrierSetNMethod.hpp"
  48 #include "gc/shared/gcVMOperations.hpp"
  49 #include "gc/shared/oopStorage.hpp"
  50 #include "gc/shared/oopStorageSet.hpp"
  51 #include "gc/shared/stringdedup/stringDedup.hpp"
  52 #include "interpreter/interpreterRuntime.hpp"
  53 #include "jfr/jfrEvents.hpp"
  54 #include "jvm.h"
  55 #include "jvmtifiles/jvmtiEnv.hpp"
  56 #include "logging/log.hpp"
  57 #include "logging/logAsyncWriter.hpp"
  58 #include "logging/logConfiguration.hpp"
  59 #include "memory/allocation.inline.hpp"
  60 #include "memory/iterator.hpp"
  61 #include "memory/oopFactory.hpp"
  62 #include "memory/resourceArea.hpp"
  63 #include "memory/universe.hpp"
  64 #include "nmt/memTracker.hpp"
  65 #include "oops/instanceKlass.hpp"
  66 #include "oops/klass.inline.hpp"
  67 #include "oops/oop.inline.hpp"
  68 #include "oops/symbol.hpp"
  69 #include "prims/jvm_misc.hpp"
  70 #include "prims/jvmtiAgentList.hpp"
  71 #include "prims/jvmtiEnvBase.hpp"
  72 #include "runtime/arguments.hpp"

  97 #include "runtime/thread.inline.hpp"
  98 #include "runtime/threadSMR.inline.hpp"
  99 #include "runtime/threads.hpp"
 100 #include "runtime/timer.hpp"
 101 #include "runtime/timerTrace.hpp"
 102 #include "runtime/trimNativeHeap.hpp"
 103 #include "runtime/vmOperations.hpp"
 104 #include "runtime/vm_version.hpp"
 105 #include "services/attachListener.hpp"
 106 #include "services/management.hpp"
 107 #include "services/threadIdTable.hpp"
 108 #include "services/threadService.hpp"
 109 #include "utilities/dtrace.hpp"
 110 #include "utilities/events.hpp"
 111 #include "utilities/macros.hpp"
 112 #include "utilities/vmError.hpp"
 113 #if INCLUDE_JVMCI
 114 #include "jvmci/jvmci.hpp"
 115 #include "jvmci/jvmciEnv.hpp"
 116 #endif
 117 #ifdef COMPILER1
 118 #include "c1/c1_Runtime1.hpp"
 119 #endif
 120 #ifdef COMPILER2
 121 #include "opto/idealGraphPrinter.hpp"
 122 #include "opto/runtime.hpp"
 123 #endif
 124 #if INCLUDE_JFR
 125 #include "jfr/jfr.hpp"
 126 #endif
 127 
 128 // Initialization after module runtime initialization
 129 void universe_post_module_init();  // must happen after call_initPhase2
 130 
 131 
 132 static void initialize_class(Symbol* class_name, TRAPS) {
 133   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
 134   InstanceKlass::cast(klass)->initialize(CHECK);
 135 }
 136 
 137 
 138 // Creates the initial ThreadGroup
 139 static Handle create_initial_thread_group(TRAPS) {
 140   Handle system_instance = JavaCalls::construct_new_instance(
 141                             vmClasses::ThreadGroup_klass(),
 142                             vmSymbols::void_method_signature(),

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

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

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

 754     if (StartAttachListener || AttachListener::init_at_startup()) {
 755       AttachListener::init();
 756     }
 757   }
 758 
 759   // Launch -Xrun agents if EagerXrunInit is not set.
 760   if (!EagerXrunInit) {
 761     JvmtiAgentList::load_xrun_agents();
 762   }
 763 
 764   Arena::start_chunk_pool_cleaner_task();
 765 
 766   // Start the service thread
 767   // The service thread enqueues JVMTI deferred events and does various hashtable
 768   // and other cleanups.  Needs to start before the compilers start posting events.
 769   ServiceThread::initialize();
 770 
 771   // Start the monitor deflation thread:
 772   MonitorDeflationThread::initialize();
 773 
 774 #if INCLUDE_CDS
 775   // Start the method sampler
 776   MethodProfiler::initialize();






















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

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