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