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