1 /*
2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
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 "cds/aotLinkedClassBulkLoader.hpp"
27 #include "cds/aotMetaspace.hpp"
28 #include "cds/cds_globals.hpp"
29 #include "cds/cdsConfig.hpp"
30 #include "cds/heapShared.inline.hpp"
31 #include "classfile/classLoader.hpp"
32 #include "classfile/javaClasses.hpp"
33 #include "classfile/javaThreadStatus.hpp"
34 #include "classfile/symbolTable.hpp"
35 #include "classfile/systemDictionary.hpp"
36 #include "classfile/vmClasses.hpp"
37 #include "classfile/vmSymbols.hpp"
38 #include "compiler/compileBroker.hpp"
39 #include "compiler/compilerThread.hpp"
40 #include "compiler/compileTask.hpp"
41 #include "gc/shared/barrierSet.hpp"
42 #include "gc/shared/barrierSetNMethod.hpp"
43 #include "gc/shared/gcVMOperations.hpp"
44 #include "gc/shared/oopStorage.hpp"
45 #include "gc/shared/oopStorageSet.hpp"
46 #include "gc/shared/stringdedup/stringDedup.hpp"
47 #include "jfr/jfrEvents.hpp"
48 #include "jvm.h"
49 #include "jvmtifiles/jvmtiEnv.hpp"
50 #include "logging/log.hpp"
51 #include "logging/logAsyncWriter.hpp"
52 #include "logging/logConfiguration.hpp"
53 #include "memory/allocation.inline.hpp"
54 #include "memory/iterator.hpp"
55 #include "memory/oopFactory.hpp"
56 #include "memory/resourceArea.hpp"
57 #include "memory/universe.hpp"
58 #include "nmt/memTracker.hpp"
59 #include "oops/instanceKlass.hpp"
60 #include "oops/klass.inline.hpp"
61 #include "oops/oop.inline.hpp"
62 #include "oops/symbol.hpp"
63 #include "prims/jvm_misc.hpp"
64 #include "prims/jvmtiAgentList.hpp"
65 #include "prims/jvmtiEnvBase.hpp"
66 #include "runtime/arguments.hpp"
67 #include "runtime/fieldDescriptor.inline.hpp"
68 #include "runtime/flags/jvmFlagLimit.hpp"
69 #include "runtime/globals.hpp"
70 #include "runtime/globals_extension.hpp"
71 #include "runtime/handles.inline.hpp"
72 #include "runtime/interfaceSupport.inline.hpp"
73 #include "runtime/java.hpp"
74 #include "runtime/javaCalls.hpp"
75 #include "runtime/javaThread.inline.hpp"
76 #include "runtime/jniHandles.inline.hpp"
77 #include "runtime/jniPeriodicChecker.hpp"
78 #include "runtime/lockStack.inline.hpp"
79 #include "runtime/monitorDeflationThread.hpp"
80 #include "runtime/mutexLocker.hpp"
81 #include "runtime/nonJavaThread.hpp"
82 #include "runtime/objectMonitor.inline.hpp"
83 #include "runtime/osThread.hpp"
84 #include "runtime/perfData.hpp"
85 #include "runtime/safepoint.hpp"
86 #include "runtime/safepointMechanism.inline.hpp"
87 #include "runtime/safepointVerifiers.hpp"
88 #include "runtime/serviceThread.hpp"
89 #include "runtime/sharedRuntime.hpp"
90 #include "runtime/stackWatermarkSet.inline.hpp"
91 #include "runtime/stubCodeGenerator.hpp"
92 #include "runtime/thread.inline.hpp"
93 #include "runtime/threads.hpp"
94 #include "runtime/threadSMR.inline.hpp"
95 #include "runtime/timer.hpp"
96 #include "runtime/timerTrace.hpp"
97 #include "runtime/trimNativeHeap.hpp"
98 #include "runtime/vm_version.hpp"
99 #include "runtime/vmOperations.hpp"
100 #include "sanitizers/address.hpp"
101 #include "services/attachListener.hpp"
102 #include "services/management.hpp"
103 #include "services/threadIdTable.hpp"
104 #include "services/threadService.hpp"
105 #include "utilities/debug.hpp"
106 #include "utilities/dtrace.hpp"
107 #include "utilities/events.hpp"
108 #include "utilities/macros.hpp"
109 #include "utilities/vmError.hpp"
110 #if INCLUDE_JVMCI
111 #include "jvmci/jvmci.hpp"
112 #include "jvmci/jvmciEnv.hpp"
113 #endif
114 #ifdef COMPILER2
115 #include "opto/idealGraphPrinter.hpp"
116 #endif
117 #if INCLUDE_JFR
118 #include "jfr/jfr.hpp"
119 #endif
120
121 // Initialization after module runtime initialization
122 void universe_post_module_init(); // must happen after call_initPhase2
123
124
125 static void initialize_class(Symbol* class_name, TRAPS) {
126 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
127 InstanceKlass::cast(klass)->initialize(CHECK);
128 }
129
130
131 // Creates the initial ThreadGroup
132 static Handle create_initial_thread_group(TRAPS) {
133 Handle system_instance = JavaCalls::construct_new_instance(
134 vmClasses::ThreadGroup_klass(),
135 vmSymbols::void_method_signature(),
136 CHECK_NH);
137 Universe::set_system_thread_group(system_instance());
138
139 Handle string = java_lang_String::create_from_str("main", CHECK_NH);
140 Handle main_instance = JavaCalls::construct_new_instance(
141 vmClasses::ThreadGroup_klass(),
142 vmSymbols::threadgroup_string_void_signature(),
143 system_instance,
144 string,
145 CHECK_NH);
146 return main_instance;
147 }
148
149 // Creates the initial Thread, and sets it to running.
150 static void create_initial_thread(Handle thread_group, JavaThread* thread,
151 TRAPS) {
152 InstanceKlass* ik = vmClasses::Thread_klass();
153 assert(ik->is_initialized(), "must be");
154 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
155
156 // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread
157 // constructor calls Thread.current(), which must be set here for the
158 // initial thread.
159 java_lang_Thread::set_thread(thread_oop(), thread);
160 thread->set_threadOopHandles(thread_oop());
161
162 Handle string = java_lang_String::create_from_str("main", CHECK);
163
164 JavaValue result(T_VOID);
165 JavaCalls::call_special(&result, thread_oop,
166 ik,
167 vmSymbols::object_initializer_name(),
168 vmSymbols::threadgroup_string_void_signature(),
169 thread_group,
170 string,
171 CHECK);
172
173 DEBUG_ONLY(int64_t main_thread_tid = java_lang_Thread::thread_id(thread_oop());)
174 assert(main_thread_tid == ThreadIdentifier::initial(), "");
175 assert(main_thread_tid == thread->monitor_owner_id(), "");
176 JFR_ONLY(assert(JFR_JVM_THREAD_ID(thread) == static_cast<traceid>(main_thread_tid), "initial tid mismatch");)
177
178 // Set thread status to running since main thread has
179 // been started and running.
180 java_lang_Thread::set_thread_status(thread_oop(),
181 JavaThreadStatus::RUNNABLE);
182 }
183
184 // Extract version and vendor specific information from
185 // java.lang.VersionProps fields.
186 // Returned char* is allocated in the thread's resource area
187 // so must be copied for permanency.
188 static const char* get_java_version_info(InstanceKlass* ik,
189 Symbol* field_name) {
190 fieldDescriptor fd;
191 bool found = ik != nullptr &&
192 ik->find_local_field(field_name,
193 vmSymbols::string_signature(), &fd);
194 if (found) {
195 oop name_oop = ik->java_mirror()->obj_field(fd.offset());
196 if (name_oop == nullptr) {
197 return nullptr;
198 }
199 const char* name = java_lang_String::as_utf8_string(name_oop);
200 return name;
201 } else {
202 return nullptr;
203 }
204 }
205
206 // ======= Threads ========
207
208 // The Threads class links together all active threads, and provides
209 // operations over all threads. It is protected by the Threads_lock,
210 // which is also used in other global contexts like safepointing.
211 // ThreadsListHandles are used to safely perform operations on one
212 // or more threads without the risk of the thread exiting during the
213 // operation.
214 //
215 // Note: The Threads_lock is currently more widely used than we
216 // would like. We are actively migrating Threads_lock uses to other
217 // mechanisms in order to reduce Threads_lock contention.
218
219 int Threads::_number_of_threads = 0;
220 int Threads::_number_of_non_daemon_threads = 0;
221 int Threads::_return_code = 0;
222 uintx Threads::_thread_claim_token = 1; // Never zero.
223
224 #ifdef ASSERT
225 bool Threads::_vm_complete = false;
226 #endif
227
228 // General purpose hook into Java code, run once when the VM is initialized.
229 // The Java library method itself may be changed independently from the VM.
230 static void call_postVMInitHook(TRAPS) {
231 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD);
232 if (klass != nullptr) {
233 JavaValue result(T_VOID);
234 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
235 vmSymbols::void_method_signature(),
236 CHECK);
237 }
238 }
239
240 // All NonJavaThreads (i.e., every non-JavaThread in the system).
241 void Threads::non_java_threads_do(ThreadClosure* tc) {
242 NoSafepointVerifier nsv;
243 for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) {
244 tc->do_thread(njti.current());
245 }
246 }
247
248 // All JavaThreads
249 #define ALL_JAVA_THREADS(X) \
250 for (JavaThread* X : *ThreadsSMRSupport::get_java_thread_list())
251
252 // All JavaThreads
253 void Threads::java_threads_do(ThreadClosure* tc) {
254 assert_locked_or_safepoint(Threads_lock);
255 // ALL_JAVA_THREADS iterates through all JavaThreads.
256 ALL_JAVA_THREADS(p) {
257 tc->do_thread(p);
258 }
259 }
260
261 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system).
262 void Threads::threads_do(ThreadClosure* tc) {
263 assert_locked_or_safepoint(Threads_lock);
264 java_threads_do(tc);
265 non_java_threads_do(tc);
266 }
267
268 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) {
269 assert_at_safepoint();
270
271 uintx claim_token = Threads::thread_claim_token();
272 ALL_JAVA_THREADS(p) {
273 if (p->claim_threads_do(is_par, claim_token)) {
274 tc->do_thread(p);
275 }
276 }
277 for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) {
278 Thread* current = njti.current();
279 if (current->claim_threads_do(is_par, claim_token)) {
280 tc->do_thread(current);
281 }
282 }
283 }
284
285 // The system initialization in the library has three phases.
286 //
287 // Phase 1: java.lang.System class initialization
288 // java.lang.System is a primordial class loaded and initialized
289 // by the VM early during startup. java.lang.System.<clinit>
290 // only does registerNatives and keeps the rest of the class
291 // initialization work later until thread initialization completes.
292 //
293 // System.initPhase1 initializes the system properties, the static
294 // fields in, out, and err. Set up java signal handlers, OS-specific
295 // system settings, and thread group of the main thread.
296 static void call_initPhase1(TRAPS) {
297 Klass* klass = vmClasses::System_klass();
298 JavaValue result(T_VOID);
299 JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(),
300 vmSymbols::void_method_signature(), CHECK);
301 }
302
303 // Phase 2. Module system initialization
304 // This will initialize the module system. Only java.base classes
305 // can be loaded until phase 2 completes.
306 //
307 // Call System.initPhase2 after the compiler initialization and jsr292
308 // classes get initialized because module initialization runs a lot of java
309 // code, that for performance reasons, should be compiled. Also, this will
310 // enable the startup code to use lambda and other language features in this
311 // phase and onward.
312 //
313 // After phase 2, The VM will begin search classes from -Xbootclasspath/a.
314 static void call_initPhase2(TRAPS) {
315 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
316
317 Klass* klass = vmClasses::System_klass();
318
319 JavaValue result(T_INT);
320 JavaCallArguments args;
321 args.push_int(DisplayVMOutputToStderr);
322 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
323 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
324 vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
325 if (result.get_jint() != JNI_OK) {
326 vm_exit_during_initialization(); // no message or exception
327 }
328
329 universe_post_module_init();
330 }
331
332 // Phase 3. final setup - set security manager, system class loader and TCCL
333 //
334 // This will instantiate and set the security manager, set the system class
335 // loader as well as the thread context class loader. The security manager
336 // and system class loader may be a custom class loaded from -Xbootclasspath/a,
337 // other modules or the application's classpath.
338 static void call_initPhase3(TRAPS) {
339 Klass* klass = vmClasses::System_klass();
340 JavaValue result(T_VOID);
341 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
342 vmSymbols::void_method_signature(), CHECK);
343 }
344
345 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
346 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
347
348 // This is before the execution of the very first Java bytecode.
349 if (CDSConfig::is_using_aot_linked_classes()) {
350 AOTLinkedClassBulkLoader::link_classes(THREAD);
351 }
352
353 initialize_class(vmSymbols::java_lang_String(), CHECK);
354
355 // Inject CompactStrings value after the static initializers for String ran.
356 java_lang_String::set_compact_strings(CompactStrings);
357
358 // Initialize java_lang.System (needed before creating the thread)
359 initialize_class(vmSymbols::java_lang_System(), CHECK);
360 // The VM creates & returns objects of this class. Make sure it's initialized.
361 initialize_class(vmSymbols::java_lang_Class(), CHECK);
362
363 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
364 Handle thread_group = create_initial_thread_group(CHECK);
365 Universe::set_main_thread_group(thread_group());
366 initialize_class(vmSymbols::java_lang_Thread(), CHECK);
367 create_initial_thread(thread_group, main_thread, CHECK);
368
369 HeapShared::init_box_classes(CHECK);
370
371 // The VM creates objects of this class.
372 initialize_class(vmSymbols::java_lang_Module(), CHECK);
373
374 #ifdef ASSERT
375 InstanceKlass *k = vmClasses::UnsafeConstants_klass();
376 assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
377 #endif
378
379 // initialize the hardware-specific constants needed by Unsafe
380 initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
381 jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
382
383 // The VM preresolves methods to these classes. Make sure that they get initialized
384 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
385 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
386
387 HeapShared::materialize_thread_object();
388
389 // Phase 1 of the system initialization in the library, java.lang.System class initialization
390 call_initPhase1(CHECK);
391
392 // Get the Java runtime name, version, and vendor info after java.lang.System is initialized.
393 // Some values are actually configure-time constants but some can be set via the jlink tool and
394 // so must be read dynamically. We treat them all the same.
395 InstanceKlass* ik = SystemDictionary::find_instance_klass(THREAD, vmSymbols::java_lang_VersionProps(),
396 Handle());
397 {
398 ResourceMark rm(main_thread);
399 JDK_Version::set_java_version(get_java_version_info(ik, vmSymbols::java_version_name()));
400
401 JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name()));
402
403 JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
404
405 JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
406
407 JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
408 }
409
410 // an instance of OutOfMemory exception has been allocated earlier
411 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
412 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
413 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
414 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
415 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
416 initialize_class(vmSymbols::jdk_internal_vm_PreemptedException(), CHECK);
417 initialize_class(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), CHECK);
418 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
419 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
420 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
421 initialize_class(vmSymbols::java_lang_InternalError(), CHECK);
422 }
423
424 void Threads::initialize_jsr292_core_classes(TRAPS) {
425 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
426
427 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
428 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
429 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
430 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
431
432 if (UseSharedSpaces) {
433 HeapShared::initialize_java_lang_invoke(CHECK);
434 }
435 }
436
437 // One-shot PeriodicTask subclass for reading the release file
438 class ReadReleaseFileTask : public PeriodicTask {
439 public:
440 ReadReleaseFileTask() : PeriodicTask(100) {}
441
442 virtual void task() {
443 os::read_image_release_file();
444
445 // Reclaim our storage and disenroll ourself.
446 delete this;
447 }
448 };
449
450 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
451 extern void JDK_Version_init();
452
453 // Preinitialize version info.
454 VM_Version::early_initialize();
455
456 // Check version
457 if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
458
459 // Deferred "static" initialization
460 NonJavaThread::init();
461
462 // Initialize library-based TLS
463 ThreadLocalStorage::init();
464
465 // Initialize the output stream module
466 ostream_init();
467
468 // Process java launcher properties.
469 Arguments::process_sun_java_launcher_properties(args);
470
471 // Initialize the os module
472 os::init();
473
474 // Initialize memory pools
475 Arena::initialize_chunk_pool();
476
477 MACOS_AARCH64_ONLY(os::current_thread_enable_wx(WXWrite));
478
479 // Record VM creation timing statistics
480 TraceVmCreationTime create_vm_timer;
481 create_vm_timer.start();
482
483 // Initialize system properties.
484 Arguments::init_system_properties();
485
486 // So that JDK version can be used as a discriminator when parsing arguments
487 JDK_Version_init();
488
489 // Update/Initialize System properties after JDK version number is known
490 Arguments::init_version_specific_system_properties();
491
492 // Make sure to initialize log configuration *before* parsing arguments
493 LogConfiguration::initialize(create_vm_timer.begin_time());
494
495 // Parse arguments
496 // Note: this internally calls os::init_container_support()
497 jint parse_result = Arguments::parse(args);
498 if (parse_result != JNI_OK) return parse_result;
499
500 // Initialize NMT right after argument parsing to keep the pre-NMT-init window small.
501 MemTracker::initialize();
502
503 os::init_before_ergo();
504
505 jint ergo_result = Arguments::apply_ergo();
506 if (ergo_result != JNI_OK) return ergo_result;
507
508 // Final check of all ranges after ergonomics which may change values.
509 if (!JVMFlagLimit::check_all_ranges()) {
510 return JNI_EINVAL;
511 }
512
513 // Final check of all 'AfterErgo' constraints after ergonomics which may change values.
514 bool constraint_result = JVMFlagLimit::check_all_constraints(JVMFlagConstraintPhase::AfterErgo);
515 if (!constraint_result) {
516 return JNI_EINVAL;
517 }
518
519 if (PauseAtStartup) {
520 os::pause();
521 }
522
523 HOTSPOT_VM_INIT_BEGIN();
524
525 // Timing (must come after argument parsing)
526 TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime));
527
528 // Initialize the os module after parsing the args
529 jint os_init_2_result = os::init_2();
530 if (os_init_2_result != JNI_OK) return os_init_2_result;
531
532 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
533 // Initialize assert poison page mechanism.
534 if (ShowRegistersOnAssert) {
535 initialize_assert_poison();
536 }
537 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
538
539 SafepointMechanism::initialize();
540
541 jint adjust_after_os_result = Arguments::adjust_after_os();
542 if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
543
544 // Initialize output stream logging
545 ostream_init_log();
546
547 // Launch -agentlib/-agentpath and converted -Xrun agents
548 JvmtiAgentList::load_agents();
549
550 // Initialize Threads state
551 _number_of_threads = 0;
552 _number_of_non_daemon_threads = 0;
553
554 // Initialize global data structures and create system classes in heap
555 vm_init_globals();
556
557 #if INCLUDE_JVMCI
558 if (JVMCICounterSize > 0) {
559 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
560 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
561 } else {
562 JavaThread::_jvmci_old_thread_counters = nullptr;
563 }
564 #endif // INCLUDE_JVMCI
565
566 // Initialize OopStorage for threadObj
567 JavaThread::_thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
568
569 // Attach the main thread to this os thread. It is added to the threads list inside
570 // universe_init(), within init_globals().
571 JavaThread* main_thread = new JavaThread();
572 main_thread->set_thread_state(_thread_in_vm);
573 main_thread->initialize_thread_current();
574 // Once mutexes and main_thread are ready, we can use NmtVirtualMemoryLocker.
575 MemTracker::NmtVirtualMemoryLocker::set_safe_to_use();
576 // must do this before set_active_handles
577 main_thread->record_stack_base_and_size();
578 main_thread->register_thread_stack_with_NMT();
579 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
580 MACOS_AARCH64_ONLY(main_thread->init_wx());
581
582 // Set the _monitor_owner_id now since we will run Java code before the Thread instance
583 // is even created. The same value will be assigned to the Thread instance on init.
584 const int64_t main_thread_tid = ThreadIdentifier::next();
585 guarantee(main_thread_tid == 3, "Must equal the PRIMORDIAL_TID used in Threads.java");
586 main_thread->set_monitor_owner_id(main_thread_tid);
587
588 if (!Thread::set_as_starting_thread(main_thread)) {
589 vm_shutdown_during_initialization(
590 "Failed necessary internal allocation. Out of swap space");
591 main_thread->smr_delete();
592 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
593 return JNI_ENOMEM;
594 }
595
596 JFR_ONLY(Jfr::initialize_main_thread(main_thread);)
597
598 // Enable guard page *after* os::create_main_thread(), otherwise it would
599 // crash Linux VM, see notes in os_linux.cpp.
600 main_thread->stack_overflow_state()->create_stack_guard_pages();
601
602 // Initialize Java-Level synchronization subsystem
603 ObjectMonitor::Initialize();
604 ObjectSynchronizer::initialize();
605
606 // Initialize global modules
607 jint status = init_globals();
608 if (status != JNI_OK) {
609 main_thread->smr_delete();
610 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
611 return status;
612 }
613
614 // Have the WatcherThread read the release file in the background.
615 ReadReleaseFileTask* read_task = new ReadReleaseFileTask();
616 read_task->enroll();
617
618 // Create WatcherThread as soon as we can since we need it in case
619 // of hangs during error reporting.
620 WatcherThread::start();
621
622 status = init_globals2();
623 if (status != JNI_OK) {
624 Threads::remove(main_thread, false);
625 // It is possible that we managed to fully initialize Universe but have then
626 // failed by throwing an exception. In that case our caller JNI_CreateJavaVM
627 // will want to report it, so we can't delete the main thread.
628 if (!main_thread->has_pending_exception()) {
629 main_thread->smr_delete();
630 }
631 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
632 return status;
633 }
634
635 ObjectMonitor::Initialize2();
636
637 JFR_ONLY(Jfr::on_create_vm_1();)
638
639 // Should be done after the heap is fully created
640 main_thread->cache_global_variables();
641
642 // Any JVMTI raw monitors entered in onload will transition into
643 // real raw monitor. VM is setup enough here for raw monitor enter.
644 JvmtiExport::transition_pending_onload_raw_monitors();
645
646 // Create the VMThread
647 { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime));
648
649 VMThread::create();
650 VMThread* vmthread = VMThread::vm_thread();
651
652 if (!os::create_thread(vmthread, os::vm_thread)) {
653 vm_exit_during_initialization("Cannot create VM thread. "
654 "Out of system resources.");
655 }
656
657 // Wait for the VM thread to become ready, and VMThread::run to initialize
658 // Monitors can have spurious returns, must always check another state flag
659 {
660 MonitorLocker ml(Notify_lock);
661 os::start_thread(vmthread);
662 while (!vmthread->is_running()) {
663 ml.wait();
664 }
665 }
666 }
667
668 assert(Universe::is_fully_initialized(), "not initialized");
669 if (VerifyDuringStartup) {
670 // Make sure we're starting with a clean slate.
671 VM_Verify verify_op;
672 VMThread::execute(&verify_op);
673 }
674
675 // We need this to update the java.vm.info property in case any flags used
676 // to initially define it have been changed. This is needed for both CDS
677 // since UseSharedSpaces may be changed after java.vm.info
678 // is initially computed. See Abstract_VM_Version::vm_info_string().
679 // This update must happen before we initialize the java classes, but
680 // after any initialization logic that might modify the flags.
681 Arguments::update_vm_info_property(VM_Version::vm_info_string());
682
683 JavaThread* THREAD = JavaThread::current(); // For exception macros.
684 HandleMark hm(THREAD);
685
686 // Always call even when there are not JVMTI environments yet, since environments
687 // may be attached late and JVMTI must track phases of VM execution
688 JvmtiExport::enter_early_start_phase();
689
690 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
691 JvmtiExport::post_early_vm_start();
692
693 // Launch -Xrun agents early if EagerXrunInit is set
694 if (EagerXrunInit) {
695 JvmtiAgentList::load_xrun_agents();
696 }
697
698 initialize_java_lang_classes(main_thread, CHECK_JNI_ERR);
699
700 quicken_jni_functions();
701
702 // No more stub generation allowed after that point.
703 StubCodeDesc::freeze();
704
705 // Prepare AOT heap loader for GC.
706 HeapShared::enable_gc();
707
708 #ifdef ADDRESS_SANITIZER
709 Asan::initialize();
710 #endif
711
712 // Set flag that basic initialization has completed. Used by exceptions and various
713 // debug stuff, that does not work until all basic classes have been initialized.
714 set_init_completed();
715
716 LogConfiguration::post_initialize();
717 Metaspace::post_initialize();
718 MutexLockerImpl::post_initialize();
719
720 HOTSPOT_VM_INIT_END();
721
722 // record VM initialization completion time
723 #if INCLUDE_MANAGEMENT
724 Management::record_vm_init_completed();
725 #endif // INCLUDE_MANAGEMENT
726
727 log_info(os)("Initialized VM with process ID %d", os::current_process_id());
728
729 if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && CreateCoredumpOnCrash) {
730 char buffer[2*JVM_MAXPATHLEN];
731 os::check_core_dump_prerequisites(buffer, sizeof(buffer), true);
732 }
733
734 // Signal Dispatcher needs to be started before VMInit event is posted
735 os::initialize_jdk_signal_support(CHECK_JNI_ERR);
736
737 // Start Attach Listener if +StartAttachListener or it can't be started lazily
738 if (!DisableAttachMechanism) {
739 AttachListener::vm_start();
740 if (StartAttachListener || AttachListener::init_at_startup()) {
741 AttachListener::init();
742 }
743 }
744
745 // Launch -Xrun agents if EagerXrunInit is not set.
746 if (!EagerXrunInit) {
747 JvmtiAgentList::load_xrun_agents();
748 }
749
750 Arena::start_chunk_pool_cleaner_task();
751
752 // Start the service thread
753 // The service thread enqueues JVMTI deferred events and does various hashtable
754 // and other cleanups. Needs to start before the compilers start posting events.
755 ServiceThread::initialize();
756
757 if (CDSConfig::is_using_aot_linked_classes()) {
758 nmethod::post_delayed_compiled_method_load_events();
759 }
760
761 // Start the monitor deflation thread:
762 MonitorDeflationThread::initialize();
763
764 // initialize compiler(s)
765 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
766 bool init_compilation = true;
767 #if INCLUDE_JVMCI
768 bool force_JVMCI_initialization = false;
769 if (EnableJVMCI) {
770 // Initialize JVMCI eagerly when it is explicitly requested.
771 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
772 force_JVMCI_initialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
773 if (!force_JVMCI_initialization && UseJVMCICompiler && !UseJVMCINativeLibrary && (!UseInterpreter || !BackgroundCompilation)) {
774 // Force initialization of jarjvmci otherwise requests for blocking
775 // compilations will not actually block until jarjvmci is initialized.
776 force_JVMCI_initialization = true;
777 }
778 if (JVMCIPrintProperties || JVMCILibDumpJNIConfig) {
779 // Both JVMCILibDumpJNIConfig and JVMCIPrintProperties exit the VM
780 // so compilation should be disabled. This prevents dumping or
781 // printing from happening more than once.
782 init_compilation = false;
783 }
784 }
785 #endif
786 if (init_compilation) {
787 CompileBroker::compilation_init(CHECK_JNI_ERR);
788 }
789 #endif
790
791 if (CDSConfig::is_using_aot_linked_classes()) {
792 SystemDictionary::restore_archived_method_handle_intrinsics();
793 AOTLinkedClassBulkLoader::init_javabase_classes(THREAD);
794 }
795
796 // Start string deduplication thread if requested.
797 if (StringDedup::is_enabled()) {
798 StringDedup::start();
799 }
800
801 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
802 // It is done after compilers are initialized, because otherwise compilations of
803 // signature polymorphic MH intrinsics can be missed
804 // (see SystemDictionary::find_method_handle_intrinsic).
805 initialize_jsr292_core_classes(CHECK_JNI_ERR);
806
807 // This will initialize the module system. Only java.base classes can be
808 // loaded until phase 2 completes
809 call_initPhase2(CHECK_JNI_ERR);
810
811 if (CDSConfig::is_using_aot_linked_classes()) {
812 AOTLinkedClassBulkLoader::init_non_javabase_classes(THREAD);
813 }
814 #ifndef PRODUCT
815 HeapShared::initialize_test_class_from_archive(THREAD);
816 #endif
817
818 JFR_ONLY(Jfr::on_create_vm_2();)
819
820 // Always call even when there are not JVMTI environments yet, since environments
821 // may be attached late and JVMTI must track phases of VM execution
822 JvmtiExport::enter_start_phase();
823
824 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
825 JvmtiExport::post_vm_start();
826
827 // Final system initialization including security manager and system class loader
828 call_initPhase3(CHECK_JNI_ERR);
829
830 // cache the system and platform class loaders
831 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
832
833 // Initiate replay training processing once preloading is over.
834 CompileBroker::init_training_replay();
835
836 AOTLinkedClassBulkLoader::replay_training_at_init_for_preloaded_classes(CHECK_JNI_ERR);
837
838 if (Continuations::enabled()) {
839 // Initialize Continuation class now so that failure to create enterSpecial/doYield
840 // special nmethods due to limited CodeCache size can be treated as a fatal error at
841 // startup with the proper message that CodeCache size is too small.
842 initialize_class(vmSymbols::jdk_internal_vm_Continuation(), CHECK_JNI_ERR);
843 }
844
845 if (NativeHeapTrimmer::enabled()) {
846 NativeHeapTrimmer::initialize();
847 }
848
849 // Always call even when there are not JVMTI environments yet, since environments
850 // may be attached late and JVMTI must track phases of VM execution
851 JvmtiExport::enter_live_phase();
852
853 // Make perfmemory accessible
854 PerfMemory::set_accessible(true);
855
856 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
857 JvmtiExport::post_vm_initialized();
858
859 #if INCLUDE_JVMCI
860 if (force_JVMCI_initialization) {
861 JVMCI::initialize_compiler_in_create_vm(CHECK_JNI_ERR);
862 }
863 #endif
864
865 JFR_ONLY(Jfr::on_create_vm_3();)
866
867 #if INCLUDE_MANAGEMENT
868 bool start_agent = true;
869 #if INCLUDE_CDS
870 start_agent = !CDSConfig::is_dumping_final_static_archive();
871 if (!start_agent) {
872 log_info(aot)("Not starting management agent during creation of AOT cache.");
873 }
874 #endif // INCLUDE_CDS
875 if (start_agent) {
876 Management::initialize(THREAD);
877
878 if (HAS_PENDING_EXCEPTION) {
879 // management agent fails to start possibly due to
880 // configuration problem and is responsible for printing
881 // stack trace if appropriate. Simply exit VM.
882 vm_exit(1);
883 }
884 }
885 #endif // INCLUDE_MANAGEMENT
886
887 if (UsePerfData) PerfDataManager::create_misc_perfdata();
888 if (CheckJNICalls) JniPeriodicChecker::engage();
889
890 call_postVMInitHook(THREAD);
891 // The Java side of PostVMInitHook.run must deal with all
892 // exceptions and provide means of diagnosis.
893 if (HAS_PENDING_EXCEPTION) {
894 CLEAR_PENDING_EXCEPTION;
895 }
896
897 // Let WatcherThread run all registered periodic tasks now.
898 // NOTE: All PeriodicTasks should be registered by now. If they
899 // aren't, late joiners might appear to start slowly (we might
900 // take a while to process their first tick).
901 WatcherThread::run_all_tasks();
902
903 // Finish materializing AOT objects
904 HeapShared::finish_materialize_objects();
905
906 create_vm_timer.end();
907 #ifdef ASSERT
908 _vm_complete = true;
909 #endif
910
911 if (CDSConfig::is_dumping_classic_static_archive()) {
912 // Classic -Xshare:dump, aka "old workflow"
913 AOTMetaspace::dump_static_archive(CHECK_JNI_ERR);
914 } else if (CDSConfig::is_dumping_final_static_archive()) {
915 tty->print_cr("Reading AOTConfiguration %s and writing AOTCache %s", AOTConfiguration, AOTCache);
916 AOTMetaspace::dump_static_archive(CHECK_JNI_ERR);
917 }
918
919 if (log_is_enabled(Info, perf, class, link)) {
920 LogStreamHandle(Info, perf, class, link) log;
921 log.print_cr("At VM initialization completion:");
922 ClassLoader::print_counters(&log);
923 }
924
925 return JNI_OK;
926 }
927
928 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
929 // the program falls off the end of main(). Another VM exit path is through
930 // vm_exit(), when the program calls System.exit() to return a value, or when
931 // there is a serious error in VM.
932 // These two separate shutdown paths are not exactly the same, but they share
933 // Shutdown.shutdown() at Java level and before_exit() and VM_Exit op at VM level.
934 //
935 // Shutdown sequence:
936 // + Shutdown native memory tracking if it is on
937 // + Wait until we are the last non-daemon thread to execute
938 // <-- every thing is still working at this moment -->
939 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
940 // shutdown hooks
941 // + Call before_exit(), prepare for VM exit
942 // > run VM level shutdown hooks (they are registered through JVM_OnExit(),
943 // currently the only user of this mechanism is File.deleteOnExit())
944 // > stop watcher thread,
945 // post thread end and vm death events to JVMTI,
946 // stop signal thread
947 // + Call JavaThread::exit(), it will:
948 // > release JNI handle blocks, remove stack guard pages
949 // > remove this thread from Threads list
950 // <-- no more Java code from this thread after this point -->
951 // + Stop VM thread, it will bring the remaining VM to a safepoint and stop
952 // the compiler threads at safepoint
953 // <-- do not use anything that could get blocked by Safepoint -->
954 // + Disable tracing at JNI/JVM barriers
955 // + Set _vm_exited flag for threads that are still running native code
956 // + Call exit_globals()
957 // > deletes tty
958 // > deletes PerfMemory resources
959 // + Delete this thread
960 // + Return to caller
961
962 void Threads::destroy_vm() {
963 JavaThread* thread = JavaThread::current();
964
965 #ifdef ASSERT
966 _vm_complete = false;
967 #endif
968 // Wait until we are the last non-daemon thread to execute, or
969 // if we are a daemon then wait until the last non-daemon thread has
970 // executed.
971 bool daemon = java_lang_Thread::is_daemon(thread->threadObj());
972 int expected = daemon ? 0 : 1;
973 {
974 MonitorLocker nu(Threads_lock);
975 while (Threads::number_of_non_daemon_threads() > expected)
976 // This wait should make safepoint checks, wait without a timeout.
977 nu.wait(0);
978 }
979
980 EventShutdown e;
981 if (e.should_commit()) {
982 e.set_reason("No remaining non-daemon Java threads");
983 e.commit();
984 }
985
986 // Hang forever on exit if we are reporting an error.
987 if (ShowMessageBoxOnError && VMError::is_error_reported()) {
988 os::infinite_sleep();
989 }
990 os::wait_for_keypress_at_exit();
991
992 // run Java level shutdown hooks
993 thread->invoke_shutdown_hooks();
994
995 before_exit(thread);
996
997 thread->exit(true);
998
999 // We are no longer on the main thread list but could still be in a
1000 // secondary list where another thread may try to interact with us.
1001 // So wait until all such interactions are complete before we bring
1002 // the VM to the termination safepoint. Normally this would be done
1003 // using thread->smr_delete() below where we delete the thread, but
1004 // we can't call that after the termination safepoint is active as
1005 // we will deadlock on the Threads_lock. Once all interactions are
1006 // complete it is safe to directly delete the thread at any time.
1007 ThreadsSMRSupport::wait_until_not_protected(thread);
1008
1009 // Stop VM thread.
1010 {
1011 // 4945125 The vm thread comes to a safepoint during exit.
1012 // GC vm_operations can get caught at the safepoint, and the
1013 // heap is unparseable if they are caught. Grab the Heap_lock
1014 // to prevent this. The GC vm_operations will not be able to
1015 // queue until after the vm thread is dead. After this point,
1016 // we'll never emerge out of the safepoint before the VM exits.
1017 // Assert that the thread is terminated so that acquiring the
1018 // Heap_lock doesn't cause the terminated thread to participate in
1019 // the safepoint protocol.
1020
1021 assert(thread->is_terminated(), "must be terminated here");
1022 MutexLocker ml(Heap_lock);
1023
1024 VMThread::wait_for_vm_thread_exit();
1025 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
1026 VMThread::destroy();
1027 }
1028
1029 // Now, all Java threads are gone except daemon threads. Daemon threads
1030 // running Java code or in VM are stopped by the Safepoint. However,
1031 // daemon threads executing native code are still running. But they
1032 // will be stopped at native=>Java/VM barriers. Note that we can't
1033 // simply kill or suspend them, as it is inherently deadlock-prone.
1034
1035 VM_Exit::set_vm_exited();
1036
1037 // Clean up ideal graph printers after the VMThread has started
1038 // the final safepoint which will block all the Compiler threads.
1039 // Note that this Thread has already logically exited so the
1040 // clean_up() function's use of a JavaThreadIteratorWithHandle
1041 // would be a problem except set_vm_exited() has remembered the
1042 // shutdown thread which is granted a policy exception.
1043 #if defined(COMPILER2) && !defined(PRODUCT)
1044 IdealGraphPrinter::clean_up();
1045 #endif
1046
1047 notify_vm_shutdown();
1048
1049 // exit_globals() will delete tty
1050 exit_globals();
1051
1052 // Deleting the shutdown thread here is safe. See comment on
1053 // wait_until_not_protected() above.
1054 delete thread;
1055
1056 #if INCLUDE_JVMCI
1057 if (JVMCICounterSize > 0) {
1058 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
1059 }
1060 #endif
1061
1062 LogConfiguration::finalize();
1063 }
1064
1065
1066 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
1067 if (version == JNI_VERSION_1_1) return JNI_TRUE;
1068 return is_supported_jni_version(version);
1069 }
1070
1071
1072 jboolean Threads::is_supported_jni_version(jint version) {
1073 if (version == JNI_VERSION_1_2) return JNI_TRUE;
1074 if (version == JNI_VERSION_1_4) return JNI_TRUE;
1075 if (version == JNI_VERSION_1_6) return JNI_TRUE;
1076 if (version == JNI_VERSION_1_8) return JNI_TRUE;
1077 if (version == JNI_VERSION_9) return JNI_TRUE;
1078 if (version == JNI_VERSION_10) return JNI_TRUE;
1079 if (version == JNI_VERSION_19) return JNI_TRUE;
1080 if (version == JNI_VERSION_20) return JNI_TRUE;
1081 if (version == JNI_VERSION_21) return JNI_TRUE;
1082 if (version == JNI_VERSION_24) return JNI_TRUE;
1083 return JNI_FALSE;
1084 }
1085
1086 void Threads::add(JavaThread* p, bool force_daemon) {
1087 // The threads lock must be owned at this point
1088 assert(Threads_lock->owned_by_self(), "must have threads lock");
1089 assert(p->monitor_owner_id() != 0, "should be set");
1090
1091 BarrierSet::barrier_set()->on_thread_attach(p);
1092
1093 // Once a JavaThread is added to the Threads list, smr_delete() has
1094 // to be used to delete it. Otherwise we can just delete it directly.
1095 p->set_on_thread_list();
1096
1097 _number_of_threads++;
1098 oop threadObj = p->threadObj();
1099 bool daemon = true;
1100 // Bootstrapping problem: threadObj can be null for initial
1101 // JavaThread (or for threads attached via JNI)
1102 if (!force_daemon &&
1103 (threadObj == nullptr || !java_lang_Thread::is_daemon(threadObj))) {
1104 _number_of_non_daemon_threads++;
1105 daemon = false;
1106 }
1107
1108 ThreadService::add_thread(p, daemon);
1109
1110 // Maintain fast thread list
1111 ThreadsSMRSupport::add_thread(p);
1112
1113 // Increase the ObjectMonitor ceiling for the new thread.
1114 ObjectSynchronizer::inc_in_use_list_ceiling();
1115
1116 // Possible GC point.
1117 Events::log(Thread::current(), "Thread added: " INTPTR_FORMAT, p2i(p));
1118
1119 // Make new thread known to active EscapeBarrier
1120 EscapeBarrier::thread_added(p);
1121 }
1122
1123 void Threads::remove(JavaThread* p, bool is_daemon) {
1124 // Extra scope needed for Thread_lock, so we can check
1125 // that we do not remove thread without safepoint code notice
1126 {
1127 ConditionalMutexLocker throttle_ml(ThreadsLockThrottle_lock, UseThreadsLockThrottleLock);
1128 MonitorLocker ml(Threads_lock);
1129
1130 if (ThreadIdTable::is_initialized()) {
1131 // This cleanup must be done before the current thread's GC barrier
1132 // is detached since we need to touch the threadObj oop.
1133 jlong tid = SharedRuntime::get_java_tid(p);
1134 ThreadIdTable::remove_thread(tid);
1135 }
1136
1137 // BarrierSet state must be destroyed after the last thread transition
1138 // before the thread terminates. Thread transitions result in calls to
1139 // StackWatermarkSet::on_safepoint(), which performs GC processing,
1140 // requiring the GC state to be alive.
1141 BarrierSet::barrier_set()->on_thread_detach(p);
1142 if (p->is_exiting()) {
1143 // If we got here via JavaThread::exit(), then we remember that the
1144 // thread's GC barrier has been detached. We don't do this when we get
1145 // here from another path, e.g., cleanup_failed_attach_current_thread().
1146 p->set_terminated(JavaThread::_thread_gc_barrier_detached);
1147 }
1148
1149 assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present");
1150
1151 // Maintain fast thread list
1152 ThreadsSMRSupport::remove_thread(p);
1153
1154 _number_of_threads--;
1155 if (!is_daemon) {
1156 _number_of_non_daemon_threads--;
1157
1158 // If this is the last non-daemon thread then we need to do
1159 // a notify on the Threads_lock so a thread waiting
1160 // on destroy_vm will wake up. But that thread could be a daemon
1161 // or non-daemon, so we notify for both the 0 and 1 case.
1162 if (number_of_non_daemon_threads() <= 1) {
1163 ml.notify_all();
1164 }
1165 }
1166 ThreadService::remove_thread(p, is_daemon);
1167
1168 // Make sure that safepoint code disregard this thread. This is needed since
1169 // the thread might mess around with locks after this point. This can cause it
1170 // to do callbacks into the safepoint code. However, the safepoint code is not aware
1171 // of this thread since it is removed from the queue.
1172 p->set_terminated(JavaThread::_thread_terminated);
1173
1174 // Notify threads waiting in EscapeBarriers
1175 EscapeBarrier::thread_removed(p);
1176 } // unlock Threads_lock and ThreadsLockThrottle_lock
1177
1178 // Reduce the ObjectMonitor ceiling for the exiting thread.
1179 ObjectSynchronizer::dec_in_use_list_ceiling();
1180
1181 // Since Events::log uses a lock, we grab it outside the Threads_lock
1182 Events::log(Thread::current(), "Thread exited: " INTPTR_FORMAT, p2i(p));
1183 }
1184
1185 // Operations on the Threads list for GC. These are not explicitly locked,
1186 // but the garbage collector must provide a safe context for them to run.
1187 // In particular, these things should never be called when the Threads_lock
1188 // is held by some other thread. (Note: the Safepoint abstraction also
1189 // uses the Threads_lock to guarantee this property. It also makes sure that
1190 // all threads gets blocked when exiting or starting).
1191
1192 void Threads::oops_do(OopClosure* f, NMethodClosure* cf) {
1193 ALL_JAVA_THREADS(p) {
1194 p->oops_do(f, cf);
1195 }
1196 VMThread::vm_thread()->oops_do(f, cf);
1197 }
1198
1199 void Threads::change_thread_claim_token() {
1200 if (++_thread_claim_token == 0) {
1201 // On overflow of the token counter, there is a risk of future
1202 // collisions between a new global token value and a stale token
1203 // for a thread, because not all iterations visit all threads.
1204 // (Though it's pretty much a theoretical concern for non-trivial
1205 // token counter sizes.) To deal with the possibility, reset all
1206 // the thread tokens to zero on global token overflow.
1207 struct ResetClaims : public ThreadClosure {
1208 virtual void do_thread(Thread* t) {
1209 t->claim_threads_do(false, 0);
1210 }
1211 } reset_claims;
1212 Threads::threads_do(&reset_claims);
1213 // On overflow, update the global token to non-zero, to
1214 // avoid the special "never claimed" initial thread value.
1215 _thread_claim_token = 1;
1216 }
1217 }
1218
1219 #ifdef ASSERT
1220 static void assert_thread_claimed(const char* kind, Thread* t, uintx expected) {
1221 const uintx token = t->threads_do_token();
1222 assert(token == expected,
1223 "%s " PTR_FORMAT " has incorrect value %zu != %zu",
1224 kind, p2i(t), token, expected);
1225 }
1226
1227 void Threads::assert_all_threads_claimed() {
1228 ALL_JAVA_THREADS(p) {
1229 assert_thread_claimed("JavaThread", p, _thread_claim_token);
1230 }
1231
1232 struct NJTClaimedVerifierClosure : public ThreadClosure {
1233 uintx _thread_claim_token;
1234
1235 NJTClaimedVerifierClosure(uintx thread_claim_token) : ThreadClosure(), _thread_claim_token(thread_claim_token) { }
1236
1237 virtual void do_thread(Thread* thread) override {
1238 assert_thread_claimed("Non-JavaThread", VMThread::vm_thread(), _thread_claim_token);
1239 }
1240 } tc(_thread_claim_token);
1241
1242 non_java_threads_do(&tc);
1243 }
1244 #endif // ASSERT
1245
1246 class ParallelOopsDoThreadClosure : public ThreadClosure {
1247 private:
1248 OopClosure* _f;
1249 NMethodClosure* _cf;
1250 public:
1251 ParallelOopsDoThreadClosure(OopClosure* f, NMethodClosure* cf) : _f(f), _cf(cf) {}
1252 void do_thread(Thread* t) {
1253 t->oops_do(_f, _cf);
1254 }
1255 };
1256
1257 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, NMethodClosure* cf) {
1258 ParallelOopsDoThreadClosure tc(f, cf);
1259 possibly_parallel_threads_do(is_par, &tc);
1260 }
1261
1262 void Threads::metadata_do(MetadataClosure* f) {
1263 ALL_JAVA_THREADS(p) {
1264 p->metadata_do(f);
1265 }
1266 }
1267
1268 class ThreadHandlesClosure : public ThreadClosure {
1269 void (*_f)(Metadata*);
1270 public:
1271 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
1272 virtual void do_thread(Thread* thread) {
1273 thread->metadata_handles_do(_f);
1274 }
1275 };
1276
1277 void Threads::metadata_handles_do(void f(Metadata*)) {
1278 // Only walk the Handles in Thread.
1279 ThreadHandlesClosure handles_closure(f);
1280 threads_do(&handles_closure);
1281 }
1282
1283 #if INCLUDE_JVMTI
1284 // Get Java threads that are waiting to enter or re-enter the specified monitor.
1285 // Java threads that are executing mounted virtual threads are not included.
1286 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list,
1287 int count,
1288 address monitor) {
1289 assert(Thread::current()->is_VM_thread(), "Must be the VM thread");
1290 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
1291
1292 int i = 0;
1293 for (JavaThread* p : *t_list) {
1294 if (!p->can_call_java()) continue;
1295
1296 oop thread_oop = JvmtiEnvBase::get_vthread_or_thread_oop(p);
1297 if (thread_oop->is_a(vmClasses::BaseVirtualThread_klass())) {
1298 continue;
1299 }
1300 // The first stage of async deflation does not affect any field
1301 // used by this comparison so the ObjectMonitor* is usable here.
1302 address pending = (address)p->current_pending_monitor();
1303 address waiting = (address)p->current_waiting_monitor();
1304 // do not include virtual threads to the list
1305 jint state = JvmtiEnvBase::get_thread_state(thread_oop, p);
1306 if (pending == monitor || (waiting == monitor &&
1307 (state & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER))
1308 ) { // found a match
1309 if (i < count) result->append(p); // save the first count matches
1310 i++;
1311 }
1312 }
1313
1314 return result;
1315 }
1316 #endif // INCLUDE_JVMTI
1317
1318 JavaThread* Threads::owning_thread_from_object(ThreadsList * t_list, oop obj) {
1319 for (JavaThread* q : *t_list) {
1320 // Need to start processing before accessing oops in the thread.
1321 StackWatermark* watermark = StackWatermarkSet::get(q, StackWatermarkKind::gc);
1322 if (watermark != nullptr) {
1323 watermark->start_processing();
1324 }
1325
1326 if (q->lock_stack().contains(obj)) {
1327 return q;
1328 }
1329 }
1330 return nullptr;
1331 }
1332
1333 JavaThread* Threads::owning_thread_from_monitor(ThreadsList* t_list, ObjectMonitor* monitor) {
1334 if (monitor->has_anonymous_owner()) {
1335 return owning_thread_from_object(t_list, monitor->object());
1336 } else {
1337 JavaThread* the_owner = nullptr;
1338 for (JavaThread* q : *t_list) {
1339 if (monitor->has_owner(q)) {
1340 the_owner = q;
1341 break;
1342 }
1343 }
1344 return the_owner;
1345 }
1346 }
1347
1348 class PrintOnClosure : public ThreadClosure {
1349 private:
1350 outputStream* _st;
1351
1352 public:
1353 PrintOnClosure(outputStream* st) :
1354 _st(st) {}
1355
1356 virtual void do_thread(Thread* thread) {
1357 if (thread != nullptr) {
1358 thread->print_on(_st);
1359 _st->cr();
1360 }
1361 }
1362 };
1363
1364 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
1365 void Threads::print_on(outputStream* st, bool print_stacks,
1366 bool internal_format, bool print_concurrent_locks,
1367 bool print_extended_info) {
1368 char buf[32];
1369 st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
1370
1371 st->print_cr("Full thread dump %s (%s %s)",
1372 VM_Version::vm_name(),
1373 VM_Version::vm_release(),
1374 VM_Version::vm_info_string());
1375 JDK_Version::current().to_string(buf, sizeof(buf));
1376 const char* runtime_name = JDK_Version::runtime_name() != nullptr ?
1377 JDK_Version::runtime_name() : "";
1378 const char* runtime_version = JDK_Version::runtime_version() != nullptr ?
1379 JDK_Version::runtime_version() : "";
1380 const char* vendor_version = JDK_Version::runtime_vendor_version() != nullptr ?
1381 JDK_Version::runtime_vendor_version() : "";
1382 const char* jdk_debug_level = VM_Version::printable_jdk_debug_level() != nullptr ?
1383 VM_Version::printable_jdk_debug_level() : "";
1384
1385 st->print_cr(" JDK version: %s%s%s (%s) (%sbuild %s)", runtime_name,
1386 (*vendor_version != '\0') ? " " : "", vendor_version,
1387 buf, jdk_debug_level, runtime_version);
1388
1389 st->cr();
1390
1391 #if INCLUDE_SERVICES
1392 // Dump concurrent locks
1393 ConcurrentLocksDump concurrent_locks;
1394 if (print_concurrent_locks) {
1395 concurrent_locks.dump_at_safepoint();
1396 }
1397 #endif // INCLUDE_SERVICES
1398
1399 ThreadsSMRSupport::print_info_on(st);
1400 st->cr();
1401
1402 ALL_JAVA_THREADS(p) {
1403 ResourceMark rm;
1404 p->print_on(st, print_extended_info);
1405 if (print_stacks) {
1406 if (internal_format) {
1407 p->trace_stack();
1408 } else {
1409 p->print_stack_on(st);
1410 if (p->is_vthread_mounted()) {
1411 st->print_cr(" Mounted virtual thread #" INT64_FORMAT, java_lang_Thread::thread_id(p->vthread()));
1412 p->print_vthread_stack_on(st);
1413 }
1414 }
1415 }
1416 st->cr();
1417 #if INCLUDE_SERVICES
1418 if (print_concurrent_locks) {
1419 concurrent_locks.print_locks_on(p, st);
1420 }
1421 #endif // INCLUDE_SERVICES
1422 }
1423
1424 PrintOnClosure cl(st);
1425 non_java_threads_do(&cl);
1426
1427 st->flush();
1428 }
1429
1430 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
1431 int buflen, bool* found_current) {
1432 if (this_thread != nullptr) {
1433 bool is_current = (current == this_thread);
1434 *found_current = *found_current || is_current;
1435 st->print("%s", is_current ? "=>" : " ");
1436
1437 st->print(PTR_FORMAT, p2i(this_thread));
1438 st->print(" ");
1439 this_thread->print_on_error(st, buf, buflen);
1440 st->cr();
1441 }
1442 }
1443
1444 class PrintOnErrorClosure : public ThreadClosure {
1445 outputStream* _st;
1446 Thread* _current;
1447 char* _buf;
1448 int _buflen;
1449 bool* _found_current;
1450 unsigned _num_printed;
1451 public:
1452 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf,
1453 int buflen, bool* found_current) :
1454 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current),
1455 _num_printed(0) {}
1456
1457 virtual void do_thread(Thread* thread) {
1458 _num_printed++;
1459 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current);
1460 }
1461
1462 unsigned num_printed() const { return _num_printed; }
1463 };
1464
1465 // Threads::print_on_error() is called by fatal error handler. It's possible
1466 // that VM is not at safepoint and/or current thread is inside signal handler.
1467 // Don't print stack trace, as the stack may not be walkable. Don't allocate
1468 // memory (even in resource area), it might deadlock the error handler.
1469 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
1470 int buflen) {
1471 ThreadsSMRSupport::print_info_on(st);
1472 st->cr();
1473
1474 bool found_current = false;
1475 st->print_cr("Java Threads: ( => current thread )");
1476 unsigned num_java = 0;
1477 ALL_JAVA_THREADS(thread) {
1478 print_on_error(thread, st, current, buf, buflen, &found_current);
1479 num_java++;
1480 }
1481 st->print_cr("Total: %u", num_java);
1482 st->cr();
1483
1484 st->print_cr("Other Threads:");
1485 unsigned num_other = ((VMThread::vm_thread() != nullptr) ? 1 : 0) +
1486 ((WatcherThread::watcher_thread() != nullptr) ? 1 : 0) +
1487 ((AsyncLogWriter::instance() != nullptr) ? 1 : 0);
1488 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current);
1489 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current);
1490 print_on_error(AsyncLogWriter::instance(), st, current, buf, buflen, &found_current);
1491
1492 if (Universe::heap() != nullptr) {
1493 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
1494 Universe::heap()->gc_threads_do(&print_closure);
1495 num_other += print_closure.num_printed();
1496 }
1497
1498 if (!found_current) {
1499 st->cr();
1500 st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
1501 current->print_on_error(st, buf, buflen);
1502 num_other++;
1503 st->cr();
1504 }
1505 st->print_cr("Total: %u", num_other);
1506 st->cr();
1507
1508 st->print_cr("Threads with active compile tasks:");
1509 unsigned num = print_threads_compiling(st, buf, buflen);
1510 st->print_cr("Total: %u", num);
1511 }
1512
1513 unsigned Threads::print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form) {
1514 unsigned num = 0;
1515 ALL_JAVA_THREADS(thread) {
1516 if (thread->is_Compiler_thread()) {
1517 CompilerThread* ct = (CompilerThread*) thread;
1518
1519 // Keep task in local variable for null check.
1520 // ct->_task might be set to null by concurring compiler thread
1521 // because it completed the compilation. The task is never freed,
1522 // though, just returned to a free list.
1523 CompileTask* task = ct->task();
1524 if (task != nullptr) {
1525 thread->print_name_on_error(st, buf, buflen);
1526 st->print(" ");
1527 task->print(st, nullptr, short_form, true);
1528 num++;
1529 }
1530 }
1531 }
1532 return num;
1533 }
1534
1535 void Threads::verify() {
1536 ALL_JAVA_THREADS(p) {
1537 p->verify();
1538 }
1539 VMThread* thread = VMThread::vm_thread();
1540 if (thread != nullptr) thread->verify();
1541 }