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