1 /*
2 * Copyright (c) 1997, 2021, 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 "precompiled.hpp"
27 #include "jvm.h"
28 #include "cds/dynamicArchive.hpp"
29 #include "cds/metaspaceShared.hpp"
30 #include "classfile/classLoader.hpp"
31 #include "classfile/javaClasses.hpp"
32 #include "classfile/javaThreadStatus.hpp"
33 #include "classfile/systemDictionary.hpp"
34 #include "classfile/vmClasses.hpp"
35 #include "classfile/vmSymbols.hpp"
36 #include "code/codeCache.hpp"
37 #include "code/scopeDesc.hpp"
38 #include "compiler/compileBroker.hpp"
39 #include "compiler/compileTask.hpp"
40 #include "compiler/compilerThread.hpp"
41 #include "gc/shared/barrierSet.hpp"
42 #include "gc/shared/collectedHeap.hpp"
43 #include "gc/shared/gcId.hpp"
44 #include "gc/shared/gcLocker.inline.hpp"
45 #include "gc/shared/gcVMOperations.hpp"
46 #include "gc/shared/oopStorage.hpp"
47 #include "gc/shared/oopStorageSet.hpp"
48 #include "gc/shared/stringdedup/stringDedup.hpp"
49 #include "gc/shared/tlab_globals.hpp"
50 #include "interpreter/interpreter.hpp"
51 #include "interpreter/linkResolver.hpp"
52 #include "interpreter/oopMapCache.hpp"
53 #include "jfr/jfrEvents.hpp"
54 #include "jvmtifiles/jvmtiEnv.hpp"
55 #include "logging/log.hpp"
56 #include "logging/logAsyncWriter.hpp"
57 #include "logging/logConfiguration.hpp"
58 #include "logging/logStream.hpp"
59 #include "memory/allocation.inline.hpp"
60 #include "memory/iterator.hpp"
61 #include "memory/oopFactory.hpp"
62 #include "memory/resourceArea.hpp"
63 #include "memory/universe.hpp"
64 #include "oops/access.inline.hpp"
65 #include "oops/instanceKlass.hpp"
66 #include "oops/klass.inline.hpp"
67 #include "oops/objArrayOop.hpp"
68 #include "oops/oop.inline.hpp"
69 #include "oops/oopHandle.inline.hpp"
70 #include "oops/symbol.hpp"
71 #include "oops/typeArrayOop.inline.hpp"
72 #include "oops/verifyOopClosure.hpp"
73 #include "prims/jvm_misc.hpp"
74 #include "prims/jvmtiDeferredUpdates.hpp"
75 #include "prims/jvmtiExport.hpp"
76 #include "prims/jvmtiThreadState.hpp"
77 #include "runtime/arguments.hpp"
78 #include "runtime/atomic.hpp"
79 #include "runtime/biasedLocking.hpp"
80 #include "runtime/fieldDescriptor.inline.hpp"
81 #include "runtime/flags/jvmFlagLimit.hpp"
82 #include "runtime/deoptimization.hpp"
83 #include "runtime/frame.inline.hpp"
84 #include "runtime/handles.inline.hpp"
85 #include "runtime/handshake.hpp"
86 #include "runtime/init.hpp"
87 #include "runtime/interfaceSupport.inline.hpp"
88 #include "runtime/java.hpp"
89 #include "runtime/javaCalls.hpp"
90 #include "runtime/jniHandles.inline.hpp"
91 #include "runtime/jniPeriodicChecker.hpp"
92 #include "runtime/lockStack.inline.hpp"
93 #include "runtime/monitorDeflationThread.hpp"
94 #include "runtime/mutexLocker.hpp"
95 #include "runtime/nonJavaThread.hpp"
96 #include "runtime/objectMonitor.inline.hpp"
97 #include "runtime/orderAccess.hpp"
98 #include "runtime/osThread.hpp"
99 #include "runtime/prefetch.inline.hpp"
100 #include "runtime/safepoint.hpp"
101 #include "runtime/safepointMechanism.inline.hpp"
102 #include "runtime/safepointVerifiers.hpp"
103 #include "runtime/serviceThread.hpp"
104 #include "runtime/sharedRuntime.hpp"
105 #include "runtime/stackFrameStream.inline.hpp"
106 #include "runtime/stackWatermarkSet.inline.hpp"
107 #include "runtime/statSampler.hpp"
108 #include "runtime/task.hpp"
109 #include "runtime/thread.inline.hpp"
110 #include "runtime/threadCritical.hpp"
111 #include "runtime/threadSMR.inline.hpp"
112 #include "runtime/threadStatisticalInfo.hpp"
113 #include "runtime/threadWXSetters.inline.hpp"
114 #include "runtime/timer.hpp"
115 #include "runtime/timerTrace.hpp"
116 #include "runtime/trimNativeHeap.hpp"
117 #include "runtime/vframe.inline.hpp"
118 #include "runtime/vframeArray.hpp"
119 #include "runtime/vframe_hp.hpp"
120 #include "runtime/vmThread.hpp"
121 #include "runtime/vmOperations.hpp"
122 #include "runtime/vm_version.hpp"
123 #include "services/attachListener.hpp"
124 #include "services/management.hpp"
125 #include "services/memTracker.hpp"
126 #include "services/threadService.hpp"
127 #include "utilities/align.hpp"
128 #include "utilities/copy.hpp"
129 #include "utilities/defaultStream.hpp"
130 #include "utilities/dtrace.hpp"
131 #include "utilities/events.hpp"
132 #include "utilities/macros.hpp"
133 #include "utilities/preserveException.hpp"
134 #include "utilities/spinYield.hpp"
135 #include "utilities/vmError.hpp"
136 #if INCLUDE_JVMCI
137 #include "jvmci/jvmci.hpp"
138 #include "jvmci/jvmciEnv.hpp"
139 #endif
140 #ifdef COMPILER1
141 #include "c1/c1_Compiler.hpp"
142 #endif
143 #ifdef COMPILER2
144 #include "opto/c2compiler.hpp"
145 #include "opto/idealGraphPrinter.hpp"
146 #endif
147 #if INCLUDE_RTM_OPT
148 #include "runtime/rtmLocking.hpp"
149 #endif
150 #if INCLUDE_JFR
151 #include "jfr/jfr.hpp"
152 #endif
153 #if INCLUDE_VM_STRUCTS
154 #include "runtime/vmStructs.hpp"
155 #endif
156
157 // Initialization after module runtime initialization
158 void universe_post_module_init(); // must happen after call_initPhase2
159
160 #ifdef DTRACE_ENABLED
161
162 // Only bother with this argument setup if dtrace is available
163
164 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
165 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
166
167 #define DTRACE_THREAD_PROBE(probe, javathread) \
168 { \
169 ResourceMark rm(this); \
170 int len = 0; \
171 const char* name = (javathread)->get_thread_name(); \
172 len = strlen(name); \
173 HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */ \
174 (char *) name, len, \
175 java_lang_Thread::thread_id((javathread)->threadObj()), \
176 (uintptr_t) (javathread)->osthread()->thread_id(), \
177 java_lang_Thread::is_daemon((javathread)->threadObj())); \
178 }
179
180 #else // ndef DTRACE_ENABLED
181
182 #define DTRACE_THREAD_PROBE(probe, javathread)
183
184 #endif // ndef DTRACE_ENABLED
185
186 #ifndef USE_LIBRARY_BASED_TLS_ONLY
187 // Current thread is maintained as a thread-local variable
188 THREAD_LOCAL Thread* Thread::_thr_current = NULL;
189 #endif
190
191 // ======= Thread ========
192 // Support for forcing alignment of thread objects for biased locking
193 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
194 if (UseBiasedLocking) {
195 const size_t alignment = markWord::biased_lock_alignment;
196 size_t aligned_size = size + (alignment - sizeof(intptr_t));
197 void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC)
198 : AllocateHeap(aligned_size, flags, CURRENT_PC,
199 AllocFailStrategy::RETURN_NULL);
200 void* aligned_addr = align_up(real_malloc_addr, alignment);
201 assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
202 ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
203 "JavaThread alignment code overflowed allocated storage");
204 if (aligned_addr != real_malloc_addr) {
205 log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
206 p2i(real_malloc_addr),
207 p2i(aligned_addr));
208 }
209 ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
210 return aligned_addr;
211 } else {
212 return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
213 : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
214 }
215 }
216
217 void Thread::operator delete(void* p) {
218 if (UseBiasedLocking) {
219 FreeHeap(((Thread*) p)->_real_malloc_address);
220 } else {
221 FreeHeap(p);
222 }
223 }
224
225 void JavaThread::smr_delete() {
226 if (_on_thread_list) {
227 ThreadsSMRSupport::smr_delete(this);
228 } else {
229 delete this;
230 }
231 }
232
233 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
234 // JavaThread
235
236 DEBUG_ONLY(Thread* Thread::_starting_thread = NULL;)
237
238 Thread::Thread() {
239
240 DEBUG_ONLY(_run_state = PRE_CALL_RUN;)
241
242 // stack and get_thread
243 set_stack_base(NULL);
244 set_stack_size(0);
245 set_lgrp_id(-1);
246 DEBUG_ONLY(clear_suspendible_thread();)
247
248 // allocated data structures
249 set_osthread(NULL);
250 set_resource_area(new (mtThread)ResourceArea());
251 DEBUG_ONLY(_current_resource_mark = NULL;)
252 set_handle_area(new (mtThread) HandleArea(NULL));
253 set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, mtClass));
254 set_active_handles(NULL);
255 set_free_handle_block(NULL);
256 set_last_handle_mark(NULL);
257 DEBUG_ONLY(_missed_ic_stub_refill_verifier = NULL);
258
259 // Initial value of zero ==> never claimed.
260 _threads_do_token = 0;
261 _threads_hazard_ptr = NULL;
262 _threads_list_ptr = NULL;
263 _nested_threads_hazard_ptr_cnt = 0;
264 _rcu_counter = 0;
265
266 // the handle mark links itself to last_handle_mark
267 new HandleMark(this);
268
269 // plain initialization
270 debug_only(_owned_locks = NULL;)
271 NOT_PRODUCT(_skip_gcalot = false;)
272 _jvmti_env_iteration_count = 0;
273 set_allocated_bytes(0);
274 _current_pending_raw_monitor = NULL;
275
276 // thread-specific hashCode stream generator state - Marsaglia shift-xor form
277 _hashStateX = os::random();
278 _hashStateY = 842502087;
279 _hashStateZ = 0x8767; // (int)(3579807591LL & 0xffff) ;
280 _hashStateW = 273326509;
281
282 // Many of the following fields are effectively final - immutable
283 // Note that nascent threads can't use the Native Monitor-Mutex
284 // construct until the _MutexEvent is initialized ...
285 // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
286 // we might instead use a stack of ParkEvents that we could provision on-demand.
287 // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
288 // and ::Release()
289 _ParkEvent = ParkEvent::Allocate(this);
290
291 #ifdef CHECK_UNHANDLED_OOPS
292 if (CheckUnhandledOops) {
293 _unhandled_oops = new UnhandledOops(this);
294 }
295 #endif // CHECK_UNHANDLED_OOPS
296 #ifdef ASSERT
297 if (UseBiasedLocking) {
298 assert(is_aligned(this, markWord::biased_lock_alignment), "forced alignment of thread object failed");
299 assert(this == _real_malloc_address ||
300 this == align_up(_real_malloc_address, markWord::biased_lock_alignment),
301 "bug in forced alignment of thread objects");
302 }
303 #endif // ASSERT
304
305 // Notify the barrier set that a thread is being created. The initial
306 // thread is created before the barrier set is available. The call to
307 // BarrierSet::on_thread_create() for this thread is therefore deferred
308 // to BarrierSet::set_barrier_set().
309 BarrierSet* const barrier_set = BarrierSet::barrier_set();
310 if (barrier_set != NULL) {
311 barrier_set->on_thread_create(this);
312 } else {
313 // Only the main thread should be created before the barrier set
314 // and that happens just before Thread::current is set. No other thread
315 // can attach as the VM is not created yet, so they can't execute this code.
316 // If the main thread creates other threads before the barrier set that is an error.
317 assert(Thread::current_or_null() == NULL, "creating thread before barrier set");
318 }
319
320 MACOS_AARCH64_ONLY(DEBUG_ONLY(_wx_init = false));
321 }
322
323 void Thread::initialize_tlab() {
324 if (UseTLAB) {
325 tlab().initialize();
326 }
327 }
328
329 void Thread::initialize_thread_current() {
330 #ifndef USE_LIBRARY_BASED_TLS_ONLY
331 assert(_thr_current == NULL, "Thread::current already initialized");
332 _thr_current = this;
333 #endif
334 assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized");
335 ThreadLocalStorage::set_thread(this);
336 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
337 }
338
339 void Thread::clear_thread_current() {
340 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
341 #ifndef USE_LIBRARY_BASED_TLS_ONLY
342 _thr_current = NULL;
343 #endif
344 ThreadLocalStorage::set_thread(NULL);
345 }
346
347 void Thread::record_stack_base_and_size() {
348 // Note: at this point, Thread object is not yet initialized. Do not rely on
349 // any members being initialized. Do not rely on Thread::current() being set.
350 // If possible, refrain from doing anything which may crash or assert since
351 // quite probably those crash dumps will be useless.
352 set_stack_base(os::current_stack_base());
353 set_stack_size(os::current_stack_size());
354
355 // Set stack limits after thread is initialized.
356 if (is_Java_thread()) {
357 as_Java_thread()->stack_overflow_state()->initialize(stack_base(), stack_end());
358 }
359 }
360
361 #if INCLUDE_NMT
362 void Thread::register_thread_stack_with_NMT() {
363 MemTracker::record_thread_stack(stack_end(), stack_size());
364 }
365
366 void Thread::unregister_thread_stack_with_NMT() {
367 MemTracker::release_thread_stack(stack_end(), stack_size());
368 }
369 #endif // INCLUDE_NMT
370
371 void Thread::call_run() {
372 DEBUG_ONLY(_run_state = CALL_RUN;)
373
374 // At this point, Thread object should be fully initialized and
375 // Thread::current() should be set.
376
377 assert(Thread::current_or_null() != NULL, "current thread is unset");
378 assert(Thread::current_or_null() == this, "current thread is wrong");
379
380 // Perform common initialization actions
381
382 MACOS_AARCH64_ONLY(this->init_wx());
383
384 register_thread_stack_with_NMT();
385
386 JFR_ONLY(Jfr::on_thread_start(this);)
387
388 log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: "
389 PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).",
390 os::current_thread_id(), p2i(stack_end()),
391 p2i(stack_base()), stack_size()/1024);
392
393 // Perform <ChildClass> initialization actions
394 DEBUG_ONLY(_run_state = PRE_RUN;)
395 this->pre_run();
396
397 // Invoke <ChildClass>::run()
398 DEBUG_ONLY(_run_state = RUN;)
399 this->run();
400 // Returned from <ChildClass>::run(). Thread finished.
401
402 // Perform common tear-down actions
403
404 assert(Thread::current_or_null() != NULL, "current thread is unset");
405 assert(Thread::current_or_null() == this, "current thread is wrong");
406
407 // Perform <ChildClass> tear-down actions
408 DEBUG_ONLY(_run_state = POST_RUN;)
409 this->post_run();
410
411 // Note: at this point the thread object may already have deleted itself,
412 // so from here on do not dereference *this*. Not all thread types currently
413 // delete themselves when they terminate. But no thread should ever be deleted
414 // asynchronously with respect to its termination - that is what _run_state can
415 // be used to check.
416
417 assert(Thread::current_or_null() == NULL, "current thread still present");
418 }
419
420 Thread::~Thread() {
421
422 // Attached threads will remain in PRE_CALL_RUN, as will threads that don't actually
423 // get started due to errors etc. Any active thread should at least reach post_run
424 // before it is deleted (usually in post_run()).
425 assert(_run_state == PRE_CALL_RUN ||
426 _run_state == POST_RUN, "Active Thread deleted before post_run(): "
427 "_run_state=%d", (int)_run_state);
428
429 // Notify the barrier set that a thread is being destroyed. Note that a barrier
430 // set might not be available if we encountered errors during bootstrapping.
431 BarrierSet* const barrier_set = BarrierSet::barrier_set();
432 if (barrier_set != NULL) {
433 barrier_set->on_thread_destroy(this);
434 }
435
436 // deallocate data structures
437 delete resource_area();
438 // since the handle marks are using the handle area, we have to deallocated the root
439 // handle mark before deallocating the thread's handle area,
440 assert(last_handle_mark() != NULL, "check we have an element");
441 delete last_handle_mark();
442 assert(last_handle_mark() == NULL, "check we have reached the end");
443
444 ParkEvent::Release(_ParkEvent);
445 // Set to NULL as a termination indicator for has_terminated().
446 Atomic::store(&_ParkEvent, (ParkEvent*)NULL);
447
448 delete handle_area();
449 delete metadata_handles();
450
451 // osthread() can be NULL, if creation of thread failed.
452 if (osthread() != NULL) os::free_thread(osthread());
453
454 // Clear Thread::current if thread is deleting itself and it has not
455 // already been done. This must be done before the memory is deallocated.
456 // Needed to ensure JNI correctly detects non-attached threads.
457 if (this == Thread::current_or_null()) {
458 Thread::clear_thread_current();
459 }
460
461 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
462 }
463
464 #ifdef ASSERT
465 // A JavaThread is considered dangling if it not handshake-safe with respect to
466 // the current thread, it is not on a ThreadsList, or not at safepoint.
467 void Thread::check_for_dangling_thread_pointer(Thread *thread) {
468 assert(!thread->is_Java_thread() ||
469 thread->as_Java_thread()->is_handshake_safe_for(Thread::current()) ||
470 !thread->as_Java_thread()->on_thread_list() ||
471 SafepointSynchronize::is_at_safepoint() ||
472 ThreadsSMRSupport::is_a_protected_JavaThread_with_lock(thread->as_Java_thread()),
473 "possibility of dangling Thread pointer");
474 }
475 #endif
476
477 // Is the target JavaThread protected by the calling Thread
478 // or by some other mechanism:
479 bool Thread::is_JavaThread_protected(const JavaThread* p) {
480 // Do the simplest check first:
481 if (SafepointSynchronize::is_at_safepoint()) {
482 // The target is protected since JavaThreads cannot exit
483 // while we're at a safepoint.
484 return true;
485 }
486
487 // If the target hasn't been started yet then it is trivially
488 // "protected". We assume the caller is the thread that will do
489 // the starting.
490 if (p->osthread() == NULL || p->osthread()->get_state() <= INITIALIZED) {
491 return true;
492 }
493
494 // Now make the simple checks based on who the caller is:
495 Thread* current_thread = Thread::current();
496 if (current_thread == p || Threads_lock->owner() == current_thread) {
497 // Target JavaThread is self or calling thread owns the Threads_lock.
498 // Second check is the same as Threads_lock->owner_is_self(),
499 // but we already have the current thread so check directly.
500 return true;
501 }
502
503 // Check the ThreadsLists associated with the calling thread (if any)
504 // to see if one of them protects the target JavaThread:
505 for (SafeThreadsListPtr* stlp = current_thread->_threads_list_ptr;
506 stlp != NULL; stlp = stlp->previous()) {
507 if (stlp->list()->includes(p)) {
508 // The target JavaThread is protected by this ThreadsList:
509 return true;
510 }
511 }
512
513 // Use this debug code with -XX:+UseNewCode to diagnose locations that
514 // are missing a ThreadsListHandle or other protection mechanism:
515 // guarantee(!UseNewCode, "current_thread=" INTPTR_FORMAT " is not protecting p="
516 // INTPTR_FORMAT, p2i(current_thread), p2i(p));
517
518 // Note: Since 'p' isn't protected by a TLH, the call to
519 // p->is_handshake_safe_for() may crash, but we have debug bits so
520 // we'll be able to figure out what protection mechanism is missing.
521 assert(p->is_handshake_safe_for(current_thread), "JavaThread=" INTPTR_FORMAT
522 " is not protected and not handshake safe.", p2i(p));
523
524 // The target JavaThread is not protected so it is not safe to query:
525 return false;
526 }
527
528 ThreadPriority Thread::get_priority(const Thread* const thread) {
529 ThreadPriority priority;
530 // Can return an error!
531 (void)os::get_priority(thread, priority);
532 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
533 return priority;
534 }
535
536 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
537 debug_only(check_for_dangling_thread_pointer(thread);)
538 // Can return an error!
539 (void)os::set_priority(thread, priority);
540 }
541
542
543 void Thread::start(Thread* thread) {
544 // Start is different from resume in that its safety is guaranteed by context or
545 // being called from a Java method synchronized on the Thread object.
546 if (thread->is_Java_thread()) {
547 // Initialize the thread state to RUNNABLE before starting this thread.
548 // Can not set it after the thread started because we do not know the
549 // exact thread state at that time. It could be in MONITOR_WAIT or
550 // in SLEEPING or some other state.
551 java_lang_Thread::set_thread_status(thread->as_Java_thread()->threadObj(),
552 JavaThreadStatus::RUNNABLE);
553 }
554 os::start_thread(thread);
555 }
556
557 // GC Support
558 bool Thread::claim_par_threads_do(uintx claim_token) {
559 uintx token = _threads_do_token;
560 if (token != claim_token) {
561 uintx res = Atomic::cmpxchg(&_threads_do_token, token, claim_token);
562 if (res == token) {
563 return true;
564 }
565 guarantee(res == claim_token, "invariant");
566 }
567 return false;
568 }
569
570 void Thread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) {
571 if (active_handles() != NULL) {
572 active_handles()->oops_do(f);
573 }
574 // Do oop for ThreadShadow
575 f->do_oop((oop*)&_pending_exception);
576 handle_area()->oops_do(f);
577 }
578
579 // If the caller is a NamedThread, then remember, in the current scope,
580 // the given JavaThread in its _processed_thread field.
581 class RememberProcessedThread: public StackObj {
582 NamedThread* _cur_thr;
583 public:
584 RememberProcessedThread(Thread* thread) {
585 Thread* self = Thread::current();
586 if (self->is_Named_thread()) {
587 _cur_thr = (NamedThread *)self;
588 assert(_cur_thr->processed_thread() == NULL, "nesting not supported");
589 _cur_thr->set_processed_thread(thread);
590 } else {
591 _cur_thr = NULL;
592 }
593 }
594
595 ~RememberProcessedThread() {
596 if (_cur_thr) {
597 assert(_cur_thr->processed_thread() != NULL, "nesting not supported");
598 _cur_thr->set_processed_thread(NULL);
599 }
600 }
601 };
602
603 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
604 // Record JavaThread to GC thread
605 RememberProcessedThread rpt(this);
606 oops_do_no_frames(f, cf);
607 oops_do_frames(f, cf);
608 }
609
610 void Thread::metadata_handles_do(void f(Metadata*)) {
611 // Only walk the Handles in Thread.
612 if (metadata_handles() != NULL) {
613 for (int i = 0; i< metadata_handles()->length(); i++) {
614 f(metadata_handles()->at(i));
615 }
616 }
617 }
618
619 void Thread::print_on(outputStream* st, bool print_extended_info) const {
620 // get_priority assumes osthread initialized
621 if (osthread() != NULL) {
622 int os_prio;
623 if (os::get_native_priority(this, &os_prio) == OS_OK) {
624 st->print("os_prio=%d ", os_prio);
625 }
626
627 st->print("cpu=%.2fms ",
628 os::thread_cpu_time(const_cast<Thread*>(this), true) / 1000000.0
629 );
630 st->print("elapsed=%.2fs ",
631 _statistical_info.getElapsedTime() / 1000.0
632 );
633 if (is_Java_thread() && (PrintExtendedThreadInfo || print_extended_info)) {
634 size_t allocated_bytes = (size_t) const_cast<Thread*>(this)->cooked_allocated_bytes();
635 st->print("allocated=" SIZE_FORMAT "%s ",
636 byte_size_in_proper_unit(allocated_bytes),
637 proper_unit_for_byte_size(allocated_bytes)
638 );
639 st->print("defined_classes=" INT64_FORMAT " ", _statistical_info.getDefineClassCount());
640 }
641
642 st->print("tid=" INTPTR_FORMAT " ", p2i(this));
643 osthread()->print_on(st);
644 }
645 ThreadsSMRSupport::print_info_on(this, st);
646 st->print(" ");
647 debug_only(if (WizardMode) print_owned_locks_on(st);)
648 }
649
650 void Thread::print() const { print_on(tty); }
651
652 // Thread::print_on_error() is called by fatal error handler. Don't use
653 // any lock or allocate memory.
654 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
655 assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates");
656
657 if (is_VM_thread()) { st->print("VMThread"); }
658 else if (is_GC_task_thread()) { st->print("GCTaskThread"); }
659 else if (is_Watcher_thread()) { st->print("WatcherThread"); }
660 else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); }
661 else if (this == AsyncLogWriter::instance()) {
662 st->print("%s", this->name());
663 } else { st->print("Thread"); }
664
665 if (is_Named_thread()) {
666 st->print(" \"%s\"", name());
667 }
668
669 OSThread* os_thr = osthread();
670 if (os_thr != NULL) {
671 if (os_thr->get_state() != ZOMBIE) {
672 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
673 p2i(stack_end()), p2i(stack_base()));
674 st->print(" [id=%d]", osthread()->thread_id());
675 } else {
676 st->print(" terminated");
677 }
678 } else {
679 st->print(" unknown state (no osThread)");
680 }
681 ThreadsSMRSupport::print_info_on(this, st);
682 }
683
684 void Thread::print_value_on(outputStream* st) const {
685 if (is_Named_thread()) {
686 st->print(" \"%s\" ", name());
687 }
688 st->print(INTPTR_FORMAT, p2i(this)); // print address
689 }
690
691 #ifdef ASSERT
692 void Thread::print_owned_locks_on(outputStream* st) const {
693 Mutex* cur = _owned_locks;
694 if (cur == NULL) {
695 st->print(" (no locks) ");
696 } else {
697 st->print_cr(" Locks owned:");
698 while (cur) {
699 cur->print_on(st);
700 cur = cur->next();
701 }
702 }
703 }
704 #endif // ASSERT
705
706 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
707 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
708 // used for compilation in the future. If that change is made, the need for these methods
709 // should be revisited, and they should be removed if possible.
710
711 bool Thread::is_lock_owned(address adr) const {
712 assert(LockingMode != LM_LIGHTWEIGHT, "should not be called with new lightweight locking");
713 return is_in_full_stack(adr);
714 }
715
716 bool Thread::set_as_starting_thread() {
717 assert(_starting_thread == NULL, "already initialized: "
718 "_starting_thread=" INTPTR_FORMAT, p2i(_starting_thread));
719 // NOTE: this must be called inside the main thread.
720 DEBUG_ONLY(_starting_thread = this;)
721 return os::create_main_thread(this->as_Java_thread());
722 }
723
724 static void initialize_class(Symbol* class_name, TRAPS) {
725 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
726 InstanceKlass::cast(klass)->initialize(CHECK);
727 }
728
729
730 // Creates the initial ThreadGroup
731 static Handle create_initial_thread_group(TRAPS) {
732 Handle system_instance = JavaCalls::construct_new_instance(
733 vmClasses::ThreadGroup_klass(),
734 vmSymbols::void_method_signature(),
735 CHECK_NH);
736 Universe::set_system_thread_group(system_instance());
737
738 Handle string = java_lang_String::create_from_str("main", CHECK_NH);
739 Handle main_instance = JavaCalls::construct_new_instance(
740 vmClasses::ThreadGroup_klass(),
741 vmSymbols::threadgroup_string_void_signature(),
742 system_instance,
743 string,
744 CHECK_NH);
745 return main_instance;
746 }
747
748 // Creates the initial Thread, and sets it to running.
749 static void create_initial_thread(Handle thread_group, JavaThread* thread,
750 TRAPS) {
751 InstanceKlass* ik = vmClasses::Thread_klass();
752 assert(ik->is_initialized(), "must be");
753 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
754
755 // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread
756 // constructor calls Thread.current(), which must be set here for the
757 // initial thread.
758 java_lang_Thread::set_thread(thread_oop(), thread);
759 java_lang_Thread::set_priority(thread_oop(), NormPriority);
760 thread->set_threadObj(thread_oop());
761
762 Handle string = java_lang_String::create_from_str("main", CHECK);
763
764 JavaValue result(T_VOID);
765 JavaCalls::call_special(&result, thread_oop,
766 ik,
767 vmSymbols::object_initializer_name(),
768 vmSymbols::threadgroup_string_void_signature(),
769 thread_group,
770 string,
771 CHECK);
772
773 // Set thread status to running since main thread has
774 // been started and running.
775 java_lang_Thread::set_thread_status(thread_oop(),
776 JavaThreadStatus::RUNNABLE);
777 }
778
779 // Extract version and vendor specific information from
780 // java.lang.VersionProps fields.
781 // Returned char* is allocated in the thread's resource area
782 // so must be copied for permanency.
783 static const char* get_java_version_info(InstanceKlass* ik,
784 Symbol* field_name) {
785 fieldDescriptor fd;
786 bool found = ik != NULL &&
787 ik->find_local_field(field_name,
788 vmSymbols::string_signature(), &fd);
789 if (found) {
790 oop name_oop = ik->java_mirror()->obj_field(fd.offset());
791 if (name_oop == NULL) {
792 return NULL;
793 }
794 const char* name = java_lang_String::as_utf8_string(name_oop);
795 return name;
796 } else {
797 return NULL;
798 }
799 }
800
801 // General purpose hook into Java code, run once when the VM is initialized.
802 // The Java library method itself may be changed independently from the VM.
803 static void call_postVMInitHook(TRAPS) {
804 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD);
805 if (klass != NULL) {
806 JavaValue result(T_VOID);
807 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
808 vmSymbols::void_method_signature(),
809 CHECK);
810 }
811 }
812
813 // Initialized by VMThread at vm_global_init
814 static OopStorage* _thread_oop_storage = NULL;
815
816 oop JavaThread::threadObj() const {
817 return _threadObj.resolve();
818 }
819
820 void JavaThread::set_threadObj(oop p) {
821 assert(_thread_oop_storage != NULL, "not yet initialized");
822 _threadObj = OopHandle(_thread_oop_storage, p);
823 }
824
825 OopStorage* JavaThread::thread_oop_storage() {
826 assert(_thread_oop_storage != NULL, "not yet initialized");
827 return _thread_oop_storage;
828 }
829
830 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
831 bool daemon, TRAPS) {
832 assert(thread_group.not_null(), "thread group should be specified");
833 assert(threadObj() == NULL, "should only create Java thread object once");
834
835 InstanceKlass* ik = vmClasses::Thread_klass();
836 assert(ik->is_initialized(), "must be");
837 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
838
839 // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon.
840 // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread
841 // constructor calls Thread.current(), which must be set here.
842 java_lang_Thread::set_thread(thread_oop(), this);
843 java_lang_Thread::set_priority(thread_oop(), NormPriority);
844 set_threadObj(thread_oop());
845
846 JavaValue result(T_VOID);
847 if (thread_name != NULL) {
848 Handle name = java_lang_String::create_from_str(thread_name, CHECK);
849 // Thread gets assigned specified name and null target
850 JavaCalls::call_special(&result,
851 thread_oop,
852 ik,
853 vmSymbols::object_initializer_name(),
854 vmSymbols::threadgroup_string_void_signature(),
855 thread_group,
856 name,
857 THREAD);
858 } else {
859 // Thread gets assigned name "Thread-nnn" and null target
860 // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
861 JavaCalls::call_special(&result,
862 thread_oop,
863 ik,
864 vmSymbols::object_initializer_name(),
865 vmSymbols::threadgroup_runnable_void_signature(),
866 thread_group,
867 Handle(),
868 THREAD);
869 }
870
871
872 if (daemon) {
873 java_lang_Thread::set_daemon(thread_oop());
874 }
875
876 if (HAS_PENDING_EXCEPTION) {
877 return;
878 }
879
880 Klass* group = vmClasses::ThreadGroup_klass();
881 Handle threadObj(THREAD, this->threadObj());
882
883 JavaCalls::call_special(&result,
884 thread_group,
885 group,
886 vmSymbols::add_method_name(),
887 vmSymbols::thread_void_signature(),
888 threadObj, // Arg 1
889 THREAD);
890 }
891
892 // ======= JavaThread ========
893
894 #if INCLUDE_JVMCI
895
896 jlong* JavaThread::_jvmci_old_thread_counters;
897
898 bool jvmci_counters_include(JavaThread* thread) {
899 return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
900 }
901
902 void JavaThread::collect_counters(jlong* array, int length) {
903 assert(length == JVMCICounterSize, "wrong value");
904 for (int i = 0; i < length; i++) {
905 array[i] = _jvmci_old_thread_counters[i];
906 }
907 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *tp = jtiwh.next(); ) {
908 if (jvmci_counters_include(tp)) {
909 for (int i = 0; i < length; i++) {
910 array[i] += tp->_jvmci_counters[i];
911 }
912 }
913 }
914 }
915
916 // Attempt to enlarge the array for per thread counters.
917 jlong* resize_counters_array(jlong* old_counters, int current_size, int new_size) {
918 jlong* new_counters = NEW_C_HEAP_ARRAY_RETURN_NULL(jlong, new_size, mtJVMCI);
919 if (new_counters == NULL) {
920 return NULL;
921 }
922 if (old_counters == NULL) {
923 old_counters = new_counters;
924 memset(old_counters, 0, sizeof(jlong) * new_size);
925 } else {
926 for (int i = 0; i < MIN2((int) current_size, new_size); i++) {
927 new_counters[i] = old_counters[i];
928 }
929 if (new_size > current_size) {
930 memset(new_counters + current_size, 0, sizeof(jlong) * (new_size - current_size));
931 }
932 FREE_C_HEAP_ARRAY(jlong, old_counters);
933 }
934 return new_counters;
935 }
936
937 // Attempt to enlarge the array for per thread counters.
938 bool JavaThread::resize_counters(int current_size, int new_size) {
939 jlong* new_counters = resize_counters_array(_jvmci_counters, current_size, new_size);
940 if (new_counters == NULL) {
941 return false;
942 } else {
943 _jvmci_counters = new_counters;
944 return true;
945 }
946 }
947
948 class VM_JVMCIResizeCounters : public VM_Operation {
949 private:
950 int _new_size;
951 bool _failed;
952
953 public:
954 VM_JVMCIResizeCounters(int new_size) : _new_size(new_size), _failed(false) { }
955 VMOp_Type type() const { return VMOp_JVMCIResizeCounters; }
956 bool allow_nested_vm_operations() const { return true; }
957 void doit() {
958 // Resize the old thread counters array
959 jlong* new_counters = resize_counters_array(JavaThread::_jvmci_old_thread_counters, JVMCICounterSize, _new_size);
960 if (new_counters == NULL) {
961 _failed = true;
962 return;
963 } else {
964 JavaThread::_jvmci_old_thread_counters = new_counters;
965 }
966
967 // Now resize each threads array
968 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *tp = jtiwh.next(); ) {
969 if (!tp->resize_counters(JVMCICounterSize, _new_size)) {
970 _failed = true;
971 break;
972 }
973 }
974 if (!_failed) {
975 JVMCICounterSize = _new_size;
976 }
977 }
978
979 bool failed() { return _failed; }
980 };
981
982 bool JavaThread::resize_all_jvmci_counters(int new_size) {
983 VM_JVMCIResizeCounters op(new_size);
984 VMThread::execute(&op);
985 return !op.failed();
986 }
987
988 #endif // INCLUDE_JVMCI
989
990 #ifdef ASSERT
991 // Checks safepoint allowed and clears unhandled oops at potential safepoints.
992 void JavaThread::check_possible_safepoint() {
993 if (_no_safepoint_count > 0) {
994 print_owned_locks();
995 assert(false, "Possible safepoint reached by thread that does not allow it");
996 }
997 #ifdef CHECK_UNHANDLED_OOPS
998 // Clear unhandled oops in JavaThreads so we get a crash right away.
999 clear_unhandled_oops();
1000 #endif // CHECK_UNHANDLED_OOPS
1001 }
1002
1003 void JavaThread::check_for_valid_safepoint_state() {
1004 // Check NoSafepointVerifier, which is implied by locks taken that can be
1005 // shared with the VM thread. This makes sure that no locks with allow_vm_block
1006 // are held.
1007 check_possible_safepoint();
1008
1009 if (thread_state() != _thread_in_vm) {
1010 fatal("LEAF method calling lock?");
1011 }
1012
1013 if (GCALotAtAllSafepoints) {
1014 // We could enter a safepoint here and thus have a gc
1015 InterfaceSupport::check_gc_alot();
1016 }
1017 }
1018 #endif // ASSERT
1019
1020 // A JavaThread is a normal Java thread
1021
1022 JavaThread::JavaThread() :
1023 // Initialize fields
1024
1025 _in_asgct(false),
1026 _on_thread_list(false),
1027 DEBUG_ONLY(_java_call_counter(0) COMMA)
1028 _entry_point(nullptr),
1029 _deopt_mark(nullptr),
1030 _deopt_nmethod(nullptr),
1031 _vframe_array_head(nullptr),
1032 _vframe_array_last(nullptr),
1033 _jvmti_deferred_updates(nullptr),
1034 _callee_target(nullptr),
1035 _vm_result(nullptr),
1036 _vm_result_2(nullptr),
1037
1038 _current_pending_monitor(NULL),
1039 _current_pending_monitor_is_from_java(true),
1040 _current_waiting_monitor(NULL),
1041 _Stalled(0),
1042
1043 _monitor_chunks(nullptr),
1044
1045 _suspend_flags(0),
1046 _async_exception_condition(_no_async_condition),
1047 _pending_async_exception(nullptr),
1048
1049 _thread_state(_thread_new),
1050 _saved_exception_pc(nullptr),
1051 #ifdef ASSERT
1052 _no_safepoint_count(0),
1053 _visited_for_critical_count(false),
1054 #endif
1055
1056 _terminated(_not_terminated),
1057 _in_deopt_handler(0),
1058 _doing_unsafe_access(false),
1059 _do_not_unlock_if_synchronized(false),
1060 _jni_attach_state(_not_attaching_via_jni),
1061 #if INCLUDE_JVMCI
1062 _pending_deoptimization(-1),
1063 _pending_monitorenter(false),
1064 _pending_transfer_to_interpreter(false),
1065 _in_retryable_allocation(false),
1066 _pending_failed_speculation(0),
1067 _jvmci{nullptr},
1068 _jvmci_counters(nullptr),
1069 _jvmci_reserved0(0),
1070 _jvmci_reserved1(0),
1071 _jvmci_reserved_oop0(nullptr),
1072 #endif // INCLUDE_JVMCI
1073
1074 _exception_oop(oop()),
1075 _exception_pc(0),
1076 _exception_handler_pc(0),
1077 _is_method_handle_return(0),
1078
1079 _jni_active_critical(0),
1080 _pending_jni_exception_check_fn(nullptr),
1081 _depth_first_number(0),
1082
1083 // JVMTI PopFrame support
1084 _popframe_condition(popframe_inactive),
1085 _frames_to_pop_failed_realloc(0),
1086
1087 _handshake(this),
1088
1089 _popframe_preserved_args(nullptr),
1090 _popframe_preserved_args_size(0),
1091
1092 _jvmti_thread_state(nullptr),
1093 _interp_only_mode(0),
1094 _should_post_on_exceptions_flag(JNI_FALSE),
1095 _thread_stat(new ThreadStatistics()),
1096
1097 _parker(),
1098 _cached_monitor_info(nullptr),
1099
1100 _class_to_be_initialized(nullptr),
1101
1102 _SleepEvent(ParkEvent::Allocate(this)),
1103
1104 _lock_stack(this) {
1105 set_jni_functions(jni_functions());
1106
1107 #if INCLUDE_JVMCI
1108 assert(_jvmci._implicit_exception_pc == nullptr, "must be");
1109 if (JVMCICounterSize > 0) {
1110 resize_counters(0, (int) JVMCICounterSize);
1111 }
1112 #endif // INCLUDE_JVMCI
1113
1114 // Setup safepoint state info for this thread
1115 ThreadSafepointState::create(this);
1116
1117 SafepointMechanism::initialize_header(this);
1118
1119 set_requires_cross_modify_fence(false);
1120
1121 pd_initialize();
1122 assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
1123 }
1124
1125 JavaThread::JavaThread(bool is_attaching_via_jni) : JavaThread() {
1126 if (is_attaching_via_jni) {
1127 _jni_attach_state = _attaching_via_jni;
1128 }
1129 }
1130
1131
1132 // interrupt support
1133
1134 void JavaThread::interrupt() {
1135 // All callers should have 'this' thread protected by a
1136 // ThreadsListHandle so that it cannot terminate and deallocate
1137 // itself.
1138 debug_only(check_for_dangling_thread_pointer(this);)
1139
1140 // For Windows _interrupt_event
1141 osthread()->set_interrupted(true);
1142
1143 // For Thread.sleep
1144 _SleepEvent->unpark();
1145
1146 // For JSR166 LockSupport.park
1147 parker()->unpark();
1148
1149 // For ObjectMonitor and JvmtiRawMonitor
1150 _ParkEvent->unpark();
1151 }
1152
1153
1154 bool JavaThread::is_interrupted(bool clear_interrupted) {
1155 debug_only(check_for_dangling_thread_pointer(this);)
1156
1157 if (_threadObj.peek() == NULL) {
1158 // If there is no j.l.Thread then it is impossible to have
1159 // been interrupted. We can find NULL during VM initialization
1160 // or when a JNI thread is still in the process of attaching.
1161 // In such cases this must be the current thread.
1162 assert(this == Thread::current(), "invariant");
1163 return false;
1164 }
1165
1166 bool interrupted = java_lang_Thread::interrupted(threadObj());
1167
1168 // NOTE that since there is no "lock" around the interrupt and
1169 // is_interrupted operations, there is the possibility that the
1170 // interrupted flag will be "false" but that the
1171 // low-level events will be in the signaled state. This is
1172 // intentional. The effect of this is that Object.wait() and
1173 // LockSupport.park() will appear to have a spurious wakeup, which
1174 // is allowed and not harmful, and the possibility is so rare that
1175 // it is not worth the added complexity to add yet another lock.
1176 // For the sleep event an explicit reset is performed on entry
1177 // to JavaThread::sleep, so there is no early return. It has also been
1178 // recommended not to put the interrupted flag into the "event"
1179 // structure because it hides the issue.
1180 // Also, because there is no lock, we must only clear the interrupt
1181 // state if we are going to report that we were interrupted; otherwise
1182 // an interrupt that happens just after we read the field would be lost.
1183 if (interrupted && clear_interrupted) {
1184 assert(this == Thread::current(), "only the current thread can clear");
1185 java_lang_Thread::set_interrupted(threadObj(), false);
1186 osthread()->set_interrupted(false);
1187 }
1188
1189 return interrupted;
1190 }
1191
1192 void JavaThread::block_if_vm_exited() {
1193 if (_terminated == _vm_exited) {
1194 // _vm_exited is set at safepoint, and Threads_lock is never released
1195 // we will block here forever.
1196 // Here we can be doing a jump from a safe state to an unsafe state without
1197 // proper transition, but it happens after the final safepoint has begun.
1198 set_thread_state(_thread_in_vm);
1199 Threads_lock->lock();
1200 ShouldNotReachHere();
1201 }
1202 }
1203
1204 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : JavaThread() {
1205 _jni_attach_state = _not_attaching_via_jni;
1206 set_entry_point(entry_point);
1207 // Create the native thread itself.
1208 // %note runtime_23
1209 os::ThreadType thr_type = os::java_thread;
1210 thr_type = entry_point == &CompilerThread::thread_entry ? os::compiler_thread :
1211 os::java_thread;
1212 os::create_thread(this, thr_type, stack_sz);
1213 // The _osthread may be NULL here because we ran out of memory (too many threads active).
1214 // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
1215 // may hold a lock and all locks must be unlocked before throwing the exception (throwing
1216 // the exception consists of creating the exception object & initializing it, initialization
1217 // will leave the VM via a JavaCall and then all locks must be unlocked).
1218 //
1219 // The thread is still suspended when we reach here. Thread must be explicit started
1220 // by creator! Furthermore, the thread must also explicitly be added to the Threads list
1221 // by calling Threads:add. The reason why this is not done here, is because the thread
1222 // object must be fully initialized (take a look at JVM_Start)
1223 }
1224
1225 JavaThread::~JavaThread() {
1226
1227 // Ask ServiceThread to release the threadObj OopHandle
1228 ServiceThread::add_oop_handle_release(_threadObj);
1229
1230 // Return the sleep event to the free list
1231 ParkEvent::Release(_SleepEvent);
1232 _SleepEvent = NULL;
1233
1234 // Free any remaining previous UnrollBlock
1235 vframeArray* old_array = vframe_array_last();
1236
1237 if (old_array != NULL) {
1238 Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
1239 old_array->set_unroll_block(NULL);
1240 delete old_info;
1241 delete old_array;
1242 }
1243
1244 JvmtiDeferredUpdates* updates = deferred_updates();
1245 if (updates != NULL) {
1246 // This can only happen if thread is destroyed before deoptimization occurs.
1247 assert(updates->count() > 0, "Updates holder not deleted");
1248 // free deferred updates.
1249 delete updates;
1250 set_deferred_updates(NULL);
1251 }
1252
1253 // All Java related clean up happens in exit
1254 ThreadSafepointState::destroy(this);
1255 if (_thread_stat != NULL) delete _thread_stat;
1256
1257 #if INCLUDE_JVMCI
1258 if (JVMCICounterSize > 0) {
1259 FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
1260 }
1261 #endif // INCLUDE_JVMCI
1262 }
1263
1264
1265 // First JavaThread specific code executed by a new Java thread.
1266 void JavaThread::pre_run() {
1267 // empty - see comments in run()
1268 }
1269
1270 // The main routine called by a new Java thread. This isn't overridden
1271 // by subclasses, instead different subclasses define a different "entry_point"
1272 // which defines the actual logic for that kind of thread.
1273 void JavaThread::run() {
1274 // initialize thread-local alloc buffer related fields
1275 initialize_tlab();
1276
1277 _stack_overflow_state.create_stack_guard_pages();
1278
1279 cache_global_variables();
1280
1281 // Thread is now sufficiently initialized to be handled by the safepoint code as being
1282 // in the VM. Change thread state from _thread_new to _thread_in_vm
1283 ThreadStateTransition::transition(this, _thread_new, _thread_in_vm);
1284 // Before a thread is on the threads list it is always safe, so after leaving the
1285 // _thread_new we should emit a instruction barrier. The distance to modified code
1286 // from here is probably far enough, but this is consistent and safe.
1287 OrderAccess::cross_modify_fence();
1288
1289 assert(JavaThread::current() == this, "sanity check");
1290 assert(!Thread::current()->owns_locks(), "sanity check");
1291
1292 DTRACE_THREAD_PROBE(start, this);
1293
1294 // This operation might block. We call that after all safepoint checks for a new thread has
1295 // been completed.
1296 set_active_handles(JNIHandleBlock::allocate_block());
1297
1298 if (JvmtiExport::should_post_thread_life()) {
1299 JvmtiExport::post_thread_start(this);
1300
1301 }
1302
1303 // We call another function to do the rest so we are sure that the stack addresses used
1304 // from there will be lower than the stack base just computed.
1305 thread_main_inner();
1306 }
1307
1308 void JavaThread::thread_main_inner() {
1309 assert(JavaThread::current() == this, "sanity check");
1310 assert(_threadObj.peek() != NULL, "just checking");
1311
1312 // Execute thread entry point unless this thread has a pending exception
1313 // or has been stopped before starting.
1314 // Note: Due to JVM_StopThread we can have pending exceptions already!
1315 if (!this->has_pending_exception() &&
1316 !java_lang_Thread::is_stillborn(this->threadObj())) {
1317 {
1318 ResourceMark rm(this);
1319 this->set_native_thread_name(this->get_thread_name());
1320 }
1321 HandleMark hm(this);
1322 this->entry_point()(this, this);
1323 }
1324
1325 DTRACE_THREAD_PROBE(stop, this);
1326
1327 // Cleanup is handled in post_run()
1328 }
1329
1330 // Shared teardown for all JavaThreads
1331 void JavaThread::post_run() {
1332 this->exit(false);
1333 this->unregister_thread_stack_with_NMT();
1334 // Defer deletion to here to ensure 'this' is still referenceable in call_run
1335 // for any shared tear-down.
1336 this->smr_delete();
1337 }
1338
1339 static void ensure_join(JavaThread* thread) {
1340 // We do not need to grab the Threads_lock, since we are operating on ourself.
1341 Handle threadObj(thread, thread->threadObj());
1342 assert(threadObj.not_null(), "java thread object must exist");
1343 ObjectLocker lock(threadObj, thread);
1344 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1345 thread->clear_pending_exception();
1346 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
1347 java_lang_Thread::set_thread_status(threadObj(), JavaThreadStatus::TERMINATED);
1348 // Clear the native thread instance - this makes isAlive return false and allows the join()
1349 // to complete once we've done the notify_all below. Needs a release() to obey Java Memory Model
1350 // requirements.
1351 java_lang_Thread::release_set_thread(threadObj(), NULL);
1352 lock.notify_all(thread);
1353 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1354 thread->clear_pending_exception();
1355 }
1356
1357 static bool is_daemon(oop threadObj) {
1358 return (threadObj != NULL && java_lang_Thread::is_daemon(threadObj));
1359 }
1360
1361 // For any new cleanup additions, please check to see if they need to be applied to
1362 // cleanup_failed_attach_current_thread as well.
1363 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
1364 assert(this == JavaThread::current(), "thread consistency check");
1365
1366 elapsedTimer _timer_exit_phase1;
1367 elapsedTimer _timer_exit_phase2;
1368 elapsedTimer _timer_exit_phase3;
1369 elapsedTimer _timer_exit_phase4;
1370
1371 if (log_is_enabled(Debug, os, thread, timer)) {
1372 _timer_exit_phase1.start();
1373 }
1374
1375 HandleMark hm(this);
1376 Handle uncaught_exception(this, this->pending_exception());
1377 this->clear_pending_exception();
1378 Handle threadObj(this, this->threadObj());
1379 assert(threadObj.not_null(), "Java thread object should be created");
1380
1381 if (!destroy_vm) {
1382 if (uncaught_exception.not_null()) {
1383 EXCEPTION_MARK;
1384 // Call method Thread.dispatchUncaughtException().
1385 Klass* thread_klass = vmClasses::Thread_klass();
1386 JavaValue result(T_VOID);
1387 JavaCalls::call_virtual(&result,
1388 threadObj, thread_klass,
1389 vmSymbols::dispatchUncaughtException_name(),
1390 vmSymbols::throwable_void_signature(),
1391 uncaught_exception,
1392 THREAD);
1393 if (HAS_PENDING_EXCEPTION) {
1394 ResourceMark rm(this);
1395 jio_fprintf(defaultStream::error_stream(),
1396 "\nException: %s thrown from the UncaughtExceptionHandler"
1397 " in thread \"%s\"\n",
1398 pending_exception()->klass()->external_name(),
1399 get_thread_name());
1400 CLEAR_PENDING_EXCEPTION;
1401 }
1402 }
1403
1404 // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
1405 // the execution of the method. If that is not enough, then we don't really care. Thread.stop
1406 // is deprecated anyhow.
1407 if (!is_Compiler_thread()) {
1408 int count = 3;
1409 while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
1410 EXCEPTION_MARK;
1411 JavaValue result(T_VOID);
1412 Klass* thread_klass = vmClasses::Thread_klass();
1413 JavaCalls::call_virtual(&result,
1414 threadObj, thread_klass,
1415 vmSymbols::exit_method_name(),
1416 vmSymbols::void_method_signature(),
1417 THREAD);
1418 CLEAR_PENDING_EXCEPTION;
1419 }
1420 }
1421 // notify JVMTI
1422 if (JvmtiExport::should_post_thread_life()) {
1423 JvmtiExport::post_thread_end(this);
1424 }
1425
1426 // The careful dance between thread suspension and exit is handled here.
1427 // Since we are in thread_in_vm state and suspension is done with handshakes,
1428 // we can just put in the exiting state and it will be correctly handled.
1429 set_terminated(_thread_exiting);
1430
1431 ThreadService::current_thread_exiting(this, is_daemon(threadObj()));
1432 } else {
1433 assert(!is_terminated() && !is_exiting(), "must not be exiting");
1434 // before_exit() has already posted JVMTI THREAD_END events
1435 }
1436
1437 if (log_is_enabled(Debug, os, thread, timer)) {
1438 _timer_exit_phase1.stop();
1439 _timer_exit_phase2.start();
1440 }
1441
1442 // Capture daemon status before the thread is marked as terminated.
1443 bool daemon = is_daemon(threadObj());
1444
1445 // Notify waiters on thread object. This has to be done after exit() is called
1446 // on the thread (if the thread is the last thread in a daemon ThreadGroup the
1447 // group should have the destroyed bit set before waiters are notified).
1448 ensure_join(this);
1449 assert(!this->has_pending_exception(), "ensure_join should have cleared");
1450
1451 if (log_is_enabled(Debug, os, thread, timer)) {
1452 _timer_exit_phase2.stop();
1453 _timer_exit_phase3.start();
1454 }
1455 // 6282335 JNI DetachCurrentThread spec states that all Java monitors
1456 // held by this thread must be released. The spec does not distinguish
1457 // between JNI-acquired and regular Java monitors. We can only see
1458 // regular Java monitors here if monitor enter-exit matching is broken.
1459 //
1460 // ensure_join() ignores IllegalThreadStateExceptions, and so does
1461 // ObjectSynchronizer::release_monitors_owned_by_thread().
1462 if (exit_type == jni_detach) {
1463 // Sanity check even though JNI DetachCurrentThread() would have
1464 // returned JNI_ERR if there was a Java frame. JavaThread exit
1465 // should be done executing Java code by the time we get here.
1466 assert(!this->has_last_Java_frame(),
1467 "should not have a Java frame when detaching or exiting");
1468 ObjectSynchronizer::release_monitors_owned_by_thread(this);
1469 assert(!this->has_pending_exception(), "release_monitors should have cleared");
1470 }
1471
1472 // These things needs to be done while we are still a Java Thread. Make sure that thread
1473 // is in a consistent state, in case GC happens
1474 JFR_ONLY(Jfr::on_thread_exit(this);)
1475
1476 if (active_handles() != NULL) {
1477 JNIHandleBlock* block = active_handles();
1478 set_active_handles(NULL);
1479 JNIHandleBlock::release_block(block);
1480 }
1481
1482 if (free_handle_block() != NULL) {
1483 JNIHandleBlock* block = free_handle_block();
1484 set_free_handle_block(NULL);
1485 JNIHandleBlock::release_block(block);
1486 }
1487
1488 // These have to be removed while this is still a valid thread.
1489 _stack_overflow_state.remove_stack_guard_pages();
1490
1491 if (UseTLAB) {
1492 tlab().retire();
1493 }
1494
1495 if (JvmtiEnv::environments_might_exist()) {
1496 JvmtiExport::cleanup_thread(this);
1497 }
1498
1499 // We need to cache the thread name for logging purposes below as once
1500 // we have called on_thread_detach this thread must not access any oops.
1501 char* thread_name = NULL;
1502 if (log_is_enabled(Debug, os, thread, timer)) {
1503 ResourceMark rm(this);
1504 thread_name = os::strdup(get_thread_name());
1505 }
1506
1507 log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").",
1508 exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
1509 os::current_thread_id());
1510
1511 if (log_is_enabled(Debug, os, thread, timer)) {
1512 _timer_exit_phase3.stop();
1513 _timer_exit_phase4.start();
1514 }
1515
1516 #if INCLUDE_JVMCI
1517 if (JVMCICounterSize > 0) {
1518 if (jvmci_counters_include(this)) {
1519 for (int i = 0; i < JVMCICounterSize; i++) {
1520 _jvmci_old_thread_counters[i] += _jvmci_counters[i];
1521 }
1522 }
1523 }
1524 #endif // INCLUDE_JVMCI
1525
1526 // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
1527 Threads::remove(this, daemon);
1528
1529 if (log_is_enabled(Debug, os, thread, timer)) {
1530 _timer_exit_phase4.stop();
1531 log_debug(os, thread, timer)("name='%s'"
1532 ", exit-phase1=" JLONG_FORMAT
1533 ", exit-phase2=" JLONG_FORMAT
1534 ", exit-phase3=" JLONG_FORMAT
1535 ", exit-phase4=" JLONG_FORMAT,
1536 thread_name,
1537 _timer_exit_phase1.milliseconds(),
1538 _timer_exit_phase2.milliseconds(),
1539 _timer_exit_phase3.milliseconds(),
1540 _timer_exit_phase4.milliseconds());
1541 os::free(thread_name);
1542 }
1543 }
1544
1545 void JavaThread::cleanup_failed_attach_current_thread(bool is_daemon) {
1546 if (active_handles() != NULL) {
1547 JNIHandleBlock* block = active_handles();
1548 set_active_handles(NULL);
1549 JNIHandleBlock::release_block(block);
1550 }
1551
1552 if (free_handle_block() != NULL) {
1553 JNIHandleBlock* block = free_handle_block();
1554 set_free_handle_block(NULL);
1555 JNIHandleBlock::release_block(block);
1556 }
1557
1558 // These have to be removed while this is still a valid thread.
1559 _stack_overflow_state.remove_stack_guard_pages();
1560
1561 if (UseTLAB) {
1562 tlab().retire();
1563 }
1564
1565 Threads::remove(this, is_daemon);
1566 this->smr_delete();
1567 }
1568
1569 JavaThread* JavaThread::active() {
1570 Thread* thread = Thread::current();
1571 if (thread->is_Java_thread()) {
1572 return thread->as_Java_thread();
1573 } else {
1574 assert(thread->is_VM_thread(), "this must be a vm thread");
1575 VM_Operation* op = ((VMThread*) thread)->vm_operation();
1576 JavaThread *ret = op == NULL ? NULL : op->calling_thread()->as_Java_thread();
1577 return ret;
1578 }
1579 }
1580
1581 bool JavaThread::is_lock_owned(address adr) const {
1582 assert(LockingMode != LM_LIGHTWEIGHT, "should not be called with new lightweight locking");
1583 if (Thread::is_lock_owned(adr)) return true;
1584
1585 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
1586 if (chunk->contains(adr)) return true;
1587 }
1588
1589 return false;
1590 }
1591
1592 oop JavaThread::exception_oop() const {
1593 return Atomic::load(&_exception_oop);
1594 }
1595
1596 void JavaThread::set_exception_oop(oop o) {
1597 Atomic::store(&_exception_oop, o);
1598 }
1599
1600 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
1601 chunk->set_next(monitor_chunks());
1602 set_monitor_chunks(chunk);
1603 }
1604
1605 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
1606 guarantee(monitor_chunks() != NULL, "must be non empty");
1607 if (monitor_chunks() == chunk) {
1608 set_monitor_chunks(chunk->next());
1609 } else {
1610 MonitorChunk* prev = monitor_chunks();
1611 while (prev->next() != chunk) prev = prev->next();
1612 prev->set_next(chunk->next());
1613 }
1614 }
1615
1616
1617 // Asynchronous exceptions support
1618 //
1619 // Note: this function shouldn't block if it's called in
1620 // _thread_in_native_trans state (such as from
1621 // check_special_condition_for_native_trans()).
1622 void JavaThread::check_and_handle_async_exceptions() {
1623 if (has_last_Java_frame() && has_async_exception_condition()) {
1624 // If we are at a polling page safepoint (not a poll return)
1625 // then we must defer async exception because live registers
1626 // will be clobbered by the exception path. Poll return is
1627 // ok because the call we a returning from already collides
1628 // with exception handling registers and so there is no issue.
1629 // (The exception handling path kills call result registers but
1630 // this is ok since the exception kills the result anyway).
1631
1632 if (is_at_poll_safepoint()) {
1633 // if the code we are returning to has deoptimized we must defer
1634 // the exception otherwise live registers get clobbered on the
1635 // exception path before deoptimization is able to retrieve them.
1636 //
1637 RegisterMap map(this, false);
1638 frame caller_fr = last_frame().sender(&map);
1639 assert(caller_fr.is_compiled_frame(), "what?");
1640 if (caller_fr.is_deoptimized_frame()) {
1641 log_info(exceptions)("deferred async exception at compiled safepoint");
1642 return;
1643 }
1644 }
1645 }
1646
1647 AsyncExceptionCondition condition = clear_async_exception_condition();
1648 if (condition == _no_async_condition) {
1649 // Conditions have changed since has_special_runtime_exit_condition()
1650 // was called:
1651 // - if we were here only because of an external suspend request,
1652 // then that was taken care of above (or cancelled) so we are done
1653 // - if we were here because of another async request, then it has
1654 // been cleared between the has_special_runtime_exit_condition()
1655 // and now so again we are done
1656 return;
1657 }
1658
1659 // Check for pending async. exception
1660 if (_pending_async_exception != NULL) {
1661 // Only overwrite an already pending exception, if it is not a threadDeath.
1662 if (!has_pending_exception() || !pending_exception()->is_a(vmClasses::ThreadDeath_klass())) {
1663
1664 // We cannot call Exceptions::_throw(...) here because we cannot block
1665 set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
1666
1667 LogTarget(Info, exceptions) lt;
1668 if (lt.is_enabled()) {
1669 ResourceMark rm;
1670 LogStream ls(lt);
1671 ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this));
1672 if (has_last_Java_frame()) {
1673 frame f = last_frame();
1674 ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp()));
1675 }
1676 ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name());
1677 }
1678 _pending_async_exception = NULL;
1679 // Clear condition from _suspend_flags since we have finished processing it.
1680 clear_suspend_flag(_has_async_exception);
1681 }
1682 }
1683
1684 if (condition == _async_unsafe_access_error && !has_pending_exception()) {
1685 // We may be at method entry which requires we save the do-not-unlock flag.
1686 UnlockFlagSaver fs(this);
1687 switch (thread_state()) {
1688 case _thread_in_vm: {
1689 JavaThread* THREAD = this;
1690 Exceptions::throw_unsafe_access_internal_error(THREAD, __FILE__, __LINE__, "a fault occurred in an unsafe memory access operation");
1691 return;
1692 }
1693 case _thread_in_native: {
1694 ThreadInVMfromNative tiv(this);
1695 JavaThread* THREAD = this;
1696 Exceptions::throw_unsafe_access_internal_error(THREAD, __FILE__, __LINE__, "a fault occurred in an unsafe memory access operation");
1697 return;
1698 }
1699 case _thread_in_Java: {
1700 ThreadInVMfromJava tiv(this);
1701 JavaThread* THREAD = this;
1702 Exceptions::throw_unsafe_access_internal_error(THREAD, __FILE__, __LINE__, "a fault occurred in a recent unsafe memory access operation in compiled Java code");
1703 return;
1704 }
1705 default:
1706 ShouldNotReachHere();
1707 }
1708 }
1709
1710 assert(has_pending_exception(), "must have handled the async condition if no exception");
1711 }
1712
1713 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
1714
1715 if (is_obj_deopt_suspend()) {
1716 frame_anchor()->make_walkable();
1717 wait_for_object_deoptimization();
1718 }
1719
1720 // We might be here for reasons in addition to the self-suspend request
1721 // so check for other async requests.
1722 if (check_asyncs) {
1723 check_and_handle_async_exceptions();
1724 }
1725
1726 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);)
1727 }
1728
1729 class InstallAsyncExceptionClosure : public HandshakeClosure {
1730 Handle _throwable; // The Throwable thrown at the target Thread
1731 public:
1732 InstallAsyncExceptionClosure(Handle throwable) : HandshakeClosure("InstallAsyncException"), _throwable(throwable) {}
1733
1734 void do_thread(Thread* thr) {
1735 JavaThread* target = thr->as_Java_thread();
1736 // Note that this now allows multiple ThreadDeath exceptions to be
1737 // thrown at a thread.
1738 // The target thread has run and has not exited yet.
1739 target->send_thread_stop(_throwable());
1740 }
1741 };
1742
1743 void JavaThread::send_async_exception(oop java_thread, oop java_throwable) {
1744 Handle throwable(Thread::current(), java_throwable);
1745 JavaThread* target = java_lang_Thread::thread(java_thread);
1746 InstallAsyncExceptionClosure vm_stop(throwable);
1747 Handshake::execute(&vm_stop, target);
1748 }
1749
1750 void JavaThread::send_thread_stop(oop java_throwable) {
1751 ResourceMark rm;
1752 assert(is_handshake_safe_for(Thread::current()),
1753 "should be self or handshakee");
1754
1755 // Do not throw asynchronous exceptions against the compiler thread
1756 // (the compiler thread should not be a Java thread -- fix in 1.4.2)
1757 if (!can_call_java()) return;
1758
1759 {
1760 // Actually throw the Throwable against the target Thread - however
1761 // only if there is no thread death exception installed already.
1762 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(vmClasses::ThreadDeath_klass())) {
1763 // If the topmost frame is a runtime stub, then we are calling into
1764 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
1765 // must deoptimize the caller before continuing, as the compiled exception handler table
1766 // may not be valid
1767 if (has_last_Java_frame()) {
1768 frame f = last_frame();
1769 if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
1770 RegisterMap reg_map(this, false);
1771 frame compiled_frame = f.sender(®_map);
1772 if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
1773 Deoptimization::deoptimize(this, compiled_frame);
1774 }
1775 }
1776 }
1777
1778 // Set async. pending exception in thread.
1779 set_pending_async_exception(java_throwable);
1780
1781 if (log_is_enabled(Info, exceptions)) {
1782 ResourceMark rm;
1783 log_info(exceptions)("Pending Async. exception installed of type: %s",
1784 InstanceKlass::cast(_pending_async_exception->klass())->external_name());
1785 }
1786 // for AbortVMOnException flag
1787 Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name());
1788 }
1789 }
1790
1791
1792 // Interrupt thread so it will wake up from a potential wait()/sleep()/park()
1793 java_lang_Thread::set_interrupted(threadObj(), true);
1794 this->interrupt();
1795 }
1796
1797
1798 // External suspension mechanism.
1799 //
1800 // Guarantees on return (for a valid target thread):
1801 // - Target thread will not execute any new bytecode.
1802 // - Target thread will not enter any new monitors.
1803 //
1804 bool JavaThread::java_suspend() {
1805 ThreadsListHandle tlh;
1806 if (!tlh.includes(this)) {
1807 log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " not on ThreadsList, no suspension", p2i(this));
1808 return false;
1809 }
1810 return this->handshake_state()->suspend();
1811 }
1812
1813 bool JavaThread::java_resume() {
1814 ThreadsListHandle tlh;
1815 if (!tlh.includes(this)) {
1816 log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " not on ThreadsList, nothing to resume", p2i(this));
1817 return false;
1818 }
1819 return this->handshake_state()->resume();
1820 }
1821
1822 // Wait for another thread to perform object reallocation and relocking on behalf of
1823 // this thread.
1824 // Raw thread state transition to _thread_blocked and back again to the original
1825 // state before returning are performed. The current thread is required to
1826 // change to _thread_blocked in order to be seen to be safepoint/handshake safe
1827 // whilst suspended and only after becoming handshake safe, the other thread can
1828 // complete the handshake used to synchronize with this thread and then perform
1829 // the reallocation and relocking. We cannot use the thread state transition
1830 // helpers because we arrive here in various states and also because the helpers
1831 // indirectly call this method. After leaving _thread_blocked we have to check
1832 // for safepoint/handshake, except if _thread_in_native. The thread is safe
1833 // without blocking then. Allowed states are enumerated in
1834 // SafepointSynchronize::block(). See also EscapeBarrier::sync_and_suspend_*()
1835
1836 void JavaThread::wait_for_object_deoptimization() {
1837 assert(!has_last_Java_frame() || frame_anchor()->walkable(), "should have walkable stack");
1838 assert(this == Thread::current(), "invariant");
1839 JavaThreadState state = thread_state();
1840
1841 bool spin_wait = os::is_MP();
1842 do {
1843 set_thread_state(_thread_blocked);
1844 // Wait for object deoptimization if requested.
1845 if (spin_wait) {
1846 // A single deoptimization is typically very short. Microbenchmarks
1847 // showed 5% better performance when spinning.
1848 const uint spin_limit = 10 * SpinYield::default_spin_limit;
1849 SpinYield spin(spin_limit);
1850 for (uint i = 0; is_obj_deopt_suspend() && i < spin_limit; i++) {
1851 spin.wait();
1852 }
1853 // Spin just once
1854 spin_wait = false;
1855 } else {
1856 MonitorLocker ml(this, EscapeBarrier_lock, Monitor::_no_safepoint_check_flag);
1857 if (is_obj_deopt_suspend()) {
1858 ml.wait();
1859 }
1860 }
1861 // The current thread could have been suspended again. We have to check for
1862 // suspend after restoring the saved state. Without this the current thread
1863 // might return to _thread_in_Java and execute bytecode.
1864 set_thread_state_fence(state);
1865
1866 if (state != _thread_in_native) {
1867 SafepointMechanism::process_if_requested(this);
1868 }
1869 // A handshake for obj. deoptimization suspend could have been processed so
1870 // we must check after processing.
1871 } while (is_obj_deopt_suspend());
1872 }
1873
1874 #ifdef ASSERT
1875 // Verify the JavaThread has not yet been published in the Threads::list, and
1876 // hence doesn't need protection from concurrent access at this stage.
1877 void JavaThread::verify_not_published() {
1878 // Cannot create a ThreadsListHandle here and check !tlh.includes(this)
1879 // since an unpublished JavaThread doesn't participate in the
1880 // Thread-SMR protocol for keeping a ThreadsList alive.
1881 assert(!on_thread_list(), "JavaThread shouldn't have been published yet!");
1882 }
1883 #endif
1884
1885 // Slow path when the native==>Java barriers detect a safepoint/handshake is
1886 // pending, when _suspend_flags is non-zero or when we need to process a stack
1887 // watermark. Also check for pending async exceptions (except unsafe access error).
1888 // Note only the native==>Java barriers can call this function when thread state
1889 // is _thread_in_native_trans.
1890 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
1891 assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
1892 assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "Unwalkable stack in native->Java transition");
1893
1894 // Enable WXWrite: called directly from interpreter native wrapper.
1895 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, thread));
1896
1897 SafepointMechanism::process_if_requested_with_exit_check(thread, false /* check asyncs */);
1898
1899 // After returning from native, it could be that the stack frames are not
1900 // yet safe to use. We catch such situations in the subsequent stack watermark
1901 // barrier, which will trap unsafe stack frames.
1902 StackWatermarkSet::before_unwind(thread);
1903
1904 if (thread->has_async_exception_condition(false /* check unsafe access error */)) {
1905 // We are in _thread_in_native_trans state, don't handle unsafe
1906 // access error since that may block.
1907 thread->check_and_handle_async_exceptions();
1908 }
1909 }
1910
1911 #ifndef PRODUCT
1912 // Deoptimization
1913 // Function for testing deoptimization
1914 void JavaThread::deoptimize() {
1915 StackFrameStream fst(this, false /* update */, true /* process_frames */);
1916 bool deopt = false; // Dump stack only if a deopt actually happens.
1917 bool only_at = strlen(DeoptimizeOnlyAt) > 0;
1918 // Iterate over all frames in the thread and deoptimize
1919 for (; !fst.is_done(); fst.next()) {
1920 if (fst.current()->can_be_deoptimized()) {
1921
1922 if (only_at) {
1923 // Deoptimize only at particular bcis. DeoptimizeOnlyAt
1924 // consists of comma or carriage return separated numbers so
1925 // search for the current bci in that string.
1926 address pc = fst.current()->pc();
1927 nmethod* nm = (nmethod*) fst.current()->cb();
1928 ScopeDesc* sd = nm->scope_desc_at(pc);
1929 char buffer[8];
1930 jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
1931 size_t len = strlen(buffer);
1932 const char * found = strstr(DeoptimizeOnlyAt, buffer);
1933 while (found != NULL) {
1934 if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
1935 (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
1936 // Check that the bci found is bracketed by terminators.
1937 break;
1938 }
1939 found = strstr(found + 1, buffer);
1940 }
1941 if (!found) {
1942 continue;
1943 }
1944 }
1945
1946 if (DebugDeoptimization && !deopt) {
1947 deopt = true; // One-time only print before deopt
1948 tty->print_cr("[BEFORE Deoptimization]");
1949 trace_frames();
1950 trace_stack();
1951 }
1952 Deoptimization::deoptimize(this, *fst.current());
1953 }
1954 }
1955
1956 if (DebugDeoptimization && deopt) {
1957 tty->print_cr("[AFTER Deoptimization]");
1958 trace_frames();
1959 }
1960 }
1961
1962
1963 // Make zombies
1964 void JavaThread::make_zombies() {
1965 for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
1966 if (fst.current()->can_be_deoptimized()) {
1967 // it is a Java nmethod
1968 nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
1969 nm->make_not_entrant();
1970 }
1971 }
1972 }
1973 #endif // PRODUCT
1974
1975
1976 void JavaThread::deoptimize_marked_methods() {
1977 if (!has_last_Java_frame()) return;
1978 StackFrameStream fst(this, false /* update */, true /* process_frames */);
1979 for (; !fst.is_done(); fst.next()) {
1980 if (fst.current()->should_be_deoptimized()) {
1981 Deoptimization::deoptimize(this, *fst.current());
1982 }
1983 }
1984 }
1985
1986 #ifdef ASSERT
1987 void JavaThread::verify_frame_info() {
1988 assert((!has_last_Java_frame() && java_call_counter() == 0) ||
1989 (has_last_Java_frame() && java_call_counter() > 0),
1990 "unexpected frame info: has_last_frame=%s, java_call_counter=%d",
1991 has_last_Java_frame() ? "true" : "false", java_call_counter());
1992 }
1993 #endif
1994
1995 void JavaThread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) {
1996 // Verify that the deferred card marks have been flushed.
1997 assert(deferred_card_mark().is_empty(), "Should be empty during GC");
1998
1999 // Traverse the GCHandles
2000 Thread::oops_do_no_frames(f, cf);
2001
2002 DEBUG_ONLY(verify_frame_info();)
2003
2004 if (has_last_Java_frame()) {
2005 // Traverse the monitor chunks
2006 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2007 chunk->oops_do(f);
2008 }
2009 }
2010
2011 assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
2012 // If we have deferred set_locals there might be oops waiting to be
2013 // written
2014 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(this);
2015 if (list != NULL) {
2016 for (int i = 0; i < list->length(); i++) {
2017 list->at(i)->oops_do(f);
2018 }
2019 }
2020
2021 // Traverse instance variables at the end since the GC may be moving things
2022 // around using this function
2023 f->do_oop((oop*) &_vm_result);
2024 f->do_oop((oop*) &_exception_oop);
2025 f->do_oop((oop*) &_pending_async_exception);
2026 #if INCLUDE_JVMCI
2027 f->do_oop((oop*) &_jvmci_reserved_oop0);
2028 #endif
2029
2030 if (jvmti_thread_state() != NULL) {
2031 jvmti_thread_state()->oops_do(f, cf);
2032 }
2033
2034 if (LockingMode == LM_LIGHTWEIGHT) {
2035 lock_stack().oops_do(f);
2036 }
2037 }
2038
2039 void JavaThread::oops_do_frames(OopClosure* f, CodeBlobClosure* cf) {
2040 if (!has_last_Java_frame()) {
2041 return;
2042 }
2043 // Finish any pending lazy GC activity for the frames
2044 StackWatermarkSet::finish_processing(this, NULL /* context */, StackWatermarkKind::gc);
2045 // Traverse the execution stack
2046 for (StackFrameStream fst(this, true /* update */, false /* process_frames */); !fst.is_done(); fst.next()) {
2047 fst.current()->oops_do(f, cf, fst.register_map());
2048 }
2049 }
2050
2051 #ifdef ASSERT
2052 void JavaThread::verify_states_for_handshake() {
2053 // This checks that the thread has a correct frame state during a handshake.
2054 verify_frame_info();
2055 }
2056 #endif
2057
2058 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
2059 DEBUG_ONLY(verify_frame_info();)
2060
2061 if (has_last_Java_frame()) {
2062 // Traverse the execution stack
2063 for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2064 fst.current()->nmethods_do(cf);
2065 }
2066 }
2067
2068 if (jvmti_thread_state() != NULL) {
2069 jvmti_thread_state()->nmethods_do(cf);
2070 }
2071 }
2072
2073 void JavaThread::metadata_do(MetadataClosure* f) {
2074 if (has_last_Java_frame()) {
2075 // Traverse the execution stack to call f() on the methods in the stack
2076 for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2077 fst.current()->metadata_do(f);
2078 }
2079 } else if (is_Compiler_thread()) {
2080 // need to walk ciMetadata in current compile tasks to keep alive.
2081 CompilerThread* ct = (CompilerThread*)this;
2082 if (ct->env() != NULL) {
2083 ct->env()->metadata_do(f);
2084 }
2085 CompileTask* task = ct->task();
2086 if (task != NULL) {
2087 task->metadata_do(f);
2088 }
2089 }
2090 }
2091
2092 // Printing
2093 const char* _get_thread_state_name(JavaThreadState _thread_state) {
2094 switch (_thread_state) {
2095 case _thread_uninitialized: return "_thread_uninitialized";
2096 case _thread_new: return "_thread_new";
2097 case _thread_new_trans: return "_thread_new_trans";
2098 case _thread_in_native: return "_thread_in_native";
2099 case _thread_in_native_trans: return "_thread_in_native_trans";
2100 case _thread_in_vm: return "_thread_in_vm";
2101 case _thread_in_vm_trans: return "_thread_in_vm_trans";
2102 case _thread_in_Java: return "_thread_in_Java";
2103 case _thread_in_Java_trans: return "_thread_in_Java_trans";
2104 case _thread_blocked: return "_thread_blocked";
2105 case _thread_blocked_trans: return "_thread_blocked_trans";
2106 default: return "unknown thread state";
2107 }
2108 }
2109
2110 #ifndef PRODUCT
2111 void JavaThread::print_thread_state_on(outputStream *st) const {
2112 st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state));
2113 };
2114 #endif // PRODUCT
2115
2116 // Called by Threads::print() for VM_PrintThreads operation
2117 void JavaThread::print_on(outputStream *st, bool print_extended_info) const {
2118 st->print_raw("\"");
2119 st->print_raw(get_thread_name());
2120 st->print_raw("\" ");
2121 oop thread_oop = threadObj();
2122 if (thread_oop != NULL) {
2123 st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop));
2124 if (java_lang_Thread::is_daemon(thread_oop)) st->print("daemon ");
2125 st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
2126 }
2127 Thread::print_on(st, print_extended_info);
2128 // print guess for valid stack memory region (assume 4K pages); helps lock debugging
2129 st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
2130 if (thread_oop != NULL) {
2131 st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
2132 }
2133 #ifndef PRODUCT
2134 _safepoint_state->print_on(st);
2135 #endif // PRODUCT
2136 if (is_Compiler_thread()) {
2137 CompileTask *task = ((CompilerThread*)this)->task();
2138 if (task != NULL) {
2139 st->print(" Compiling: ");
2140 task->print(st, NULL, true, false);
2141 } else {
2142 st->print(" No compile task");
2143 }
2144 st->cr();
2145 }
2146 }
2147
2148 void JavaThread::print() const { print_on(tty); }
2149
2150 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
2151 st->print("%s", get_thread_name_string(buf, buflen));
2152 }
2153
2154 // Called by fatal error handler. The difference between this and
2155 // JavaThread::print() is that we can't grab lock or allocate memory.
2156 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
2157 st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
2158 oop thread_obj = threadObj();
2159 if (thread_obj != NULL) {
2160 if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
2161 }
2162 st->print(" [");
2163 st->print("%s", _get_thread_state_name(_thread_state));
2164 if (osthread()) {
2165 st->print(", id=%d", osthread()->thread_id());
2166 }
2167 st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
2168 p2i(stack_end()), p2i(stack_base()));
2169 st->print("]");
2170
2171 ThreadsSMRSupport::print_info_on(this, st);
2172 return;
2173 }
2174
2175
2176 // Verification
2177
2178 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
2179 // ignore if there is no stack
2180 if (!has_last_Java_frame()) return;
2181 // traverse the stack frames. Starts from top frame.
2182 for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2183 frame* fr = fst.current();
2184 f(fr, fst.register_map());
2185 }
2186 }
2187
2188 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
2189
2190 void JavaThread::verify() {
2191 // Verify oops in the thread.
2192 oops_do(&VerifyOopClosure::verify_oop, NULL);
2193
2194 // Verify the stack frames.
2195 frames_do(frame_verify);
2196 }
2197
2198 // CR 6300358 (sub-CR 2137150)
2199 // Most callers of this method assume that it can't return NULL but a
2200 // thread may not have a name whilst it is in the process of attaching to
2201 // the VM - see CR 6412693, and there are places where a JavaThread can be
2202 // seen prior to having its threadObj set (e.g., JNI attaching threads and
2203 // if vm exit occurs during initialization). These cases can all be accounted
2204 // for such that this method never returns NULL.
2205 const char* JavaThread::get_thread_name() const {
2206 if (Thread::is_JavaThread_protected(this)) {
2207 // The target JavaThread is protected so get_thread_name_string() is safe:
2208 return get_thread_name_string();
2209 }
2210
2211 // The target JavaThread is not protected so we return the default:
2212 return Thread::name();
2213 }
2214
2215 // Returns a non-NULL representation of this thread's name, or a suitable
2216 // descriptive string if there is no set name.
2217 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
2218 const char* name_str;
2219 oop thread_obj = threadObj();
2220 if (thread_obj != NULL) {
2221 oop name = java_lang_Thread::name(thread_obj);
2222 if (name != NULL) {
2223 if (buf == NULL) {
2224 name_str = java_lang_String::as_utf8_string(name);
2225 } else {
2226 name_str = java_lang_String::as_utf8_string(name, buf, buflen);
2227 }
2228 } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
2229 name_str = "<no-name - thread is attaching>";
2230 } else {
2231 name_str = Thread::name();
2232 }
2233 } else {
2234 name_str = Thread::name();
2235 }
2236 assert(name_str != NULL, "unexpected NULL thread name");
2237 return name_str;
2238 }
2239
2240 // Helper to extract the name from the thread oop for logging.
2241 const char* JavaThread::name_for(oop thread_obj) {
2242 assert(thread_obj != NULL, "precondition");
2243 oop name = java_lang_Thread::name(thread_obj);
2244 const char* name_str;
2245 if (name != NULL) {
2246 name_str = java_lang_String::as_utf8_string(name);
2247 } else {
2248 name_str = "<un-named>";
2249 }
2250 return name_str;
2251 }
2252
2253 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
2254
2255 assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2256 assert(NoPriority <= prio && prio <= MaxPriority, "sanity check");
2257 // Link Java Thread object <-> C++ Thread
2258
2259 // Get the C++ thread object (an oop) from the JNI handle (a jthread)
2260 // and put it into a new Handle. The Handle "thread_oop" can then
2261 // be used to pass the C++ thread object to other methods.
2262
2263 // Set the Java level thread object (jthread) field of the
2264 // new thread (a JavaThread *) to C++ thread object using the
2265 // "thread_oop" handle.
2266
2267 // Set the thread field (a JavaThread *) of the
2268 // oop representing the java_lang_Thread to the new thread (a JavaThread *).
2269
2270 Handle thread_oop(Thread::current(),
2271 JNIHandles::resolve_non_null(jni_thread));
2272 assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
2273 "must be initialized");
2274 set_threadObj(thread_oop());
2275
2276 if (prio == NoPriority) {
2277 prio = java_lang_Thread::priority(thread_oop());
2278 assert(prio != NoPriority, "A valid priority should be present");
2279 }
2280
2281 // Push the Java priority down to the native thread; needs Threads_lock
2282 Thread::set_priority(this, prio);
2283
2284 // Add the new thread to the Threads list and set it in motion.
2285 // We must have threads lock in order to call Threads::add.
2286 // It is crucial that we do not block before the thread is
2287 // added to the Threads list for if a GC happens, then the java_thread oop
2288 // will not be visited by GC.
2289 Threads::add(this);
2290 // Publish the JavaThread* in java.lang.Thread after the JavaThread* is
2291 // on a ThreadsList. We don't want to wait for the release when the
2292 // Theads_lock is dropped somewhere in the caller since the JavaThread*
2293 // is already visible to JVM/TI via the ThreadsList.
2294 java_lang_Thread::release_set_thread(thread_oop(), this);
2295 }
2296
2297 oop JavaThread::current_park_blocker() {
2298 // Support for JSR-166 locks
2299 oop thread_oop = threadObj();
2300 if (thread_oop != NULL) {
2301 return java_lang_Thread::park_blocker(thread_oop);
2302 }
2303 return NULL;
2304 }
2305
2306 // Print current stack trace for checked JNI warnings and JNI fatal errors.
2307 // This is the external format, selecting the platform
2308 // as applicable, and allowing for a native-only stack.
2309 void JavaThread::print_jni_stack() {
2310 assert(this == JavaThread::current(), "Can't print stack of other threads");
2311 if (!has_last_Java_frame()) {
2312 ResourceMark rm(this);
2313 char* buf = NEW_RESOURCE_ARRAY_RETURN_NULL(char, O_BUFLEN);
2314 if (buf == nullptr) {
2315 tty->print_cr("Unable to print native stack - out of memory");
2316 return;
2317 }
2318 frame f = os::current_frame();
2319 VMError::print_native_stack(tty, f, this,
2320 buf, O_BUFLEN);
2321 } else {
2322 print_stack_on(tty);
2323 }
2324 }
2325
2326 void JavaThread::print_stack_on(outputStream* st) {
2327 if (!has_last_Java_frame()) return;
2328
2329 Thread* current_thread = Thread::current();
2330 ResourceMark rm(current_thread);
2331 HandleMark hm(current_thread);
2332
2333 RegisterMap reg_map(this);
2334 vframe* start_vf = last_java_vframe(®_map);
2335 int count = 0;
2336 for (vframe* f = start_vf; f != NULL; f = f->sender()) {
2337 if (f->is_java_frame()) {
2338 javaVFrame* jvf = javaVFrame::cast(f);
2339 java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
2340
2341 // Print out lock information
2342 if (JavaMonitorsInStackTrace) {
2343 jvf->print_lock_info_on(st, count);
2344 }
2345 } else {
2346 // Ignore non-Java frames
2347 }
2348
2349 // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0
2350 count++;
2351 if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return;
2352 }
2353 }
2354
2355
2356 // JVMTI PopFrame support
2357 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
2358 assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
2359 if (in_bytes(size_in_bytes) != 0) {
2360 _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
2361 _popframe_preserved_args_size = in_bytes(size_in_bytes);
2362 Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
2363 }
2364 }
2365
2366 void* JavaThread::popframe_preserved_args() {
2367 return _popframe_preserved_args;
2368 }
2369
2370 ByteSize JavaThread::popframe_preserved_args_size() {
2371 return in_ByteSize(_popframe_preserved_args_size);
2372 }
2373
2374 WordSize JavaThread::popframe_preserved_args_size_in_words() {
2375 int sz = in_bytes(popframe_preserved_args_size());
2376 assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
2377 return in_WordSize(sz / wordSize);
2378 }
2379
2380 void JavaThread::popframe_free_preserved_args() {
2381 assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
2382 FREE_C_HEAP_ARRAY(char, (char*)_popframe_preserved_args);
2383 _popframe_preserved_args = NULL;
2384 _popframe_preserved_args_size = 0;
2385 }
2386
2387 #ifndef PRODUCT
2388
2389 void JavaThread::trace_frames() {
2390 tty->print_cr("[Describe stack]");
2391 int frame_no = 1;
2392 for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2393 tty->print(" %d. ", frame_no++);
2394 fst.current()->print_value_on(tty, this);
2395 tty->cr();
2396 }
2397 }
2398
2399 class PrintAndVerifyOopClosure: public OopClosure {
2400 protected:
2401 template <class T> inline void do_oop_work(T* p) {
2402 oop obj = RawAccess<>::oop_load(p);
2403 if (obj == NULL) return;
2404 tty->print(INTPTR_FORMAT ": ", p2i(p));
2405 if (oopDesc::is_oop_or_null(obj)) {
2406 if (obj->is_objArray()) {
2407 tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj));
2408 } else {
2409 obj->print();
2410 }
2411 } else {
2412 tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj));
2413 }
2414 tty->cr();
2415 }
2416 public:
2417 virtual void do_oop(oop* p) { do_oop_work(p); }
2418 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
2419 };
2420
2421 #ifdef ASSERT
2422 // Print or validate the layout of stack frames
2423 void JavaThread::print_frame_layout(int depth, bool validate_only) {
2424 ResourceMark rm;
2425 PreserveExceptionMark pm(this);
2426 FrameValues values;
2427 int frame_no = 0;
2428 for (StackFrameStream fst(this, false /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2429 fst.current()->describe(values, ++frame_no);
2430 if (depth == frame_no) break;
2431 }
2432 if (validate_only) {
2433 values.validate();
2434 } else {
2435 tty->print_cr("[Describe stack layout]");
2436 values.print(this);
2437 }
2438 }
2439 #endif
2440
2441 void JavaThread::trace_stack_from(vframe* start_vf) {
2442 ResourceMark rm;
2443 int vframe_no = 1;
2444 for (vframe* f = start_vf; f; f = f->sender()) {
2445 if (f->is_java_frame()) {
2446 javaVFrame::cast(f)->print_activation(vframe_no++);
2447 } else {
2448 f->print();
2449 }
2450 if (vframe_no > StackPrintLimit) {
2451 tty->print_cr("...<more frames>...");
2452 return;
2453 }
2454 }
2455 }
2456
2457
2458 void JavaThread::trace_stack() {
2459 if (!has_last_Java_frame()) return;
2460 Thread* current_thread = Thread::current();
2461 ResourceMark rm(current_thread);
2462 HandleMark hm(current_thread);
2463 RegisterMap reg_map(this);
2464 trace_stack_from(last_java_vframe(®_map));
2465 }
2466
2467
2468 #endif // PRODUCT
2469
2470
2471 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
2472 assert(reg_map != NULL, "a map must be given");
2473 frame f = last_frame();
2474 for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) {
2475 if (vf->is_java_frame()) return javaVFrame::cast(vf);
2476 }
2477 return NULL;
2478 }
2479
2480
2481 Klass* JavaThread::security_get_caller_class(int depth) {
2482 vframeStream vfst(this);
2483 vfst.security_get_caller_frame(depth);
2484 if (!vfst.at_end()) {
2485 return vfst.method()->method_holder();
2486 }
2487 return NULL;
2488 }
2489
2490 // java.lang.Thread.sleep support
2491 // Returns true if sleep time elapsed as expected, and false
2492 // if the thread was interrupted.
2493 bool JavaThread::sleep(jlong millis) {
2494 assert(this == Thread::current(), "thread consistency check");
2495
2496 ParkEvent * const slp = this->_SleepEvent;
2497 // Because there can be races with thread interruption sending an unpark()
2498 // to the event, we explicitly reset it here to avoid an immediate return.
2499 // The actual interrupt state will be checked before we park().
2500 slp->reset();
2501 // Thread interruption establishes a happens-before ordering in the
2502 // Java Memory Model, so we need to ensure we synchronize with the
2503 // interrupt state.
2504 OrderAccess::fence();
2505
2506 jlong prevtime = os::javaTimeNanos();
2507
2508 for (;;) {
2509 // interruption has precedence over timing out
2510 if (this->is_interrupted(true)) {
2511 return false;
2512 }
2513
2514 if (millis <= 0) {
2515 return true;
2516 }
2517
2518 {
2519 ThreadBlockInVM tbivm(this);
2520 OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
2521 slp->park(millis);
2522 }
2523
2524 // Update elapsed time tracking
2525 jlong newtime = os::javaTimeNanos();
2526 if (newtime - prevtime < 0) {
2527 // time moving backwards, should only happen if no monotonic clock
2528 // not a guarantee() because JVM should not abort on kernel/glibc bugs
2529 assert(false,
2530 "unexpected time moving backwards detected in JavaThread::sleep()");
2531 } else {
2532 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
2533 }
2534 prevtime = newtime;
2535 }
2536 }
2537
2538
2539 // ======= Threads ========
2540
2541 // The Threads class links together all active threads, and provides
2542 // operations over all threads. It is protected by the Threads_lock,
2543 // which is also used in other global contexts like safepointing.
2544 // ThreadsListHandles are used to safely perform operations on one
2545 // or more threads without the risk of the thread exiting during the
2546 // operation.
2547 //
2548 // Note: The Threads_lock is currently more widely used than we
2549 // would like. We are actively migrating Threads_lock uses to other
2550 // mechanisms in order to reduce Threads_lock contention.
2551
2552 int Threads::_number_of_threads = 0;
2553 int Threads::_number_of_non_daemon_threads = 0;
2554 int Threads::_return_code = 0;
2555 uintx Threads::_thread_claim_token = 1; // Never zero.
2556 size_t JavaThread::_stack_size_at_create = 0;
2557
2558 #ifdef ASSERT
2559 bool Threads::_vm_complete = false;
2560 #endif
2561
2562 static inline void *prefetch_and_load_ptr(void **addr, intx prefetch_interval) {
2563 Prefetch::read((void*)addr, prefetch_interval);
2564 return *addr;
2565 }
2566
2567 // Possibly the ugliest for loop the world has seen. C++ does not allow
2568 // multiple types in the declaration section of the for loop. In this case
2569 // we are only dealing with pointers and hence can cast them. It looks ugly
2570 // but macros are ugly and therefore it's fine to make things absurdly ugly.
2571 #define DO_JAVA_THREADS(LIST, X) \
2572 for (JavaThread *MACRO_scan_interval = (JavaThread*)(uintptr_t)PrefetchScanIntervalInBytes, \
2573 *MACRO_list = (JavaThread*)(LIST), \
2574 **MACRO_end = ((JavaThread**)((ThreadsList*)MACRO_list)->threads()) + ((ThreadsList*)MACRO_list)->length(), \
2575 **MACRO_current_p = (JavaThread**)((ThreadsList*)MACRO_list)->threads(), \
2576 *X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval); \
2577 MACRO_current_p != MACRO_end; \
2578 MACRO_current_p++, \
2579 X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval))
2580
2581 // All JavaThreads
2582 #define ALL_JAVA_THREADS(X) DO_JAVA_THREADS(ThreadsSMRSupport::get_java_thread_list(), X)
2583
2584 // All NonJavaThreads (i.e., every non-JavaThread in the system).
2585 void Threads::non_java_threads_do(ThreadClosure* tc) {
2586 NoSafepointVerifier nsv;
2587 for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) {
2588 tc->do_thread(njti.current());
2589 }
2590 }
2591
2592 // All JavaThreads
2593 void Threads::java_threads_do(ThreadClosure* tc) {
2594 assert_locked_or_safepoint(Threads_lock);
2595 // ALL_JAVA_THREADS iterates through all JavaThreads.
2596 ALL_JAVA_THREADS(p) {
2597 tc->do_thread(p);
2598 }
2599 }
2600
2601 void Threads::java_threads_and_vm_thread_do(ThreadClosure* tc) {
2602 assert_locked_or_safepoint(Threads_lock);
2603 java_threads_do(tc);
2604 tc->do_thread(VMThread::vm_thread());
2605 }
2606
2607 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system).
2608 void Threads::threads_do(ThreadClosure* tc) {
2609 assert_locked_or_safepoint(Threads_lock);
2610 java_threads_do(tc);
2611 non_java_threads_do(tc);
2612 }
2613
2614 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) {
2615 uintx claim_token = Threads::thread_claim_token();
2616 ALL_JAVA_THREADS(p) {
2617 if (p->claim_threads_do(is_par, claim_token)) {
2618 tc->do_thread(p);
2619 }
2620 }
2621 VMThread* vmt = VMThread::vm_thread();
2622 if (vmt->claim_threads_do(is_par, claim_token)) {
2623 tc->do_thread(vmt);
2624 }
2625 }
2626
2627 // The system initialization in the library has three phases.
2628 //
2629 // Phase 1: java.lang.System class initialization
2630 // java.lang.System is a primordial class loaded and initialized
2631 // by the VM early during startup. java.lang.System.<clinit>
2632 // only does registerNatives and keeps the rest of the class
2633 // initialization work later until thread initialization completes.
2634 //
2635 // System.initPhase1 initializes the system properties, the static
2636 // fields in, out, and err. Set up java signal handlers, OS-specific
2637 // system settings, and thread group of the main thread.
2638 static void call_initPhase1(TRAPS) {
2639 Klass* klass = vmClasses::System_klass();
2640 JavaValue result(T_VOID);
2641 JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(),
2642 vmSymbols::void_method_signature(), CHECK);
2643 }
2644
2645 // Phase 2. Module system initialization
2646 // This will initialize the module system. Only java.base classes
2647 // can be loaded until phase 2 completes.
2648 //
2649 // Call System.initPhase2 after the compiler initialization and jsr292
2650 // classes get initialized because module initialization runs a lot of java
2651 // code, that for performance reasons, should be compiled. Also, this will
2652 // enable the startup code to use lambda and other language features in this
2653 // phase and onward.
2654 //
2655 // After phase 2, The VM will begin search classes from -Xbootclasspath/a.
2656 static void call_initPhase2(TRAPS) {
2657 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
2658
2659 Klass* klass = vmClasses::System_klass();
2660
2661 JavaValue result(T_INT);
2662 JavaCallArguments args;
2663 args.push_int(DisplayVMOutputToStderr);
2664 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
2665 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
2666 vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
2667 if (result.get_jint() != JNI_OK) {
2668 vm_exit_during_initialization(); // no message or exception
2669 }
2670
2671 universe_post_module_init();
2672 }
2673
2674 // Phase 3. final setup - set security manager, system class loader and TCCL
2675 //
2676 // This will instantiate and set the security manager, set the system class
2677 // loader as well as the thread context class loader. The security manager
2678 // and system class loader may be a custom class loaded from -Xbootclasspath/a,
2679 // other modules or the application's classpath.
2680 static void call_initPhase3(TRAPS) {
2681 Klass* klass = vmClasses::System_klass();
2682 JavaValue result(T_VOID);
2683 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
2684 vmSymbols::void_method_signature(), CHECK);
2685 }
2686
2687 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
2688 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
2689
2690 if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
2691 create_vm_init_libraries();
2692 }
2693
2694 initialize_class(vmSymbols::java_lang_String(), CHECK);
2695
2696 // Inject CompactStrings value after the static initializers for String ran.
2697 java_lang_String::set_compact_strings(CompactStrings);
2698
2699 // Initialize java_lang.System (needed before creating the thread)
2700 initialize_class(vmSymbols::java_lang_System(), CHECK);
2701 // The VM creates & returns objects of this class. Make sure it's initialized.
2702 initialize_class(vmSymbols::java_lang_Class(), CHECK);
2703 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
2704 Handle thread_group = create_initial_thread_group(CHECK);
2705 Universe::set_main_thread_group(thread_group());
2706 initialize_class(vmSymbols::java_lang_Thread(), CHECK);
2707 create_initial_thread(thread_group, main_thread, CHECK);
2708
2709 // The VM creates objects of this class.
2710 initialize_class(vmSymbols::java_lang_Module(), CHECK);
2711
2712 #ifdef ASSERT
2713 InstanceKlass *k = vmClasses::UnsafeConstants_klass();
2714 assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
2715 #endif
2716
2717 // initialize the hardware-specific constants needed by Unsafe
2718 initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
2719 jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
2720
2721 // The VM preresolves methods to these classes. Make sure that they get initialized
2722 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
2723 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
2724
2725 // Phase 1 of the system initialization in the library, java.lang.System class initialization
2726 call_initPhase1(CHECK);
2727
2728 // Get the Java runtime name, version, and vendor info after java.lang.System is initialized.
2729 // Some values are actually configure-time constants but some can be set via the jlink tool and
2730 // so must be read dynamically. We treat them all the same.
2731 InstanceKlass* ik = SystemDictionary::find_instance_klass(vmSymbols::java_lang_VersionProps(),
2732 Handle(), Handle());
2733 {
2734 ResourceMark rm(main_thread);
2735 JDK_Version::set_java_version(get_java_version_info(ik, vmSymbols::java_version_name()));
2736
2737 JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name()));
2738
2739 JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
2740
2741 JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
2742
2743 JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
2744 }
2745
2746 // an instance of OutOfMemory exception has been allocated earlier
2747 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
2748 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
2749 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
2750 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
2751 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
2752 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
2753 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
2754 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
2755 }
2756
2757 void Threads::initialize_jsr292_core_classes(TRAPS) {
2758 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
2759
2760 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
2761 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
2762 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
2763 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
2764 }
2765
2766 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
2767 extern void JDK_Version_init();
2768
2769 // Preinitialize version info.
2770 VM_Version::early_initialize();
2771
2772 // Check version
2773 if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
2774
2775 // Initialize library-based TLS
2776 ThreadLocalStorage::init();
2777
2778 // Initialize the output stream module
2779 ostream_init();
2780
2781 // Process java launcher properties.
2782 Arguments::process_sun_java_launcher_properties(args);
2783
2784 // Initialize the os module
2785 os::init();
2786
2787 MACOS_AARCH64_ONLY(os::current_thread_enable_wx(WXWrite));
2788
2789 // Record VM creation timing statistics
2790 TraceVmCreationTime create_vm_timer;
2791 create_vm_timer.start();
2792
2793 // Initialize system properties.
2794 Arguments::init_system_properties();
2795
2796 // So that JDK version can be used as a discriminator when parsing arguments
2797 JDK_Version_init();
2798
2799 // Update/Initialize System properties after JDK version number is known
2800 Arguments::init_version_specific_system_properties();
2801
2802 // Make sure to initialize log configuration *before* parsing arguments
2803 LogConfiguration::initialize(create_vm_timer.begin_time());
2804
2805 // Parse arguments
2806 // Note: this internally calls os::init_container_support()
2807 jint parse_result = Arguments::parse(args);
2808 if (parse_result != JNI_OK) return parse_result;
2809
2810 #if INCLUDE_NMT
2811 // Initialize NMT right after argument parsing to keep the pre-NMT-init window small.
2812 MemTracker::initialize();
2813 #endif // INCLUDE_NMT
2814
2815 os::init_before_ergo();
2816
2817 jint ergo_result = Arguments::apply_ergo();
2818 if (ergo_result != JNI_OK) return ergo_result;
2819
2820 // Final check of all ranges after ergonomics which may change values.
2821 if (!JVMFlagLimit::check_all_ranges()) {
2822 return JNI_EINVAL;
2823 }
2824
2825 // Final check of all 'AfterErgo' constraints after ergonomics which may change values.
2826 bool constraint_result = JVMFlagLimit::check_all_constraints(JVMFlagConstraintPhase::AfterErgo);
2827 if (!constraint_result) {
2828 return JNI_EINVAL;
2829 }
2830
2831 if (PauseAtStartup) {
2832 os::pause();
2833 }
2834
2835 HOTSPOT_VM_INIT_BEGIN();
2836
2837 // Timing (must come after argument parsing)
2838 TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime));
2839
2840 // Initialize the os module after parsing the args
2841 jint os_init_2_result = os::init_2();
2842 if (os_init_2_result != JNI_OK) return os_init_2_result;
2843
2844 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
2845 // Initialize assert poison page mechanism.
2846 if (ShowRegistersOnAssert) {
2847 initialize_assert_poison();
2848 }
2849 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
2850
2851 SafepointMechanism::initialize();
2852
2853 jint adjust_after_os_result = Arguments::adjust_after_os();
2854 if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
2855
2856 // Initialize output stream logging
2857 ostream_init_log();
2858
2859 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
2860 // Must be before create_vm_init_agents()
2861 if (Arguments::init_libraries_at_startup()) {
2862 convert_vm_init_libraries_to_agents();
2863 }
2864
2865 // Should happen before any agent attaches and pokes into vmStructs
2866 #if INCLUDE_VM_STRUCTS
2867 if (UseCompactObjectHeaders) {
2868 VMStructs::compact_headers_overrides();
2869 }
2870 #endif
2871
2872 // Launch -agentlib/-agentpath and converted -Xrun agents
2873 if (Arguments::init_agents_at_startup()) {
2874 create_vm_init_agents();
2875 }
2876
2877 // Initialize Threads state
2878 _number_of_threads = 0;
2879 _number_of_non_daemon_threads = 0;
2880
2881 // Initialize global data structures and create system classes in heap
2882 vm_init_globals();
2883
2884 #if INCLUDE_JVMCI
2885 if (JVMCICounterSize > 0) {
2886 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
2887 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
2888 } else {
2889 JavaThread::_jvmci_old_thread_counters = NULL;
2890 }
2891 #endif // INCLUDE_JVMCI
2892
2893 // Initialize OopStorage for threadObj
2894 _thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
2895
2896 // Attach the main thread to this os thread
2897 JavaThread* main_thread = new JavaThread();
2898 main_thread->set_thread_state(_thread_in_vm);
2899 main_thread->initialize_thread_current();
2900 // must do this before set_active_handles
2901 main_thread->record_stack_base_and_size();
2902 main_thread->register_thread_stack_with_NMT();
2903 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
2904 MACOS_AARCH64_ONLY(main_thread->init_wx());
2905
2906 if (!main_thread->set_as_starting_thread()) {
2907 vm_shutdown_during_initialization(
2908 "Failed necessary internal allocation. Out of swap space");
2909 main_thread->smr_delete();
2910 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
2911 return JNI_ENOMEM;
2912 }
2913
2914 // Enable guard page *after* os::create_main_thread(), otherwise it would
2915 // crash Linux VM, see notes in os_linux.cpp.
2916 main_thread->stack_overflow_state()->create_stack_guard_pages();
2917
2918 // Initialize Java-Level synchronization subsystem
2919 ObjectMonitor::Initialize();
2920 ObjectSynchronizer::initialize();
2921
2922 // Initialize global modules
2923 jint status = init_globals();
2924 if (status != JNI_OK) {
2925 main_thread->smr_delete();
2926 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
2927 return status;
2928 }
2929
2930 JFR_ONLY(Jfr::on_create_vm_1();)
2931
2932 // Should be done after the heap is fully created
2933 main_thread->cache_global_variables();
2934
2935 { MutexLocker mu(Threads_lock);
2936 Threads::add(main_thread);
2937 }
2938
2939 // Any JVMTI raw monitors entered in onload will transition into
2940 // real raw monitor. VM is setup enough here for raw monitor enter.
2941 JvmtiExport::transition_pending_onload_raw_monitors();
2942
2943 // Create the VMThread
2944 { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime));
2945
2946 VMThread::create();
2947 Thread* vmthread = VMThread::vm_thread();
2948
2949 if (!os::create_thread(vmthread, os::vm_thread)) {
2950 vm_exit_during_initialization("Cannot create VM thread. "
2951 "Out of system resources.");
2952 }
2953
2954 // Wait for the VM thread to become ready, and VMThread::run to initialize
2955 // Monitors can have spurious returns, must always check another state flag
2956 {
2957 MonitorLocker ml(Notify_lock);
2958 os::start_thread(vmthread);
2959 while (vmthread->active_handles() == NULL) {
2960 ml.wait();
2961 }
2962 }
2963 }
2964
2965 assert(Universe::is_fully_initialized(), "not initialized");
2966 if (VerifyDuringStartup) {
2967 // Make sure we're starting with a clean slate.
2968 VM_Verify verify_op;
2969 VMThread::execute(&verify_op);
2970 }
2971
2972 // We need this to update the java.vm.info property in case any flags used
2973 // to initially define it have been changed. This is needed for both CDS
2974 // since UseSharedSpaces may be changed after java.vm.info
2975 // is initially computed. See Abstract_VM_Version::vm_info_string().
2976 // This update must happen before we initialize the java classes, but
2977 // after any initialization logic that might modify the flags.
2978 Arguments::update_vm_info_property(VM_Version::vm_info_string());
2979
2980 JavaThread* THREAD = JavaThread::current(); // For exception macros.
2981 HandleMark hm(THREAD);
2982
2983 // Always call even when there are not JVMTI environments yet, since environments
2984 // may be attached late and JVMTI must track phases of VM execution
2985 JvmtiExport::enter_early_start_phase();
2986
2987 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
2988 JvmtiExport::post_early_vm_start();
2989
2990 initialize_java_lang_classes(main_thread, CHECK_JNI_ERR);
2991
2992 quicken_jni_functions();
2993
2994 // No more stub generation allowed after that point.
2995 StubCodeDesc::freeze();
2996
2997 // Set flag that basic initialization has completed. Used by exceptions and various
2998 // debug stuff, that does not work until all basic classes have been initialized.
2999 set_init_completed();
3000
3001 LogConfiguration::post_initialize();
3002 Metaspace::post_initialize();
3003
3004 HOTSPOT_VM_INIT_END();
3005
3006 // record VM initialization completion time
3007 #if INCLUDE_MANAGEMENT
3008 Management::record_vm_init_completed();
3009 #endif // INCLUDE_MANAGEMENT
3010
3011 // Signal Dispatcher needs to be started before VMInit event is posted
3012 os::initialize_jdk_signal_support(CHECK_JNI_ERR);
3013
3014 // Start Attach Listener if +StartAttachListener or it can't be started lazily
3015 if (!DisableAttachMechanism) {
3016 AttachListener::vm_start();
3017 if (StartAttachListener || AttachListener::init_at_startup()) {
3018 AttachListener::init();
3019 }
3020 }
3021
3022 // Launch -Xrun agents
3023 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3024 // back-end can launch with -Xdebug -Xrunjdwp.
3025 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3026 create_vm_init_libraries();
3027 }
3028
3029 Chunk::start_chunk_pool_cleaner_task();
3030
3031 // Start the service thread
3032 // The service thread enqueues JVMTI deferred events and does various hashtable
3033 // and other cleanups. Needs to start before the compilers start posting events.
3034 ServiceThread::initialize();
3035
3036 // Start the monitor deflation thread:
3037 MonitorDeflationThread::initialize();
3038
3039 // initialize compiler(s)
3040 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
3041 #if INCLUDE_JVMCI
3042 bool force_JVMCI_intialization = false;
3043 if (EnableJVMCI) {
3044 // Initialize JVMCI eagerly when it is explicitly requested.
3045 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
3046 force_JVMCI_intialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
3047
3048 if (!force_JVMCI_intialization) {
3049 // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking
3050 // compilations via JVMCI will not actually block until JVMCI is initialized.
3051 force_JVMCI_intialization = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation);
3052 }
3053 }
3054 #endif
3055 CompileBroker::compilation_init_phase1(CHECK_JNI_ERR);
3056 // Postpone completion of compiler initialization to after JVMCI
3057 // is initialized to avoid timeouts of blocking compilations.
3058 if (JVMCI_ONLY(!force_JVMCI_intialization) NOT_JVMCI(true)) {
3059 CompileBroker::compilation_init_phase2();
3060 }
3061 #endif
3062
3063 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
3064 // It is done after compilers are initialized, because otherwise compilations of
3065 // signature polymorphic MH intrinsics can be missed
3066 // (see SystemDictionary::find_method_handle_intrinsic).
3067 initialize_jsr292_core_classes(CHECK_JNI_ERR);
3068
3069 // This will initialize the module system. Only java.base classes can be
3070 // loaded until phase 2 completes
3071 call_initPhase2(CHECK_JNI_ERR);
3072
3073 JFR_ONLY(Jfr::on_create_vm_2();)
3074
3075 // Always call even when there are not JVMTI environments yet, since environments
3076 // may be attached late and JVMTI must track phases of VM execution
3077 JvmtiExport::enter_start_phase();
3078
3079 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
3080 JvmtiExport::post_vm_start();
3081
3082 // Final system initialization including security manager and system class loader
3083 call_initPhase3(CHECK_JNI_ERR);
3084
3085 // cache the system and platform class loaders
3086 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
3087
3088 #if INCLUDE_CDS
3089 // capture the module path info from the ModuleEntryTable
3090 ClassLoader::initialize_module_path(THREAD);
3091 if (HAS_PENDING_EXCEPTION) {
3092 java_lang_Throwable::print(PENDING_EXCEPTION, tty);
3093 vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly");
3094 }
3095 #endif
3096
3097 #if INCLUDE_JVMCI
3098 if (force_JVMCI_intialization) {
3099 JVMCI::initialize_compiler(CHECK_JNI_ERR);
3100 CompileBroker::compilation_init_phase2();
3101 }
3102 #endif
3103
3104 if (NativeHeapTrimmer::enabled()) {
3105 NativeHeapTrimmer::initialize();
3106 }
3107
3108 // Always call even when there are not JVMTI environments yet, since environments
3109 // may be attached late and JVMTI must track phases of VM execution
3110 JvmtiExport::enter_live_phase();
3111
3112 // Make perfmemory accessible
3113 PerfMemory::set_accessible(true);
3114
3115 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3116 JvmtiExport::post_vm_initialized();
3117
3118 JFR_ONLY(Jfr::on_create_vm_3();)
3119
3120 #if INCLUDE_MANAGEMENT
3121 Management::initialize(THREAD);
3122
3123 if (HAS_PENDING_EXCEPTION) {
3124 // management agent fails to start possibly due to
3125 // configuration problem and is responsible for printing
3126 // stack trace if appropriate. Simply exit VM.
3127 vm_exit(1);
3128 }
3129 #endif // INCLUDE_MANAGEMENT
3130
3131 StatSampler::engage();
3132 if (CheckJNICalls) JniPeriodicChecker::engage();
3133
3134 BiasedLocking::init();
3135
3136 #if INCLUDE_RTM_OPT
3137 RTMLockingCounters::init();
3138 #endif
3139
3140 call_postVMInitHook(THREAD);
3141 // The Java side of PostVMInitHook.run must deal with all
3142 // exceptions and provide means of diagnosis.
3143 if (HAS_PENDING_EXCEPTION) {
3144 CLEAR_PENDING_EXCEPTION;
3145 }
3146
3147 {
3148 MutexLocker ml(PeriodicTask_lock);
3149 // Make sure the WatcherThread can be started by WatcherThread::start()
3150 // or by dynamic enrollment.
3151 WatcherThread::make_startable();
3152 // Start up the WatcherThread if there are any periodic tasks
3153 // NOTE: All PeriodicTasks should be registered by now. If they
3154 // aren't, late joiners might appear to start slowly (we might
3155 // take a while to process their first tick).
3156 if (PeriodicTask::num_tasks() > 0) {
3157 WatcherThread::start();
3158 }
3159 }
3160
3161 create_vm_timer.end();
3162 #ifdef ASSERT
3163 _vm_complete = true;
3164 #endif
3165
3166 if (DumpSharedSpaces) {
3167 MetaspaceShared::preload_and_dump();
3168 ShouldNotReachHere();
3169 }
3170
3171 return JNI_OK;
3172 }
3173
3174 // type for the Agent_OnLoad and JVM_OnLoad entry points
3175 extern "C" {
3176 typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
3177 }
3178 // Find a command line agent library and return its entry point for
3179 // -agentlib: -agentpath: -Xrun
3180 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
3181 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent,
3182 const char *on_load_symbols[],
3183 size_t num_symbol_entries) {
3184 OnLoadEntry_t on_load_entry = NULL;
3185 void *library = NULL;
3186
3187 if (!agent->valid()) {
3188 char buffer[JVM_MAXPATHLEN];
3189 char ebuf[1024] = "";
3190 const char *name = agent->name();
3191 const char *msg = "Could not find agent library ";
3192
3193 // First check to see if agent is statically linked into executable
3194 if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) {
3195 library = agent->os_lib();
3196 } else if (agent->is_absolute_path()) {
3197 library = os::dll_load(name, ebuf, sizeof ebuf);
3198 if (library == NULL) {
3199 const char *sub_msg = " in absolute path, with error: ";
3200 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
3201 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
3202 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
3203 // If we can't find the agent, exit.
3204 vm_exit_during_initialization(buf, NULL);
3205 FREE_C_HEAP_ARRAY(char, buf);
3206 }
3207 } else {
3208 // Try to load the agent from the standard dll directory
3209 if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
3210 name)) {
3211 library = os::dll_load(buffer, ebuf, sizeof ebuf);
3212 }
3213 if (library == NULL) { // Try the library path directory.
3214 if (os::dll_build_name(buffer, sizeof(buffer), name)) {
3215 library = os::dll_load(buffer, ebuf, sizeof ebuf);
3216 }
3217 if (library == NULL) {
3218 const char *sub_msg = " on the library path, with error: ";
3219 const char *sub_msg2 = "\nModule java.instrument may be missing from runtime image.";
3220
3221 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) +
3222 strlen(ebuf) + strlen(sub_msg2) + 1;
3223 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
3224 if (!agent->is_instrument_lib()) {
3225 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
3226 } else {
3227 jio_snprintf(buf, len, "%s%s%s%s%s", msg, name, sub_msg, ebuf, sub_msg2);
3228 }
3229 // If we can't find the agent, exit.
3230 vm_exit_during_initialization(buf, NULL);
3231 FREE_C_HEAP_ARRAY(char, buf);
3232 }
3233 }
3234 }
3235 agent->set_os_lib(library);
3236 agent->set_valid();
3237 }
3238
3239 // Find the OnLoad function.
3240 on_load_entry =
3241 CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent,
3242 false,
3243 on_load_symbols,
3244 num_symbol_entries));
3245 return on_load_entry;
3246 }
3247
3248 // Find the JVM_OnLoad entry point
3249 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
3250 const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
3251 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
3252 }
3253
3254 // Find the Agent_OnLoad entry point
3255 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
3256 const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
3257 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
3258 }
3259
3260 // For backwards compatibility with -Xrun
3261 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
3262 // treated like -agentpath:
3263 // Must be called before agent libraries are created
3264 void Threads::convert_vm_init_libraries_to_agents() {
3265 AgentLibrary* agent;
3266 AgentLibrary* next;
3267
3268 for (agent = Arguments::libraries(); agent != NULL; agent = next) {
3269 next = agent->next(); // cache the next agent now as this agent may get moved off this list
3270 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
3271
3272 // If there is an JVM_OnLoad function it will get called later,
3273 // otherwise see if there is an Agent_OnLoad
3274 if (on_load_entry == NULL) {
3275 on_load_entry = lookup_agent_on_load(agent);
3276 if (on_load_entry != NULL) {
3277 // switch it to the agent list -- so that Agent_OnLoad will be called,
3278 // JVM_OnLoad won't be attempted and Agent_OnUnload will
3279 Arguments::convert_library_to_agent(agent);
3280 } else {
3281 vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
3282 }
3283 }
3284 }
3285 }
3286
3287 // Create agents for -agentlib: -agentpath: and converted -Xrun
3288 // Invokes Agent_OnLoad
3289 // Called very early -- before JavaThreads exist
3290 void Threads::create_vm_init_agents() {
3291 extern struct JavaVM_ main_vm;
3292 AgentLibrary* agent;
3293
3294 JvmtiExport::enter_onload_phase();
3295
3296 for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
3297 // CDS dumping does not support native JVMTI agent.
3298 // CDS dumping supports Java agent if the AllowArchivingWithJavaAgent diagnostic option is specified.
3299 if (Arguments::is_dumping_archive()) {
3300 if(!agent->is_instrument_lib()) {
3301 vm_exit_during_cds_dumping("CDS dumping does not support native JVMTI agent, name", agent->name());
3302 } else if (!AllowArchivingWithJavaAgent) {
3303 vm_exit_during_cds_dumping(
3304 "Must enable AllowArchivingWithJavaAgent in order to run Java agent during CDS dumping");
3305 }
3306 }
3307
3308 OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent);
3309
3310 if (on_load_entry != NULL) {
3311 // Invoke the Agent_OnLoad function
3312 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
3313 if (err != JNI_OK) {
3314 vm_exit_during_initialization("agent library failed to init", agent->name());
3315 }
3316 } else {
3317 vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
3318 }
3319 }
3320
3321 JvmtiExport::enter_primordial_phase();
3322 }
3323
3324 extern "C" {
3325 typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
3326 }
3327
3328 void Threads::shutdown_vm_agents() {
3329 // Send any Agent_OnUnload notifications
3330 const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
3331 size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols);
3332 extern struct JavaVM_ main_vm;
3333 for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
3334
3335 // Find the Agent_OnUnload function.
3336 Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
3337 os::find_agent_function(agent,
3338 false,
3339 on_unload_symbols,
3340 num_symbol_entries));
3341
3342 // Invoke the Agent_OnUnload function
3343 if (unload_entry != NULL) {
3344 JavaThread* thread = JavaThread::current();
3345 ThreadToNativeFromVM ttn(thread);
3346 HandleMark hm(thread);
3347 (*unload_entry)(&main_vm);
3348 }
3349 }
3350 }
3351
3352 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
3353 // Invokes JVM_OnLoad
3354 void Threads::create_vm_init_libraries() {
3355 extern struct JavaVM_ main_vm;
3356 AgentLibrary* agent;
3357
3358 for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
3359 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
3360
3361 if (on_load_entry != NULL) {
3362 // Invoke the JVM_OnLoad function
3363 JavaThread* thread = JavaThread::current();
3364 ThreadToNativeFromVM ttn(thread);
3365 HandleMark hm(thread);
3366 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
3367 if (err != JNI_OK) {
3368 vm_exit_during_initialization("-Xrun library failed to init", agent->name());
3369 }
3370 } else {
3371 vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
3372 }
3373 }
3374 }
3375
3376
3377 // Last thread running calls java.lang.Shutdown.shutdown()
3378 void JavaThread::invoke_shutdown_hooks() {
3379 HandleMark hm(this);
3380
3381 // We could get here with a pending exception, if so clear it now or
3382 // it will cause MetaspaceShared::link_and_cleanup_shared_classes to
3383 // fail for dynamic dump.
3384 if (this->has_pending_exception()) {
3385 this->clear_pending_exception();
3386 }
3387
3388 #if INCLUDE_CDS
3389 // Link all classes for dynamic CDS dumping before vm exit.
3390 // Same operation is being done in JVM_BeforeHalt for handling the
3391 // case where the application calls System.exit().
3392 if (DynamicDumpSharedSpaces) {
3393 DynamicArchive::prepare_for_dynamic_dumping_at_exit();
3394 }
3395 #endif
3396
3397 EXCEPTION_MARK;
3398 Klass* shutdown_klass =
3399 SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
3400 THREAD);
3401 if (shutdown_klass != NULL) {
3402 // SystemDictionary::resolve_or_null will return null if there was
3403 // an exception. If we cannot load the Shutdown class, just don't
3404 // call Shutdown.shutdown() at all. This will mean the shutdown hooks
3405 // won't be run. Note that if a shutdown hook was registered,
3406 // the Shutdown class would have already been loaded
3407 // (Runtime.addShutdownHook will load it).
3408 JavaValue result(T_VOID);
3409 JavaCalls::call_static(&result,
3410 shutdown_klass,
3411 vmSymbols::shutdown_name(),
3412 vmSymbols::void_method_signature(),
3413 THREAD);
3414 }
3415 CLEAR_PENDING_EXCEPTION;
3416 }
3417
3418 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
3419 // the program falls off the end of main(). Another VM exit path is through
3420 // vm_exit() when the program calls System.exit() to return a value or when
3421 // there is a serious error in VM. The two shutdown paths are not exactly
3422 // the same, but they share Shutdown.shutdown() at Java level and before_exit()
3423 // and VM_Exit op at VM level.
3424 //
3425 // Shutdown sequence:
3426 // + Shutdown native memory tracking if it is on
3427 // + Wait until we are the last non-daemon thread to execute
3428 // <-- every thing is still working at this moment -->
3429 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
3430 // shutdown hooks
3431 // + Call before_exit(), prepare for VM exit
3432 // > run VM level shutdown hooks (they are registered through JVM_OnExit(),
3433 // currently the only user of this mechanism is File.deleteOnExit())
3434 // > stop StatSampler, watcher thread,
3435 // post thread end and vm death events to JVMTI,
3436 // stop signal thread
3437 // + Call JavaThread::exit(), it will:
3438 // > release JNI handle blocks, remove stack guard pages
3439 // > remove this thread from Threads list
3440 // <-- no more Java code from this thread after this point -->
3441 // + Stop VM thread, it will bring the remaining VM to a safepoint and stop
3442 // the compiler threads at safepoint
3443 // <-- do not use anything that could get blocked by Safepoint -->
3444 // + Disable tracing at JNI/JVM barriers
3445 // + Set _vm_exited flag for threads that are still running native code
3446 // + Call exit_globals()
3447 // > deletes tty
3448 // > deletes PerfMemory resources
3449 // + Delete this thread
3450 // + Return to caller
3451
3452 void Threads::destroy_vm() {
3453 JavaThread* thread = JavaThread::current();
3454
3455 #ifdef ASSERT
3456 _vm_complete = false;
3457 #endif
3458 // Wait until we are the last non-daemon thread to execute
3459 {
3460 MonitorLocker nu(Threads_lock);
3461 while (Threads::number_of_non_daemon_threads() > 1)
3462 // This wait should make safepoint checks, wait without a timeout.
3463 nu.wait(0);
3464 }
3465
3466 EventShutdown e;
3467 if (e.should_commit()) {
3468 e.set_reason("No remaining non-daemon Java threads");
3469 e.commit();
3470 }
3471
3472 // Hang forever on exit if we are reporting an error.
3473 if (ShowMessageBoxOnError && VMError::is_error_reported()) {
3474 os::infinite_sleep();
3475 }
3476 os::wait_for_keypress_at_exit();
3477
3478 // run Java level shutdown hooks
3479 thread->invoke_shutdown_hooks();
3480
3481 before_exit(thread);
3482
3483 thread->exit(true);
3484
3485 // We are no longer on the main thread list but could still be in a
3486 // secondary list where another thread may try to interact with us.
3487 // So wait until all such interactions are complete before we bring
3488 // the VM to the termination safepoint. Normally this would be done
3489 // using thread->smr_delete() below where we delete the thread, but
3490 // we can't call that after the termination safepoint is active as
3491 // we will deadlock on the Threads_lock. Once all interactions are
3492 // complete it is safe to directly delete the thread at any time.
3493 ThreadsSMRSupport::wait_until_not_protected(thread);
3494
3495 // Stop VM thread.
3496 {
3497 // 4945125 The vm thread comes to a safepoint during exit.
3498 // GC vm_operations can get caught at the safepoint, and the
3499 // heap is unparseable if they are caught. Grab the Heap_lock
3500 // to prevent this. The GC vm_operations will not be able to
3501 // queue until after the vm thread is dead. After this point,
3502 // we'll never emerge out of the safepoint before the VM exits.
3503 // Assert that the thread is terminated so that acquiring the
3504 // Heap_lock doesn't cause the terminated thread to participate in
3505 // the safepoint protocol.
3506
3507 assert(thread->is_terminated(), "must be terminated here");
3508 MutexLocker ml(Heap_lock);
3509
3510 VMThread::wait_for_vm_thread_exit();
3511 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
3512 VMThread::destroy();
3513 }
3514
3515 // Now, all Java threads are gone except daemon threads. Daemon threads
3516 // running Java code or in VM are stopped by the Safepoint. However,
3517 // daemon threads executing native code are still running. But they
3518 // will be stopped at native=>Java/VM barriers. Note that we can't
3519 // simply kill or suspend them, as it is inherently deadlock-prone.
3520
3521 VM_Exit::set_vm_exited();
3522
3523 // Clean up ideal graph printers after the VMThread has started
3524 // the final safepoint which will block all the Compiler threads.
3525 // Note that this Thread has already logically exited so the
3526 // clean_up() function's use of a JavaThreadIteratorWithHandle
3527 // would be a problem except set_vm_exited() has remembered the
3528 // shutdown thread which is granted a policy exception.
3529 #if defined(COMPILER2) && !defined(PRODUCT)
3530 IdealGraphPrinter::clean_up();
3531 #endif
3532
3533 notify_vm_shutdown();
3534
3535 // exit_globals() will delete tty
3536 exit_globals();
3537
3538 // Deleting the shutdown thread here is safe. See comment on
3539 // wait_until_not_protected() above.
3540 delete thread;
3541
3542 #if INCLUDE_JVMCI
3543 if (JVMCICounterSize > 0) {
3544 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
3545 }
3546 #endif
3547
3548 LogConfiguration::finalize();
3549 }
3550
3551
3552 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
3553 if (version == JNI_VERSION_1_1) return JNI_TRUE;
3554 return is_supported_jni_version(version);
3555 }
3556
3557
3558 jboolean Threads::is_supported_jni_version(jint version) {
3559 if (version == JNI_VERSION_1_2) return JNI_TRUE;
3560 if (version == JNI_VERSION_1_4) return JNI_TRUE;
3561 if (version == JNI_VERSION_1_6) return JNI_TRUE;
3562 if (version == JNI_VERSION_1_8) return JNI_TRUE;
3563 if (version == JNI_VERSION_9) return JNI_TRUE;
3564 if (version == JNI_VERSION_10) return JNI_TRUE;
3565 return JNI_FALSE;
3566 }
3567
3568
3569 void Threads::add(JavaThread* p, bool force_daemon) {
3570 // The threads lock must be owned at this point
3571 assert(Threads_lock->owned_by_self(), "must have threads lock");
3572
3573 BarrierSet::barrier_set()->on_thread_attach(p);
3574
3575 // Once a JavaThread is added to the Threads list, smr_delete() has
3576 // to be used to delete it. Otherwise we can just delete it directly.
3577 p->set_on_thread_list();
3578
3579 _number_of_threads++;
3580 oop threadObj = p->threadObj();
3581 bool daemon = true;
3582 // Bootstrapping problem: threadObj can be null for initial
3583 // JavaThread (or for threads attached via JNI)
3584 if ((!force_daemon) && !is_daemon((threadObj))) {
3585 _number_of_non_daemon_threads++;
3586 daemon = false;
3587 }
3588
3589 ThreadService::add_thread(p, daemon);
3590
3591 // Maintain fast thread list
3592 ThreadsSMRSupport::add_thread(p);
3593
3594 // Increase the ObjectMonitor ceiling for the new thread.
3595 ObjectSynchronizer::inc_in_use_list_ceiling();
3596
3597 // Possible GC point.
3598 Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p));
3599
3600 // Make new thread known to active EscapeBarrier
3601 EscapeBarrier::thread_added(p);
3602 }
3603
3604 void Threads::remove(JavaThread* p, bool is_daemon) {
3605 // Extra scope needed for Thread_lock, so we can check
3606 // that we do not remove thread without safepoint code notice
3607 { MonitorLocker ml(Threads_lock);
3608
3609 // BarrierSet state must be destroyed after the last thread transition
3610 // before the thread terminates. Thread transitions result in calls to
3611 // StackWatermarkSet::on_safepoint(), which performs GC processing,
3612 // requiring the GC state to be alive.
3613 BarrierSet::barrier_set()->on_thread_detach(p);
3614
3615 assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present");
3616
3617 // Maintain fast thread list
3618 ThreadsSMRSupport::remove_thread(p);
3619
3620 _number_of_threads--;
3621 if (!is_daemon) {
3622 _number_of_non_daemon_threads--;
3623
3624 // Only one thread left, do a notify on the Threads_lock so a thread waiting
3625 // on destroy_vm will wake up.
3626 if (number_of_non_daemon_threads() == 1) {
3627 ml.notify_all();
3628 }
3629 }
3630 ThreadService::remove_thread(p, is_daemon);
3631
3632 // Make sure that safepoint code disregard this thread. This is needed since
3633 // the thread might mess around with locks after this point. This can cause it
3634 // to do callbacks into the safepoint code. However, the safepoint code is not aware
3635 // of this thread since it is removed from the queue.
3636 p->set_terminated(JavaThread::_thread_terminated);
3637
3638 // Notify threads waiting in EscapeBarriers
3639 EscapeBarrier::thread_removed(p);
3640 } // unlock Threads_lock
3641
3642 // Reduce the ObjectMonitor ceiling for the exiting thread.
3643 ObjectSynchronizer::dec_in_use_list_ceiling();
3644
3645 // Since Events::log uses a lock, we grab it outside the Threads_lock
3646 Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p));
3647 }
3648
3649 // Operations on the Threads list for GC. These are not explicitly locked,
3650 // but the garbage collector must provide a safe context for them to run.
3651 // In particular, these things should never be called when the Threads_lock
3652 // is held by some other thread. (Note: the Safepoint abstraction also
3653 // uses the Threads_lock to guarantee this property. It also makes sure that
3654 // all threads gets blocked when exiting or starting).
3655
3656 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) {
3657 ALL_JAVA_THREADS(p) {
3658 p->oops_do(f, cf);
3659 }
3660 VMThread::vm_thread()->oops_do(f, cf);
3661 }
3662
3663 void Threads::change_thread_claim_token() {
3664 if (++_thread_claim_token == 0) {
3665 // On overflow of the token counter, there is a risk of future
3666 // collisions between a new global token value and a stale token
3667 // for a thread, because not all iterations visit all threads.
3668 // (Though it's pretty much a theoretical concern for non-trivial
3669 // token counter sizes.) To deal with the possibility, reset all
3670 // the thread tokens to zero on global token overflow.
3671 struct ResetClaims : public ThreadClosure {
3672 virtual void do_thread(Thread* t) {
3673 t->claim_threads_do(false, 0);
3674 }
3675 } reset_claims;
3676 Threads::threads_do(&reset_claims);
3677 // On overflow, update the global token to non-zero, to
3678 // avoid the special "never claimed" initial thread value.
3679 _thread_claim_token = 1;
3680 }
3681 }
3682
3683 #ifdef ASSERT
3684 void assert_thread_claimed(const char* kind, Thread* t, uintx expected) {
3685 const uintx token = t->threads_do_token();
3686 assert(token == expected,
3687 "%s " PTR_FORMAT " has incorrect value " UINTX_FORMAT " != "
3688 UINTX_FORMAT, kind, p2i(t), token, expected);
3689 }
3690
3691 void Threads::assert_all_threads_claimed() {
3692 ALL_JAVA_THREADS(p) {
3693 assert_thread_claimed("Thread", p, _thread_claim_token);
3694 }
3695 assert_thread_claimed("VMThread", VMThread::vm_thread(), _thread_claim_token);
3696 }
3697 #endif // ASSERT
3698
3699 class ParallelOopsDoThreadClosure : public ThreadClosure {
3700 private:
3701 OopClosure* _f;
3702 CodeBlobClosure* _cf;
3703 public:
3704 ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {}
3705 void do_thread(Thread* t) {
3706 t->oops_do(_f, _cf);
3707 }
3708 };
3709
3710 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) {
3711 ParallelOopsDoThreadClosure tc(f, cf);
3712 possibly_parallel_threads_do(is_par, &tc);
3713 }
3714
3715 void Threads::metadata_do(MetadataClosure* f) {
3716 ALL_JAVA_THREADS(p) {
3717 p->metadata_do(f);
3718 }
3719 }
3720
3721 class ThreadHandlesClosure : public ThreadClosure {
3722 void (*_f)(Metadata*);
3723 public:
3724 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
3725 virtual void do_thread(Thread* thread) {
3726 thread->metadata_handles_do(_f);
3727 }
3728 };
3729
3730 void Threads::metadata_handles_do(void f(Metadata*)) {
3731 // Only walk the Handles in Thread.
3732 ThreadHandlesClosure handles_closure(f);
3733 threads_do(&handles_closure);
3734 }
3735
3736 // Get count Java threads that are waiting to enter the specified monitor.
3737 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list,
3738 int count,
3739 address monitor) {
3740 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
3741
3742 int i = 0;
3743 DO_JAVA_THREADS(t_list, p) {
3744 if (!p->can_call_java()) continue;
3745
3746 // The first stage of async deflation does not affect any field
3747 // used by this comparison so the ObjectMonitor* is usable here.
3748 address pending = (address)p->current_pending_monitor();
3749 if (pending == monitor) { // found a match
3750 if (i < count) result->append(p); // save the first count matches
3751 i++;
3752 }
3753 }
3754
3755 return result;
3756 }
3757
3758
3759 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list,
3760 address owner) {
3761 assert(LockingMode != LM_LIGHTWEIGHT, "Not with new lightweight locking");
3762 // NULL owner means not locked so we can skip the search
3763 if (owner == NULL) return NULL;
3764
3765 DO_JAVA_THREADS(t_list, p) {
3766 // first, see if owner is the address of a Java thread
3767 if (owner == (address)p) return p;
3768 }
3769
3770 // Cannot assert on lack of success here since this function may be
3771 // used by code that is trying to report useful problem information
3772 // like deadlock detection.
3773 if (UseHeavyMonitors) return NULL;
3774
3775 // If we didn't find a matching Java thread and we didn't force use of
3776 // heavyweight monitors, then the owner is the stack address of the
3777 // Lock Word in the owning Java thread's stack.
3778 //
3779 JavaThread* the_owner = NULL;
3780 DO_JAVA_THREADS(t_list, q) {
3781 if (q->is_lock_owned(owner)) {
3782 the_owner = q;
3783 break;
3784 }
3785 }
3786
3787 // cannot assert on lack of success here; see above comment
3788 return the_owner;
3789 }
3790
3791 JavaThread* Threads::owning_thread_from_object(ThreadsList * t_list, oop obj) {
3792 assert(LockingMode == LM_LIGHTWEIGHT, "Only with new lightweight locking");
3793 DO_JAVA_THREADS(t_list, q) {
3794 // Need to start processing before accessing oops in the thread.
3795 StackWatermark* watermark = StackWatermarkSet::get(q, StackWatermarkKind::gc);
3796 if (watermark != nullptr) {
3797 watermark->start_processing();
3798 }
3799
3800 if (q->lock_stack().contains(obj)) {
3801 return q;
3802 }
3803 }
3804 return NULL;
3805 }
3806
3807 JavaThread* Threads::owning_thread_from_monitor(ThreadsList* t_list, ObjectMonitor* monitor) {
3808 if (LockingMode == LM_LIGHTWEIGHT) {
3809 if (monitor->is_owner_anonymous()) {
3810 return owning_thread_from_object(t_list, monitor->object());
3811 } else {
3812 Thread* owner = reinterpret_cast<Thread*>(monitor->owner());
3813 assert(owner == NULL || owner->is_Java_thread(), "only JavaThreads own monitors");
3814 return reinterpret_cast<JavaThread*>(owner);
3815 }
3816 } else {
3817 address owner = (address)monitor->owner();
3818 return owning_thread_from_monitor_owner(t_list, owner);
3819 }
3820 }
3821
3822 class PrintOnClosure : public ThreadClosure {
3823 private:
3824 outputStream* _st;
3825
3826 public:
3827 PrintOnClosure(outputStream* st) :
3828 _st(st) {}
3829
3830 virtual void do_thread(Thread* thread) {
3831 if (thread != NULL) {
3832 thread->print_on(_st);
3833 _st->cr();
3834 }
3835 }
3836 };
3837
3838 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
3839 void Threads::print_on(outputStream* st, bool print_stacks,
3840 bool internal_format, bool print_concurrent_locks,
3841 bool print_extended_info) {
3842 char buf[32];
3843 st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
3844
3845 st->print_cr("Full thread dump %s (%s %s):",
3846 VM_Version::vm_name(),
3847 VM_Version::vm_release(),
3848 VM_Version::vm_info_string());
3849 st->cr();
3850
3851 #if INCLUDE_SERVICES
3852 // Dump concurrent locks
3853 ConcurrentLocksDump concurrent_locks;
3854 if (print_concurrent_locks) {
3855 concurrent_locks.dump_at_safepoint();
3856 }
3857 #endif // INCLUDE_SERVICES
3858
3859 ThreadsSMRSupport::print_info_on(st);
3860 st->cr();
3861
3862 ALL_JAVA_THREADS(p) {
3863 ResourceMark rm;
3864 p->print_on(st, print_extended_info);
3865 if (print_stacks) {
3866 if (internal_format) {
3867 p->trace_stack();
3868 } else {
3869 p->print_stack_on(st);
3870 }
3871 }
3872 st->cr();
3873 #if INCLUDE_SERVICES
3874 if (print_concurrent_locks) {
3875 concurrent_locks.print_locks_on(p, st);
3876 }
3877 #endif // INCLUDE_SERVICES
3878 }
3879
3880 PrintOnClosure cl(st);
3881 cl.do_thread(VMThread::vm_thread());
3882 Universe::heap()->gc_threads_do(&cl);
3883 if (StringDedup::is_enabled()) {
3884 StringDedup::threads_do(&cl);
3885 }
3886 cl.do_thread(WatcherThread::watcher_thread());
3887 cl.do_thread(AsyncLogWriter::instance());
3888
3889 st->flush();
3890 }
3891
3892 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
3893 int buflen, bool* found_current) {
3894 if (this_thread != NULL) {
3895 bool is_current = (current == this_thread);
3896 *found_current = *found_current || is_current;
3897 st->print("%s", is_current ? "=>" : " ");
3898
3899 st->print(PTR_FORMAT, p2i(this_thread));
3900 st->print(" ");
3901 this_thread->print_on_error(st, buf, buflen);
3902 st->cr();
3903 }
3904 }
3905
3906 class PrintOnErrorClosure : public ThreadClosure {
3907 outputStream* _st;
3908 Thread* _current;
3909 char* _buf;
3910 int _buflen;
3911 bool* _found_current;
3912 public:
3913 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf,
3914 int buflen, bool* found_current) :
3915 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {}
3916
3917 virtual void do_thread(Thread* thread) {
3918 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current);
3919 }
3920 };
3921
3922 // Threads::print_on_error() is called by fatal error handler. It's possible
3923 // that VM is not at safepoint and/or current thread is inside signal handler.
3924 // Don't print stack trace, as the stack may not be walkable. Don't allocate
3925 // memory (even in resource area), it might deadlock the error handler.
3926 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
3927 int buflen) {
3928 ThreadsSMRSupport::print_info_on(st);
3929 st->cr();
3930
3931 bool found_current = false;
3932 st->print_cr("Java Threads: ( => current thread )");
3933 ALL_JAVA_THREADS(thread) {
3934 print_on_error(thread, st, current, buf, buflen, &found_current);
3935 }
3936 st->cr();
3937
3938 st->print_cr("Other Threads:");
3939 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current);
3940 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current);
3941 print_on_error(AsyncLogWriter::instance(), st, current, buf, buflen, &found_current);
3942
3943 if (Universe::heap() != NULL) {
3944 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
3945 Universe::heap()->gc_threads_do(&print_closure);
3946 }
3947
3948 if (StringDedup::is_enabled()) {
3949 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
3950 StringDedup::threads_do(&print_closure);
3951 }
3952
3953 if (!found_current) {
3954 st->cr();
3955 st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
3956 current->print_on_error(st, buf, buflen);
3957 st->cr();
3958 }
3959 st->cr();
3960
3961 st->print_cr("Threads with active compile tasks:");
3962 print_threads_compiling(st, buf, buflen);
3963 }
3964
3965 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form) {
3966 ALL_JAVA_THREADS(thread) {
3967 if (thread->is_Compiler_thread()) {
3968 CompilerThread* ct = (CompilerThread*) thread;
3969
3970 // Keep task in local variable for NULL check.
3971 // ct->_task might be set to NULL by concurring compiler thread
3972 // because it completed the compilation. The task is never freed,
3973 // though, just returned to a free list.
3974 CompileTask* task = ct->task();
3975 if (task != NULL) {
3976 thread->print_name_on_error(st, buf, buflen);
3977 st->print(" ");
3978 task->print(st, NULL, short_form, true);
3979 }
3980 }
3981 }
3982 }
3983
3984
3985 // Ad-hoc mutual exclusion primitives: SpinLock
3986 //
3987 // We employ SpinLocks _only for low-contention, fixed-length
3988 // short-duration critical sections where we're concerned
3989 // about native mutex_t or HotSpot Mutex:: latency.
3990 //
3991 // TODO-FIXME: ListLock should be of type SpinLock.
3992 // We should make this a 1st-class type, integrated into the lock
3993 // hierarchy as leaf-locks. Critically, the SpinLock structure
3994 // should have sufficient padding to avoid false-sharing and excessive
3995 // cache-coherency traffic.
3996
3997
3998 typedef volatile int SpinLockT;
3999
4000 void Thread::SpinAcquire(volatile int * adr, const char * LockName) {
4001 if (Atomic::cmpxchg(adr, 0, 1) == 0) {
4002 return; // normal fast-path return
4003 }
4004
4005 // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
4006 int ctr = 0;
4007 int Yields = 0;
4008 for (;;) {
4009 while (*adr != 0) {
4010 ++ctr;
4011 if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
4012 if (Yields > 5) {
4013 os::naked_short_sleep(1);
4014 } else {
4015 os::naked_yield();
4016 ++Yields;
4017 }
4018 } else {
4019 SpinPause();
4020 }
4021 }
4022 if (Atomic::cmpxchg(adr, 0, 1) == 0) return;
4023 }
4024 }
4025
4026 void Thread::SpinRelease(volatile int * adr) {
4027 assert(*adr != 0, "invariant");
4028 OrderAccess::fence(); // guarantee at least release consistency.
4029 // Roach-motel semantics.
4030 // It's safe if subsequent LDs and STs float "up" into the critical section,
4031 // but prior LDs and STs within the critical section can't be allowed
4032 // to reorder or float past the ST that releases the lock.
4033 // Loads and stores in the critical section - which appear in program
4034 // order before the store that releases the lock - must also appear
4035 // before the store that releases the lock in memory visibility order.
4036 // Conceptually we need a #loadstore|#storestore "release" MEMBAR before
4037 // the ST of 0 into the lock-word which releases the lock, so fence
4038 // more than covers this on all platforms.
4039 *adr = 0;
4040 }
4041
4042
4043 void Threads::verify() {
4044 ALL_JAVA_THREADS(p) {
4045 p->verify();
4046 }
4047 VMThread* thread = VMThread::vm_thread();
4048 if (thread != NULL) thread->verify();
4049 }
4050
4051 #ifndef PRODUCT
4052 void JavaThread::verify_cross_modify_fence_failure(JavaThread *thread) {
4053 report_vm_error(__FILE__, __LINE__, "Cross modify fence failure", "%p", thread);
4054 }
4055 #endif
4056
4057 // Starts the target JavaThread as a daemon of the given priority, and
4058 // bound to the given java.lang.Thread instance.
4059 // The Threads_lock is held for the duration.
4060 void JavaThread::start_internal_daemon(JavaThread* current, JavaThread* target,
4061 Handle thread_oop, ThreadPriority prio) {
4062
4063 assert(target->osthread()!= NULL, "target thread is not properly initialized");
4064
4065 MutexLocker mu(current, Threads_lock);
4066
4067 // Initialize the fields of the thread_oop first.
4068 if (prio != NoPriority) {
4069 java_lang_Thread::set_priority(thread_oop(), prio);
4070 // Note: we don't call os::set_priority here. Possibly we should,
4071 // else all threads should call it themselves when they first run.
4072 }
4073
4074 java_lang_Thread::set_daemon(thread_oop());
4075
4076 // Now bind the thread_oop to the target JavaThread.
4077 target->set_threadObj(thread_oop());
4078
4079 Threads::add(target); // target is now visible for safepoint/handshake
4080 // Publish the JavaThread* in java.lang.Thread after the JavaThread* is
4081 // on a ThreadsList. We don't want to wait for the release when the
4082 // Theads_lock is dropped when the 'mu' destructor is run since the
4083 // JavaThread* is already visible to JVM/TI via the ThreadsList.
4084 java_lang_Thread::release_set_thread(thread_oop(), target); // isAlive == true now
4085 Thread::start(target);
4086 }
4087
4088 void JavaThread::vm_exit_on_osthread_failure(JavaThread* thread) {
4089 // At this point it may be possible that no osthread was created for the
4090 // JavaThread due to lack of resources. However, since this must work
4091 // for critical system threads just check and abort if this fails.
4092 if (thread->osthread() == nullptr) {
4093 // This isn't really an OOM condition, but historically this is what
4094 // we report.
4095 vm_exit_during_initialization("java.lang.OutOfMemoryError",
4096 os::native_thread_creation_failed_msg());
4097 }
4098 }