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