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