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