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