1 /*
2 * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "jvm.h"
27 #include "aot/aotLoader.hpp"
28 #include "classfile/classLoader.hpp"
29 #include "classfile/javaClasses.hpp"
30 #include "classfile/moduleEntry.hpp"
31 #include "classfile/systemDictionary.hpp"
32 #include "classfile/vmSymbols.hpp"
33 #include "code/codeCache.hpp"
34 #include "code/scopeDesc.hpp"
35 #include "compiler/compileBroker.hpp"
36 #include "compiler/compileTask.hpp"
37 #include "gc/shared/barrierSet.hpp"
38 #include "gc/shared/gcId.hpp"
39 #include "gc/shared/gcLocker.inline.hpp"
40 #include "gc/shared/workgroup.hpp"
41 #include "interpreter/interpreter.hpp"
42 #include "interpreter/linkResolver.hpp"
43 #include "interpreter/oopMapCache.hpp"
44 #include "jfr/jfrEvents.hpp"
45 #include "jvmtifiles/jvmtiEnv.hpp"
46 #include "logging/log.hpp"
47 #include "logging/logConfiguration.hpp"
48 #include "logging/logStream.hpp"
49 #include "memory/allocation.inline.hpp"
50 #include "memory/iterator.hpp"
51 #include "memory/metaspaceShared.hpp"
52 #include "memory/oopFactory.hpp"
53 #include "memory/resourceArea.hpp"
54 #include "memory/universe.hpp"
55 #include "oops/access.inline.hpp"
56 #include "oops/instanceKlass.hpp"
57 #include "oops/objArrayOop.hpp"
58 #include "oops/oop.inline.hpp"
59 #include "oops/symbol.hpp"
60 #include "oops/typeArrayOop.inline.hpp"
61 #include "oops/inlineKlass.hpp"
62 #include "oops/verifyOopClosure.hpp"
63 #include "prims/jvm_misc.hpp"
64 #include "prims/jvmtiExport.hpp"
65 #include "prims/jvmtiThreadState.hpp"
66 #include "runtime/arguments.hpp"
67 #include "runtime/atomic.hpp"
68 #include "runtime/biasedLocking.hpp"
69 #include "runtime/fieldDescriptor.inline.hpp"
70 #include "runtime/flags/jvmFlagConstraintList.hpp"
71 #include "runtime/flags/jvmFlagRangeList.hpp"
72 #include "runtime/deoptimization.hpp"
73 #include "runtime/frame.inline.hpp"
74 #include "runtime/handles.inline.hpp"
75 #include "runtime/handshake.hpp"
76 #include "runtime/init.hpp"
77 #include "runtime/interfaceSupport.inline.hpp"
78 #include "runtime/java.hpp"
79 #include "runtime/javaCalls.hpp"
80 #include "runtime/jniHandles.inline.hpp"
81 #include "runtime/jniPeriodicChecker.hpp"
82 #include "runtime/memprofiler.hpp"
83 #include "runtime/mutexLocker.hpp"
84 #include "runtime/objectMonitor.hpp"
85 #include "runtime/orderAccess.hpp"
86 #include "runtime/osThread.hpp"
87 #include "runtime/prefetch.inline.hpp"
88 #include "runtime/safepoint.hpp"
89 #include "runtime/safepointMechanism.inline.hpp"
90 #include "runtime/safepointVerifiers.hpp"
91 #include "runtime/serviceThread.hpp"
92 #include "runtime/sharedRuntime.hpp"
93 #include "runtime/statSampler.hpp"
94 #include "runtime/stubRoutines.hpp"
95 #include "runtime/sweeper.hpp"
96 #include "runtime/task.hpp"
97 #include "runtime/thread.inline.hpp"
98 #include "runtime/threadCritical.hpp"
99 #include "runtime/threadSMR.inline.hpp"
100 #include "runtime/threadStatisticalInfo.hpp"
101 #include "runtime/timer.hpp"
102 #include "runtime/timerTrace.hpp"
103 #include "runtime/vframe.inline.hpp"
104 #include "runtime/vframeArray.hpp"
105 #include "runtime/vframe_hp.hpp"
106 #include "runtime/vmThread.hpp"
107 #include "runtime/vmOperations.hpp"
108 #include "runtime/vm_version.hpp"
109 #include "services/attachListener.hpp"
110 #include "services/management.hpp"
111 #include "services/memTracker.hpp"
112 #include "services/threadService.hpp"
113 #include "utilities/align.hpp"
114 #include "utilities/copy.hpp"
115 #include "utilities/defaultStream.hpp"
116 #include "utilities/dtrace.hpp"
117 #include "utilities/events.hpp"
118 #include "utilities/macros.hpp"
119 #include "utilities/preserveException.hpp"
120 #include "utilities/singleWriterSynchronizer.hpp"
121 #include "utilities/vmError.hpp"
122 #if INCLUDE_JVMCI
123 #include "jvmci/jvmci.hpp"
124 #include "jvmci/jvmciEnv.hpp"
125 #endif
126 #ifdef COMPILER1
127 #include "c1/c1_Compiler.hpp"
128 #endif
129 #ifdef COMPILER2
130 #include "opto/c2compiler.hpp"
131 #include "opto/idealGraphPrinter.hpp"
132 #endif
133 #if INCLUDE_RTM_OPT
134 #include "runtime/rtmLocking.hpp"
135 #endif
136 #if INCLUDE_JFR
137 #include "jfr/jfr.hpp"
138 #endif
139
140 // Initialization after module runtime initialization
141 void universe_post_module_init(); // must happen after call_initPhase2
142
143 #ifdef DTRACE_ENABLED
144
145 // Only bother with this argument setup if dtrace is available
146
147 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
148 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
149
150 #define DTRACE_THREAD_PROBE(probe, javathread) \
151 { \
152 ResourceMark rm(this); \
153 int len = 0; \
154 const char* name = (javathread)->get_thread_name(); \
155 len = strlen(name); \
156 HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */ \
157 (char *) name, len, \
158 java_lang_Thread::thread_id((javathread)->threadObj()), \
159 (uintptr_t) (javathread)->osthread()->thread_id(), \
160 java_lang_Thread::is_daemon((javathread)->threadObj())); \
161 }
162
163 #else // ndef DTRACE_ENABLED
164
165 #define DTRACE_THREAD_PROBE(probe, javathread)
166
167 #endif // ndef DTRACE_ENABLED
168
169 #ifndef USE_LIBRARY_BASED_TLS_ONLY
170 // Current thread is maintained as a thread-local variable
171 THREAD_LOCAL Thread* Thread::_thr_current = NULL;
172 #endif
173
174 // ======= Thread ========
175 // Support for forcing alignment of thread objects for biased locking
176 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
177 if (UseBiasedLocking) {
178 const size_t alignment = markWord::biased_lock_alignment;
179 size_t aligned_size = size + (alignment - sizeof(intptr_t));
180 void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC)
181 : AllocateHeap(aligned_size, flags, CURRENT_PC,
182 AllocFailStrategy::RETURN_NULL);
183 void* aligned_addr = align_up(real_malloc_addr, alignment);
184 assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
185 ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
186 "JavaThread alignment code overflowed allocated storage");
187 if (aligned_addr != real_malloc_addr) {
188 log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
189 p2i(real_malloc_addr),
190 p2i(aligned_addr));
191 }
192 ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
193 return aligned_addr;
194 } else {
195 return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
196 : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
197 }
198 }
199
200 void Thread::operator delete(void* p) {
201 if (UseBiasedLocking) {
202 FreeHeap(((Thread*) p)->_real_malloc_address);
203 } else {
204 FreeHeap(p);
205 }
206 }
207
208 void JavaThread::smr_delete() {
209 if (_on_thread_list) {
210 ThreadsSMRSupport::smr_delete(this);
211 } else {
212 delete this;
213 }
214 }
215
216 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
217 // JavaThread
218
219 DEBUG_ONLY(Thread* Thread::_starting_thread = NULL;)
220
221 Thread::Thread() {
222
223 DEBUG_ONLY(_run_state = PRE_CALL_RUN;)
224
225 // stack and get_thread
226 set_stack_base(NULL);
227 set_stack_size(0);
228 set_lgrp_id(-1);
229 DEBUG_ONLY(clear_suspendible_thread();)
230
231 // allocated data structures
232 set_osthread(NULL);
233 set_resource_area(new (mtThread)ResourceArea());
234 DEBUG_ONLY(_current_resource_mark = NULL;)
235 set_handle_area(new (mtThread) HandleArea(NULL));
236 set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, mtClass));
237 set_active_handles(NULL);
238 set_free_handle_block(NULL);
239 set_last_handle_mark(NULL);
240 DEBUG_ONLY(_missed_ic_stub_refill_verifier = NULL);
241
242 // Initial value of zero ==> never claimed.
243 _threads_do_token = 0;
244 _threads_hazard_ptr = NULL;
245 _threads_list_ptr = NULL;
246 _nested_threads_hazard_ptr_cnt = 0;
247 _rcu_counter = 0;
248
249 // the handle mark links itself to last_handle_mark
250 new HandleMark(this);
251
252 // plain initialization
253 debug_only(_owned_locks = NULL;)
254 NOT_PRODUCT(_no_safepoint_count = 0;)
255 NOT_PRODUCT(_skip_gcalot = false;)
256 _jvmti_env_iteration_count = 0;
257 set_allocated_bytes(0);
258 _vm_operation_started_count = 0;
259 _vm_operation_completed_count = 0;
260 _current_pending_monitor = NULL;
261 _current_pending_monitor_is_from_java = true;
262 _current_waiting_monitor = NULL;
263 _current_pending_raw_monitor = NULL;
264 _num_nested_signal = 0;
265 om_free_list = NULL;
266 om_free_count = 0;
267 om_free_provision = 32;
268 om_in_use_list = NULL;
269 om_in_use_count = 0;
270
271 #ifdef ASSERT
272 _visited_for_critical_count = false;
273 #endif
274
275 _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true,
276 Monitor::_safepoint_check_sometimes);
277 _suspend_flags = 0;
278
279 // thread-specific hashCode stream generator state - Marsaglia shift-xor form
280 _hashStateX = os::random();
281 _hashStateY = 842502087;
282 _hashStateZ = 0x8767; // (int)(3579807591LL & 0xffff) ;
283 _hashStateW = 273326509;
284
285 _OnTrap = 0;
286 _Stalled = 0;
287 _TypeTag = 0x2BAD;
288
289 // Many of the following fields are effectively final - immutable
290 // Note that nascent threads can't use the Native Monitor-Mutex
291 // construct until the _MutexEvent is initialized ...
292 // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
293 // we might instead use a stack of ParkEvents that we could provision on-demand.
294 // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
295 // and ::Release()
296 _ParkEvent = ParkEvent::Allocate(this);
297 _MuxEvent = ParkEvent::Allocate(this);
298
299 #ifdef CHECK_UNHANDLED_OOPS
300 if (CheckUnhandledOops) {
301 _unhandled_oops = new UnhandledOops(this);
302 }
303 #endif // CHECK_UNHANDLED_OOPS
304 #ifdef ASSERT
305 if (UseBiasedLocking) {
306 assert(is_aligned(this, markWord::biased_lock_alignment), "forced alignment of thread object failed");
307 assert(this == _real_malloc_address ||
308 this == align_up(_real_malloc_address, markWord::biased_lock_alignment),
309 "bug in forced alignment of thread objects");
310 }
311 #endif // ASSERT
312
313 // Notify the barrier set that a thread is being created. The initial
314 // thread is created before the barrier set is available. The call to
315 // BarrierSet::on_thread_create() for this thread is therefore deferred
316 // to BarrierSet::set_barrier_set().
317 BarrierSet* const barrier_set = BarrierSet::barrier_set();
318 if (barrier_set != NULL) {
319 barrier_set->on_thread_create(this);
320 } else {
321 // Only the main thread should be created before the barrier set
322 // and that happens just before Thread::current is set. No other thread
323 // can attach as the VM is not created yet, so they can't execute this code.
324 // If the main thread creates other threads before the barrier set that is an error.
325 assert(Thread::current_or_null() == NULL, "creating thread before barrier set");
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 ((JavaThread*) this)->set_stack_overflow_limit();
358 ((JavaThread*) this)->set_reserved_stack_activation(stack_base());
359 }
360 }
361
362 #if INCLUDE_NMT
363 void Thread::register_thread_stack_with_NMT() {
364 MemTracker::record_thread_stack(stack_end(), stack_size());
365 }
366 #endif // INCLUDE_NMT
367
368 void Thread::call_run() {
369 DEBUG_ONLY(_run_state = CALL_RUN;)
370
371 // At this point, Thread object should be fully initialized and
372 // Thread::current() should be set.
373
374 assert(Thread::current_or_null() != NULL, "current thread is unset");
375 assert(Thread::current_or_null() == this, "current thread is wrong");
376
377 // Perform common initialization actions
378
379 register_thread_stack_with_NMT();
380
381 JFR_ONLY(Jfr::on_thread_start(this);)
382
383 log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: "
384 PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).",
385 os::current_thread_id(), p2i(stack_end()),
386 p2i(stack_base()), stack_size()/1024);
387
388 // Perform <ChildClass> initialization actions
389 DEBUG_ONLY(_run_state = PRE_RUN;)
390 this->pre_run();
391
392 // Invoke <ChildClass>::run()
393 DEBUG_ONLY(_run_state = RUN;)
394 this->run();
395 // Returned from <ChildClass>::run(). Thread finished.
396
397 // Perform common tear-down actions
398
399 assert(Thread::current_or_null() != NULL, "current thread is unset");
400 assert(Thread::current_or_null() == this, "current thread is wrong");
401
402 // Perform <ChildClass> tear-down actions
403 DEBUG_ONLY(_run_state = POST_RUN;)
404 this->post_run();
405
406 // Note: at this point the thread object may already have deleted itself,
407 // so from here on do not dereference *this*. Not all thread types currently
408 // delete themselves when they terminate. But no thread should ever be deleted
409 // asynchronously with respect to its termination - that is what _run_state can
410 // be used to check.
411
412 assert(Thread::current_or_null() == NULL, "current thread still present");
413 }
414
415 Thread::~Thread() {
416
417 // Attached threads will remain in PRE_CALL_RUN, as will threads that don't actually
418 // get started due to errors etc. Any active thread should at least reach post_run
419 // before it is deleted (usually in post_run()).
420 assert(_run_state == PRE_CALL_RUN ||
421 _run_state == POST_RUN, "Active Thread deleted before post_run(): "
422 "_run_state=%d", (int)_run_state);
423
424 // Notify the barrier set that a thread is being destroyed. Note that a barrier
425 // set might not be available if we encountered errors during bootstrapping.
426 BarrierSet* const barrier_set = BarrierSet::barrier_set();
427 if (barrier_set != NULL) {
428 barrier_set->on_thread_destroy(this);
429 }
430
431 // stack_base can be NULL if the thread is never started or exited before
432 // record_stack_base_and_size called. Although, we would like to ensure
433 // that all started threads do call record_stack_base_and_size(), there is
434 // not proper way to enforce that.
435 #if INCLUDE_NMT
436 if (_stack_base != NULL) {
437 MemTracker::release_thread_stack(stack_end(), stack_size());
438 #ifdef ASSERT
439 set_stack_base(NULL);
440 #endif
441 }
442 #endif // INCLUDE_NMT
443
444 // deallocate data structures
445 delete resource_area();
446 // since the handle marks are using the handle area, we have to deallocated the root
447 // handle mark before deallocating the thread's handle area,
448 assert(last_handle_mark() != NULL, "check we have an element");
449 delete last_handle_mark();
450 assert(last_handle_mark() == NULL, "check we have reached the end");
451
452 // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
453 // We NULL out the fields for good hygiene.
454 ParkEvent::Release(_ParkEvent); _ParkEvent = NULL;
455 ParkEvent::Release(_MuxEvent); _MuxEvent = NULL;
456
457 delete handle_area();
458 delete metadata_handles();
459
460 // SR_handler uses this as a termination indicator -
461 // needs to happen before os::free_thread()
462 delete _SR_lock;
463 _SR_lock = NULL;
464
465 // osthread() can be NULL, if creation of thread failed.
466 if (osthread() != NULL) os::free_thread(osthread());
467
468 // Clear Thread::current if thread is deleting itself and it has not
469 // already been done. This must be done before the memory is deallocated.
470 // Needed to ensure JNI correctly detects non-attached threads.
471 if (this == Thread::current_or_null()) {
472 Thread::clear_thread_current();
473 }
474
475 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
476 }
477
478 #ifdef ASSERT
479 // A JavaThread is considered "dangling" if it is not the current
480 // thread, has been added the Threads list, the system is not at a
481 // safepoint and the Thread is not "protected".
482 //
483 void Thread::check_for_dangling_thread_pointer(Thread *thread) {
484 assert(!thread->is_Java_thread() || Thread::current() == thread ||
485 !((JavaThread *) thread)->on_thread_list() ||
486 SafepointSynchronize::is_at_safepoint() ||
487 ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread),
488 "possibility of dangling Thread pointer");
489 }
490 #endif
491
492 ThreadPriority Thread::get_priority(const Thread* const thread) {
493 ThreadPriority priority;
494 // Can return an error!
495 (void)os::get_priority(thread, priority);
496 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
497 return priority;
498 }
499
500 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
501 debug_only(check_for_dangling_thread_pointer(thread);)
502 // Can return an error!
503 (void)os::set_priority(thread, priority);
504 }
505
506
507 void Thread::start(Thread* thread) {
508 // Start is different from resume in that its safety is guaranteed by context or
509 // being called from a Java method synchronized on the Thread object.
510 if (!DisableStartThread) {
511 if (thread->is_Java_thread()) {
512 // Initialize the thread state to RUNNABLE before starting this thread.
513 // Can not set it after the thread started because we do not know the
514 // exact thread state at that time. It could be in MONITOR_WAIT or
515 // in SLEEPING or some other state.
516 java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
517 java_lang_Thread::RUNNABLE);
518 }
519 os::start_thread(thread);
520 }
521 }
522
523 class InstallAsyncExceptionClosure : public HandshakeClosure {
524 Handle _throwable; // The Throwable thrown at the target Thread
525 public:
526 InstallAsyncExceptionClosure(Handle throwable) : HandshakeClosure("InstallAsyncException"), _throwable(throwable) {}
527
528 void do_thread(Thread* thr) {
529 JavaThread* target = (JavaThread*)thr;
530 // Note that this now allows multiple ThreadDeath exceptions to be
531 // thrown at a thread.
532 // The target thread has run and has not exited yet.
533 target->send_thread_stop(_throwable());
534 }
535 };
536
537 void Thread::send_async_exception(oop java_thread, oop java_throwable) {
538 Handle throwable(Thread::current(), java_throwable);
539 JavaThread* target = java_lang_Thread::thread(java_thread);
540 InstallAsyncExceptionClosure vm_stop(throwable);
541 Handshake::execute(&vm_stop, target);
542 }
543
544
545 // Check if an external suspend request has completed (or has been
546 // cancelled). Returns true if the thread is externally suspended and
547 // false otherwise.
548 //
549 // The bits parameter returns information about the code path through
550 // the routine. Useful for debugging:
551 //
552 // set in is_ext_suspend_completed():
553 // 0x00000001 - routine was entered
554 // 0x00000010 - routine return false at end
555 // 0x00000100 - thread exited (return false)
556 // 0x00000200 - suspend request cancelled (return false)
557 // 0x00000400 - thread suspended (return true)
558 // 0x00001000 - thread is in a suspend equivalent state (return true)
559 // 0x00002000 - thread is native and walkable (return true)
560 // 0x00004000 - thread is native_trans and walkable (needed retry)
561 //
562 // set in wait_for_ext_suspend_completion():
563 // 0x00010000 - routine was entered
564 // 0x00020000 - suspend request cancelled before loop (return false)
565 // 0x00040000 - thread suspended before loop (return true)
566 // 0x00080000 - suspend request cancelled in loop (return false)
567 // 0x00100000 - thread suspended in loop (return true)
568 // 0x00200000 - suspend not completed during retry loop (return false)
569
570 // Helper class for tracing suspend wait debug bits.
571 //
572 // 0x00000100 indicates that the target thread exited before it could
573 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
574 // 0x00080000 each indicate a cancelled suspend request so they don't
575 // count as wait failures either.
576 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000)
577
578 class TraceSuspendDebugBits : public StackObj {
579 private:
580 JavaThread * jt;
581 bool is_wait;
582 bool called_by_wait; // meaningful when !is_wait
583 uint32_t * bits;
584
585 public:
586 TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait,
587 uint32_t *_bits) {
588 jt = _jt;
589 is_wait = _is_wait;
590 called_by_wait = _called_by_wait;
591 bits = _bits;
592 }
593
594 ~TraceSuspendDebugBits() {
595 if (!is_wait) {
596 #if 1
597 // By default, don't trace bits for is_ext_suspend_completed() calls.
598 // That trace is very chatty.
599 return;
600 #else
601 if (!called_by_wait) {
602 // If tracing for is_ext_suspend_completed() is enabled, then only
603 // trace calls to it from wait_for_ext_suspend_completion()
604 return;
605 }
606 #endif
607 }
608
609 if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) {
610 if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) {
611 MutexLocker ml(Threads_lock); // needed for get_thread_name()
612 ResourceMark rm;
613
614 tty->print_cr(
615 "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
616 jt->get_thread_name(), *bits);
617
618 guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed");
619 }
620 }
621 }
622 };
623 #undef DEBUG_FALSE_BITS
624
625
626 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay,
627 uint32_t *bits) {
628 TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
629
630 bool did_trans_retry = false; // only do thread_in_native_trans retry once
631 bool do_trans_retry; // flag to force the retry
632
633 *bits |= 0x00000001;
634
635 do {
636 do_trans_retry = false;
637
638 if (is_exiting()) {
639 // Thread is in the process of exiting. This is always checked
640 // first to reduce the risk of dereferencing a freed JavaThread.
641 *bits |= 0x00000100;
642 return false;
643 }
644
645 if (!is_external_suspend()) {
646 // Suspend request is cancelled. This is always checked before
647 // is_ext_suspended() to reduce the risk of a rogue resume
648 // confusing the thread that made the suspend request.
649 *bits |= 0x00000200;
650 return false;
651 }
652
653 if (is_ext_suspended()) {
654 // thread is suspended
655 *bits |= 0x00000400;
656 return true;
657 }
658
659 // Now that we no longer do hard suspends of threads running
660 // native code, the target thread can be changing thread state
661 // while we are in this routine:
662 //
663 // _thread_in_native -> _thread_in_native_trans -> _thread_blocked
664 //
665 // We save a copy of the thread state as observed at this moment
666 // and make our decision about suspend completeness based on the
667 // copy. This closes the race where the thread state is seen as
668 // _thread_in_native_trans in the if-thread_blocked check, but is
669 // seen as _thread_blocked in if-thread_in_native_trans check.
670 JavaThreadState save_state = thread_state();
671
672 if (save_state == _thread_blocked && is_suspend_equivalent()) {
673 // If the thread's state is _thread_blocked and this blocking
674 // condition is known to be equivalent to a suspend, then we can
675 // consider the thread to be externally suspended. This means that
676 // the code that sets _thread_blocked has been modified to do
677 // self-suspension if the blocking condition releases. We also
678 // used to check for CONDVAR_WAIT here, but that is now covered by
679 // the _thread_blocked with self-suspension check.
680 //
681 // Return true since we wouldn't be here unless there was still an
682 // external suspend request.
683 *bits |= 0x00001000;
684 return true;
685 } else if (save_state == _thread_in_native && frame_anchor()->walkable()) {
686 // Threads running native code will self-suspend on native==>VM/Java
687 // transitions. If its stack is walkable (should always be the case
688 // unless this function is called before the actual java_suspend()
689 // call), then the wait is done.
690 *bits |= 0x00002000;
691 return true;
692 } else if (!called_by_wait && !did_trans_retry &&
693 save_state == _thread_in_native_trans &&
694 frame_anchor()->walkable()) {
695 // The thread is transitioning from thread_in_native to another
696 // thread state. check_safepoint_and_suspend_for_native_trans()
697 // will force the thread to self-suspend. If it hasn't gotten
698 // there yet we may have caught the thread in-between the native
699 // code check above and the self-suspend. Lucky us. If we were
700 // called by wait_for_ext_suspend_completion(), then it
701 // will be doing the retries so we don't have to.
702 //
703 // Since we use the saved thread state in the if-statement above,
704 // there is a chance that the thread has already transitioned to
705 // _thread_blocked by the time we get here. In that case, we will
706 // make a single unnecessary pass through the logic below. This
707 // doesn't hurt anything since we still do the trans retry.
708
709 *bits |= 0x00004000;
710
711 // Once the thread leaves thread_in_native_trans for another
712 // thread state, we break out of this retry loop. We shouldn't
713 // need this flag to prevent us from getting back here, but
714 // sometimes paranoia is good.
715 did_trans_retry = true;
716
717 // We wait for the thread to transition to a more usable state.
718 for (int i = 1; i <= SuspendRetryCount; i++) {
719 // We used to do an "os::yield_all(i)" call here with the intention
720 // that yielding would increase on each retry. However, the parameter
721 // is ignored on Linux which means the yield didn't scale up. Waiting
722 // on the SR_lock below provides a much more predictable scale up for
723 // the delay. It also provides a simple/direct point to check for any
724 // safepoint requests from the VMThread
725
726 // temporarily drops SR_lock while doing wait with safepoint check
727 // (if we're a JavaThread - the WatcherThread can also call this)
728 // and increase delay with each retry
729 if (Thread::current()->is_Java_thread()) {
730 SR_lock()->wait(i * delay);
731 } else {
732 SR_lock()->wait_without_safepoint_check(i * delay);
733 }
734
735 // check the actual thread state instead of what we saved above
736 if (thread_state() != _thread_in_native_trans) {
737 // the thread has transitioned to another thread state so
738 // try all the checks (except this one) one more time.
739 do_trans_retry = true;
740 break;
741 }
742 } // end retry loop
743
744
745 }
746 } while (do_trans_retry);
747
748 *bits |= 0x00000010;
749 return false;
750 }
751
752 // Wait for an external suspend request to complete (or be cancelled).
753 // Returns true if the thread is externally suspended and false otherwise.
754 //
755 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
756 uint32_t *bits) {
757 TraceSuspendDebugBits tsdb(this, true /* is_wait */,
758 false /* !called_by_wait */, bits);
759
760 // local flag copies to minimize SR_lock hold time
761 bool is_suspended;
762 bool pending;
763 uint32_t reset_bits;
764
765 // set a marker so is_ext_suspend_completed() knows we are the caller
766 *bits |= 0x00010000;
767
768 // We use reset_bits to reinitialize the bits value at the top of
769 // each retry loop. This allows the caller to make use of any
770 // unused bits for their own marking purposes.
771 reset_bits = *bits;
772
773 {
774 MutexLocker ml(SR_lock(), Mutex::_no_safepoint_check_flag);
775 is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
776 delay, bits);
777 pending = is_external_suspend();
778 }
779 // must release SR_lock to allow suspension to complete
780
781 if (!pending) {
782 // A cancelled suspend request is the only false return from
783 // is_ext_suspend_completed() that keeps us from entering the
784 // retry loop.
785 *bits |= 0x00020000;
786 return false;
787 }
788
789 if (is_suspended) {
790 *bits |= 0x00040000;
791 return true;
792 }
793
794 for (int i = 1; i <= retries; i++) {
795 *bits = reset_bits; // reinit to only track last retry
796
797 // We used to do an "os::yield_all(i)" call here with the intention
798 // that yielding would increase on each retry. However, the parameter
799 // is ignored on Linux which means the yield didn't scale up. Waiting
800 // on the SR_lock below provides a much more predictable scale up for
801 // the delay. It also provides a simple/direct point to check for any
802 // safepoint requests from the VMThread
803
804 {
805 Thread* t = Thread::current();
806 MonitorLocker ml(SR_lock(),
807 t->is_Java_thread() ? Mutex::_safepoint_check_flag : Mutex::_no_safepoint_check_flag);
808 // wait with safepoint check (if we're a JavaThread - the WatcherThread
809 // can also call this) and increase delay with each retry
810 ml.wait(i * delay);
811
812 is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
813 delay, bits);
814
815 // It is possible for the external suspend request to be cancelled
816 // (by a resume) before the actual suspend operation is completed.
817 // Refresh our local copy to see if we still need to wait.
818 pending = is_external_suspend();
819 }
820
821 if (!pending) {
822 // A cancelled suspend request is the only false return from
823 // is_ext_suspend_completed() that keeps us from staying in the
824 // retry loop.
825 *bits |= 0x00080000;
826 return false;
827 }
828
829 if (is_suspended) {
830 *bits |= 0x00100000;
831 return true;
832 }
833 } // end retry loop
834
835 // thread did not suspend after all our retries
836 *bits |= 0x00200000;
837 return false;
838 }
839
840 // Called from API entry points which perform stack walking. If the
841 // associated JavaThread is the current thread, then wait_for_suspend
842 // is not used. Otherwise, it determines if we should wait for the
843 // "other" thread to complete external suspension. (NOTE: in future
844 // releases the suspension mechanism should be reimplemented so this
845 // is not necessary.)
846 //
847 bool
848 JavaThread::is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits) {
849 if (this != JavaThread::current()) {
850 // "other" threads require special handling.
851 if (wait_for_suspend) {
852 // We are allowed to wait for the external suspend to complete
853 // so give the other thread a chance to get suspended.
854 if (!wait_for_ext_suspend_completion(SuspendRetryCount,
855 SuspendRetryDelay, bits)) {
856 // Didn't make it so let the caller know.
857 return false;
858 }
859 }
860 // We aren't allowed to wait for the external suspend to complete
861 // so if the other thread isn't externally suspended we need to
862 // let the caller know.
863 else if (!is_ext_suspend_completed_with_lock(bits)) {
864 return false;
865 }
866 }
867
868 return true;
869 }
870
871 // GC Support
872 bool Thread::claim_par_threads_do(uintx claim_token) {
873 uintx token = _threads_do_token;
874 if (token != claim_token) {
875 uintx res = Atomic::cmpxchg(&_threads_do_token, token, claim_token);
876 if (res == token) {
877 return true;
878 }
879 guarantee(res == claim_token, "invariant");
880 }
881 return false;
882 }
883
884 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
885 if (active_handles() != NULL) {
886 active_handles()->oops_do(f);
887 }
888 // Do oop for ThreadShadow
889 f->do_oop((oop*)&_pending_exception);
890 handle_area()->oops_do(f);
891
892 // We scan thread local monitor lists here, and the remaining global
893 // monitors in ObjectSynchronizer::oops_do().
894 ObjectSynchronizer::thread_local_used_oops_do(this, f);
895 }
896
897 void Thread::metadata_handles_do(void f(Metadata*)) {
898 // Only walk the Handles in Thread.
899 if (metadata_handles() != NULL) {
900 for (int i = 0; i< metadata_handles()->length(); i++) {
901 f(metadata_handles()->at(i));
902 }
903 }
904 }
905
906 void Thread::print_on(outputStream* st, bool print_extended_info) const {
907 // get_priority assumes osthread initialized
908 if (osthread() != NULL) {
909 int os_prio;
910 if (os::get_native_priority(this, &os_prio) == OS_OK) {
911 st->print("os_prio=%d ", os_prio);
912 }
913
914 st->print("cpu=%.2fms ",
915 os::thread_cpu_time(const_cast<Thread*>(this), true) / 1000000.0
916 );
917 st->print("elapsed=%.2fs ",
918 _statistical_info.getElapsedTime() / 1000.0
919 );
920 if (is_Java_thread() && (PrintExtendedThreadInfo || print_extended_info)) {
921 size_t allocated_bytes = (size_t) const_cast<Thread*>(this)->cooked_allocated_bytes();
922 st->print("allocated=" SIZE_FORMAT "%s ",
923 byte_size_in_proper_unit(allocated_bytes),
924 proper_unit_for_byte_size(allocated_bytes)
925 );
926 st->print("defined_classes=" INT64_FORMAT " ", _statistical_info.getDefineClassCount());
927 }
928
929 st->print("tid=" INTPTR_FORMAT " ", p2i(this));
930 osthread()->print_on(st);
931 }
932 ThreadsSMRSupport::print_info_on(this, st);
933 st->print(" ");
934 debug_only(if (WizardMode) print_owned_locks_on(st);)
935 }
936
937 void Thread::print() const { print_on(tty); }
938
939 // Thread::print_on_error() is called by fatal error handler. Don't use
940 // any lock or allocate memory.
941 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
942 assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates");
943
944 if (is_VM_thread()) { st->print("VMThread"); }
945 else if (is_GC_task_thread()) { st->print("GCTaskThread"); }
946 else if (is_Watcher_thread()) { st->print("WatcherThread"); }
947 else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); }
948 else { st->print("Thread"); }
949
950 if (is_Named_thread()) {
951 st->print(" \"%s\"", name());
952 }
953
954 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
955 p2i(stack_end()), p2i(stack_base()));
956
957 if (osthread()) {
958 st->print(" [id=%d]", osthread()->thread_id());
959 }
960
961 ThreadsSMRSupport::print_info_on(this, st);
962 }
963
964 void Thread::print_value_on(outputStream* st) const {
965 if (is_Named_thread()) {
966 st->print(" \"%s\" ", name());
967 }
968 st->print(INTPTR_FORMAT, p2i(this)); // print address
969 }
970
971 #ifdef ASSERT
972 void Thread::print_owned_locks_on(outputStream* st) const {
973 Mutex* cur = _owned_locks;
974 if (cur == NULL) {
975 st->print(" (no locks) ");
976 } else {
977 st->print_cr(" Locks owned:");
978 while (cur) {
979 cur->print_on(st);
980 cur = cur->next();
981 }
982 }
983 }
984
985 // Checks safepoint allowed and clears unhandled oops at potential safepoints.
986 void Thread::check_possible_safepoint() {
987 if (!is_Java_thread()) return;
988
989 if (_no_safepoint_count > 0) {
990 print_owned_locks();
991 fatal("Possible safepoint reached by thread that does not allow it");
992 }
993 #ifdef CHECK_UNHANDLED_OOPS
994 // Clear unhandled oops in JavaThreads so we get a crash right away.
995 clear_unhandled_oops();
996 #endif // CHECK_UNHANDLED_OOPS
997 }
998
999 void Thread::check_for_valid_safepoint_state() {
1000 if (!is_Java_thread()) return;
1001
1002 // Check NoSafepointVerifier, which is implied by locks taken that can be
1003 // shared with the VM thread. This makes sure that no locks with allow_vm_block
1004 // are held.
1005 check_possible_safepoint();
1006
1007 if (((JavaThread*)this)->thread_state() != _thread_in_vm) {
1008 fatal("LEAF method calling lock?");
1009 }
1010
1011 if (GCALotAtAllSafepoints) {
1012 // We could enter a safepoint here and thus have a gc
1013 InterfaceSupport::check_gc_alot();
1014 }
1015 }
1016 #endif // ASSERT
1017
1018 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
1019 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
1020 // used for compilation in the future. If that change is made, the need for these methods
1021 // should be revisited, and they should be removed if possible.
1022
1023 bool Thread::is_lock_owned(address adr) const {
1024 return is_in_full_stack(adr);
1025 }
1026
1027 bool Thread::set_as_starting_thread() {
1028 assert(_starting_thread == NULL, "already initialized: "
1029 "_starting_thread=" INTPTR_FORMAT, p2i(_starting_thread));
1030 // NOTE: this must be called inside the main thread.
1031 DEBUG_ONLY(_starting_thread = this;)
1032 return os::create_main_thread((JavaThread*)this);
1033 }
1034
1035 static void initialize_class(Symbol* class_name, TRAPS) {
1036 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
1037 InstanceKlass::cast(klass)->initialize(CHECK);
1038 }
1039
1040
1041 // Creates the initial ThreadGroup
1042 static Handle create_initial_thread_group(TRAPS) {
1043 Handle system_instance = JavaCalls::construct_new_instance(
1044 SystemDictionary::ThreadGroup_klass(),
1045 vmSymbols::void_method_signature(),
1046 CHECK_NH);
1047 Universe::set_system_thread_group(system_instance());
1048
1049 Handle string = java_lang_String::create_from_str("main", CHECK_NH);
1050 Handle main_instance = JavaCalls::construct_new_instance(
1051 SystemDictionary::ThreadGroup_klass(),
1052 vmSymbols::threadgroup_string_void_signature(),
1053 system_instance,
1054 string,
1055 CHECK_NH);
1056 return main_instance;
1057 }
1058
1059 // Creates the initial Thread
1060 static oop create_initial_thread(Handle thread_group, JavaThread* thread,
1061 TRAPS) {
1062 InstanceKlass* ik = SystemDictionary::Thread_klass();
1063 assert(ik->is_initialized(), "must be");
1064 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK_NULL);
1065
1066 // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread
1067 // constructor calls Thread.current(), which must be set here for the
1068 // initial thread.
1069 java_lang_Thread::set_thread(thread_oop(), thread);
1070 java_lang_Thread::set_priority(thread_oop(), NormPriority);
1071 thread->set_threadObj(thread_oop());
1072
1073 Handle string = java_lang_String::create_from_str("main", CHECK_NULL);
1074
1075 JavaValue result(T_VOID);
1076 JavaCalls::call_special(&result, thread_oop,
1077 ik,
1078 vmSymbols::object_initializer_name(),
1079 vmSymbols::threadgroup_string_void_signature(),
1080 thread_group,
1081 string,
1082 CHECK_NULL);
1083 return thread_oop();
1084 }
1085
1086 char java_runtime_name[128] = "";
1087 char java_runtime_version[128] = "";
1088 char java_runtime_vendor_version[128] = "";
1089 char java_runtime_vendor_vm_bug_url[128] = "";
1090
1091 // extract the JRE name from java.lang.VersionProps.java_runtime_name
1092 static const char* get_java_runtime_name(TRAPS) {
1093 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(),
1094 Handle(), Handle(), CHECK_AND_CLEAR_NULL);
1095 fieldDescriptor fd;
1096 bool found = k != NULL &&
1097 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(),
1098 vmSymbols::string_signature(), &fd);
1099 if (found) {
1100 oop name_oop = k->java_mirror()->obj_field(fd.offset());
1101 if (name_oop == NULL) {
1102 return NULL;
1103 }
1104 const char* name = java_lang_String::as_utf8_string(name_oop,
1105 java_runtime_name,
1106 sizeof(java_runtime_name));
1107 return name;
1108 } else {
1109 return NULL;
1110 }
1111 }
1112
1113 // extract the JRE version from java.lang.VersionProps.java_runtime_version
1114 static const char* get_java_runtime_version(TRAPS) {
1115 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(),
1116 Handle(), Handle(), CHECK_AND_CLEAR_NULL);
1117 fieldDescriptor fd;
1118 bool found = k != NULL &&
1119 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(),
1120 vmSymbols::string_signature(), &fd);
1121 if (found) {
1122 oop name_oop = k->java_mirror()->obj_field(fd.offset());
1123 if (name_oop == NULL) {
1124 return NULL;
1125 }
1126 const char* name = java_lang_String::as_utf8_string(name_oop,
1127 java_runtime_version,
1128 sizeof(java_runtime_version));
1129 return name;
1130 } else {
1131 return NULL;
1132 }
1133 }
1134
1135 // extract the JRE vendor version from java.lang.VersionProps.VENDOR_VERSION
1136 static const char* get_java_runtime_vendor_version(TRAPS) {
1137 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(),
1138 Handle(), Handle(), CHECK_AND_CLEAR_NULL);
1139 fieldDescriptor fd;
1140 bool found = k != NULL &&
1141 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_vendor_version_name(),
1142 vmSymbols::string_signature(), &fd);
1143 if (found) {
1144 oop name_oop = k->java_mirror()->obj_field(fd.offset());
1145 if (name_oop == NULL) {
1146 return NULL;
1147 }
1148 const char* name = java_lang_String::as_utf8_string(name_oop,
1149 java_runtime_vendor_version,
1150 sizeof(java_runtime_vendor_version));
1151 return name;
1152 } else {
1153 return NULL;
1154 }
1155 }
1156
1157 // extract the JRE vendor VM bug URL from java.lang.VersionProps.VENDOR_URL_VM_BUG
1158 static const char* get_java_runtime_vendor_vm_bug_url(TRAPS) {
1159 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(),
1160 Handle(), Handle(), CHECK_AND_CLEAR_NULL);
1161 fieldDescriptor fd;
1162 bool found = k != NULL &&
1163 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_vendor_vm_bug_url_name(),
1164 vmSymbols::string_signature(), &fd);
1165 if (found) {
1166 oop name_oop = k->java_mirror()->obj_field(fd.offset());
1167 if (name_oop == NULL) {
1168 return NULL;
1169 }
1170 const char* name = java_lang_String::as_utf8_string(name_oop,
1171 java_runtime_vendor_vm_bug_url,
1172 sizeof(java_runtime_vendor_vm_bug_url));
1173 return name;
1174 } else {
1175 return NULL;
1176 }
1177 }
1178
1179 // General purpose hook into Java code, run once when the VM is initialized.
1180 // The Java library method itself may be changed independently from the VM.
1181 static void call_postVMInitHook(TRAPS) {
1182 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD);
1183 if (klass != NULL) {
1184 JavaValue result(T_VOID);
1185 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
1186 vmSymbols::void_method_signature(),
1187 CHECK);
1188 }
1189 }
1190
1191 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
1192 bool daemon, TRAPS) {
1193 assert(thread_group.not_null(), "thread group should be specified");
1194 assert(threadObj() == NULL, "should only create Java thread object once");
1195
1196 InstanceKlass* ik = SystemDictionary::Thread_klass();
1197 assert(ik->is_initialized(), "must be");
1198 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
1199
1200 // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon.
1201 // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread
1202 // constructor calls Thread.current(), which must be set here.
1203 java_lang_Thread::set_thread(thread_oop(), this);
1204 java_lang_Thread::set_priority(thread_oop(), NormPriority);
1205 set_threadObj(thread_oop());
1206
1207 JavaValue result(T_VOID);
1208 if (thread_name != NULL) {
1209 Handle name = java_lang_String::create_from_str(thread_name, CHECK);
1210 // Thread gets assigned specified name and null target
1211 JavaCalls::call_special(&result,
1212 thread_oop,
1213 ik,
1214 vmSymbols::object_initializer_name(),
1215 vmSymbols::threadgroup_string_void_signature(),
1216 thread_group,
1217 name,
1218 THREAD);
1219 } else {
1220 // Thread gets assigned name "Thread-nnn" and null target
1221 // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
1222 JavaCalls::call_special(&result,
1223 thread_oop,
1224 ik,
1225 vmSymbols::object_initializer_name(),
1226 vmSymbols::threadgroup_runnable_void_signature(),
1227 thread_group,
1228 Handle(),
1229 THREAD);
1230 }
1231
1232
1233 if (daemon) {
1234 java_lang_Thread::set_daemon(thread_oop());
1235 }
1236
1237 if (HAS_PENDING_EXCEPTION) {
1238 return;
1239 }
1240
1241 Klass* group = SystemDictionary::ThreadGroup_klass();
1242 Handle threadObj(THREAD, this->threadObj());
1243
1244 JavaCalls::call_special(&result,
1245 thread_group,
1246 group,
1247 vmSymbols::add_method_name(),
1248 vmSymbols::thread_void_signature(),
1249 threadObj, // Arg 1
1250 THREAD);
1251 }
1252
1253 // List of all NonJavaThreads and safe iteration over that list.
1254
1255 class NonJavaThread::List {
1256 public:
1257 NonJavaThread* volatile _head;
1258 SingleWriterSynchronizer _protect;
1259
1260 List() : _head(NULL), _protect() {}
1261 };
1262
1263 NonJavaThread::List NonJavaThread::_the_list;
1264
1265 NonJavaThread::Iterator::Iterator() :
1266 _protect_enter(_the_list._protect.enter()),
1267 _current(Atomic::load_acquire(&_the_list._head))
1268 {}
1269
1270 NonJavaThread::Iterator::~Iterator() {
1271 _the_list._protect.exit(_protect_enter);
1272 }
1273
1274 void NonJavaThread::Iterator::step() {
1275 assert(!end(), "precondition");
1276 _current = Atomic::load_acquire(&_current->_next);
1277 }
1278
1279 NonJavaThread::NonJavaThread() : Thread(), _next(NULL) {
1280 assert(BarrierSet::barrier_set() != NULL, "NonJavaThread created too soon!");
1281 }
1282
1283 NonJavaThread::~NonJavaThread() { }
1284
1285 void NonJavaThread::add_to_the_list() {
1286 MutexLocker ml(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag);
1287 // Initialize BarrierSet-related data before adding to list.
1288 BarrierSet::barrier_set()->on_thread_attach(this);
1289 Atomic::release_store(&_next, _the_list._head);
1290 Atomic::release_store(&_the_list._head, this);
1291 }
1292
1293 void NonJavaThread::remove_from_the_list() {
1294 {
1295 MutexLocker ml(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag);
1296 // Cleanup BarrierSet-related data before removing from list.
1297 BarrierSet::barrier_set()->on_thread_detach(this);
1298 NonJavaThread* volatile* p = &_the_list._head;
1299 for (NonJavaThread* t = *p; t != NULL; p = &t->_next, t = *p) {
1300 if (t == this) {
1301 *p = _next;
1302 break;
1303 }
1304 }
1305 }
1306 // Wait for any in-progress iterators. Concurrent synchronize is not
1307 // allowed, so do it while holding a dedicated lock. Outside and distinct
1308 // from NJTList_lock in case an iteration attempts to lock it.
1309 MutexLocker ml(NonJavaThreadsListSync_lock, Mutex::_no_safepoint_check_flag);
1310 _the_list._protect.synchronize();
1311 _next = NULL; // Safe to drop the link now.
1312 }
1313
1314 void NonJavaThread::pre_run() {
1315 add_to_the_list();
1316
1317 // This is slightly odd in that NamedThread is a subclass, but
1318 // in fact name() is defined in Thread
1319 assert(this->name() != NULL, "thread name was not set before it was started");
1320 this->set_native_thread_name(this->name());
1321 }
1322
1323 void NonJavaThread::post_run() {
1324 JFR_ONLY(Jfr::on_thread_exit(this);)
1325 remove_from_the_list();
1326 // Ensure thread-local-storage is cleared before termination.
1327 Thread::clear_thread_current();
1328 }
1329
1330 // NamedThread -- non-JavaThread subclasses with multiple
1331 // uniquely named instances should derive from this.
1332 NamedThread::NamedThread() :
1333 NonJavaThread(),
1334 _name(NULL),
1335 _processed_thread(NULL),
1336 _gc_id(GCId::undefined())
1337 {}
1338
1339 NamedThread::~NamedThread() {
1340 FREE_C_HEAP_ARRAY(char, _name);
1341 }
1342
1343 void NamedThread::set_name(const char* format, ...) {
1344 guarantee(_name == NULL, "Only get to set name once.");
1345 _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
1346 va_list ap;
1347 va_start(ap, format);
1348 jio_vsnprintf(_name, max_name_len, format, ap);
1349 va_end(ap);
1350 }
1351
1352 void NamedThread::print_on(outputStream* st) const {
1353 st->print("\"%s\" ", name());
1354 Thread::print_on(st);
1355 st->cr();
1356 }
1357
1358
1359 // ======= WatcherThread ========
1360
1361 // The watcher thread exists to simulate timer interrupts. It should
1362 // be replaced by an abstraction over whatever native support for
1363 // timer interrupts exists on the platform.
1364
1365 WatcherThread* WatcherThread::_watcher_thread = NULL;
1366 bool WatcherThread::_startable = false;
1367 volatile bool WatcherThread::_should_terminate = false;
1368
1369 WatcherThread::WatcherThread() : NonJavaThread() {
1370 assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
1371 if (os::create_thread(this, os::watcher_thread)) {
1372 _watcher_thread = this;
1373
1374 // Set the watcher thread to the highest OS priority which should not be
1375 // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY
1376 // is created. The only normal thread using this priority is the reference
1377 // handler thread, which runs for very short intervals only.
1378 // If the VMThread's priority is not lower than the WatcherThread profiling
1379 // will be inaccurate.
1380 os::set_priority(this, MaxPriority);
1381 if (!DisableStartThread) {
1382 os::start_thread(this);
1383 }
1384 }
1385 }
1386
1387 int WatcherThread::sleep() const {
1388 // The WatcherThread does not participate in the safepoint protocol
1389 // for the PeriodicTask_lock because it is not a JavaThread.
1390 MonitorLocker ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
1391
1392 if (_should_terminate) {
1393 // check for termination before we do any housekeeping or wait
1394 return 0; // we did not sleep.
1395 }
1396
1397 // remaining will be zero if there are no tasks,
1398 // causing the WatcherThread to sleep until a task is
1399 // enrolled
1400 int remaining = PeriodicTask::time_to_wait();
1401 int time_slept = 0;
1402
1403 // we expect this to timeout - we only ever get unparked when
1404 // we should terminate or when a new task has been enrolled
1405 OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
1406
1407 jlong time_before_loop = os::javaTimeNanos();
1408
1409 while (true) {
1410 bool timedout = ml.wait(remaining);
1411 jlong now = os::javaTimeNanos();
1412
1413 if (remaining == 0) {
1414 // if we didn't have any tasks we could have waited for a long time
1415 // consider the time_slept zero and reset time_before_loop
1416 time_slept = 0;
1417 time_before_loop = now;
1418 } else {
1419 // need to recalculate since we might have new tasks in _tasks
1420 time_slept = (int) ((now - time_before_loop) / 1000000);
1421 }
1422
1423 // Change to task list or spurious wakeup of some kind
1424 if (timedout || _should_terminate) {
1425 break;
1426 }
1427
1428 remaining = PeriodicTask::time_to_wait();
1429 if (remaining == 0) {
1430 // Last task was just disenrolled so loop around and wait until
1431 // another task gets enrolled
1432 continue;
1433 }
1434
1435 remaining -= time_slept;
1436 if (remaining <= 0) {
1437 break;
1438 }
1439 }
1440
1441 return time_slept;
1442 }
1443
1444 void WatcherThread::run() {
1445 assert(this == watcher_thread(), "just checking");
1446
1447 this->set_active_handles(JNIHandleBlock::allocate_block());
1448 while (true) {
1449 assert(watcher_thread() == Thread::current(), "thread consistency check");
1450 assert(watcher_thread() == this, "thread consistency check");
1451
1452 // Calculate how long it'll be until the next PeriodicTask work
1453 // should be done, and sleep that amount of time.
1454 int time_waited = sleep();
1455
1456 if (VMError::is_error_reported()) {
1457 // A fatal error has happened, the error handler(VMError::report_and_die)
1458 // should abort JVM after creating an error log file. However in some
1459 // rare cases, the error handler itself might deadlock. Here periodically
1460 // check for error reporting timeouts, and if it happens, just proceed to
1461 // abort the VM.
1462
1463 // This code is in WatcherThread because WatcherThread wakes up
1464 // periodically so the fatal error handler doesn't need to do anything;
1465 // also because the WatcherThread is less likely to crash than other
1466 // threads.
1467
1468 for (;;) {
1469 // Note: we use naked sleep in this loop because we want to avoid using
1470 // any kind of VM infrastructure which may be broken at this point.
1471 if (VMError::check_timeout()) {
1472 // We hit error reporting timeout. Error reporting was interrupted and
1473 // will be wrapping things up now (closing files etc). Give it some more
1474 // time, then quit the VM.
1475 os::naked_short_sleep(200);
1476 // Print a message to stderr.
1477 fdStream err(defaultStream::output_fd());
1478 err.print_raw_cr("# [ timer expired, abort... ]");
1479 // skip atexit/vm_exit/vm_abort hooks
1480 os::die();
1481 }
1482
1483 // Wait a second, then recheck for timeout.
1484 os::naked_short_sleep(999);
1485 }
1486 }
1487
1488 if (_should_terminate) {
1489 // check for termination before posting the next tick
1490 break;
1491 }
1492
1493 PeriodicTask::real_time_tick(time_waited);
1494 }
1495
1496 // Signal that it is terminated
1497 {
1498 MutexLocker mu(Terminator_lock, Mutex::_no_safepoint_check_flag);
1499 _watcher_thread = NULL;
1500 Terminator_lock->notify_all();
1501 }
1502 }
1503
1504 void WatcherThread::start() {
1505 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1506
1507 if (watcher_thread() == NULL && _startable) {
1508 _should_terminate = false;
1509 // Create the single instance of WatcherThread
1510 new WatcherThread();
1511 }
1512 }
1513
1514 void WatcherThread::make_startable() {
1515 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1516 _startable = true;
1517 }
1518
1519 void WatcherThread::stop() {
1520 {
1521 // Follow normal safepoint aware lock enter protocol since the
1522 // WatcherThread is stopped by another JavaThread.
1523 MutexLocker ml(PeriodicTask_lock);
1524 _should_terminate = true;
1525
1526 WatcherThread* watcher = watcher_thread();
1527 if (watcher != NULL) {
1528 // unpark the WatcherThread so it can see that it should terminate
1529 watcher->unpark();
1530 }
1531 }
1532
1533 MonitorLocker mu(Terminator_lock);
1534
1535 while (watcher_thread() != NULL) {
1536 // This wait should make safepoint checks, wait without a timeout,
1537 // and wait as a suspend-equivalent condition.
1538 mu.wait(0, Mutex::_as_suspend_equivalent_flag);
1539 }
1540 }
1541
1542 void WatcherThread::unpark() {
1543 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1544 PeriodicTask_lock->notify();
1545 }
1546
1547 void WatcherThread::print_on(outputStream* st) const {
1548 st->print("\"%s\" ", name());
1549 Thread::print_on(st);
1550 st->cr();
1551 }
1552
1553 // ======= JavaThread ========
1554
1555 #if INCLUDE_JVMCI
1556
1557 jlong* JavaThread::_jvmci_old_thread_counters;
1558
1559 bool jvmci_counters_include(JavaThread* thread) {
1560 return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
1561 }
1562
1563 void JavaThread::collect_counters(jlong* array, int length) {
1564 assert(length == JVMCICounterSize, "wrong value");
1565 for (int i = 0; i < length; i++) {
1566 array[i] = _jvmci_old_thread_counters[i];
1567 }
1568 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *tp = jtiwh.next(); ) {
1569 if (jvmci_counters_include(tp)) {
1570 for (int i = 0; i < length; i++) {
1571 array[i] += tp->_jvmci_counters[i];
1572 }
1573 }
1574 }
1575 }
1576
1577 // Attempt to enlarge the array for per thread counters.
1578 jlong* resize_counters_array(jlong* old_counters, int current_size, int new_size) {
1579 jlong* new_counters = NEW_C_HEAP_ARRAY(jlong, new_size, mtJVMCI);
1580 if (old_counters == NULL) {
1581 old_counters = new_counters;
1582 memset(old_counters, 0, sizeof(jlong) * new_size);
1583 } else {
1584 for (int i = 0; i < MIN2((int) current_size, new_size); i++) {
1585 new_counters[i] = old_counters[i];
1586 }
1587 if (new_size > current_size) {
1588 memset(new_counters + current_size, 0, sizeof(jlong) * (new_size - current_size));
1589 }
1590 FREE_C_HEAP_ARRAY(jlong, old_counters);
1591 }
1592 return new_counters;
1593 }
1594
1595 // Attempt to enlarge the array for per thread counters.
1596 void JavaThread::resize_counters(int current_size, int new_size) {
1597 _jvmci_counters = resize_counters_array(_jvmci_counters, current_size, new_size);
1598 }
1599
1600 class VM_JVMCIResizeCounters : public VM_Operation {
1601 private:
1602 int _new_size;
1603
1604 public:
1605 VM_JVMCIResizeCounters(int new_size) : _new_size(new_size) { }
1606 VMOp_Type type() const { return VMOp_JVMCIResizeCounters; }
1607 bool allow_nested_vm_operations() const { return true; }
1608 void doit() {
1609 // Resize the old thread counters array
1610 jlong* new_counters = resize_counters_array(JavaThread::_jvmci_old_thread_counters, JVMCICounterSize, _new_size);
1611 JavaThread::_jvmci_old_thread_counters = new_counters;
1612
1613 // Now resize each threads array
1614 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *tp = jtiwh.next(); ) {
1615 tp->resize_counters(JVMCICounterSize, _new_size);
1616 }
1617 JVMCICounterSize = _new_size;
1618 }
1619 };
1620
1621 void JavaThread::resize_all_jvmci_counters(int new_size) {
1622 VM_JVMCIResizeCounters op(new_size);
1623 VMThread::execute(&op);
1624 }
1625
1626 #endif // INCLUDE_JVMCI
1627
1628 // A JavaThread is a normal Java thread
1629
1630 void JavaThread::initialize() {
1631 // Initialize fields
1632
1633 set_saved_exception_pc(NULL);
1634 set_threadObj(NULL);
1635 _anchor.clear();
1636 set_entry_point(NULL);
1637 set_jni_functions(jni_functions());
1638 set_callee_target(NULL);
1639 set_vm_result(NULL);
1640 set_vm_result_2(NULL);
1641 set_return_buffered_value(NULL);
1642 set_vframe_array_head(NULL);
1643 set_vframe_array_last(NULL);
1644 set_deferred_locals(NULL);
1645 set_deopt_mark(NULL);
1646 set_deopt_compiled_method(NULL);
1647 set_monitor_chunks(NULL);
1648 _on_thread_list = false;
1649 _thread_state = _thread_new;
1650 _terminated = _not_terminated;
1651 _array_for_gc = NULL;
1652 _suspend_equivalent = false;
1653 _in_deopt_handler = 0;
1654 _doing_unsafe_access = false;
1655 _stack_guard_state = stack_guard_unused;
1656 #if INCLUDE_JVMCI
1657 _pending_monitorenter = false;
1658 _pending_deoptimization = -1;
1659 _pending_failed_speculation = 0;
1660 _pending_transfer_to_interpreter = false;
1661 _in_retryable_allocation = false;
1662 _jvmci._alternate_call_target = NULL;
1663 assert(_jvmci._implicit_exception_pc == NULL, "must be");
1664 _jvmci_counters = NULL;
1665 if (JVMCICounterSize > 0) {
1666 resize_counters(0, (int) JVMCICounterSize);
1667 }
1668 #endif // INCLUDE_JVMCI
1669 _reserved_stack_activation = NULL; // stack base not known yet
1670 set_exception_oop(oop());
1671 _exception_pc = 0;
1672 _exception_handler_pc = 0;
1673 _is_method_handle_return = 0;
1674 _jvmti_thread_state= NULL;
1675 _should_post_on_exceptions_flag = JNI_FALSE;
1676 _interp_only_mode = 0;
1677 _special_runtime_exit_condition = _no_async_condition;
1678 _pending_async_exception = NULL;
1679 _thread_stat = NULL;
1680 _thread_stat = new ThreadStatistics();
1681 _jni_active_critical = 0;
1682 _pending_jni_exception_check_fn = NULL;
1683 _do_not_unlock_if_synchronized = false;
1684 _cached_monitor_info = NULL;
1685 _parker = Parker::Allocate(this);
1686 _SleepEvent = ParkEvent::Allocate(this);
1687 // Setup safepoint state info for this thread
1688 ThreadSafepointState::create(this);
1689 _handshake.set_handshakee(this);
1690
1691 debug_only(_java_call_counter = 0);
1692
1693 // JVMTI PopFrame support
1694 _popframe_condition = popframe_inactive;
1695 _popframe_preserved_args = NULL;
1696 _popframe_preserved_args_size = 0;
1697 _frames_to_pop_failed_realloc = 0;
1698
1699 SafepointMechanism::initialize_header(this);
1700
1701 _class_to_be_initialized = NULL;
1702
1703 pd_initialize();
1704 }
1705
1706 JavaThread::JavaThread(bool is_attaching_via_jni) :
1707 Thread() {
1708 initialize();
1709 if (is_attaching_via_jni) {
1710 _jni_attach_state = _attaching_via_jni;
1711 } else {
1712 _jni_attach_state = _not_attaching_via_jni;
1713 }
1714 assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
1715 }
1716
1717
1718 // interrupt support
1719
1720 void JavaThread::interrupt() {
1721 debug_only(check_for_dangling_thread_pointer(this);)
1722
1723 // For Windows _interrupt_event
1724 osthread()->set_interrupted(true);
1725
1726 // For Thread.sleep
1727 _SleepEvent->unpark();
1728
1729 // For JSR166 LockSupport.park
1730 parker()->unpark();
1731
1732 // For ObjectMonitor and JvmtiRawMonitor
1733 _ParkEvent->unpark();
1734 }
1735
1736
1737 bool JavaThread::is_interrupted(bool clear_interrupted) {
1738 debug_only(check_for_dangling_thread_pointer(this);)
1739
1740 if (threadObj() == NULL) {
1741 // If there is no j.l.Thread then it is impossible to have
1742 // been interrupted. We can find NULL during VM initialization
1743 // or when a JNI thread is still in the process of attaching.
1744 // In such cases this must be the current thread.
1745 assert(this == Thread::current(), "invariant");
1746 return false;
1747 }
1748
1749 bool interrupted = java_lang_Thread::interrupted(threadObj());
1750
1751 // NOTE that since there is no "lock" around the interrupt and
1752 // is_interrupted operations, there is the possibility that the
1753 // interrupted flag will be "false" but that the
1754 // low-level events will be in the signaled state. This is
1755 // intentional. The effect of this is that Object.wait() and
1756 // LockSupport.park() will appear to have a spurious wakeup, which
1757 // is allowed and not harmful, and the possibility is so rare that
1758 // it is not worth the added complexity to add yet another lock.
1759 // For the sleep event an explicit reset is performed on entry
1760 // to JavaThread::sleep, so there is no early return. It has also been
1761 // recommended not to put the interrupted flag into the "event"
1762 // structure because it hides the issue.
1763 // Also, because there is no lock, we must only clear the interrupt
1764 // state if we are going to report that we were interrupted; otherwise
1765 // an interrupt that happens just after we read the field would be lost.
1766 if (interrupted && clear_interrupted) {
1767 assert(this == Thread::current(), "only the current thread can clear");
1768 java_lang_Thread::set_interrupted(threadObj(), false);
1769 osthread()->set_interrupted(false);
1770 }
1771
1772 return interrupted;
1773 }
1774
1775 bool JavaThread::reguard_stack(address cur_sp) {
1776 if (_stack_guard_state != stack_guard_yellow_reserved_disabled
1777 && _stack_guard_state != stack_guard_reserved_disabled) {
1778 return true; // Stack already guarded or guard pages not needed.
1779 }
1780
1781 if (register_stack_overflow()) {
1782 // For those architectures which have separate register and
1783 // memory stacks, we must check the register stack to see if
1784 // it has overflowed.
1785 return false;
1786 }
1787
1788 // Java code never executes within the yellow zone: the latter is only
1789 // there to provoke an exception during stack banging. If java code
1790 // is executing there, either StackShadowPages should be larger, or
1791 // some exception code in c1, c2 or the interpreter isn't unwinding
1792 // when it should.
1793 guarantee(cur_sp > stack_reserved_zone_base(),
1794 "not enough space to reguard - increase StackShadowPages");
1795 if (_stack_guard_state == stack_guard_yellow_reserved_disabled) {
1796 enable_stack_yellow_reserved_zone();
1797 if (reserved_stack_activation() != stack_base()) {
1798 set_reserved_stack_activation(stack_base());
1799 }
1800 } else if (_stack_guard_state == stack_guard_reserved_disabled) {
1801 set_reserved_stack_activation(stack_base());
1802 enable_stack_reserved_zone();
1803 }
1804 return true;
1805 }
1806
1807 bool JavaThread::reguard_stack(void) {
1808 return reguard_stack(os::current_stack_pointer());
1809 }
1810
1811 void JavaThread::block_if_vm_exited() {
1812 if (_terminated == _vm_exited) {
1813 // _vm_exited is set at safepoint, and Threads_lock is never released
1814 // we will block here forever.
1815 // Here we can be doing a jump from a safe state to an unsafe state without
1816 // proper transition, but it happens after the final safepoint has begun.
1817 set_thread_state(_thread_in_vm);
1818 Threads_lock->lock();
1819 ShouldNotReachHere();
1820 }
1821 }
1822
1823
1824 // Remove this ifdef when C1 is ported to the compiler interface.
1825 static void compiler_thread_entry(JavaThread* thread, TRAPS);
1826 static void sweeper_thread_entry(JavaThread* thread, TRAPS);
1827
1828 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
1829 Thread() {
1830 initialize();
1831 _jni_attach_state = _not_attaching_via_jni;
1832 set_entry_point(entry_point);
1833 // Create the native thread itself.
1834 // %note runtime_23
1835 os::ThreadType thr_type = os::java_thread;
1836 thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
1837 os::java_thread;
1838 os::create_thread(this, thr_type, stack_sz);
1839 // The _osthread may be NULL here because we ran out of memory (too many threads active).
1840 // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
1841 // may hold a lock and all locks must be unlocked before throwing the exception (throwing
1842 // the exception consists of creating the exception object & initializing it, initialization
1843 // will leave the VM via a JavaCall and then all locks must be unlocked).
1844 //
1845 // The thread is still suspended when we reach here. Thread must be explicit started
1846 // by creator! Furthermore, the thread must also explicitly be added to the Threads list
1847 // by calling Threads:add. The reason why this is not done here, is because the thread
1848 // object must be fully initialized (take a look at JVM_Start)
1849 }
1850
1851 JavaThread::~JavaThread() {
1852
1853 // JSR166 -- return the parker to the free list
1854 Parker::Release(_parker);
1855 _parker = NULL;
1856
1857 // Return the sleep event to the free list
1858 ParkEvent::Release(_SleepEvent);
1859 _SleepEvent = NULL;
1860
1861 // Free any remaining previous UnrollBlock
1862 vframeArray* old_array = vframe_array_last();
1863
1864 if (old_array != NULL) {
1865 Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
1866 old_array->set_unroll_block(NULL);
1867 delete old_info;
1868 delete old_array;
1869 }
1870
1871 GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals();
1872 if (deferred != NULL) {
1873 // This can only happen if thread is destroyed before deoptimization occurs.
1874 assert(deferred->length() != 0, "empty array!");
1875 do {
1876 jvmtiDeferredLocalVariableSet* dlv = deferred->at(0);
1877 deferred->remove_at(0);
1878 // individual jvmtiDeferredLocalVariableSet are CHeapObj's
1879 delete dlv;
1880 } while (deferred->length() != 0);
1881 delete deferred;
1882 }
1883
1884 // All Java related clean up happens in exit
1885 ThreadSafepointState::destroy(this);
1886 if (_thread_stat != NULL) delete _thread_stat;
1887
1888 #if INCLUDE_JVMCI
1889 if (JVMCICounterSize > 0) {
1890 if (jvmci_counters_include(this)) {
1891 for (int i = 0; i < JVMCICounterSize; i++) {
1892 _jvmci_old_thread_counters[i] += _jvmci_counters[i];
1893 }
1894 }
1895 FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
1896 }
1897 #endif // INCLUDE_JVMCI
1898 }
1899
1900
1901 // First JavaThread specific code executed by a new Java thread.
1902 void JavaThread::pre_run() {
1903 // empty - see comments in run()
1904 }
1905
1906 // The main routine called by a new Java thread. This isn't overridden
1907 // by subclasses, instead different subclasses define a different "entry_point"
1908 // which defines the actual logic for that kind of thread.
1909 void JavaThread::run() {
1910 // initialize thread-local alloc buffer related fields
1911 this->initialize_tlab();
1912
1913 // Used to test validity of stack trace backs.
1914 // This can't be moved into pre_run() else we invalidate
1915 // the requirement that thread_main_inner is lower on
1916 // the stack. Consequently all the initialization logic
1917 // stays here in run() rather than pre_run().
1918 this->record_base_of_stack_pointer();
1919
1920 this->create_stack_guard_pages();
1921
1922 this->cache_global_variables();
1923
1924 // Thread is now sufficiently initialized to be handled by the safepoint code as being
1925 // in the VM. Change thread state from _thread_new to _thread_in_vm
1926 ThreadStateTransition::transition(this, _thread_new, _thread_in_vm);
1927 // Before a thread is on the threads list it is always safe, so after leaving the
1928 // _thread_new we should emit a instruction barrier. The distance to modified code
1929 // from here is probably far enough, but this is consistent and safe.
1930 OrderAccess::cross_modify_fence();
1931
1932 assert(JavaThread::current() == this, "sanity check");
1933 assert(!Thread::current()->owns_locks(), "sanity check");
1934
1935 DTRACE_THREAD_PROBE(start, this);
1936
1937 // This operation might block. We call that after all safepoint checks for a new thread has
1938 // been completed.
1939 this->set_active_handles(JNIHandleBlock::allocate_block());
1940
1941 if (JvmtiExport::should_post_thread_life()) {
1942 JvmtiExport::post_thread_start(this);
1943
1944 }
1945
1946 // We call another function to do the rest so we are sure that the stack addresses used
1947 // from there will be lower than the stack base just computed.
1948 thread_main_inner();
1949 }
1950
1951 void JavaThread::thread_main_inner() {
1952 assert(JavaThread::current() == this, "sanity check");
1953 assert(this->threadObj() != NULL, "just checking");
1954
1955 // Execute thread entry point unless this thread has a pending exception
1956 // or has been stopped before starting.
1957 // Note: Due to JVM_StopThread we can have pending exceptions already!
1958 if (!this->has_pending_exception() &&
1959 !java_lang_Thread::is_stillborn(this->threadObj())) {
1960 {
1961 ResourceMark rm(this);
1962 this->set_native_thread_name(this->get_thread_name());
1963 }
1964 HandleMark hm(this);
1965 this->entry_point()(this, this);
1966 }
1967
1968 DTRACE_THREAD_PROBE(stop, this);
1969
1970 // Cleanup is handled in post_run()
1971 }
1972
1973 // Shared teardown for all JavaThreads
1974 void JavaThread::post_run() {
1975 this->exit(false);
1976 // Defer deletion to here to ensure 'this' is still referenceable in call_run
1977 // for any shared tear-down.
1978 this->smr_delete();
1979 }
1980
1981 static void ensure_join(JavaThread* thread) {
1982 // We do not need to grab the Threads_lock, since we are operating on ourself.
1983 Handle threadObj(thread, thread->threadObj());
1984 assert(threadObj.not_null(), "java thread object must exist");
1985 ObjectLocker lock(threadObj, thread);
1986 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1987 thread->clear_pending_exception();
1988 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
1989 java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1990 // Clear the native thread instance - this makes isAlive return false and allows the join()
1991 // to complete once we've done the notify_all below
1992 java_lang_Thread::set_thread(threadObj(), NULL);
1993 lock.notify_all(thread);
1994 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1995 thread->clear_pending_exception();
1996 }
1997
1998 static bool is_daemon(oop threadObj) {
1999 return (threadObj != NULL && java_lang_Thread::is_daemon(threadObj));
2000 }
2001
2002 // For any new cleanup additions, please check to see if they need to be applied to
2003 // cleanup_failed_attach_current_thread as well.
2004 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
2005 assert(this == JavaThread::current(), "thread consistency check");
2006
2007 elapsedTimer _timer_exit_phase1;
2008 elapsedTimer _timer_exit_phase2;
2009 elapsedTimer _timer_exit_phase3;
2010 elapsedTimer _timer_exit_phase4;
2011
2012 if (log_is_enabled(Debug, os, thread, timer)) {
2013 _timer_exit_phase1.start();
2014 }
2015
2016 HandleMark hm(this);
2017 Handle uncaught_exception(this, this->pending_exception());
2018 this->clear_pending_exception();
2019 Handle threadObj(this, this->threadObj());
2020 assert(threadObj.not_null(), "Java thread object should be created");
2021
2022 // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place
2023 {
2024 EXCEPTION_MARK;
2025
2026 CLEAR_PENDING_EXCEPTION;
2027 }
2028 if (!destroy_vm) {
2029 if (uncaught_exception.not_null()) {
2030 EXCEPTION_MARK;
2031 // Call method Thread.dispatchUncaughtException().
2032 Klass* thread_klass = SystemDictionary::Thread_klass();
2033 JavaValue result(T_VOID);
2034 JavaCalls::call_virtual(&result,
2035 threadObj, thread_klass,
2036 vmSymbols::dispatchUncaughtException_name(),
2037 vmSymbols::throwable_void_signature(),
2038 uncaught_exception,
2039 THREAD);
2040 if (HAS_PENDING_EXCEPTION) {
2041 ResourceMark rm(this);
2042 jio_fprintf(defaultStream::error_stream(),
2043 "\nException: %s thrown from the UncaughtExceptionHandler"
2044 " in thread \"%s\"\n",
2045 pending_exception()->klass()->external_name(),
2046 get_thread_name());
2047 CLEAR_PENDING_EXCEPTION;
2048 }
2049 }
2050
2051 // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
2052 // the execution of the method. If that is not enough, then we don't really care. Thread.stop
2053 // is deprecated anyhow.
2054 if (!is_Compiler_thread()) {
2055 int count = 3;
2056 while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
2057 EXCEPTION_MARK;
2058 JavaValue result(T_VOID);
2059 Klass* thread_klass = SystemDictionary::Thread_klass();
2060 JavaCalls::call_virtual(&result,
2061 threadObj, thread_klass,
2062 vmSymbols::exit_method_name(),
2063 vmSymbols::void_method_signature(),
2064 THREAD);
2065 CLEAR_PENDING_EXCEPTION;
2066 }
2067 }
2068 // notify JVMTI
2069 if (JvmtiExport::should_post_thread_life()) {
2070 JvmtiExport::post_thread_end(this);
2071 }
2072
2073 // We have notified the agents that we are exiting, before we go on,
2074 // we must check for a pending external suspend request and honor it
2075 // in order to not surprise the thread that made the suspend request.
2076 while (true) {
2077 {
2078 MutexLocker ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2079 if (!is_external_suspend()) {
2080 set_terminated(_thread_exiting);
2081 ThreadService::current_thread_exiting(this, is_daemon(threadObj()));
2082 break;
2083 }
2084 // Implied else:
2085 // Things get a little tricky here. We have a pending external
2086 // suspend request, but we are holding the SR_lock so we
2087 // can't just self-suspend. So we temporarily drop the lock
2088 // and then self-suspend.
2089 }
2090
2091 ThreadBlockInVM tbivm(this);
2092 java_suspend_self();
2093
2094 // We're done with this suspend request, but we have to loop around
2095 // and check again. Eventually we will get SR_lock without a pending
2096 // external suspend request and will be able to mark ourselves as
2097 // exiting.
2098 }
2099 // no more external suspends are allowed at this point
2100 } else {
2101 assert(!is_terminated() && !is_exiting(), "must not be exiting");
2102 // before_exit() has already posted JVMTI THREAD_END events
2103 }
2104
2105 if (log_is_enabled(Debug, os, thread, timer)) {
2106 _timer_exit_phase1.stop();
2107 _timer_exit_phase2.start();
2108 }
2109
2110 // Capture daemon status before the thread is marked as terminated.
2111 bool daemon = is_daemon(threadObj());
2112
2113 // Notify waiters on thread object. This has to be done after exit() is called
2114 // on the thread (if the thread is the last thread in a daemon ThreadGroup the
2115 // group should have the destroyed bit set before waiters are notified).
2116 ensure_join(this);
2117 assert(!this->has_pending_exception(), "ensure_join should have cleared");
2118
2119 if (log_is_enabled(Debug, os, thread, timer)) {
2120 _timer_exit_phase2.stop();
2121 _timer_exit_phase3.start();
2122 }
2123 // 6282335 JNI DetachCurrentThread spec states that all Java monitors
2124 // held by this thread must be released. The spec does not distinguish
2125 // between JNI-acquired and regular Java monitors. We can only see
2126 // regular Java monitors here if monitor enter-exit matching is broken.
2127 //
2128 // ensure_join() ignores IllegalThreadStateExceptions, and so does
2129 // ObjectSynchronizer::release_monitors_owned_by_thread().
2130 if (exit_type == jni_detach) {
2131 // Sanity check even though JNI DetachCurrentThread() would have
2132 // returned JNI_ERR if there was a Java frame. JavaThread exit
2133 // should be done executing Java code by the time we get here.
2134 assert(!this->has_last_Java_frame(),
2135 "should not have a Java frame when detaching or exiting");
2136 ObjectSynchronizer::release_monitors_owned_by_thread(this);
2137 assert(!this->has_pending_exception(), "release_monitors should have cleared");
2138 }
2139
2140 // These things needs to be done while we are still a Java Thread. Make sure that thread
2141 // is in a consistent state, in case GC happens
2142 JFR_ONLY(Jfr::on_thread_exit(this);)
2143
2144 if (active_handles() != NULL) {
2145 JNIHandleBlock* block = active_handles();
2146 set_active_handles(NULL);
2147 JNIHandleBlock::release_block(block);
2148 }
2149
2150 if (free_handle_block() != NULL) {
2151 JNIHandleBlock* block = free_handle_block();
2152 set_free_handle_block(NULL);
2153 JNIHandleBlock::release_block(block);
2154 }
2155
2156 // These have to be removed while this is still a valid thread.
2157 remove_stack_guard_pages();
2158
2159 if (UseTLAB) {
2160 tlab().retire();
2161 }
2162
2163 if (JvmtiEnv::environments_might_exist()) {
2164 JvmtiExport::cleanup_thread(this);
2165 }
2166
2167 // We need to cache the thread name for logging purposes below as once
2168 // we have called on_thread_detach this thread must not access any oops.
2169 char* thread_name = NULL;
2170 if (log_is_enabled(Debug, os, thread, timer)) {
2171 ResourceMark rm(this);
2172 thread_name = os::strdup(get_thread_name());
2173 }
2174
2175 // We must flush any deferred card marks and other various GC barrier
2176 // related buffers (e.g. G1 SATB buffer and G1 dirty card queue buffer)
2177 // before removing a thread from the list of active threads.
2178 BarrierSet::barrier_set()->on_thread_detach(this);
2179
2180 log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").",
2181 exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
2182 os::current_thread_id());
2183
2184 if (log_is_enabled(Debug, os, thread, timer)) {
2185 _timer_exit_phase3.stop();
2186 _timer_exit_phase4.start();
2187 }
2188 // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
2189 Threads::remove(this, daemon);
2190
2191 if (log_is_enabled(Debug, os, thread, timer)) {
2192 _timer_exit_phase4.stop();
2193 log_debug(os, thread, timer)("name='%s'"
2194 ", exit-phase1=" JLONG_FORMAT
2195 ", exit-phase2=" JLONG_FORMAT
2196 ", exit-phase3=" JLONG_FORMAT
2197 ", exit-phase4=" JLONG_FORMAT,
2198 thread_name,
2199 _timer_exit_phase1.milliseconds(),
2200 _timer_exit_phase2.milliseconds(),
2201 _timer_exit_phase3.milliseconds(),
2202 _timer_exit_phase4.milliseconds());
2203 os::free(thread_name);
2204 }
2205 }
2206
2207 void JavaThread::cleanup_failed_attach_current_thread(bool is_daemon) {
2208 if (active_handles() != NULL) {
2209 JNIHandleBlock* block = active_handles();
2210 set_active_handles(NULL);
2211 JNIHandleBlock::release_block(block);
2212 }
2213
2214 if (free_handle_block() != NULL) {
2215 JNIHandleBlock* block = free_handle_block();
2216 set_free_handle_block(NULL);
2217 JNIHandleBlock::release_block(block);
2218 }
2219
2220 // These have to be removed while this is still a valid thread.
2221 remove_stack_guard_pages();
2222
2223 if (UseTLAB) {
2224 tlab().retire();
2225 }
2226
2227 BarrierSet::barrier_set()->on_thread_detach(this);
2228
2229 Threads::remove(this, is_daemon);
2230 this->smr_delete();
2231 }
2232
2233 JavaThread* JavaThread::active() {
2234 Thread* thread = Thread::current();
2235 if (thread->is_Java_thread()) {
2236 return (JavaThread*) thread;
2237 } else {
2238 assert(thread->is_VM_thread(), "this must be a vm thread");
2239 VM_Operation* op = ((VMThread*) thread)->vm_operation();
2240 JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
2241 assert(ret->is_Java_thread(), "must be a Java thread");
2242 return ret;
2243 }
2244 }
2245
2246 bool JavaThread::is_lock_owned(address adr) const {
2247 if (Thread::is_lock_owned(adr)) return true;
2248
2249 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2250 if (chunk->contains(adr)) return true;
2251 }
2252
2253 return false;
2254 }
2255
2256 oop JavaThread::exception_oop() const {
2257 return Atomic::load(&_exception_oop);
2258 }
2259
2260 void JavaThread::set_exception_oop(oop o) {
2261 Atomic::store(&_exception_oop, o);
2262 }
2263
2264 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
2265 chunk->set_next(monitor_chunks());
2266 set_monitor_chunks(chunk);
2267 }
2268
2269 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
2270 guarantee(monitor_chunks() != NULL, "must be non empty");
2271 if (monitor_chunks() == chunk) {
2272 set_monitor_chunks(chunk->next());
2273 } else {
2274 MonitorChunk* prev = monitor_chunks();
2275 while (prev->next() != chunk) prev = prev->next();
2276 prev->set_next(chunk->next());
2277 }
2278 }
2279
2280 // JVM support.
2281
2282 // Note: this function shouldn't block if it's called in
2283 // _thread_in_native_trans state (such as from
2284 // check_special_condition_for_native_trans()).
2285 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) {
2286
2287 if (has_last_Java_frame() && has_async_condition()) {
2288 // If we are at a polling page safepoint (not a poll return)
2289 // then we must defer async exception because live registers
2290 // will be clobbered by the exception path. Poll return is
2291 // ok because the call we a returning from already collides
2292 // with exception handling registers and so there is no issue.
2293 // (The exception handling path kills call result registers but
2294 // this is ok since the exception kills the result anyway).
2295
2296 if (is_at_poll_safepoint()) {
2297 // if the code we are returning to has deoptimized we must defer
2298 // the exception otherwise live registers get clobbered on the
2299 // exception path before deoptimization is able to retrieve them.
2300 //
2301 RegisterMap map(this, false);
2302 frame caller_fr = last_frame().sender(&map);
2303 assert(caller_fr.is_compiled_frame(), "what?");
2304 if (caller_fr.is_deoptimized_frame()) {
2305 log_info(exceptions)("deferred async exception at compiled safepoint");
2306 return;
2307 }
2308 }
2309 }
2310
2311 JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition();
2312 if (condition == _no_async_condition) {
2313 // Conditions have changed since has_special_runtime_exit_condition()
2314 // was called:
2315 // - if we were here only because of an external suspend request,
2316 // then that was taken care of above (or cancelled) so we are done
2317 // - if we were here because of another async request, then it has
2318 // been cleared between the has_special_runtime_exit_condition()
2319 // and now so again we are done
2320 return;
2321 }
2322
2323 // Check for pending async. exception
2324 if (_pending_async_exception != NULL) {
2325 // Only overwrite an already pending exception, if it is not a threadDeath.
2326 if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) {
2327
2328 // We cannot call Exceptions::_throw(...) here because we cannot block
2329 set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
2330
2331 LogTarget(Info, exceptions) lt;
2332 if (lt.is_enabled()) {
2333 ResourceMark rm;
2334 LogStream ls(lt);
2335 ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this));
2336 if (has_last_Java_frame()) {
2337 frame f = last_frame();
2338 ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp()));
2339 }
2340 ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name());
2341 }
2342 _pending_async_exception = NULL;
2343 clear_has_async_exception();
2344 }
2345 }
2346
2347 if (check_unsafe_error &&
2348 condition == _async_unsafe_access_error && !has_pending_exception()) {
2349 condition = _no_async_condition; // done
2350 switch (thread_state()) {
2351 case _thread_in_vm: {
2352 JavaThread* THREAD = this;
2353 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
2354 }
2355 case _thread_in_native: {
2356 ThreadInVMfromNative tiv(this);
2357 JavaThread* THREAD = this;
2358 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
2359 }
2360 case _thread_in_Java: {
2361 ThreadInVMfromJava tiv(this);
2362 JavaThread* THREAD = this;
2363 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
2364 }
2365 default:
2366 ShouldNotReachHere();
2367 }
2368 }
2369
2370 assert(condition == _no_async_condition || has_pending_exception() ||
2371 (!check_unsafe_error && condition == _async_unsafe_access_error),
2372 "must have handled the async condition, if no exception");
2373 }
2374
2375 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
2376
2377 // Check for pending external suspend.
2378 if (is_external_suspend_with_lock()) {
2379 frame_anchor()->make_walkable(this);
2380 java_suspend_self_with_safepoint_check();
2381 }
2382
2383 // We might be here for reasons in addition to the self-suspend request
2384 // so check for other async requests.
2385 if (check_asyncs) {
2386 check_and_handle_async_exceptions();
2387 }
2388
2389 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);)
2390 }
2391
2392 void JavaThread::send_thread_stop(oop java_throwable) {
2393 ResourceMark rm;
2394 assert(Thread::current()->is_VM_thread() || Thread::current() == this, "should be in the vm thread");
2395
2396 // Do not throw asynchronous exceptions against the compiler thread
2397 // (the compiler thread should not be a Java thread -- fix in 1.4.2)
2398 if (!can_call_java()) return;
2399
2400 {
2401 // Actually throw the Throwable against the target Thread - however
2402 // only if there is no thread death exception installed already.
2403 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
2404 // If the topmost frame is a runtime stub, then we are calling into
2405 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
2406 // must deoptimize the caller before continuing, as the compiled exception handler table
2407 // may not be valid
2408 if (has_last_Java_frame()) {
2409 frame f = last_frame();
2410 if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
2411 RegisterMap reg_map(this, false);
2412 frame compiled_frame = f.sender(®_map);
2413 if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
2414 Deoptimization::deoptimize(this, compiled_frame);
2415 }
2416 }
2417 }
2418
2419 // Set async. pending exception in thread.
2420 set_pending_async_exception(java_throwable);
2421
2422 if (log_is_enabled(Info, exceptions)) {
2423 ResourceMark rm;
2424 log_info(exceptions)("Pending Async. exception installed of type: %s",
2425 InstanceKlass::cast(_pending_async_exception->klass())->external_name());
2426 }
2427 // for AbortVMOnException flag
2428 Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name());
2429 }
2430 }
2431
2432
2433 // Interrupt thread so it will wake up from a potential wait()/sleep()/park()
2434 java_lang_Thread::set_interrupted(threadObj(), true);
2435 this->interrupt();
2436 }
2437
2438 // External suspension mechanism.
2439 //
2440 // Tell the VM to suspend a thread when ever it knows that it does not hold on
2441 // to any VM_locks and it is at a transition
2442 // Self-suspension will happen on the transition out of the vm.
2443 // Catch "this" coming in from JNIEnv pointers when the thread has been freed
2444 //
2445 // Guarantees on return:
2446 // + Target thread will not execute any new bytecode (that's why we need to
2447 // force a safepoint)
2448 // + Target thread will not enter any new monitors
2449 //
2450 void JavaThread::java_suspend() {
2451 ThreadsListHandle tlh;
2452 if (!tlh.includes(this) || threadObj() == NULL || is_exiting()) {
2453 return;
2454 }
2455
2456 { MutexLocker ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2457 if (!is_external_suspend()) {
2458 // a racing resume has cancelled us; bail out now
2459 return;
2460 }
2461
2462 // suspend is done
2463 uint32_t debug_bits = 0;
2464 // Warning: is_ext_suspend_completed() may temporarily drop the
2465 // SR_lock to allow the thread to reach a stable thread state if
2466 // it is currently in a transient thread state.
2467 if (is_ext_suspend_completed(false /* !called_by_wait */,
2468 SuspendRetryDelay, &debug_bits)) {
2469 return;
2470 }
2471 }
2472
2473 if (Thread::current() == this) {
2474 // Safely self-suspend.
2475 // If we don't do this explicitly it will implicitly happen
2476 // before we transition back to Java, and on some other thread-state
2477 // transition paths, but not as we exit a JVM TI SuspendThread call.
2478 // As SuspendThread(current) must not return (until resumed) we must
2479 // self-suspend here.
2480 ThreadBlockInVM tbivm(this);
2481 java_suspend_self();
2482 } else {
2483 VM_ThreadSuspend vm_suspend;
2484 VMThread::execute(&vm_suspend);
2485 }
2486 }
2487
2488 // Part II of external suspension.
2489 // A JavaThread self suspends when it detects a pending external suspend
2490 // request. This is usually on transitions. It is also done in places
2491 // where continuing to the next transition would surprise the caller,
2492 // e.g., monitor entry.
2493 //
2494 // Returns the number of times that the thread self-suspended.
2495 //
2496 // Note: DO NOT call java_suspend_self() when you just want to block current
2497 // thread. java_suspend_self() is the second stage of cooperative
2498 // suspension for external suspend requests and should only be used
2499 // to complete an external suspend request.
2500 //
2501 int JavaThread::java_suspend_self() {
2502 assert(thread_state() == _thread_blocked, "wrong state for java_suspend_self()");
2503 int ret = 0;
2504
2505 // we are in the process of exiting so don't suspend
2506 if (is_exiting()) {
2507 clear_external_suspend();
2508 return ret;
2509 }
2510
2511 assert(_anchor.walkable() ||
2512 (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()),
2513 "must have walkable stack");
2514
2515 MonitorLocker ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2516
2517 assert(!this->is_ext_suspended(),
2518 "a thread trying to self-suspend should not already be suspended");
2519
2520 if (this->is_suspend_equivalent()) {
2521 // If we are self-suspending as a result of the lifting of a
2522 // suspend equivalent condition, then the suspend_equivalent
2523 // flag is not cleared until we set the ext_suspended flag so
2524 // that wait_for_ext_suspend_completion() returns consistent
2525 // results.
2526 this->clear_suspend_equivalent();
2527 }
2528
2529 // A racing resume may have cancelled us before we grabbed SR_lock
2530 // above. Or another external suspend request could be waiting for us
2531 // by the time we return from SR_lock()->wait(). The thread
2532 // that requested the suspension may already be trying to walk our
2533 // stack and if we return now, we can change the stack out from under
2534 // it. This would be a "bad thing (TM)" and cause the stack walker
2535 // to crash. We stay self-suspended until there are no more pending
2536 // external suspend requests.
2537 while (is_external_suspend()) {
2538 ret++;
2539 this->set_ext_suspended();
2540
2541 // _ext_suspended flag is cleared by java_resume()
2542 while (is_ext_suspended()) {
2543 ml.wait();
2544 }
2545 }
2546 return ret;
2547 }
2548
2549 // Helper routine to set up the correct thread state before calling java_suspend_self.
2550 // This is called when regular thread-state transition helpers can't be used because
2551 // we can be in various states, in particular _thread_in_native_trans.
2552 // Because this thread is external suspended the safepoint code will count it as at
2553 // a safepoint, regardless of what its actual current thread-state is. But
2554 // is_ext_suspend_completed() may be waiting to see a thread transition from
2555 // _thread_in_native_trans to _thread_blocked. So we set the thread state directly
2556 // to _thread_blocked. The problem with setting thread state directly is that a
2557 // safepoint could happen just after java_suspend_self() returns after being resumed,
2558 // and the VM thread will see the _thread_blocked state. So we must check for a safepoint
2559 // after restoring the state to make sure we won't leave while a safepoint is in progress.
2560 // However, not all initial-states are allowed when performing a safepoint check, as we
2561 // should never be blocking at a safepoint whilst in those states. Of these 'bad' states
2562 // only _thread_in_native is possible when executing this code (based on our two callers).
2563 // A thread that is _thread_in_native is already safepoint-safe and so it doesn't matter
2564 // whether the VMThread sees the _thread_blocked state, or the _thread_in_native state,
2565 // and so we don't need the explicit safepoint check.
2566
2567 void JavaThread::java_suspend_self_with_safepoint_check() {
2568 assert(this == Thread::current(), "invariant");
2569 JavaThreadState state = thread_state();
2570 set_thread_state(_thread_blocked);
2571 java_suspend_self();
2572 set_thread_state_fence(state);
2573 // Since we are not using a regular thread-state transition helper here,
2574 // we must manually emit the instruction barrier after leaving a safe state.
2575 OrderAccess::cross_modify_fence();
2576 if (state != _thread_in_native) {
2577 SafepointMechanism::block_if_requested(this);
2578 }
2579 }
2580
2581 #ifdef ASSERT
2582 // Verify the JavaThread has not yet been published in the Threads::list, and
2583 // hence doesn't need protection from concurrent access at this stage.
2584 void JavaThread::verify_not_published() {
2585 // Cannot create a ThreadsListHandle here and check !tlh.includes(this)
2586 // since an unpublished JavaThread doesn't participate in the
2587 // Thread-SMR protocol for keeping a ThreadsList alive.
2588 assert(!on_thread_list(), "JavaThread shouldn't have been published yet!");
2589 }
2590 #endif
2591
2592 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2593 // progress or when _suspend_flags is non-zero.
2594 // Current thread needs to self-suspend if there is a suspend request and/or
2595 // block if a safepoint is in progress.
2596 // Async exception ISN'T checked.
2597 // Note only the ThreadInVMfromNative transition can call this function
2598 // directly and when thread state is _thread_in_native_trans
2599 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
2600 assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
2601
2602 assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
2603
2604 if (thread->is_external_suspend()) {
2605 thread->java_suspend_self_with_safepoint_check();
2606 } else {
2607 SafepointMechanism::block_if_requested(thread);
2608 }
2609
2610 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(thread);)
2611 }
2612
2613 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2614 // progress or when _suspend_flags is non-zero.
2615 // Current thread needs to self-suspend if there is a suspend request and/or
2616 // block if a safepoint is in progress.
2617 // Also check for pending async exception (not including unsafe access error).
2618 // Note only the native==>VM/Java barriers can call this function and when
2619 // thread state is _thread_in_native_trans.
2620 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
2621 check_safepoint_and_suspend_for_native_trans(thread);
2622
2623 if (thread->has_async_exception()) {
2624 // We are in _thread_in_native_trans state, don't handle unsafe
2625 // access error since that may block.
2626 thread->check_and_handle_async_exceptions(false);
2627 }
2628 }
2629
2630 // This is a variant of the normal
2631 // check_special_condition_for_native_trans with slightly different
2632 // semantics for use by critical native wrappers. It does all the
2633 // normal checks but also performs the transition back into
2634 // thread_in_Java state. This is required so that critical natives
2635 // can potentially block and perform a GC if they are the last thread
2636 // exiting the GCLocker.
2637 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) {
2638 check_special_condition_for_native_trans(thread);
2639
2640 // Finish the transition
2641 thread->set_thread_state(_thread_in_Java);
2642
2643 if (thread->do_critical_native_unlock()) {
2644 ThreadInVMfromJavaNoAsyncException tiv(thread);
2645 GCLocker::unlock_critical(thread);
2646 thread->clear_critical_native_unlock();
2647 }
2648 }
2649
2650 // We need to guarantee the Threads_lock here, since resumes are not
2651 // allowed during safepoint synchronization
2652 // Can only resume from an external suspension
2653 void JavaThread::java_resume() {
2654 assert_locked_or_safepoint(Threads_lock);
2655
2656 // Sanity check: thread is gone, has started exiting or the thread
2657 // was not externally suspended.
2658 ThreadsListHandle tlh;
2659 if (!tlh.includes(this) || is_exiting() || !is_external_suspend()) {
2660 return;
2661 }
2662
2663 MutexLocker ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2664
2665 clear_external_suspend();
2666
2667 if (is_ext_suspended()) {
2668 clear_ext_suspended();
2669 SR_lock()->notify_all();
2670 }
2671 }
2672
2673 size_t JavaThread::_stack_red_zone_size = 0;
2674 size_t JavaThread::_stack_yellow_zone_size = 0;
2675 size_t JavaThread::_stack_reserved_zone_size = 0;
2676 size_t JavaThread::_stack_shadow_zone_size = 0;
2677
2678 void JavaThread::create_stack_guard_pages() {
2679 if (!os::uses_stack_guard_pages() ||
2680 _stack_guard_state != stack_guard_unused ||
2681 (DisablePrimordialThreadGuardPages && os::is_primordial_thread())) {
2682 log_info(os, thread)("Stack guard page creation for thread "
2683 UINTX_FORMAT " disabled", os::current_thread_id());
2684 return;
2685 }
2686 address low_addr = stack_end();
2687 size_t len = stack_guard_zone_size();
2688
2689 assert(is_aligned(low_addr, os::vm_page_size()), "Stack base should be the start of a page");
2690 assert(is_aligned(len, os::vm_page_size()), "Stack size should be a multiple of page size");
2691
2692 int must_commit = os::must_commit_stack_guard_pages();
2693 // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len);
2694
2695 if (must_commit && !os::create_stack_guard_pages((char *) low_addr, len)) {
2696 log_warning(os, thread)("Attempt to allocate stack guard pages failed.");
2697 return;
2698 }
2699
2700 if (os::guard_memory((char *) low_addr, len)) {
2701 _stack_guard_state = stack_guard_enabled;
2702 } else {
2703 log_warning(os, thread)("Attempt to protect stack guard pages failed ("
2704 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2705 if (os::uncommit_memory((char *) low_addr, len)) {
2706 log_warning(os, thread)("Attempt to deallocate stack guard pages failed.");
2707 }
2708 return;
2709 }
2710
2711 log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages activated: "
2712 PTR_FORMAT "-" PTR_FORMAT ".",
2713 os::current_thread_id(), p2i(low_addr), p2i(low_addr + len));
2714 }
2715
2716 void JavaThread::remove_stack_guard_pages() {
2717 assert(Thread::current() == this, "from different thread");
2718 if (_stack_guard_state == stack_guard_unused) return;
2719 address low_addr = stack_end();
2720 size_t len = stack_guard_zone_size();
2721
2722 if (os::must_commit_stack_guard_pages()) {
2723 if (os::remove_stack_guard_pages((char *) low_addr, len)) {
2724 _stack_guard_state = stack_guard_unused;
2725 } else {
2726 log_warning(os, thread)("Attempt to deallocate stack guard pages failed ("
2727 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2728 return;
2729 }
2730 } else {
2731 if (_stack_guard_state == stack_guard_unused) return;
2732 if (os::unguard_memory((char *) low_addr, len)) {
2733 _stack_guard_state = stack_guard_unused;
2734 } else {
2735 log_warning(os, thread)("Attempt to unprotect stack guard pages failed ("
2736 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2737 return;
2738 }
2739 }
2740
2741 log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages removed: "
2742 PTR_FORMAT "-" PTR_FORMAT ".",
2743 os::current_thread_id(), p2i(low_addr), p2i(low_addr + len));
2744 }
2745
2746 void JavaThread::enable_stack_reserved_zone() {
2747 assert(_stack_guard_state == stack_guard_reserved_disabled, "inconsistent state");
2748
2749 // The base notation is from the stack's point of view, growing downward.
2750 // We need to adjust it to work correctly with guard_memory()
2751 address base = stack_reserved_zone_base() - stack_reserved_zone_size();
2752
2753 guarantee(base < stack_base(),"Error calculating stack reserved zone");
2754 guarantee(base < os::current_stack_pointer(),"Error calculating stack reserved zone");
2755
2756 if (os::guard_memory((char *) base, stack_reserved_zone_size())) {
2757 _stack_guard_state = stack_guard_enabled;
2758 } else {
2759 warning("Attempt to guard stack reserved zone failed.");
2760 }
2761 enable_register_stack_guard();
2762 }
2763
2764 void JavaThread::disable_stack_reserved_zone() {
2765 assert(_stack_guard_state == stack_guard_enabled, "inconsistent state");
2766
2767 // Simply return if called for a thread that does not use guard pages.
2768 if (_stack_guard_state != stack_guard_enabled) return;
2769
2770 // The base notation is from the stack's point of view, growing downward.
2771 // We need to adjust it to work correctly with guard_memory()
2772 address base = stack_reserved_zone_base() - stack_reserved_zone_size();
2773
2774 if (os::unguard_memory((char *)base, stack_reserved_zone_size())) {
2775 _stack_guard_state = stack_guard_reserved_disabled;
2776 } else {
2777 warning("Attempt to unguard stack reserved zone failed.");
2778 }
2779 disable_register_stack_guard();
2780 }
2781
2782 void JavaThread::enable_stack_yellow_reserved_zone() {
2783 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2784 assert(_stack_guard_state != stack_guard_enabled, "already enabled");
2785
2786 // The base notation is from the stacks point of view, growing downward.
2787 // We need to adjust it to work correctly with guard_memory()
2788 address base = stack_red_zone_base();
2789
2790 guarantee(base < stack_base(), "Error calculating stack yellow zone");
2791 guarantee(base < os::current_stack_pointer(), "Error calculating stack yellow zone");
2792
2793 if (os::guard_memory((char *) base, stack_yellow_reserved_zone_size())) {
2794 _stack_guard_state = stack_guard_enabled;
2795 } else {
2796 warning("Attempt to guard stack yellow zone failed.");
2797 }
2798 enable_register_stack_guard();
2799 }
2800
2801 void JavaThread::disable_stack_yellow_reserved_zone() {
2802 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2803 assert(_stack_guard_state != stack_guard_yellow_reserved_disabled, "already disabled");
2804
2805 // Simply return if called for a thread that does not use guard pages.
2806 if (_stack_guard_state == stack_guard_unused) return;
2807
2808 // The base notation is from the stacks point of view, growing downward.
2809 // We need to adjust it to work correctly with guard_memory()
2810 address base = stack_red_zone_base();
2811
2812 if (os::unguard_memory((char *)base, stack_yellow_reserved_zone_size())) {
2813 _stack_guard_state = stack_guard_yellow_reserved_disabled;
2814 } else {
2815 warning("Attempt to unguard stack yellow zone failed.");
2816 }
2817 disable_register_stack_guard();
2818 }
2819
2820 void JavaThread::enable_stack_red_zone() {
2821 // The base notation is from the stacks point of view, growing downward.
2822 // We need to adjust it to work correctly with guard_memory()
2823 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2824 address base = stack_red_zone_base() - stack_red_zone_size();
2825
2826 guarantee(base < stack_base(), "Error calculating stack red zone");
2827 guarantee(base < os::current_stack_pointer(), "Error calculating stack red zone");
2828
2829 if (!os::guard_memory((char *) base, stack_red_zone_size())) {
2830 warning("Attempt to guard stack red zone failed.");
2831 }
2832 }
2833
2834 void JavaThread::disable_stack_red_zone() {
2835 // The base notation is from the stacks point of view, growing downward.
2836 // We need to adjust it to work correctly with guard_memory()
2837 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2838 address base = stack_red_zone_base() - stack_red_zone_size();
2839 if (!os::unguard_memory((char *)base, stack_red_zone_size())) {
2840 warning("Attempt to unguard stack red zone failed.");
2841 }
2842 }
2843
2844 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
2845 // ignore is there is no stack
2846 if (!has_last_Java_frame()) return;
2847 // Because this method is used to verify oops, it must support
2848 // oops in buffered values
2849
2850 // traverse the stack frames. Starts from top frame.
2851 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2852 frame* fr = fst.current();
2853 f(fr, fst.register_map());
2854 }
2855 }
2856
2857
2858 #ifndef PRODUCT
2859 // Deoptimization
2860 // Function for testing deoptimization
2861 void JavaThread::deoptimize() {
2862 StackFrameStream fst(this, false);
2863 bool deopt = false; // Dump stack only if a deopt actually happens.
2864 bool only_at = strlen(DeoptimizeOnlyAt) > 0;
2865 // Iterate over all frames in the thread and deoptimize
2866 for (; !fst.is_done(); fst.next()) {
2867 if (fst.current()->can_be_deoptimized()) {
2868
2869 if (only_at) {
2870 // Deoptimize only at particular bcis. DeoptimizeOnlyAt
2871 // consists of comma or carriage return separated numbers so
2872 // search for the current bci in that string.
2873 address pc = fst.current()->pc();
2874 nmethod* nm = (nmethod*) fst.current()->cb();
2875 ScopeDesc* sd = nm->scope_desc_at(pc);
2876 char buffer[8];
2877 jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
2878 size_t len = strlen(buffer);
2879 const char * found = strstr(DeoptimizeOnlyAt, buffer);
2880 while (found != NULL) {
2881 if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
2882 (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
2883 // Check that the bci found is bracketed by terminators.
2884 break;
2885 }
2886 found = strstr(found + 1, buffer);
2887 }
2888 if (!found) {
2889 continue;
2890 }
2891 }
2892
2893 if (DebugDeoptimization && !deopt) {
2894 deopt = true; // One-time only print before deopt
2895 tty->print_cr("[BEFORE Deoptimization]");
2896 trace_frames();
2897 trace_stack();
2898 }
2899 Deoptimization::deoptimize(this, *fst.current());
2900 }
2901 }
2902
2903 if (DebugDeoptimization && deopt) {
2904 tty->print_cr("[AFTER Deoptimization]");
2905 trace_frames();
2906 }
2907 }
2908
2909
2910 // Make zombies
2911 void JavaThread::make_zombies() {
2912 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2913 if (fst.current()->can_be_deoptimized()) {
2914 // it is a Java nmethod
2915 nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
2916 nm->make_not_entrant();
2917 }
2918 }
2919 }
2920 #endif // PRODUCT
2921
2922
2923 void JavaThread::deoptimize_marked_methods() {
2924 if (!has_last_Java_frame()) return;
2925 StackFrameStream fst(this, false);
2926 for (; !fst.is_done(); fst.next()) {
2927 if (fst.current()->should_be_deoptimized()) {
2928 Deoptimization::deoptimize(this, *fst.current());
2929 }
2930 }
2931 }
2932
2933 // If the caller is a NamedThread, then remember, in the current scope,
2934 // the given JavaThread in its _processed_thread field.
2935 class RememberProcessedThread: public StackObj {
2936 NamedThread* _cur_thr;
2937 public:
2938 RememberProcessedThread(JavaThread* jthr) {
2939 Thread* thread = Thread::current();
2940 if (thread->is_Named_thread()) {
2941 _cur_thr = (NamedThread *)thread;
2942 _cur_thr->set_processed_thread(jthr);
2943 } else {
2944 _cur_thr = NULL;
2945 }
2946 }
2947
2948 ~RememberProcessedThread() {
2949 if (_cur_thr) {
2950 _cur_thr->set_processed_thread(NULL);
2951 }
2952 }
2953 };
2954
2955 void JavaThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
2956 // Verify that the deferred card marks have been flushed.
2957 assert(deferred_card_mark().is_empty(), "Should be empty during GC");
2958
2959 // Traverse the GCHandles
2960 Thread::oops_do(f, cf);
2961
2962 assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2963 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2964
2965 if (has_last_Java_frame()) {
2966 // Record JavaThread to GC thread
2967 RememberProcessedThread rpt(this);
2968
2969 // traverse the registered growable array
2970 if (_array_for_gc != NULL) {
2971 for (int index = 0; index < _array_for_gc->length(); index++) {
2972 f->do_oop(_array_for_gc->adr_at(index));
2973 }
2974 }
2975
2976 // Traverse the monitor chunks
2977 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2978 chunk->oops_do(f);
2979 }
2980
2981 // Traverse the execution stack
2982 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2983 fst.current()->oops_do(f, cf, fst.register_map());
2984 }
2985 }
2986
2987 assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
2988 // If we have deferred set_locals there might be oops waiting to be
2989 // written
2990 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals();
2991 if (list != NULL) {
2992 for (int i = 0; i < list->length(); i++) {
2993 list->at(i)->oops_do(f);
2994 }
2995 }
2996
2997 // Traverse instance variables at the end since the GC may be moving things
2998 // around using this function
2999 f->do_oop((oop*) &_threadObj);
3000 f->do_oop((oop*) &_vm_result);
3001 f->do_oop((oop*) &_exception_oop);
3002 f->do_oop((oop*) &_pending_async_exception);
3003
3004 if (jvmti_thread_state() != NULL) {
3005 jvmti_thread_state()->oops_do(f, cf);
3006 }
3007 }
3008
3009 #ifdef ASSERT
3010 void JavaThread::verify_states_for_handshake() {
3011 // This checks that the thread has a correct frame state during a handshake.
3012 assert((!has_last_Java_frame() && java_call_counter() == 0) ||
3013 (has_last_Java_frame() && java_call_counter() > 0),
3014 "unexpected frame info: has_last_frame=%d, java_call_counter=%d",
3015 has_last_Java_frame(), java_call_counter());
3016 }
3017 #endif
3018
3019 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
3020 assert((!has_last_Java_frame() && java_call_counter() == 0) ||
3021 (has_last_Java_frame() && java_call_counter() > 0),
3022 "unexpected frame info: has_last_frame=%d, java_call_counter=%d",
3023 has_last_Java_frame(), java_call_counter());
3024
3025 if (has_last_Java_frame()) {
3026 // Traverse the execution stack
3027 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
3028 fst.current()->nmethods_do(cf);
3029 }
3030 }
3031
3032 if (jvmti_thread_state() != NULL) {
3033 jvmti_thread_state()->nmethods_do(cf);
3034 }
3035 }
3036
3037 void JavaThread::metadata_do(MetadataClosure* f) {
3038 if (has_last_Java_frame()) {
3039 // Traverse the execution stack to call f() on the methods in the stack
3040 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
3041 fst.current()->metadata_do(f);
3042 }
3043 } else if (is_Compiler_thread()) {
3044 // need to walk ciMetadata in current compile tasks to keep alive.
3045 CompilerThread* ct = (CompilerThread*)this;
3046 if (ct->env() != NULL) {
3047 ct->env()->metadata_do(f);
3048 }
3049 CompileTask* task = ct->task();
3050 if (task != NULL) {
3051 task->metadata_do(f);
3052 }
3053 }
3054 }
3055
3056 // Printing
3057 const char* _get_thread_state_name(JavaThreadState _thread_state) {
3058 switch (_thread_state) {
3059 case _thread_uninitialized: return "_thread_uninitialized";
3060 case _thread_new: return "_thread_new";
3061 case _thread_new_trans: return "_thread_new_trans";
3062 case _thread_in_native: return "_thread_in_native";
3063 case _thread_in_native_trans: return "_thread_in_native_trans";
3064 case _thread_in_vm: return "_thread_in_vm";
3065 case _thread_in_vm_trans: return "_thread_in_vm_trans";
3066 case _thread_in_Java: return "_thread_in_Java";
3067 case _thread_in_Java_trans: return "_thread_in_Java_trans";
3068 case _thread_blocked: return "_thread_blocked";
3069 case _thread_blocked_trans: return "_thread_blocked_trans";
3070 default: return "unknown thread state";
3071 }
3072 }
3073
3074 #ifndef PRODUCT
3075 void JavaThread::print_thread_state_on(outputStream *st) const {
3076 st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state));
3077 };
3078 #endif // PRODUCT
3079
3080 // Called by Threads::print() for VM_PrintThreads operation
3081 void JavaThread::print_on(outputStream *st, bool print_extended_info) const {
3082 st->print_raw("\"");
3083 st->print_raw(get_thread_name());
3084 st->print_raw("\" ");
3085 oop thread_oop = threadObj();
3086 if (thread_oop != NULL) {
3087 st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop));
3088 if (java_lang_Thread::is_daemon(thread_oop)) st->print("daemon ");
3089 st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
3090 }
3091 Thread::print_on(st, print_extended_info);
3092 // print guess for valid stack memory region (assume 4K pages); helps lock debugging
3093 st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
3094 if (thread_oop != NULL) {
3095 st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
3096 }
3097 #ifndef PRODUCT
3098 _safepoint_state->print_on(st);
3099 #endif // PRODUCT
3100 if (is_Compiler_thread()) {
3101 CompileTask *task = ((CompilerThread*)this)->task();
3102 if (task != NULL) {
3103 st->print(" Compiling: ");
3104 task->print(st, NULL, true, false);
3105 } else {
3106 st->print(" No compile task");
3107 }
3108 st->cr();
3109 }
3110 }
3111
3112 void JavaThread::print() const { print_on(tty); }
3113
3114 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
3115 st->print("%s", get_thread_name_string(buf, buflen));
3116 }
3117
3118 // Called by fatal error handler. The difference between this and
3119 // JavaThread::print() is that we can't grab lock or allocate memory.
3120 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
3121 st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
3122 oop thread_obj = threadObj();
3123 if (thread_obj != NULL) {
3124 if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
3125 }
3126 st->print(" [");
3127 st->print("%s", _get_thread_state_name(_thread_state));
3128 if (osthread()) {
3129 st->print(", id=%d", osthread()->thread_id());
3130 }
3131 st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
3132 p2i(stack_end()), p2i(stack_base()));
3133 st->print("]");
3134
3135 ThreadsSMRSupport::print_info_on(this, st);
3136 return;
3137 }
3138
3139 // Verification
3140
3141 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
3142
3143 void JavaThread::verify() {
3144 // Verify oops in the thread.
3145 oops_do(&VerifyOopClosure::verify_oop, NULL);
3146
3147 // Verify the stack frames.
3148 frames_do(frame_verify);
3149 }
3150
3151 // CR 6300358 (sub-CR 2137150)
3152 // Most callers of this method assume that it can't return NULL but a
3153 // thread may not have a name whilst it is in the process of attaching to
3154 // the VM - see CR 6412693, and there are places where a JavaThread can be
3155 // seen prior to having it's threadObj set (eg JNI attaching threads and
3156 // if vm exit occurs during initialization). These cases can all be accounted
3157 // for such that this method never returns NULL.
3158 const char* JavaThread::get_thread_name() const {
3159 #ifdef ASSERT
3160 // early safepoints can hit while current thread does not yet have TLS
3161 if (!SafepointSynchronize::is_at_safepoint()) {
3162 Thread *cur = Thread::current();
3163 if (!(cur->is_Java_thread() && cur == this)) {
3164 // Current JavaThreads are allowed to get their own name without
3165 // the Threads_lock.
3166 assert_locked_or_safepoint_or_handshake(Threads_lock, this);
3167 }
3168 }
3169 #endif // ASSERT
3170 return get_thread_name_string();
3171 }
3172
3173 // Returns a non-NULL representation of this thread's name, or a suitable
3174 // descriptive string if there is no set name
3175 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
3176 const char* name_str;
3177 oop thread_obj = threadObj();
3178 if (thread_obj != NULL) {
3179 oop name = java_lang_Thread::name(thread_obj);
3180 if (name != NULL) {
3181 if (buf == NULL) {
3182 name_str = java_lang_String::as_utf8_string(name);
3183 } else {
3184 name_str = java_lang_String::as_utf8_string(name, buf, buflen);
3185 }
3186 } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
3187 name_str = "<no-name - thread is attaching>";
3188 } else {
3189 name_str = Thread::name();
3190 }
3191 } else {
3192 name_str = Thread::name();
3193 }
3194 assert(name_str != NULL, "unexpected NULL thread name");
3195 return name_str;
3196 }
3197
3198 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
3199
3200 assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
3201 assert(NoPriority <= prio && prio <= MaxPriority, "sanity check");
3202 // Link Java Thread object <-> C++ Thread
3203
3204 // Get the C++ thread object (an oop) from the JNI handle (a jthread)
3205 // and put it into a new Handle. The Handle "thread_oop" can then
3206 // be used to pass the C++ thread object to other methods.
3207
3208 // Set the Java level thread object (jthread) field of the
3209 // new thread (a JavaThread *) to C++ thread object using the
3210 // "thread_oop" handle.
3211
3212 // Set the thread field (a JavaThread *) of the
3213 // oop representing the java_lang_Thread to the new thread (a JavaThread *).
3214
3215 Handle thread_oop(Thread::current(),
3216 JNIHandles::resolve_non_null(jni_thread));
3217 assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
3218 "must be initialized");
3219 set_threadObj(thread_oop());
3220 java_lang_Thread::set_thread(thread_oop(), this);
3221
3222 if (prio == NoPriority) {
3223 prio = java_lang_Thread::priority(thread_oop());
3224 assert(prio != NoPriority, "A valid priority should be present");
3225 }
3226
3227 // Push the Java priority down to the native thread; needs Threads_lock
3228 Thread::set_priority(this, prio);
3229
3230 // Add the new thread to the Threads list and set it in motion.
3231 // We must have threads lock in order to call Threads::add.
3232 // It is crucial that we do not block before the thread is
3233 // added to the Threads list for if a GC happens, then the java_thread oop
3234 // will not be visited by GC.
3235 Threads::add(this);
3236 }
3237
3238 oop JavaThread::current_park_blocker() {
3239 // Support for JSR-166 locks
3240 oop thread_oop = threadObj();
3241 if (thread_oop != NULL) {
3242 return java_lang_Thread::park_blocker(thread_oop);
3243 }
3244 return NULL;
3245 }
3246
3247
3248 void JavaThread::print_stack_on(outputStream* st) {
3249 if (!has_last_Java_frame()) return;
3250 ResourceMark rm;
3251 HandleMark hm;
3252
3253 RegisterMap reg_map(this);
3254 vframe* start_vf = last_java_vframe(®_map);
3255 int count = 0;
3256 for (vframe* f = start_vf; f != NULL; f = f->sender()) {
3257 if (f->is_java_frame()) {
3258 javaVFrame* jvf = javaVFrame::cast(f);
3259 java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
3260
3261 // Print out lock information
3262 if (JavaMonitorsInStackTrace) {
3263 jvf->print_lock_info_on(st, count);
3264 }
3265 } else {
3266 // Ignore non-Java frames
3267 }
3268
3269 // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0
3270 count++;
3271 if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return;
3272 }
3273 }
3274
3275
3276 // JVMTI PopFrame support
3277 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
3278 assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
3279 if (in_bytes(size_in_bytes) != 0) {
3280 _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
3281 _popframe_preserved_args_size = in_bytes(size_in_bytes);
3282 Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
3283 }
3284 }
3285
3286 void* JavaThread::popframe_preserved_args() {
3287 return _popframe_preserved_args;
3288 }
3289
3290 ByteSize JavaThread::popframe_preserved_args_size() {
3291 return in_ByteSize(_popframe_preserved_args_size);
3292 }
3293
3294 WordSize JavaThread::popframe_preserved_args_size_in_words() {
3295 int sz = in_bytes(popframe_preserved_args_size());
3296 assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
3297 return in_WordSize(sz / wordSize);
3298 }
3299
3300 void JavaThread::popframe_free_preserved_args() {
3301 assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
3302 FREE_C_HEAP_ARRAY(char, (char*)_popframe_preserved_args);
3303 _popframe_preserved_args = NULL;
3304 _popframe_preserved_args_size = 0;
3305 }
3306
3307 #ifndef PRODUCT
3308
3309 void JavaThread::trace_frames() {
3310 tty->print_cr("[Describe stack]");
3311 int frame_no = 1;
3312 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
3313 tty->print(" %d. ", frame_no++);
3314 fst.current()->print_value_on(tty, this);
3315 tty->cr();
3316 }
3317 }
3318
3319 class PrintAndVerifyOopClosure: public OopClosure {
3320 protected:
3321 template <class T> inline void do_oop_work(T* p) {
3322 oop obj = RawAccess<>::oop_load(p);
3323 if (obj == NULL) return;
3324 tty->print(INTPTR_FORMAT ": ", p2i(p));
3325 if (oopDesc::is_oop_or_null(obj)) {
3326 if (obj->is_objArray()) {
3327 tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj));
3328 } else {
3329 obj->print();
3330 }
3331 } else {
3332 tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj));
3333 }
3334 tty->cr();
3335 }
3336 public:
3337 virtual void do_oop(oop* p) { do_oop_work(p); }
3338 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
3339 };
3340
3341 #ifdef ASSERT
3342 // Print or validate the layout of stack frames
3343 void JavaThread::print_frame_layout(int depth, bool validate_only) {
3344 ResourceMark rm;
3345 PRESERVE_EXCEPTION_MARK;
3346 FrameValues values;
3347 int frame_no = 0;
3348 for (StackFrameStream fst(this, false); !fst.is_done(); fst.next()) {
3349 fst.current()->describe(values, ++frame_no);
3350 if (depth == frame_no) break;
3351 }
3352 if (validate_only) {
3353 values.validate();
3354 } else {
3355 tty->print_cr("[Describe stack layout]");
3356 values.print(this);
3357 }
3358 }
3359 #endif
3360
3361 void JavaThread::trace_stack_from(vframe* start_vf) {
3362 ResourceMark rm;
3363 int vframe_no = 1;
3364 for (vframe* f = start_vf; f; f = f->sender()) {
3365 if (f->is_java_frame()) {
3366 javaVFrame::cast(f)->print_activation(vframe_no++);
3367 } else {
3368 f->print();
3369 }
3370 if (vframe_no > StackPrintLimit) {
3371 tty->print_cr("...<more frames>...");
3372 return;
3373 }
3374 }
3375 }
3376
3377
3378 void JavaThread::trace_stack() {
3379 if (!has_last_Java_frame()) return;
3380 ResourceMark rm;
3381 HandleMark hm;
3382 RegisterMap reg_map(this);
3383 trace_stack_from(last_java_vframe(®_map));
3384 }
3385
3386
3387 #endif // PRODUCT
3388
3389
3390 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
3391 assert(reg_map != NULL, "a map must be given");
3392 frame f = last_frame();
3393 for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) {
3394 if (vf->is_java_frame()) return javaVFrame::cast(vf);
3395 }
3396 return NULL;
3397 }
3398
3399
3400 Klass* JavaThread::security_get_caller_class(int depth) {
3401 vframeStream vfst(this);
3402 vfst.security_get_caller_frame(depth);
3403 if (!vfst.at_end()) {
3404 return vfst.method()->method_holder();
3405 }
3406 return NULL;
3407 }
3408
3409 // java.lang.Thread.sleep support
3410 // Returns true if sleep time elapsed as expected, and false
3411 // if the thread was interrupted.
3412 bool JavaThread::sleep(jlong millis) {
3413 assert(this == Thread::current(), "thread consistency check");
3414
3415 ParkEvent * const slp = this->_SleepEvent;
3416 // Because there can be races with thread interruption sending an unpark()
3417 // to the event, we explicitly reset it here to avoid an immediate return.
3418 // The actual interrupt state will be checked before we park().
3419 slp->reset();
3420 // Thread interruption establishes a happens-before ordering in the
3421 // Java Memory Model, so we need to ensure we synchronize with the
3422 // interrupt state.
3423 OrderAccess::fence();
3424
3425 jlong prevtime = os::javaTimeNanos();
3426
3427 for (;;) {
3428 // interruption has precedence over timing out
3429 if (this->is_interrupted(true)) {
3430 return false;
3431 }
3432
3433 if (millis <= 0) {
3434 return true;
3435 }
3436
3437 {
3438 ThreadBlockInVM tbivm(this);
3439 OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
3440
3441 this->set_suspend_equivalent();
3442 // cleared by handle_special_suspend_equivalent_condition() or
3443 // java_suspend_self() via check_and_wait_while_suspended()
3444
3445 slp->park(millis);
3446
3447 // were we externally suspended while we were waiting?
3448 this->check_and_wait_while_suspended();
3449 }
3450
3451 // Update elapsed time tracking
3452 jlong newtime = os::javaTimeNanos();
3453 if (newtime - prevtime < 0) {
3454 // time moving backwards, should only happen if no monotonic clock
3455 // not a guarantee() because JVM should not abort on kernel/glibc bugs
3456 assert(!os::supports_monotonic_clock(),
3457 "unexpected time moving backwards detected in JavaThread::sleep()");
3458 } else {
3459 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
3460 }
3461 prevtime = newtime;
3462 }
3463 }
3464
3465 static void compiler_thread_entry(JavaThread* thread, TRAPS) {
3466 assert(thread->is_Compiler_thread(), "must be compiler thread");
3467 CompileBroker::compiler_thread_loop();
3468 }
3469
3470 static void sweeper_thread_entry(JavaThread* thread, TRAPS) {
3471 NMethodSweeper::sweeper_loop();
3472 }
3473
3474 // Create a CompilerThread
3475 CompilerThread::CompilerThread(CompileQueue* queue,
3476 CompilerCounters* counters)
3477 : JavaThread(&compiler_thread_entry) {
3478 _env = NULL;
3479 _log = NULL;
3480 _task = NULL;
3481 _queue = queue;
3482 _counters = counters;
3483 _buffer_blob = NULL;
3484 _compiler = NULL;
3485
3486 // Compiler uses resource area for compilation, let's bias it to mtCompiler
3487 resource_area()->bias_to(mtCompiler);
3488
3489 #ifndef PRODUCT
3490 _ideal_graph_printer = NULL;
3491 #endif
3492 }
3493
3494 CompilerThread::~CompilerThread() {
3495 // Delete objects which were allocated on heap.
3496 delete _counters;
3497 }
3498
3499 bool CompilerThread::can_call_java() const {
3500 return _compiler != NULL && _compiler->is_jvmci();
3501 }
3502
3503 // Create sweeper thread
3504 CodeCacheSweeperThread::CodeCacheSweeperThread()
3505 : JavaThread(&sweeper_thread_entry) {
3506 _scanned_compiled_method = NULL;
3507 }
3508
3509 void CodeCacheSweeperThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
3510 JavaThread::oops_do(f, cf);
3511 if (_scanned_compiled_method != NULL && cf != NULL) {
3512 // Safepoints can occur when the sweeper is scanning an nmethod so
3513 // process it here to make sure it isn't unloaded in the middle of
3514 // a scan.
3515 cf->do_code_blob(_scanned_compiled_method);
3516 }
3517 }
3518
3519 void CodeCacheSweeperThread::nmethods_do(CodeBlobClosure* cf) {
3520 JavaThread::nmethods_do(cf);
3521 if (_scanned_compiled_method != NULL && cf != NULL) {
3522 // Safepoints can occur when the sweeper is scanning an nmethod so
3523 // process it here to make sure it isn't unloaded in the middle of
3524 // a scan.
3525 cf->do_code_blob(_scanned_compiled_method);
3526 }
3527 }
3528
3529
3530 // ======= Threads ========
3531
3532 // The Threads class links together all active threads, and provides
3533 // operations over all threads. It is protected by the Threads_lock,
3534 // which is also used in other global contexts like safepointing.
3535 // ThreadsListHandles are used to safely perform operations on one
3536 // or more threads without the risk of the thread exiting during the
3537 // operation.
3538 //
3539 // Note: The Threads_lock is currently more widely used than we
3540 // would like. We are actively migrating Threads_lock uses to other
3541 // mechanisms in order to reduce Threads_lock contention.
3542
3543 int Threads::_number_of_threads = 0;
3544 int Threads::_number_of_non_daemon_threads = 0;
3545 int Threads::_return_code = 0;
3546 uintx Threads::_thread_claim_token = 1; // Never zero.
3547 size_t JavaThread::_stack_size_at_create = 0;
3548
3549 #ifdef ASSERT
3550 bool Threads::_vm_complete = false;
3551 #endif
3552
3553 static inline void *prefetch_and_load_ptr(void **addr, intx prefetch_interval) {
3554 Prefetch::read((void*)addr, prefetch_interval);
3555 return *addr;
3556 }
3557
3558 // Possibly the ugliest for loop the world has seen. C++ does not allow
3559 // multiple types in the declaration section of the for loop. In this case
3560 // we are only dealing with pointers and hence can cast them. It looks ugly
3561 // but macros are ugly and therefore it's fine to make things absurdly ugly.
3562 #define DO_JAVA_THREADS(LIST, X) \
3563 for (JavaThread *MACRO_scan_interval = (JavaThread*)(uintptr_t)PrefetchScanIntervalInBytes, \
3564 *MACRO_list = (JavaThread*)(LIST), \
3565 **MACRO_end = ((JavaThread**)((ThreadsList*)MACRO_list)->threads()) + ((ThreadsList*)MACRO_list)->length(), \
3566 **MACRO_current_p = (JavaThread**)((ThreadsList*)MACRO_list)->threads(), \
3567 *X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval); \
3568 MACRO_current_p != MACRO_end; \
3569 MACRO_current_p++, \
3570 X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval))
3571
3572 // All JavaThreads
3573 #define ALL_JAVA_THREADS(X) DO_JAVA_THREADS(ThreadsSMRSupport::get_java_thread_list(), X)
3574
3575 // All NonJavaThreads (i.e., every non-JavaThread in the system).
3576 void Threads::non_java_threads_do(ThreadClosure* tc) {
3577 NoSafepointVerifier nsv;
3578 for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) {
3579 tc->do_thread(njti.current());
3580 }
3581 }
3582
3583 // All JavaThreads
3584 void Threads::java_threads_do(ThreadClosure* tc) {
3585 assert_locked_or_safepoint(Threads_lock);
3586 // ALL_JAVA_THREADS iterates through all JavaThreads.
3587 ALL_JAVA_THREADS(p) {
3588 tc->do_thread(p);
3589 }
3590 }
3591
3592 void Threads::java_threads_and_vm_thread_do(ThreadClosure* tc) {
3593 assert_locked_or_safepoint(Threads_lock);
3594 java_threads_do(tc);
3595 tc->do_thread(VMThread::vm_thread());
3596 }
3597
3598 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system).
3599 void Threads::threads_do(ThreadClosure* tc) {
3600 assert_locked_or_safepoint(Threads_lock);
3601 java_threads_do(tc);
3602 non_java_threads_do(tc);
3603 }
3604
3605 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) {
3606 uintx claim_token = Threads::thread_claim_token();
3607 ALL_JAVA_THREADS(p) {
3608 if (p->claim_threads_do(is_par, claim_token)) {
3609 tc->do_thread(p);
3610 }
3611 }
3612 VMThread* vmt = VMThread::vm_thread();
3613 if (vmt->claim_threads_do(is_par, claim_token)) {
3614 tc->do_thread(vmt);
3615 }
3616 }
3617
3618 // The system initialization in the library has three phases.
3619 //
3620 // Phase 1: java.lang.System class initialization
3621 // java.lang.System is a primordial class loaded and initialized
3622 // by the VM early during startup. java.lang.System.<clinit>
3623 // only does registerNatives and keeps the rest of the class
3624 // initialization work later until thread initialization completes.
3625 //
3626 // System.initPhase1 initializes the system properties, the static
3627 // fields in, out, and err. Set up java signal handlers, OS-specific
3628 // system settings, and thread group of the main thread.
3629 static void call_initPhase1(TRAPS) {
3630 Klass* klass = SystemDictionary::System_klass();
3631 JavaValue result(T_VOID);
3632 JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(),
3633 vmSymbols::void_method_signature(), CHECK);
3634 }
3635
3636 // Phase 2. Module system initialization
3637 // This will initialize the module system. Only java.base classes
3638 // can be loaded until phase 2 completes.
3639 //
3640 // Call System.initPhase2 after the compiler initialization and jsr292
3641 // classes get initialized because module initialization runs a lot of java
3642 // code, that for performance reasons, should be compiled. Also, this will
3643 // enable the startup code to use lambda and other language features in this
3644 // phase and onward.
3645 //
3646 // After phase 2, The VM will begin search classes from -Xbootclasspath/a.
3647 static void call_initPhase2(TRAPS) {
3648 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
3649
3650 Klass* klass = SystemDictionary::System_klass();
3651
3652 JavaValue result(T_INT);
3653 JavaCallArguments args;
3654 args.push_int(DisplayVMOutputToStderr);
3655 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
3656 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
3657 vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
3658 if (result.get_jint() != JNI_OK) {
3659 vm_exit_during_initialization(); // no message or exception
3660 }
3661
3662 universe_post_module_init();
3663 }
3664
3665 // Phase 3. final setup - set security manager, system class loader and TCCL
3666 //
3667 // This will instantiate and set the security manager, set the system class
3668 // loader as well as the thread context class loader. The security manager
3669 // and system class loader may be a custom class loaded from -Xbootclasspath/a,
3670 // other modules or the application's classpath.
3671 static void call_initPhase3(TRAPS) {
3672 Klass* klass = SystemDictionary::System_klass();
3673 JavaValue result(T_VOID);
3674 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
3675 vmSymbols::void_method_signature(), CHECK);
3676 }
3677
3678 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
3679 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
3680
3681 if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
3682 create_vm_init_libraries();
3683 }
3684
3685 initialize_class(vmSymbols::java_lang_String(), CHECK);
3686
3687 // Inject CompactStrings value after the static initializers for String ran.
3688 java_lang_String::set_compact_strings(CompactStrings);
3689
3690 // Initialize java_lang.System (needed before creating the thread)
3691 initialize_class(vmSymbols::java_lang_System(), CHECK);
3692 // The VM creates & returns objects of this class. Make sure it's initialized.
3693 initialize_class(vmSymbols::java_lang_Class(), CHECK);
3694 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
3695 Handle thread_group = create_initial_thread_group(CHECK);
3696 Universe::set_main_thread_group(thread_group());
3697 initialize_class(vmSymbols::java_lang_Thread(), CHECK);
3698 oop thread_object = create_initial_thread(thread_group, main_thread, CHECK);
3699 main_thread->set_threadObj(thread_object);
3700
3701 // Set thread status to running since main thread has
3702 // been started and running.
3703 java_lang_Thread::set_thread_status(thread_object,
3704 java_lang_Thread::RUNNABLE);
3705
3706 // The VM creates objects of this class.
3707 initialize_class(vmSymbols::java_lang_Module(), CHECK);
3708
3709 #ifdef ASSERT
3710 InstanceKlass *k = SystemDictionary::UnsafeConstants_klass();
3711 assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
3712 #endif
3713
3714 // initialize the hardware-specific constants needed by Unsafe
3715 initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
3716 jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
3717
3718 // The VM preresolves methods to these classes. Make sure that they get initialized
3719 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
3720 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
3721
3722 // Phase 1 of the system initialization in the library, java.lang.System class initialization
3723 call_initPhase1(CHECK);
3724
3725 // get the Java runtime name, version, and vendor info after java.lang.System is initialized
3726 JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
3727 JDK_Version::set_runtime_version(get_java_runtime_version(THREAD));
3728 JDK_Version::set_runtime_vendor_version(get_java_runtime_vendor_version(THREAD));
3729 JDK_Version::set_runtime_vendor_vm_bug_url(get_java_runtime_vendor_vm_bug_url(THREAD));
3730
3731 // an instance of OutOfMemory exception has been allocated earlier
3732 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
3733 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
3734 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
3735 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
3736 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
3737 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
3738 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
3739 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
3740
3741 // Eager box cache initialization only if AOT is on and any library is loaded.
3742 AOTLoader::initialize_box_caches(CHECK);
3743 }
3744
3745 void Threads::initialize_jsr292_core_classes(TRAPS) {
3746 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
3747
3748 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
3749 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
3750 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
3751 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
3752 }
3753
3754 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
3755 extern void JDK_Version_init();
3756
3757 // Preinitialize version info.
3758 VM_Version::early_initialize();
3759
3760 // Check version
3761 if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
3762
3763 // Initialize library-based TLS
3764 ThreadLocalStorage::init();
3765
3766 // Initialize the output stream module
3767 ostream_init();
3768
3769 // Process java launcher properties.
3770 Arguments::process_sun_java_launcher_properties(args);
3771
3772 // Initialize the os module
3773 os::init();
3774
3775 // Record VM creation timing statistics
3776 TraceVmCreationTime create_vm_timer;
3777 create_vm_timer.start();
3778
3779 // Initialize system properties.
3780 Arguments::init_system_properties();
3781
3782 // So that JDK version can be used as a discriminator when parsing arguments
3783 JDK_Version_init();
3784
3785 // Update/Initialize System properties after JDK version number is known
3786 Arguments::init_version_specific_system_properties();
3787
3788 // Make sure to initialize log configuration *before* parsing arguments
3789 LogConfiguration::initialize(create_vm_timer.begin_time());
3790
3791 // Parse arguments
3792 // Note: this internally calls os::init_container_support()
3793 jint parse_result = Arguments::parse(args);
3794 if (parse_result != JNI_OK) return parse_result;
3795
3796 os::init_before_ergo();
3797
3798 jint ergo_result = Arguments::apply_ergo();
3799 if (ergo_result != JNI_OK) return ergo_result;
3800
3801 // Final check of all ranges after ergonomics which may change values.
3802 if (!JVMFlagRangeList::check_ranges()) {
3803 return JNI_EINVAL;
3804 }
3805
3806 // Final check of all 'AfterErgo' constraints after ergonomics which may change values.
3807 bool constraint_result = JVMFlagConstraintList::check_constraints(JVMFlagConstraint::AfterErgo);
3808 if (!constraint_result) {
3809 return JNI_EINVAL;
3810 }
3811
3812 if (PauseAtStartup) {
3813 os::pause();
3814 }
3815
3816 HOTSPOT_VM_INIT_BEGIN();
3817
3818 // Timing (must come after argument parsing)
3819 TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime));
3820
3821 // Initialize the os module after parsing the args
3822 jint os_init_2_result = os::init_2();
3823 if (os_init_2_result != JNI_OK) return os_init_2_result;
3824
3825 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
3826 // Initialize assert poison page mechanism.
3827 if (ShowRegistersOnAssert) {
3828 initialize_assert_poison();
3829 }
3830 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
3831
3832 SafepointMechanism::initialize();
3833
3834 jint adjust_after_os_result = Arguments::adjust_after_os();
3835 if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
3836
3837 // Initialize output stream logging
3838 ostream_init_log();
3839
3840 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
3841 // Must be before create_vm_init_agents()
3842 if (Arguments::init_libraries_at_startup()) {
3843 convert_vm_init_libraries_to_agents();
3844 }
3845
3846 // Launch -agentlib/-agentpath and converted -Xrun agents
3847 if (Arguments::init_agents_at_startup()) {
3848 create_vm_init_agents();
3849 }
3850
3851 // Initialize Threads state
3852 _number_of_threads = 0;
3853 _number_of_non_daemon_threads = 0;
3854
3855 // Initialize global data structures and create system classes in heap
3856 vm_init_globals();
3857
3858 #if INCLUDE_JVMCI
3859 if (JVMCICounterSize > 0) {
3860 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
3861 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
3862 } else {
3863 JavaThread::_jvmci_old_thread_counters = NULL;
3864 }
3865 #endif // INCLUDE_JVMCI
3866
3867 // Attach the main thread to this os thread
3868 JavaThread* main_thread = new JavaThread();
3869 main_thread->set_thread_state(_thread_in_vm);
3870 main_thread->initialize_thread_current();
3871 // must do this before set_active_handles
3872 main_thread->record_stack_base_and_size();
3873 main_thread->register_thread_stack_with_NMT();
3874 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
3875
3876 if (!main_thread->set_as_starting_thread()) {
3877 vm_shutdown_during_initialization(
3878 "Failed necessary internal allocation. Out of swap space");
3879 main_thread->smr_delete();
3880 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3881 return JNI_ENOMEM;
3882 }
3883
3884 // Enable guard page *after* os::create_main_thread(), otherwise it would
3885 // crash Linux VM, see notes in os_linux.cpp.
3886 main_thread->create_stack_guard_pages();
3887
3888 // Initialize Java-Level synchronization subsystem
3889 ObjectMonitor::Initialize();
3890
3891 // Initialize global modules
3892 jint status = init_globals();
3893 if (status != JNI_OK) {
3894 main_thread->smr_delete();
3895 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3896 return status;
3897 }
3898
3899 JFR_ONLY(Jfr::on_create_vm_1();)
3900
3901 // Should be done after the heap is fully created
3902 main_thread->cache_global_variables();
3903
3904 HandleMark hm;
3905
3906 { MutexLocker mu(Threads_lock);
3907 Threads::add(main_thread);
3908 }
3909
3910 // Any JVMTI raw monitors entered in onload will transition into
3911 // real raw monitor. VM is setup enough here for raw monitor enter.
3912 JvmtiExport::transition_pending_onload_raw_monitors();
3913
3914 // Create the VMThread
3915 { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime));
3916
3917 VMThread::create();
3918 Thread* vmthread = VMThread::vm_thread();
3919
3920 if (!os::create_thread(vmthread, os::vm_thread)) {
3921 vm_exit_during_initialization("Cannot create VM thread. "
3922 "Out of system resources.");
3923 }
3924
3925 // Wait for the VM thread to become ready, and VMThread::run to initialize
3926 // Monitors can have spurious returns, must always check another state flag
3927 {
3928 MonitorLocker ml(Notify_lock);
3929 os::start_thread(vmthread);
3930 while (vmthread->active_handles() == NULL) {
3931 ml.wait();
3932 }
3933 }
3934 }
3935
3936 assert(Universe::is_fully_initialized(), "not initialized");
3937 if (VerifyDuringStartup) {
3938 // Make sure we're starting with a clean slate.
3939 VM_Verify verify_op;
3940 VMThread::execute(&verify_op);
3941 }
3942
3943 // We need this to update the java.vm.info property in case any flags used
3944 // to initially define it have been changed. This is needed for both CDS and
3945 // AOT, since UseSharedSpaces and UseAOT may be changed after java.vm.info
3946 // is initially computed. See Abstract_VM_Version::vm_info_string().
3947 // This update must happen before we initialize the java classes, but
3948 // after any initialization logic that might modify the flags.
3949 Arguments::update_vm_info_property(VM_Version::vm_info_string());
3950
3951 Thread* THREAD = Thread::current();
3952
3953 // Always call even when there are not JVMTI environments yet, since environments
3954 // may be attached late and JVMTI must track phases of VM execution
3955 JvmtiExport::enter_early_start_phase();
3956
3957 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
3958 JvmtiExport::post_early_vm_start();
3959
3960 initialize_java_lang_classes(main_thread, CHECK_JNI_ERR);
3961
3962 quicken_jni_functions();
3963
3964 // No more stub generation allowed after that point.
3965 StubCodeDesc::freeze();
3966
3967 // Set flag that basic initialization has completed. Used by exceptions and various
3968 // debug stuff, that does not work until all basic classes have been initialized.
3969 set_init_completed();
3970
3971 LogConfiguration::post_initialize();
3972 Metaspace::post_initialize();
3973
3974 HOTSPOT_VM_INIT_END();
3975
3976 // record VM initialization completion time
3977 #if INCLUDE_MANAGEMENT
3978 Management::record_vm_init_completed();
3979 #endif // INCLUDE_MANAGEMENT
3980
3981 // Signal Dispatcher needs to be started before VMInit event is posted
3982 os::initialize_jdk_signal_support(CHECK_JNI_ERR);
3983
3984 // Start Attach Listener if +StartAttachListener or it can't be started lazily
3985 if (!DisableAttachMechanism) {
3986 AttachListener::vm_start();
3987 if (StartAttachListener || AttachListener::init_at_startup()) {
3988 AttachListener::init();
3989 }
3990 }
3991
3992 // Launch -Xrun agents
3993 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3994 // back-end can launch with -Xdebug -Xrunjdwp.
3995 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3996 create_vm_init_libraries();
3997 }
3998
3999 if (CleanChunkPoolAsync) {
4000 Chunk::start_chunk_pool_cleaner_task();
4001 }
4002
4003 // Start the service thread
4004 // The service thread enqueues JVMTI deferred events and does various hashtable
4005 // and other cleanups. Needs to start before the compilers start posting events.
4006 ServiceThread::initialize();
4007
4008 // initialize compiler(s)
4009 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
4010 #if INCLUDE_JVMCI
4011 bool force_JVMCI_intialization = false;
4012 if (EnableJVMCI) {
4013 // Initialize JVMCI eagerly when it is explicitly requested.
4014 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
4015 force_JVMCI_intialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
4016
4017 if (!force_JVMCI_intialization) {
4018 // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking
4019 // compilations via JVMCI will not actually block until JVMCI is initialized.
4020 force_JVMCI_intialization = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation);
4021 }
4022 }
4023 #endif
4024 CompileBroker::compilation_init_phase1(CHECK_JNI_ERR);
4025 // Postpone completion of compiler initialization to after JVMCI
4026 // is initialized to avoid timeouts of blocking compilations.
4027 if (JVMCI_ONLY(!force_JVMCI_intialization) NOT_JVMCI(true)) {
4028 CompileBroker::compilation_init_phase2();
4029 }
4030 #endif
4031
4032 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
4033 // It is done after compilers are initialized, because otherwise compilations of
4034 // signature polymorphic MH intrinsics can be missed
4035 // (see SystemDictionary::find_method_handle_intrinsic).
4036 initialize_jsr292_core_classes(CHECK_JNI_ERR);
4037
4038 // This will initialize the module system. Only java.base classes can be
4039 // loaded until phase 2 completes
4040 call_initPhase2(CHECK_JNI_ERR);
4041
4042 JFR_ONLY(Jfr::on_create_vm_2();)
4043
4044 // Always call even when there are not JVMTI environments yet, since environments
4045 // may be attached late and JVMTI must track phases of VM execution
4046 JvmtiExport::enter_start_phase();
4047
4048 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
4049 JvmtiExport::post_vm_start();
4050
4051 // Final system initialization including security manager and system class loader
4052 call_initPhase3(CHECK_JNI_ERR);
4053
4054 // cache the system and platform class loaders
4055 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
4056
4057 #if INCLUDE_CDS
4058 // capture the module path info from the ModuleEntryTable
4059 ClassLoader::initialize_module_path(THREAD);
4060 #endif
4061
4062 #if INCLUDE_JVMCI
4063 if (force_JVMCI_intialization) {
4064 JVMCI::initialize_compiler(CHECK_JNI_ERR);
4065 CompileBroker::compilation_init_phase2();
4066 }
4067 #endif
4068
4069 // Always call even when there are not JVMTI environments yet, since environments
4070 // may be attached late and JVMTI must track phases of VM execution
4071 JvmtiExport::enter_live_phase();
4072
4073 // Make perfmemory accessible
4074 PerfMemory::set_accessible(true);
4075
4076 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
4077 JvmtiExport::post_vm_initialized();
4078
4079 JFR_ONLY(Jfr::on_create_vm_3();)
4080
4081 #if INCLUDE_MANAGEMENT
4082 Management::initialize(THREAD);
4083
4084 if (HAS_PENDING_EXCEPTION) {
4085 // management agent fails to start possibly due to
4086 // configuration problem and is responsible for printing
4087 // stack trace if appropriate. Simply exit VM.
4088 vm_exit(1);
4089 }
4090 #endif // INCLUDE_MANAGEMENT
4091
4092 if (MemProfiling) MemProfiler::engage();
4093 StatSampler::engage();
4094 if (CheckJNICalls) JniPeriodicChecker::engage();
4095
4096 BiasedLocking::init();
4097
4098 #if INCLUDE_RTM_OPT
4099 RTMLockingCounters::init();
4100 #endif
4101
4102 call_postVMInitHook(THREAD);
4103 // The Java side of PostVMInitHook.run must deal with all
4104 // exceptions and provide means of diagnosis.
4105 if (HAS_PENDING_EXCEPTION) {
4106 CLEAR_PENDING_EXCEPTION;
4107 }
4108
4109 {
4110 MutexLocker ml(PeriodicTask_lock);
4111 // Make sure the WatcherThread can be started by WatcherThread::start()
4112 // or by dynamic enrollment.
4113 WatcherThread::make_startable();
4114 // Start up the WatcherThread if there are any periodic tasks
4115 // NOTE: All PeriodicTasks should be registered by now. If they
4116 // aren't, late joiners might appear to start slowly (we might
4117 // take a while to process their first tick).
4118 if (PeriodicTask::num_tasks() > 0) {
4119 WatcherThread::start();
4120 }
4121 }
4122
4123 create_vm_timer.end();
4124 #ifdef ASSERT
4125 _vm_complete = true;
4126 #endif
4127
4128 if (DumpSharedSpaces) {
4129 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
4130 ShouldNotReachHere();
4131 }
4132
4133 return JNI_OK;
4134 }
4135
4136 // type for the Agent_OnLoad and JVM_OnLoad entry points
4137 extern "C" {
4138 typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
4139 }
4140 // Find a command line agent library and return its entry point for
4141 // -agentlib: -agentpath: -Xrun
4142 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
4143 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent,
4144 const char *on_load_symbols[],
4145 size_t num_symbol_entries) {
4146 OnLoadEntry_t on_load_entry = NULL;
4147 void *library = NULL;
4148
4149 if (!agent->valid()) {
4150 char buffer[JVM_MAXPATHLEN];
4151 char ebuf[1024] = "";
4152 const char *name = agent->name();
4153 const char *msg = "Could not find agent library ";
4154
4155 // First check to see if agent is statically linked into executable
4156 if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) {
4157 library = agent->os_lib();
4158 } else if (agent->is_absolute_path()) {
4159 library = os::dll_load(name, ebuf, sizeof ebuf);
4160 if (library == NULL) {
4161 const char *sub_msg = " in absolute path, with error: ";
4162 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
4163 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
4164 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
4165 // If we can't find the agent, exit.
4166 vm_exit_during_initialization(buf, NULL);
4167 FREE_C_HEAP_ARRAY(char, buf);
4168 }
4169 } else {
4170 // Try to load the agent from the standard dll directory
4171 if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
4172 name)) {
4173 library = os::dll_load(buffer, ebuf, sizeof ebuf);
4174 }
4175 if (library == NULL) { // Try the library path directory.
4176 if (os::dll_build_name(buffer, sizeof(buffer), name)) {
4177 library = os::dll_load(buffer, ebuf, sizeof ebuf);
4178 }
4179 if (library == NULL) {
4180 const char *sub_msg = " on the library path, with error: ";
4181 const char *sub_msg2 = "\nModule java.instrument may be missing from runtime image.";
4182
4183 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) +
4184 strlen(ebuf) + strlen(sub_msg2) + 1;
4185 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
4186 if (!agent->is_instrument_lib()) {
4187 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
4188 } else {
4189 jio_snprintf(buf, len, "%s%s%s%s%s", msg, name, sub_msg, ebuf, sub_msg2);
4190 }
4191 // If we can't find the agent, exit.
4192 vm_exit_during_initialization(buf, NULL);
4193 FREE_C_HEAP_ARRAY(char, buf);
4194 }
4195 }
4196 }
4197 agent->set_os_lib(library);
4198 agent->set_valid();
4199 }
4200
4201 // Find the OnLoad function.
4202 on_load_entry =
4203 CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent,
4204 false,
4205 on_load_symbols,
4206 num_symbol_entries));
4207 return on_load_entry;
4208 }
4209
4210 // Find the JVM_OnLoad entry point
4211 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
4212 const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
4213 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
4214 }
4215
4216 // Find the Agent_OnLoad entry point
4217 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
4218 const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
4219 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
4220 }
4221
4222 // For backwards compatibility with -Xrun
4223 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
4224 // treated like -agentpath:
4225 // Must be called before agent libraries are created
4226 void Threads::convert_vm_init_libraries_to_agents() {
4227 AgentLibrary* agent;
4228 AgentLibrary* next;
4229
4230 for (agent = Arguments::libraries(); agent != NULL; agent = next) {
4231 next = agent->next(); // cache the next agent now as this agent may get moved off this list
4232 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
4233
4234 // If there is an JVM_OnLoad function it will get called later,
4235 // otherwise see if there is an Agent_OnLoad
4236 if (on_load_entry == NULL) {
4237 on_load_entry = lookup_agent_on_load(agent);
4238 if (on_load_entry != NULL) {
4239 // switch it to the agent list -- so that Agent_OnLoad will be called,
4240 // JVM_OnLoad won't be attempted and Agent_OnUnload will
4241 Arguments::convert_library_to_agent(agent);
4242 } else {
4243 vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
4244 }
4245 }
4246 }
4247 }
4248
4249 // Create agents for -agentlib: -agentpath: and converted -Xrun
4250 // Invokes Agent_OnLoad
4251 // Called very early -- before JavaThreads exist
4252 void Threads::create_vm_init_agents() {
4253 extern struct JavaVM_ main_vm;
4254 AgentLibrary* agent;
4255
4256 JvmtiExport::enter_onload_phase();
4257
4258 for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
4259 // CDS dumping does not support native JVMTI agent.
4260 // CDS dumping supports Java agent if the AllowArchivingWithJavaAgent diagnostic option is specified.
4261 if (Arguments::is_dumping_archive()) {
4262 if(!agent->is_instrument_lib()) {
4263 vm_exit_during_cds_dumping("CDS dumping does not support native JVMTI agent, name", agent->name());
4264 } else if (!AllowArchivingWithJavaAgent) {
4265 vm_exit_during_cds_dumping(
4266 "Must enable AllowArchivingWithJavaAgent in order to run Java agent during CDS dumping");
4267 }
4268 }
4269
4270 OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent);
4271
4272 if (on_load_entry != NULL) {
4273 // Invoke the Agent_OnLoad function
4274 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
4275 if (err != JNI_OK) {
4276 vm_exit_during_initialization("agent library failed to init", agent->name());
4277 }
4278 } else {
4279 vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
4280 }
4281 }
4282
4283 JvmtiExport::enter_primordial_phase();
4284 }
4285
4286 extern "C" {
4287 typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
4288 }
4289
4290 void Threads::shutdown_vm_agents() {
4291 // Send any Agent_OnUnload notifications
4292 const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
4293 size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols);
4294 extern struct JavaVM_ main_vm;
4295 for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
4296
4297 // Find the Agent_OnUnload function.
4298 Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
4299 os::find_agent_function(agent,
4300 false,
4301 on_unload_symbols,
4302 num_symbol_entries));
4303
4304 // Invoke the Agent_OnUnload function
4305 if (unload_entry != NULL) {
4306 JavaThread* thread = JavaThread::current();
4307 ThreadToNativeFromVM ttn(thread);
4308 HandleMark hm(thread);
4309 (*unload_entry)(&main_vm);
4310 }
4311 }
4312 }
4313
4314 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
4315 // Invokes JVM_OnLoad
4316 void Threads::create_vm_init_libraries() {
4317 extern struct JavaVM_ main_vm;
4318 AgentLibrary* agent;
4319
4320 for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
4321 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
4322
4323 if (on_load_entry != NULL) {
4324 // Invoke the JVM_OnLoad function
4325 JavaThread* thread = JavaThread::current();
4326 ThreadToNativeFromVM ttn(thread);
4327 HandleMark hm(thread);
4328 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
4329 if (err != JNI_OK) {
4330 vm_exit_during_initialization("-Xrun library failed to init", agent->name());
4331 }
4332 } else {
4333 vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
4334 }
4335 }
4336 }
4337
4338
4339 // Last thread running calls java.lang.Shutdown.shutdown()
4340 void JavaThread::invoke_shutdown_hooks() {
4341 HandleMark hm(this);
4342
4343 // Link all classes for dynamic CDS dumping before vm exit.
4344 // Same operation is being done in JVM_BeforeHalt for handling the
4345 // case where the application calls System.exit().
4346 if (DynamicDumpSharedSpaces) {
4347 MetaspaceShared::link_and_cleanup_shared_classes(this);
4348 }
4349
4350 // We could get here with a pending exception, if so clear it now.
4351 if (this->has_pending_exception()) {
4352 this->clear_pending_exception();
4353 }
4354
4355 EXCEPTION_MARK;
4356 Klass* shutdown_klass =
4357 SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
4358 THREAD);
4359 if (shutdown_klass != NULL) {
4360 // SystemDictionary::resolve_or_null will return null if there was
4361 // an exception. If we cannot load the Shutdown class, just don't
4362 // call Shutdown.shutdown() at all. This will mean the shutdown hooks
4363 // won't be run. Note that if a shutdown hook was registered,
4364 // the Shutdown class would have already been loaded
4365 // (Runtime.addShutdownHook will load it).
4366 JavaValue result(T_VOID);
4367 JavaCalls::call_static(&result,
4368 shutdown_klass,
4369 vmSymbols::shutdown_name(),
4370 vmSymbols::void_method_signature(),
4371 THREAD);
4372 }
4373 CLEAR_PENDING_EXCEPTION;
4374 }
4375
4376 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
4377 // the program falls off the end of main(). Another VM exit path is through
4378 // vm_exit() when the program calls System.exit() to return a value or when
4379 // there is a serious error in VM. The two shutdown paths are not exactly
4380 // the same, but they share Shutdown.shutdown() at Java level and before_exit()
4381 // and VM_Exit op at VM level.
4382 //
4383 // Shutdown sequence:
4384 // + Shutdown native memory tracking if it is on
4385 // + Wait until we are the last non-daemon thread to execute
4386 // <-- every thing is still working at this moment -->
4387 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level
4388 // shutdown hooks
4389 // + Call before_exit(), prepare for VM exit
4390 // > run VM level shutdown hooks (they are registered through JVM_OnExit(),
4391 // currently the only user of this mechanism is File.deleteOnExit())
4392 // > stop StatSampler, watcher thread,
4393 // post thread end and vm death events to JVMTI,
4394 // stop signal thread
4395 // + Call JavaThread::exit(), it will:
4396 // > release JNI handle blocks, remove stack guard pages
4397 // > remove this thread from Threads list
4398 // <-- no more Java code from this thread after this point -->
4399 // + Stop VM thread, it will bring the remaining VM to a safepoint and stop
4400 // the compiler threads at safepoint
4401 // <-- do not use anything that could get blocked by Safepoint -->
4402 // + Disable tracing at JNI/JVM barriers
4403 // + Set _vm_exited flag for threads that are still running native code
4404 // + Call exit_globals()
4405 // > deletes tty
4406 // > deletes PerfMemory resources
4407 // + Delete this thread
4408 // + Return to caller
4409
4410 bool Threads::destroy_vm() {
4411 JavaThread* thread = JavaThread::current();
4412
4413 #ifdef ASSERT
4414 _vm_complete = false;
4415 #endif
4416 // Wait until we are the last non-daemon thread to execute
4417 { MonitorLocker nu(Threads_lock);
4418 while (Threads::number_of_non_daemon_threads() > 1)
4419 // This wait should make safepoint checks, wait without a timeout,
4420 // and wait as a suspend-equivalent condition.
4421 nu.wait(0, Mutex::_as_suspend_equivalent_flag);
4422 }
4423
4424 EventShutdown e;
4425 if (e.should_commit()) {
4426 e.set_reason("No remaining non-daemon Java threads");
4427 e.commit();
4428 }
4429
4430 // Hang forever on exit if we are reporting an error.
4431 if (ShowMessageBoxOnError && VMError::is_error_reported()) {
4432 os::infinite_sleep();
4433 }
4434 os::wait_for_keypress_at_exit();
4435
4436 // run Java level shutdown hooks
4437 thread->invoke_shutdown_hooks();
4438
4439 before_exit(thread);
4440
4441 thread->exit(true);
4442
4443 // We are no longer on the main thread list but could still be in a
4444 // secondary list where another thread may try to interact with us.
4445 // So wait until all such interactions are complete before we bring
4446 // the VM to the termination safepoint. Normally this would be done
4447 // using thread->smr_delete() below where we delete the thread, but
4448 // we can't call that after the termination safepoint is active as
4449 // we will deadlock on the Threads_lock. Once all interactions are
4450 // complete it is safe to directly delete the thread at any time.
4451 ThreadsSMRSupport::wait_until_not_protected(thread);
4452
4453 // Stop VM thread.
4454 {
4455 // 4945125 The vm thread comes to a safepoint during exit.
4456 // GC vm_operations can get caught at the safepoint, and the
4457 // heap is unparseable if they are caught. Grab the Heap_lock
4458 // to prevent this. The GC vm_operations will not be able to
4459 // queue until after the vm thread is dead. After this point,
4460 // we'll never emerge out of the safepoint before the VM exits.
4461
4462 MutexLocker ml(Heap_lock, Mutex::_no_safepoint_check_flag);
4463
4464 VMThread::wait_for_vm_thread_exit();
4465 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
4466 VMThread::destroy();
4467 }
4468
4469 // Now, all Java threads are gone except daemon threads. Daemon threads
4470 // running Java code or in VM are stopped by the Safepoint. However,
4471 // daemon threads executing native code are still running. But they
4472 // will be stopped at native=>Java/VM barriers. Note that we can't
4473 // simply kill or suspend them, as it is inherently deadlock-prone.
4474
4475 VM_Exit::set_vm_exited();
4476
4477 // Clean up ideal graph printers after the VMThread has started
4478 // the final safepoint which will block all the Compiler threads.
4479 // Note that this Thread has already logically exited so the
4480 // clean_up() function's use of a JavaThreadIteratorWithHandle
4481 // would be a problem except set_vm_exited() has remembered the
4482 // shutdown thread which is granted a policy exception.
4483 #if defined(COMPILER2) && !defined(PRODUCT)
4484 IdealGraphPrinter::clean_up();
4485 #endif
4486
4487 notify_vm_shutdown();
4488
4489 // exit_globals() will delete tty
4490 exit_globals();
4491
4492 // Deleting the shutdown thread here is safe. See comment on
4493 // wait_until_not_protected() above.
4494 delete thread;
4495
4496 #if INCLUDE_JVMCI
4497 if (JVMCICounterSize > 0) {
4498 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
4499 }
4500 #endif
4501
4502 LogConfiguration::finalize();
4503
4504 return true;
4505 }
4506
4507
4508 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
4509 if (version == JNI_VERSION_1_1) return JNI_TRUE;
4510 return is_supported_jni_version(version);
4511 }
4512
4513
4514 jboolean Threads::is_supported_jni_version(jint version) {
4515 if (version == JNI_VERSION_1_2) return JNI_TRUE;
4516 if (version == JNI_VERSION_1_4) return JNI_TRUE;
4517 if (version == JNI_VERSION_1_6) return JNI_TRUE;
4518 if (version == JNI_VERSION_1_8) return JNI_TRUE;
4519 if (version == JNI_VERSION_9) return JNI_TRUE;
4520 if (version == JNI_VERSION_10) return JNI_TRUE;
4521 return JNI_FALSE;
4522 }
4523
4524
4525 void Threads::add(JavaThread* p, bool force_daemon) {
4526 // The threads lock must be owned at this point
4527 assert(Threads_lock->owned_by_self(), "must have threads lock");
4528
4529 BarrierSet::barrier_set()->on_thread_attach(p);
4530
4531 // Once a JavaThread is added to the Threads list, smr_delete() has
4532 // to be used to delete it. Otherwise we can just delete it directly.
4533 p->set_on_thread_list();
4534
4535 _number_of_threads++;
4536 oop threadObj = p->threadObj();
4537 bool daemon = true;
4538 // Bootstrapping problem: threadObj can be null for initial
4539 // JavaThread (or for threads attached via JNI)
4540 if ((!force_daemon) && !is_daemon((threadObj))) {
4541 _number_of_non_daemon_threads++;
4542 daemon = false;
4543 }
4544
4545 ThreadService::add_thread(p, daemon);
4546
4547 // Maintain fast thread list
4548 ThreadsSMRSupport::add_thread(p);
4549
4550 // Possible GC point.
4551 Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p));
4552 }
4553
4554 void Threads::remove(JavaThread* p, bool is_daemon) {
4555
4556 // Reclaim the ObjectMonitors from the om_in_use_list and om_free_list of the moribund thread.
4557 ObjectSynchronizer::om_flush(p);
4558
4559 // Extra scope needed for Thread_lock, so we can check
4560 // that we do not remove thread without safepoint code notice
4561 { MonitorLocker ml(Threads_lock);
4562
4563 assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present");
4564
4565 // Maintain fast thread list
4566 ThreadsSMRSupport::remove_thread(p);
4567
4568 _number_of_threads--;
4569 if (!is_daemon) {
4570 _number_of_non_daemon_threads--;
4571
4572 // Only one thread left, do a notify on the Threads_lock so a thread waiting
4573 // on destroy_vm will wake up.
4574 if (number_of_non_daemon_threads() == 1) {
4575 ml.notify_all();
4576 }
4577 }
4578 ThreadService::remove_thread(p, is_daemon);
4579
4580 // Make sure that safepoint code disregard this thread. This is needed since
4581 // the thread might mess around with locks after this point. This can cause it
4582 // to do callbacks into the safepoint code. However, the safepoint code is not aware
4583 // of this thread since it is removed from the queue.
4584 p->set_terminated_value();
4585 } // unlock Threads_lock
4586
4587 // Since Events::log uses a lock, we grab it outside the Threads_lock
4588 Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p));
4589 }
4590
4591 // Operations on the Threads list for GC. These are not explicitly locked,
4592 // but the garbage collector must provide a safe context for them to run.
4593 // In particular, these things should never be called when the Threads_lock
4594 // is held by some other thread. (Note: the Safepoint abstraction also
4595 // uses the Threads_lock to guarantee this property. It also makes sure that
4596 // all threads gets blocked when exiting or starting).
4597
4598 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) {
4599 ALL_JAVA_THREADS(p) {
4600 p->oops_do(f, cf);
4601 }
4602 VMThread::vm_thread()->oops_do(f, cf);
4603 }
4604
4605 void Threads::change_thread_claim_token() {
4606 if (++_thread_claim_token == 0) {
4607 // On overflow of the token counter, there is a risk of future
4608 // collisions between a new global token value and a stale token
4609 // for a thread, because not all iterations visit all threads.
4610 // (Though it's pretty much a theoretical concern for non-trivial
4611 // token counter sizes.) To deal with the possibility, reset all
4612 // the thread tokens to zero on global token overflow.
4613 struct ResetClaims : public ThreadClosure {
4614 virtual void do_thread(Thread* t) {
4615 t->claim_threads_do(false, 0);
4616 }
4617 } reset_claims;
4618 Threads::threads_do(&reset_claims);
4619 // On overflow, update the global token to non-zero, to
4620 // avoid the special "never claimed" initial thread value.
4621 _thread_claim_token = 1;
4622 }
4623 }
4624
4625 #ifdef ASSERT
4626 void assert_thread_claimed(const char* kind, Thread* t, uintx expected) {
4627 const uintx token = t->threads_do_token();
4628 assert(token == expected,
4629 "%s " PTR_FORMAT " has incorrect value " UINTX_FORMAT " != "
4630 UINTX_FORMAT, kind, p2i(t), token, expected);
4631 }
4632
4633 void Threads::assert_all_threads_claimed() {
4634 ALL_JAVA_THREADS(p) {
4635 assert_thread_claimed("Thread", p, _thread_claim_token);
4636 }
4637 assert_thread_claimed("VMThread", VMThread::vm_thread(), _thread_claim_token);
4638 }
4639 #endif // ASSERT
4640
4641 class ParallelOopsDoThreadClosure : public ThreadClosure {
4642 private:
4643 OopClosure* _f;
4644 CodeBlobClosure* _cf;
4645 public:
4646 ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {}
4647 void do_thread(Thread* t) {
4648 t->oops_do(_f, _cf);
4649 }
4650 };
4651
4652 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) {
4653 ParallelOopsDoThreadClosure tc(f, cf);
4654 possibly_parallel_threads_do(is_par, &tc);
4655 }
4656
4657 void Threads::nmethods_do(CodeBlobClosure* cf) {
4658 ALL_JAVA_THREADS(p) {
4659 // This is used by the code cache sweeper to mark nmethods that are active
4660 // on the stack of a Java thread. Ignore the sweeper thread itself to avoid
4661 // marking CodeCacheSweeperThread::_scanned_compiled_method as active.
4662 if(!p->is_Code_cache_sweeper_thread()) {
4663 p->nmethods_do(cf);
4664 }
4665 }
4666 }
4667
4668 void Threads::metadata_do(MetadataClosure* f) {
4669 ALL_JAVA_THREADS(p) {
4670 p->metadata_do(f);
4671 }
4672 }
4673
4674 class ThreadHandlesClosure : public ThreadClosure {
4675 void (*_f)(Metadata*);
4676 public:
4677 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
4678 virtual void do_thread(Thread* thread) {
4679 thread->metadata_handles_do(_f);
4680 }
4681 };
4682
4683 void Threads::metadata_handles_do(void f(Metadata*)) {
4684 // Only walk the Handles in Thread.
4685 ThreadHandlesClosure handles_closure(f);
4686 threads_do(&handles_closure);
4687 }
4688
4689 // Get count Java threads that are waiting to enter the specified monitor.
4690 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list,
4691 int count,
4692 address monitor) {
4693 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
4694
4695 int i = 0;
4696 DO_JAVA_THREADS(t_list, p) {
4697 if (!p->can_call_java()) continue;
4698
4699 // The first stage of async deflation does not affect any field
4700 // used by this comparison so the ObjectMonitor* is usable here.
4701 address pending = (address)p->current_pending_monitor();
4702 if (pending == monitor) { // found a match
4703 if (i < count) result->append(p); // save the first count matches
4704 i++;
4705 }
4706 }
4707
4708 return result;
4709 }
4710
4711
4712 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list,
4713 address owner) {
4714 // NULL owner means not locked so we can skip the search
4715 if (owner == NULL) return NULL;
4716
4717 DO_JAVA_THREADS(t_list, p) {
4718 // first, see if owner is the address of a Java thread
4719 if (owner == (address)p) return p;
4720 }
4721
4722 // Cannot assert on lack of success here since this function may be
4723 // used by code that is trying to report useful problem information
4724 // like deadlock detection.
4725 if (UseHeavyMonitors) return NULL;
4726
4727 // If we didn't find a matching Java thread and we didn't force use of
4728 // heavyweight monitors, then the owner is the stack address of the
4729 // Lock Word in the owning Java thread's stack.
4730 //
4731 JavaThread* the_owner = NULL;
4732 DO_JAVA_THREADS(t_list, q) {
4733 if (q->is_lock_owned(owner)) {
4734 the_owner = q;
4735 break;
4736 }
4737 }
4738
4739 // cannot assert on lack of success here; see above comment
4740 return the_owner;
4741 }
4742
4743 class PrintOnClosure : public ThreadClosure {
4744 private:
4745 outputStream* _st;
4746
4747 public:
4748 PrintOnClosure(outputStream* st) :
4749 _st(st) {}
4750
4751 virtual void do_thread(Thread* thread) {
4752 if (thread != NULL) {
4753 thread->print_on(_st);
4754 _st->cr();
4755 }
4756 }
4757 };
4758
4759 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
4760 void Threads::print_on(outputStream* st, bool print_stacks,
4761 bool internal_format, bool print_concurrent_locks,
4762 bool print_extended_info) {
4763 char buf[32];
4764 st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
4765
4766 st->print_cr("Full thread dump %s (%s %s):",
4767 VM_Version::vm_name(),
4768 VM_Version::vm_release(),
4769 VM_Version::vm_info_string());
4770 st->cr();
4771
4772 #if INCLUDE_SERVICES
4773 // Dump concurrent locks
4774 ConcurrentLocksDump concurrent_locks;
4775 if (print_concurrent_locks) {
4776 concurrent_locks.dump_at_safepoint();
4777 }
4778 #endif // INCLUDE_SERVICES
4779
4780 ThreadsSMRSupport::print_info_on(st);
4781 st->cr();
4782
4783 ALL_JAVA_THREADS(p) {
4784 ResourceMark rm;
4785 p->print_on(st, print_extended_info);
4786 if (print_stacks) {
4787 if (internal_format) {
4788 p->trace_stack();
4789 } else {
4790 p->print_stack_on(st);
4791 }
4792 }
4793 st->cr();
4794 #if INCLUDE_SERVICES
4795 if (print_concurrent_locks) {
4796 concurrent_locks.print_locks_on(p, st);
4797 }
4798 #endif // INCLUDE_SERVICES
4799 }
4800
4801 PrintOnClosure cl(st);
4802 cl.do_thread(VMThread::vm_thread());
4803 Universe::heap()->gc_threads_do(&cl);
4804 cl.do_thread(WatcherThread::watcher_thread());
4805
4806 st->flush();
4807 }
4808
4809 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
4810 int buflen, bool* found_current) {
4811 if (this_thread != NULL) {
4812 bool is_current = (current == this_thread);
4813 *found_current = *found_current || is_current;
4814 st->print("%s", is_current ? "=>" : " ");
4815
4816 st->print(PTR_FORMAT, p2i(this_thread));
4817 st->print(" ");
4818 this_thread->print_on_error(st, buf, buflen);
4819 st->cr();
4820 }
4821 }
4822
4823 class PrintOnErrorClosure : public ThreadClosure {
4824 outputStream* _st;
4825 Thread* _current;
4826 char* _buf;
4827 int _buflen;
4828 bool* _found_current;
4829 public:
4830 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf,
4831 int buflen, bool* found_current) :
4832 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {}
4833
4834 virtual void do_thread(Thread* thread) {
4835 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current);
4836 }
4837 };
4838
4839 // Threads::print_on_error() is called by fatal error handler. It's possible
4840 // that VM is not at safepoint and/or current thread is inside signal handler.
4841 // Don't print stack trace, as the stack may not be walkable. Don't allocate
4842 // memory (even in resource area), it might deadlock the error handler.
4843 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
4844 int buflen) {
4845 ThreadsSMRSupport::print_info_on(st);
4846 st->cr();
4847
4848 bool found_current = false;
4849 st->print_cr("Java Threads: ( => current thread )");
4850 ALL_JAVA_THREADS(thread) {
4851 print_on_error(thread, st, current, buf, buflen, &found_current);
4852 }
4853 st->cr();
4854
4855 st->print_cr("Other Threads:");
4856 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current);
4857 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current);
4858
4859 if (Universe::heap() != NULL) {
4860 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
4861 Universe::heap()->gc_threads_do(&print_closure);
4862 }
4863
4864 if (!found_current) {
4865 st->cr();
4866 st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
4867 current->print_on_error(st, buf, buflen);
4868 st->cr();
4869 }
4870 st->cr();
4871
4872 st->print_cr("Threads with active compile tasks:");
4873 print_threads_compiling(st, buf, buflen);
4874 }
4875
4876 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form) {
4877 ALL_JAVA_THREADS(thread) {
4878 if (thread->is_Compiler_thread()) {
4879 CompilerThread* ct = (CompilerThread*) thread;
4880
4881 // Keep task in local variable for NULL check.
4882 // ct->_task might be set to NULL by concurring compiler thread
4883 // because it completed the compilation. The task is never freed,
4884 // though, just returned to a free list.
4885 CompileTask* task = ct->task();
4886 if (task != NULL) {
4887 thread->print_name_on_error(st, buf, buflen);
4888 st->print(" ");
4889 task->print(st, NULL, short_form, true);
4890 }
4891 }
4892 }
4893 }
4894
4895
4896 // Internal SpinLock and Mutex
4897 // Based on ParkEvent
4898
4899 // Ad-hoc mutual exclusion primitives: SpinLock and Mux
4900 //
4901 // We employ SpinLocks _only for low-contention, fixed-length
4902 // short-duration critical sections where we're concerned
4903 // about native mutex_t or HotSpot Mutex:: latency.
4904 // The mux construct provides a spin-then-block mutual exclusion
4905 // mechanism.
4906 //
4907 // Testing has shown that contention on the ListLock guarding gFreeList
4908 // is common. If we implement ListLock as a simple SpinLock it's common
4909 // for the JVM to devolve to yielding with little progress. This is true
4910 // despite the fact that the critical sections protected by ListLock are
4911 // extremely short.
4912 //
4913 // TODO-FIXME: ListLock should be of type SpinLock.
4914 // We should make this a 1st-class type, integrated into the lock
4915 // hierarchy as leaf-locks. Critically, the SpinLock structure
4916 // should have sufficient padding to avoid false-sharing and excessive
4917 // cache-coherency traffic.
4918
4919
4920 typedef volatile int SpinLockT;
4921
4922 void Thread::SpinAcquire(volatile int * adr, const char * LockName) {
4923 if (Atomic::cmpxchg(adr, 0, 1) == 0) {
4924 return; // normal fast-path return
4925 }
4926
4927 // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
4928 int ctr = 0;
4929 int Yields = 0;
4930 for (;;) {
4931 while (*adr != 0) {
4932 ++ctr;
4933 if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
4934 if (Yields > 5) {
4935 os::naked_short_sleep(1);
4936 } else {
4937 os::naked_yield();
4938 ++Yields;
4939 }
4940 } else {
4941 SpinPause();
4942 }
4943 }
4944 if (Atomic::cmpxchg(adr, 0, 1) == 0) return;
4945 }
4946 }
4947
4948 void Thread::SpinRelease(volatile int * adr) {
4949 assert(*adr != 0, "invariant");
4950 OrderAccess::fence(); // guarantee at least release consistency.
4951 // Roach-motel semantics.
4952 // It's safe if subsequent LDs and STs float "up" into the critical section,
4953 // but prior LDs and STs within the critical section can't be allowed
4954 // to reorder or float past the ST that releases the lock.
4955 // Loads and stores in the critical section - which appear in program
4956 // order before the store that releases the lock - must also appear
4957 // before the store that releases the lock in memory visibility order.
4958 // Conceptually we need a #loadstore|#storestore "release" MEMBAR before
4959 // the ST of 0 into the lock-word which releases the lock, so fence
4960 // more than covers this on all platforms.
4961 *adr = 0;
4962 }
4963
4964 // muxAcquire and muxRelease:
4965 //
4966 // * muxAcquire and muxRelease support a single-word lock-word construct.
4967 // The LSB of the word is set IFF the lock is held.
4968 // The remainder of the word points to the head of a singly-linked list
4969 // of threads blocked on the lock.
4970 //
4971 // * The current implementation of muxAcquire-muxRelease uses its own
4972 // dedicated Thread._MuxEvent instance. If we're interested in
4973 // minimizing the peak number of extant ParkEvent instances then
4974 // we could eliminate _MuxEvent and "borrow" _ParkEvent as long
4975 // as certain invariants were satisfied. Specifically, care would need
4976 // to be taken with regards to consuming unpark() "permits".
4977 // A safe rule of thumb is that a thread would never call muxAcquire()
4978 // if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently
4979 // park(). Otherwise the _ParkEvent park() operation in muxAcquire() could
4980 // consume an unpark() permit intended for monitorenter, for instance.
4981 // One way around this would be to widen the restricted-range semaphore
4982 // implemented in park(). Another alternative would be to provide
4983 // multiple instances of the PlatformEvent() for each thread. One
4984 // instance would be dedicated to muxAcquire-muxRelease, for instance.
4985 //
4986 // * Usage:
4987 // -- Only as leaf locks
4988 // -- for short-term locking only as muxAcquire does not perform
4989 // thread state transitions.
4990 //
4991 // Alternatives:
4992 // * We could implement muxAcquire and muxRelease with MCS or CLH locks
4993 // but with parking or spin-then-park instead of pure spinning.
4994 // * Use Taura-Oyama-Yonenzawa locks.
4995 // * It's possible to construct a 1-0 lock if we encode the lockword as
4996 // (List,LockByte). Acquire will CAS the full lockword while Release
4997 // will STB 0 into the LockByte. The 1-0 scheme admits stranding, so
4998 // acquiring threads use timers (ParkTimed) to detect and recover from
4999 // the stranding window. Thread/Node structures must be aligned on 256-byte
5000 // boundaries by using placement-new.
5001 // * Augment MCS with advisory back-link fields maintained with CAS().
5002 // Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner.
5003 // The validity of the backlinks must be ratified before we trust the value.
5004 // If the backlinks are invalid the exiting thread must back-track through the
5005 // the forward links, which are always trustworthy.
5006 // * Add a successor indication. The LockWord is currently encoded as
5007 // (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable
5008 // to provide the usual futile-wakeup optimization.
5009 // See RTStt for details.
5010 //
5011
5012
5013 const intptr_t LOCKBIT = 1;
5014
5015 void Thread::muxAcquire(volatile intptr_t * Lock, const char * LockName) {
5016 intptr_t w = Atomic::cmpxchg(Lock, (intptr_t)0, LOCKBIT);
5017 if (w == 0) return;
5018 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(Lock, w, w|LOCKBIT) == w) {
5019 return;
5020 }
5021
5022 ParkEvent * const Self = Thread::current()->_MuxEvent;
5023 assert((intptr_t(Self) & LOCKBIT) == 0, "invariant");
5024 for (;;) {
5025 int its = (os::is_MP() ? 100 : 0) + 1;
5026
5027 // Optional spin phase: spin-then-park strategy
5028 while (--its >= 0) {
5029 w = *Lock;
5030 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(Lock, w, w|LOCKBIT) == w) {
5031 return;
5032 }
5033 }
5034
5035 Self->reset();
5036 Self->OnList = intptr_t(Lock);
5037 // The following fence() isn't _strictly necessary as the subsequent
5038 // CAS() both serializes execution and ratifies the fetched *Lock value.
5039 OrderAccess::fence();
5040 for (;;) {
5041 w = *Lock;
5042 if ((w & LOCKBIT) == 0) {
5043 if (Atomic::cmpxchg(Lock, w, w|LOCKBIT) == w) {
5044 Self->OnList = 0; // hygiene - allows stronger asserts
5045 return;
5046 }
5047 continue; // Interference -- *Lock changed -- Just retry
5048 }
5049 assert(w & LOCKBIT, "invariant");
5050 Self->ListNext = (ParkEvent *) (w & ~LOCKBIT);
5051 if (Atomic::cmpxchg(Lock, w, intptr_t(Self)|LOCKBIT) == w) break;
5052 }
5053
5054 while (Self->OnList != 0) {
5055 Self->park();
5056 }
5057 }
5058 }
5059
5060 // Release() must extract a successor from the list and then wake that thread.
5061 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme
5062 // similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based
5063 // Release() would :
5064 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list.
5065 // (B) Extract a successor from the private list "in-hand"
5066 // (C) attempt to CAS() the residual back into *Lock over null.
5067 // If there were any newly arrived threads and the CAS() would fail.
5068 // In that case Release() would detach the RATs, re-merge the list in-hand
5069 // with the RATs and repeat as needed. Alternately, Release() might
5070 // detach and extract a successor, but then pass the residual list to the wakee.
5071 // The wakee would be responsible for reattaching and remerging before it
5072 // competed for the lock.
5073 //
5074 // Both "pop" and DMR are immune from ABA corruption -- there can be
5075 // multiple concurrent pushers, but only one popper or detacher.
5076 // This implementation pops from the head of the list. This is unfair,
5077 // but tends to provide excellent throughput as hot threads remain hot.
5078 // (We wake recently run threads first).
5079 //
5080 // All paths through muxRelease() will execute a CAS.
5081 // Release consistency -- We depend on the CAS in muxRelease() to provide full
5082 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations
5083 // executed within the critical section are complete and globally visible before the
5084 // store (CAS) to the lock-word that releases the lock becomes globally visible.
5085 void Thread::muxRelease(volatile intptr_t * Lock) {
5086 for (;;) {
5087 const intptr_t w = Atomic::cmpxchg(Lock, LOCKBIT, (intptr_t)0);
5088 assert(w & LOCKBIT, "invariant");
5089 if (w == LOCKBIT) return;
5090 ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT);
5091 assert(List != NULL, "invariant");
5092 assert(List->OnList == intptr_t(Lock), "invariant");
5093 ParkEvent * const nxt = List->ListNext;
5094 guarantee((intptr_t(nxt) & LOCKBIT) == 0, "invariant");
5095
5096 // The following CAS() releases the lock and pops the head element.
5097 // The CAS() also ratifies the previously fetched lock-word value.
5098 if (Atomic::cmpxchg(Lock, w, intptr_t(nxt)) != w) {
5099 continue;
5100 }
5101 List->OnList = 0;
5102 OrderAccess::fence();
5103 List->unpark();
5104 return;
5105 }
5106 }
5107
5108
5109 void Threads::verify() {
5110 ALL_JAVA_THREADS(p) {
5111 p->verify();
5112 }
5113 VMThread* thread = VMThread::vm_thread();
5114 if (thread != NULL) thread->verify();
5115 }