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() ||
2475       _stack_guard_state != stack_guard_unused ||
2476       (DisablePrimordialThreadGuardPages && os::is_primordial_thread())) {
2477       log_info(os, thread)("Stack guard page creation for thread "
2478                            UINTX_FORMAT " disabled", os::current_thread_id());
2479     return;
2480   }
2481   address low_addr = stack_end();
2482   size_t len = stack_guard_zone_size();
2483 
2484   assert(is_aligned(low_addr, os::vm_page_size()), "Stack base should be the start of a page");
2485   assert(is_aligned(len, os::vm_page_size()), "Stack size should be a multiple of page size");
2486 
2487   int must_commit = os::must_commit_stack_guard_pages();
2488   // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len);
2489 
2490   if (must_commit && !os::create_stack_guard_pages((char *) low_addr, len)) {
2491     log_warning(os, thread)("Attempt to allocate stack guard pages failed.");
2492     return;
2493   }
2494 
2495   if (os::guard_memory((char *) low_addr, len)) {
2496     _stack_guard_state = stack_guard_enabled;
2497   } else {
2498     log_warning(os, thread)("Attempt to protect stack guard pages failed ("
2499       PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2500     if (os::uncommit_memory((char *) low_addr, len)) {
2501       log_warning(os, thread)("Attempt to deallocate stack guard pages failed.");
2502     }
2503     return;
2504   }
2505 
2506   log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages activated: "
2507     PTR_FORMAT "-" PTR_FORMAT ".",
2508     os::current_thread_id(), p2i(low_addr), p2i(low_addr + len));
2509 }
2510 
2511 void JavaThread::remove_stack_guard_pages() {
2512   assert(Thread::current() == this, "from different thread");
2513   if (_stack_guard_state == stack_guard_unused) return;
2514   address low_addr = stack_end();
2515   size_t len = stack_guard_zone_size();
2516 
2517   if (os::must_commit_stack_guard_pages()) {
2518     if (os::remove_stack_guard_pages((char *) low_addr, len)) {
2519       _stack_guard_state = stack_guard_unused;
2520     } else {
2521       log_warning(os, thread)("Attempt to deallocate stack guard pages failed ("
2522         PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2523       return;
2524     }
2525   } else {
2526     if (_stack_guard_state == stack_guard_unused) return;
2527     if (os::unguard_memory((char *) low_addr, len)) {
2528       _stack_guard_state = stack_guard_unused;
2529     } else {
2530       log_warning(os, thread)("Attempt to unprotect stack guard pages failed ("
2531         PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2532       return;
2533     }
2534   }
2535 
2536   log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages removed: "
2537     PTR_FORMAT "-" PTR_FORMAT ".",
2538     os::current_thread_id(), p2i(low_addr), p2i(low_addr + len));
2539 }
2540 
2541 void JavaThread::enable_stack_reserved_zone() {
2542   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2543   assert(_stack_guard_state != stack_guard_enabled, "already enabled");
2544 
2545   // The base notation is from the stack's point of view, growing downward.
2546   // We need to adjust it to work correctly with guard_memory()
2547   address base = stack_reserved_zone_base() - stack_reserved_zone_size();
2548 
2549   guarantee(base < stack_base(),"Error calculating stack reserved zone");
2550   guarantee(base < os::current_stack_pointer(),"Error calculating stack reserved zone");
2551 
2552   if (os::guard_memory((char *) base, stack_reserved_zone_size())) {
2553     _stack_guard_state = stack_guard_enabled;
2554   } else {
2555     warning("Attempt to guard stack reserved zone failed.");
2556   }
2557   enable_register_stack_guard();
2558 }
2559 
2560 void JavaThread::disable_stack_reserved_zone() {
2561   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2562   assert(_stack_guard_state != stack_guard_reserved_disabled, "already disabled");
2563 
2564   // Simply return if called for a thread that does not use guard pages.
2565   if (_stack_guard_state == stack_guard_unused) return;
2566 
2567   // The base notation is from the stack's point of view, growing downward.
2568   // We need to adjust it to work correctly with guard_memory()
2569   address base = stack_reserved_zone_base() - stack_reserved_zone_size();
2570 
2571   if (os::unguard_memory((char *)base, stack_reserved_zone_size())) {
2572     _stack_guard_state = stack_guard_reserved_disabled;
2573   } else {
2574     warning("Attempt to unguard stack reserved zone failed.");
2575   }
2576   disable_register_stack_guard();
2577 }
2578 
2579 void JavaThread::enable_stack_yellow_reserved_zone() {
2580   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2581   assert(_stack_guard_state != stack_guard_enabled, "already enabled");
2582 
2583   // The base notation is from the stacks point of view, growing downward.
2584   // We need to adjust it to work correctly with guard_memory()
2585   address base = stack_red_zone_base();
2586 
2587   guarantee(base < stack_base(), "Error calculating stack yellow zone");
2588   guarantee(base < os::current_stack_pointer(), "Error calculating stack yellow zone");
2589 
2590   if (os::guard_memory((char *) base, stack_yellow_reserved_zone_size())) {
2591     _stack_guard_state = stack_guard_enabled;
2592   } else {
2593     warning("Attempt to guard stack yellow zone failed.");
2594   }
2595   enable_register_stack_guard();
2596 }
2597 
2598 void JavaThread::disable_stack_yellow_reserved_zone() {
2599   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2600   assert(_stack_guard_state != stack_guard_yellow_reserved_disabled, "already disabled");
2601 
2602   // Simply return if called for a thread that does not use guard pages.
2603   if (_stack_guard_state == stack_guard_unused) return;
2604 
2605   // The base notation is from the stacks point of view, growing downward.
2606   // We need to adjust it to work correctly with guard_memory()
2607   address base = stack_red_zone_base();
2608 
2609   if (os::unguard_memory((char *)base, stack_yellow_reserved_zone_size())) {
2610     _stack_guard_state = stack_guard_yellow_reserved_disabled;
2611   } else {
2612     warning("Attempt to unguard stack yellow zone failed.");
2613   }
2614   disable_register_stack_guard();
2615 }
2616 
2617 void JavaThread::enable_stack_red_zone() {
2618   // The base notation is from the stacks point of view, growing downward.
2619   // We need to adjust it to work correctly with guard_memory()
2620   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2621   address base = stack_red_zone_base() - stack_red_zone_size();
2622 
2623   guarantee(base < stack_base(), "Error calculating stack red zone");
2624   guarantee(base < os::current_stack_pointer(), "Error calculating stack red zone");
2625 
2626   if (!os::guard_memory((char *) base, stack_red_zone_size())) {
2627     warning("Attempt to guard stack red zone failed.");
2628   }
2629 }
2630 
2631 void JavaThread::disable_stack_red_zone() {
2632   // The base notation is from the stacks point of view, growing downward.
2633   // We need to adjust it to work correctly with guard_memory()
2634   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2635   address base = stack_red_zone_base() - stack_red_zone_size();
2636   if (!os::unguard_memory((char *)base, stack_red_zone_size())) {
2637     warning("Attempt to unguard stack red zone failed.");
2638   }
2639 }
2640 
2641 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
2642   // ignore is there is no stack
2643   if (!has_last_Java_frame()) return;
2644   // traverse the stack frames. Starts from top frame.
2645   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2646     frame* fr = fst.current();
2647     f(fr, fst.register_map());
2648   }
2649 }
2650 
2651 
2652 #ifndef PRODUCT
2653 // Deoptimization
2654 // Function for testing deoptimization
2655 void JavaThread::deoptimize() {
2656   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2657   StackFrameStream fst(this, UseBiasedLocking);
2658   bool deopt = false;           // Dump stack only if a deopt actually happens.
2659   bool only_at = strlen(DeoptimizeOnlyAt) > 0;
2660   // Iterate over all frames in the thread and deoptimize
2661   for (; !fst.is_done(); fst.next()) {
2662     if (fst.current()->can_be_deoptimized()) {
2663 
2664       if (only_at) {
2665         // Deoptimize only at particular bcis.  DeoptimizeOnlyAt
2666         // consists of comma or carriage return separated numbers so
2667         // search for the current bci in that string.
2668         address pc = fst.current()->pc();
2669         nmethod* nm =  (nmethod*) fst.current()->cb();
2670         ScopeDesc* sd = nm->scope_desc_at(pc);
2671         char buffer[8];
2672         jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
2673         size_t len = strlen(buffer);
2674         const char * found = strstr(DeoptimizeOnlyAt, buffer);
2675         while (found != NULL) {
2676           if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
2677               (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
2678             // Check that the bci found is bracketed by terminators.
2679             break;
2680           }
2681           found = strstr(found + 1, buffer);
2682         }
2683         if (!found) {
2684           continue;
2685         }
2686       }
2687 
2688       if (DebugDeoptimization && !deopt) {
2689         deopt = true; // One-time only print before deopt
2690         tty->print_cr("[BEFORE Deoptimization]");
2691         trace_frames();
2692         trace_stack();
2693       }
2694       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2695     }
2696   }
2697 
2698   if (DebugDeoptimization && deopt) {
2699     tty->print_cr("[AFTER Deoptimization]");
2700     trace_frames();
2701   }
2702 }
2703 
2704 
2705 // Make zombies
2706 void JavaThread::make_zombies() {
2707   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2708     if (fst.current()->can_be_deoptimized()) {
2709       // it is a Java nmethod
2710       nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
2711       nm->make_not_entrant();
2712     }
2713   }
2714 }
2715 #endif // PRODUCT
2716 
2717 
2718 void JavaThread::deoptimized_wrt_marked_nmethods() {
2719   if (!has_last_Java_frame()) return;
2720   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2721   StackFrameStream fst(this, UseBiasedLocking);
2722   for (; !fst.is_done(); fst.next()) {
2723     if (fst.current()->should_be_deoptimized()) {
2724       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2725     }
2726   }
2727 }
2728 
2729 
2730 // If the caller is a NamedThread, then remember, in the current scope,
2731 // the given JavaThread in its _processed_thread field.
2732 class RememberProcessedThread: public StackObj {
2733   NamedThread* _cur_thr;
2734  public:
2735   RememberProcessedThread(JavaThread* jthr) {
2736     Thread* thread = Thread::current();
2737     if (thread->is_Named_thread()) {
2738       _cur_thr = (NamedThread *)thread;
2739       _cur_thr->set_processed_thread(jthr);
2740     } else {
2741       _cur_thr = NULL;
2742     }
2743   }
2744 
2745   ~RememberProcessedThread() {
2746     if (_cur_thr) {
2747       _cur_thr->set_processed_thread(NULL);
2748     }
2749   }
2750 };
2751 
2752 void JavaThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
2753   // Verify that the deferred card marks have been flushed.
2754   assert(deferred_card_mark().is_empty(), "Should be empty during GC");
2755 
2756   // Traverse the GCHandles
2757   Thread::oops_do(f, cf);
2758 
2759   JVMCI_ONLY(f->do_oop((oop*)&_pending_failed_speculation);)
2760 
2761   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2762          (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2763 
2764   if (has_last_Java_frame()) {
2765     // Record JavaThread to GC thread
2766     RememberProcessedThread rpt(this);
2767 
2768     // Traverse the privileged stack
2769     if (_privileged_stack_top != NULL) {
2770       _privileged_stack_top->oops_do(f);
2771     }
2772 
2773     // traverse the registered growable array
2774     if (_array_for_gc != NULL) {
2775       for (int index = 0; index < _array_for_gc->length(); index++) {
2776         f->do_oop(_array_for_gc->adr_at(index));
2777       }
2778     }
2779 
2780     // Traverse the monitor chunks
2781     for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2782       chunk->oops_do(f);
2783     }
2784 
2785     // Traverse the execution stack
2786     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2787       fst.current()->oops_do(f, cf, fst.register_map());
2788     }
2789   }
2790 
2791   // callee_target is never live across a gc point so NULL it here should
2792   // it still contain a methdOop.
2793 
2794   set_callee_target(NULL);
2795 
2796   assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
2797   // If we have deferred set_locals there might be oops waiting to be
2798   // written
2799   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals();
2800   if (list != NULL) {
2801     for (int i = 0; i < list->length(); i++) {
2802       list->at(i)->oops_do(f);
2803     }
2804   }
2805 
2806   // Traverse instance variables at the end since the GC may be moving things
2807   // around using this function
2808   f->do_oop((oop*) &_threadObj);
2809   f->do_oop((oop*) &_vm_result);
2810   f->do_oop((oop*) &_exception_oop);
2811   f->do_oop((oop*) &_pending_async_exception);
2812 
2813   if (jvmti_thread_state() != NULL) {
2814     jvmti_thread_state()->oops_do(f);
2815   }
2816 }
2817 
2818 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
2819   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2820          (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2821 
2822   if (has_last_Java_frame()) {
2823     // Traverse the execution stack
2824     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2825       fst.current()->nmethods_do(cf);
2826     }
2827   }
2828 }
2829 
2830 void JavaThread::metadata_do(void f(Metadata*)) {
2831   if (has_last_Java_frame()) {
2832     // Traverse the execution stack to call f() on the methods in the stack
2833     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2834       fst.current()->metadata_do(f);
2835     }
2836   } else if (is_Compiler_thread()) {
2837     // need to walk ciMetadata in current compile tasks to keep alive.
2838     CompilerThread* ct = (CompilerThread*)this;
2839     if (ct->env() != NULL) {
2840       ct->env()->metadata_do(f);
2841     }
2842     if (ct->task() != NULL) {
2843       ct->task()->metadata_do(f);
2844     }
2845   }
2846 }
2847 
2848 // Printing
2849 const char* _get_thread_state_name(JavaThreadState _thread_state) {
2850   switch (_thread_state) {
2851   case _thread_uninitialized:     return "_thread_uninitialized";
2852   case _thread_new:               return "_thread_new";
2853   case _thread_new_trans:         return "_thread_new_trans";
2854   case _thread_in_native:         return "_thread_in_native";
2855   case _thread_in_native_trans:   return "_thread_in_native_trans";
2856   case _thread_in_vm:             return "_thread_in_vm";
2857   case _thread_in_vm_trans:       return "_thread_in_vm_trans";
2858   case _thread_in_Java:           return "_thread_in_Java";
2859   case _thread_in_Java_trans:     return "_thread_in_Java_trans";
2860   case _thread_blocked:           return "_thread_blocked";
2861   case _thread_blocked_trans:     return "_thread_blocked_trans";
2862   default:                        return "unknown thread state";
2863   }
2864 }
2865 
2866 #ifndef PRODUCT
2867 void JavaThread::print_thread_state_on(outputStream *st) const {
2868   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
2869 };
2870 void JavaThread::print_thread_state() const {
2871   print_thread_state_on(tty);
2872 }
2873 #endif // PRODUCT
2874 
2875 // Called by Threads::print() for VM_PrintThreads operation
2876 void JavaThread::print_on(outputStream *st) const {
2877   st->print_raw("\"");
2878   st->print_raw(get_thread_name());
2879   st->print_raw("\" ");
2880   oop thread_oop = threadObj();
2881   if (thread_oop != NULL) {
2882     st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop));
2883     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
2884     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
2885   }
2886   Thread::print_on(st);
2887   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
2888   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
2889   if (thread_oop != NULL) {
2890     st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
2891   }
2892 #ifndef PRODUCT
2893   print_thread_state_on(st);
2894   _safepoint_state->print_on(st);
2895 #endif // PRODUCT
2896   if (is_Compiler_thread()) {
2897     CompilerThread* ct = (CompilerThread*)this;
2898     if (ct->task() != NULL) {
2899       st->print("   Compiling: ");
2900       ct->task()->print(st, NULL, true, false);
2901     } else {
2902       st->print("   No compile task");
2903     }
2904     st->cr();
2905   }
2906 }
2907 
2908 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
2909   st->print("%s", get_thread_name_string(buf, buflen));
2910 }
2911 
2912 // Called by fatal error handler. The difference between this and
2913 // JavaThread::print() is that we can't grab lock or allocate memory.
2914 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
2915   st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
2916   oop thread_obj = threadObj();
2917   if (thread_obj != NULL) {
2918     if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
2919   }
2920   st->print(" [");
2921   st->print("%s", _get_thread_state_name(_thread_state));
2922   if (osthread()) {
2923     st->print(", id=%d", osthread()->thread_id());
2924   }
2925   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
2926             p2i(stack_end()), p2i(stack_base()));
2927   st->print("]");
2928   return;
2929 }
2930 
2931 // Verification
2932 
2933 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
2934 
2935 void JavaThread::verify() {
2936   // Verify oops in the thread.
2937   oops_do(&VerifyOopClosure::verify_oop, NULL);
2938 
2939   // Verify the stack frames.
2940   frames_do(frame_verify);
2941 }
2942 
2943 // CR 6300358 (sub-CR 2137150)
2944 // Most callers of this method assume that it can't return NULL but a
2945 // thread may not have a name whilst it is in the process of attaching to
2946 // the VM - see CR 6412693, and there are places where a JavaThread can be
2947 // seen prior to having it's threadObj set (eg JNI attaching threads and
2948 // if vm exit occurs during initialization). These cases can all be accounted
2949 // for such that this method never returns NULL.
2950 const char* JavaThread::get_thread_name() const {
2951 #ifdef ASSERT
2952   // early safepoints can hit while current thread does not yet have TLS
2953   if (!SafepointSynchronize::is_at_safepoint()) {
2954     Thread *cur = Thread::current();
2955     if (!(cur->is_Java_thread() && cur == this)) {
2956       // Current JavaThreads are allowed to get their own name without
2957       // the Threads_lock.
2958       assert_locked_or_safepoint(Threads_lock);
2959     }
2960   }
2961 #endif // ASSERT
2962   return get_thread_name_string();
2963 }
2964 
2965 // Returns a non-NULL representation of this thread's name, or a suitable
2966 // descriptive string if there is no set name
2967 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
2968   const char* name_str;
2969   oop thread_obj = threadObj();
2970   if (thread_obj != NULL) {
2971     oop name = java_lang_Thread::name(thread_obj);
2972     if (name != NULL) {
2973       if (buf == NULL) {
2974         name_str = java_lang_String::as_utf8_string(name);
2975       } else {
2976         name_str = java_lang_String::as_utf8_string(name, buf, buflen);
2977       }
2978     } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
2979       name_str = "<no-name - thread is attaching>";
2980     } else {
2981       name_str = Thread::name();
2982     }
2983   } else {
2984     name_str = Thread::name();
2985   }
2986   assert(name_str != NULL, "unexpected NULL thread name");
2987   return name_str;
2988 }
2989 
2990 
2991 const char* JavaThread::get_threadgroup_name() const {
2992   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
2993   oop thread_obj = threadObj();
2994   if (thread_obj != NULL) {
2995     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
2996     if (thread_group != NULL) {
2997       // ThreadGroup.name can be null
2998       return java_lang_ThreadGroup::name(thread_group);
2999     }
3000   }
3001   return NULL;
3002 }
3003 
3004 const char* JavaThread::get_parent_name() const {
3005   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
3006   oop thread_obj = threadObj();
3007   if (thread_obj != NULL) {
3008     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
3009     if (thread_group != NULL) {
3010       oop parent = java_lang_ThreadGroup::parent(thread_group);
3011       if (parent != NULL) {
3012         // ThreadGroup.name can be null
3013         return java_lang_ThreadGroup::name(parent);
3014       }
3015     }
3016   }
3017   return NULL;
3018 }
3019 
3020 ThreadPriority JavaThread::java_priority() const {
3021   oop thr_oop = threadObj();
3022   if (thr_oop == NULL) return NormPriority; // Bootstrapping
3023   ThreadPriority priority = java_lang_Thread::priority(thr_oop);
3024   assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
3025   return priority;
3026 }
3027 
3028 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
3029 
3030   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
3031   // Link Java Thread object <-> C++ Thread
3032 
3033   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
3034   // and put it into a new Handle.  The Handle "thread_oop" can then
3035   // be used to pass the C++ thread object to other methods.
3036 
3037   // Set the Java level thread object (jthread) field of the
3038   // new thread (a JavaThread *) to C++ thread object using the
3039   // "thread_oop" handle.
3040 
3041   // Set the thread field (a JavaThread *) of the
3042   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
3043 
3044   Handle thread_oop(Thread::current(),
3045                     JNIHandles::resolve_non_null(jni_thread));
3046   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
3047          "must be initialized");
3048   set_threadObj(thread_oop());
3049   java_lang_Thread::set_thread(thread_oop(), this);
3050 
3051   if (prio == NoPriority) {
3052     prio = java_lang_Thread::priority(thread_oop());
3053     assert(prio != NoPriority, "A valid priority should be present");
3054   }
3055 
3056   // Push the Java priority down to the native thread; needs Threads_lock
3057   Thread::set_priority(this, prio);
3058 
3059   prepare_ext();
3060 
3061   // Add the new thread to the Threads list and set it in motion.
3062   // We must have threads lock in order to call Threads::add.
3063   // It is crucial that we do not block before the thread is
3064   // added to the Threads list for if a GC happens, then the java_thread oop
3065   // will not be visited by GC.
3066   Threads::add(this);
3067 }
3068 
3069 oop JavaThread::current_park_blocker() {
3070   // Support for JSR-166 locks
3071   oop thread_oop = threadObj();
3072   if (thread_oop != NULL &&
3073       JDK_Version::current().supports_thread_park_blocker()) {
3074     return java_lang_Thread::park_blocker(thread_oop);
3075   }
3076   return NULL;
3077 }
3078 
3079 
3080 void JavaThread::print_stack_on(outputStream* st) {
3081   if (!has_last_Java_frame()) return;
3082   ResourceMark rm;
3083   HandleMark   hm;
3084 
3085   RegisterMap reg_map(this);
3086   vframe* start_vf = last_java_vframe(&reg_map);
3087   int count = 0;
3088   for (vframe* f = start_vf; f; f = f->sender()) {
3089     if (f->is_java_frame()) {
3090       javaVFrame* jvf = javaVFrame::cast(f);
3091       java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
3092 
3093       // Print out lock information
3094       if (JavaMonitorsInStackTrace) {
3095         jvf->print_lock_info_on(st, count);
3096       }
3097     } else {
3098       // Ignore non-Java frames
3099     }
3100 
3101     // Bail-out case for too deep stacks
3102     count++;
3103     if (MaxJavaStackTraceDepth == count) return;
3104   }
3105 }
3106 
3107 
3108 // JVMTI PopFrame support
3109 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
3110   assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
3111   if (in_bytes(size_in_bytes) != 0) {
3112     _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
3113     _popframe_preserved_args_size = in_bytes(size_in_bytes);
3114     Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
3115   }
3116 }
3117 
3118 void* JavaThread::popframe_preserved_args() {
3119   return _popframe_preserved_args;
3120 }
3121 
3122 ByteSize JavaThread::popframe_preserved_args_size() {
3123   return in_ByteSize(_popframe_preserved_args_size);
3124 }
3125 
3126 WordSize JavaThread::popframe_preserved_args_size_in_words() {
3127   int sz = in_bytes(popframe_preserved_args_size());
3128   assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
3129   return in_WordSize(sz / wordSize);
3130 }
3131 
3132 void JavaThread::popframe_free_preserved_args() {
3133   assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
3134   FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args);
3135   _popframe_preserved_args = NULL;
3136   _popframe_preserved_args_size = 0;
3137 }
3138 
3139 #ifndef PRODUCT
3140 
3141 void JavaThread::trace_frames() {
3142   tty->print_cr("[Describe stack]");
3143   int frame_no = 1;
3144   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
3145     tty->print("  %d. ", frame_no++);
3146     fst.current()->print_value_on(tty, this);
3147     tty->cr();
3148   }
3149 }
3150 
3151 class PrintAndVerifyOopClosure: public OopClosure {
3152  protected:
3153   template <class T> inline void do_oop_work(T* p) {
3154     oop obj = oopDesc::load_decode_heap_oop(p);
3155     if (obj == NULL) return;
3156     tty->print(INTPTR_FORMAT ": ", p2i(p));
3157     if (oopDesc::is_oop_or_null(obj)) {
3158       if (obj->is_objArray()) {
3159         tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj));
3160       } else {
3161         obj->print();
3162       }
3163     } else {
3164       tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj));
3165     }
3166     tty->cr();
3167   }
3168  public:
3169   virtual void do_oop(oop* p) { do_oop_work(p); }
3170   virtual void do_oop(narrowOop* p)  { do_oop_work(p); }
3171 };
3172 
3173 
3174 static void oops_print(frame* f, const RegisterMap *map) {
3175   PrintAndVerifyOopClosure print;
3176   f->print_value();
3177   f->oops_do(&print, NULL, (RegisterMap*)map);
3178 }
3179 
3180 // Print our all the locations that contain oops and whether they are
3181 // valid or not.  This useful when trying to find the oldest frame
3182 // where an oop has gone bad since the frame walk is from youngest to
3183 // oldest.
3184 void JavaThread::trace_oops() {
3185   tty->print_cr("[Trace oops]");
3186   frames_do(oops_print);
3187 }
3188 
3189 
3190 #ifdef ASSERT
3191 // Print or validate the layout of stack frames
3192 void JavaThread::print_frame_layout(int depth, bool validate_only) {
3193   ResourceMark rm;
3194   PRESERVE_EXCEPTION_MARK;
3195   FrameValues values;
3196   int frame_no = 0;
3197   for (StackFrameStream fst(this, false); !fst.is_done(); fst.next()) {
3198     fst.current()->describe(values, ++frame_no);
3199     if (depth == frame_no) break;
3200   }
3201   if (validate_only) {
3202     values.validate();
3203   } else {
3204     tty->print_cr("[Describe stack layout]");
3205     values.print(this);
3206   }
3207 }
3208 #endif
3209 
3210 void JavaThread::trace_stack_from(vframe* start_vf) {
3211   ResourceMark rm;
3212   int vframe_no = 1;
3213   for (vframe* f = start_vf; f; f = f->sender()) {
3214     if (f->is_java_frame()) {
3215       javaVFrame::cast(f)->print_activation(vframe_no++);
3216     } else {
3217       f->print();
3218     }
3219     if (vframe_no > StackPrintLimit) {
3220       tty->print_cr("...<more frames>...");
3221       return;
3222     }
3223   }
3224 }
3225 
3226 
3227 void JavaThread::trace_stack() {
3228   if (!has_last_Java_frame()) return;
3229   ResourceMark rm;
3230   HandleMark   hm;
3231   RegisterMap reg_map(this);
3232   trace_stack_from(last_java_vframe(&reg_map));
3233 }
3234 
3235 
3236 #endif // PRODUCT
3237 
3238 
3239 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
3240   assert(reg_map != NULL, "a map must be given");
3241   frame f = last_frame();
3242   for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) {
3243     if (vf->is_java_frame()) return javaVFrame::cast(vf);
3244   }
3245   return NULL;
3246 }
3247 
3248 
3249 Klass* JavaThread::security_get_caller_class(int depth) {
3250   vframeStream vfst(this);
3251   vfst.security_get_caller_frame(depth);
3252   if (!vfst.at_end()) {
3253     return vfst.method()->method_holder();
3254   }
3255   return NULL;
3256 }
3257 
3258 static void compiler_thread_entry(JavaThread* thread, TRAPS) {
3259   assert(thread->is_Compiler_thread(), "must be compiler thread");
3260   CompileBroker::compiler_thread_loop();
3261 }
3262 
3263 static void sweeper_thread_entry(JavaThread* thread, TRAPS) {
3264   NMethodSweeper::sweeper_loop();
3265 }
3266 
3267 // Create a CompilerThread
3268 CompilerThread::CompilerThread(CompileQueue* queue,
3269                                CompilerCounters* counters)
3270                                : JavaThread(&compiler_thread_entry) {
3271   _env   = NULL;
3272   _log   = NULL;
3273   _task  = NULL;
3274   _queue = queue;
3275   _counters = counters;
3276   _buffer_blob = NULL;
3277   _compiler = NULL;
3278 
3279   // Compiler uses resource area for compilation, let's bias it to mtCompiler
3280   resource_area()->bias_to(mtCompiler);
3281 
3282 #ifndef PRODUCT
3283   _ideal_graph_printer = NULL;
3284 #endif
3285 }
3286 
3287 bool CompilerThread::can_call_java() const {
3288   return _compiler != NULL && _compiler->is_jvmci();
3289 }
3290 
3291 // Create sweeper thread
3292 CodeCacheSweeperThread::CodeCacheSweeperThread()
3293 : JavaThread(&sweeper_thread_entry) {
3294   _scanned_compiled_method = NULL;
3295 }
3296 
3297 void CodeCacheSweeperThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
3298   JavaThread::oops_do(f, cf);
3299   if (_scanned_compiled_method != NULL && cf != NULL) {
3300     // Safepoints can occur when the sweeper is scanning an nmethod so
3301     // process it here to make sure it isn't unloaded in the middle of
3302     // a scan.
3303     cf->do_code_blob(_scanned_compiled_method);
3304   }
3305 }
3306 
3307 void CodeCacheSweeperThread::nmethods_do(CodeBlobClosure* cf) {
3308   JavaThread::nmethods_do(cf);
3309   if (_scanned_compiled_method != NULL && cf != NULL) {
3310     // Safepoints can occur when the sweeper is scanning an nmethod so
3311     // process it here to make sure it isn't unloaded in the middle of
3312     // a scan.
3313     cf->do_code_blob(_scanned_compiled_method);
3314   }
3315 }
3316 
3317 
3318 // ======= Threads ========
3319 
3320 // The Threads class links together all active threads, and provides
3321 // operations over all threads.  It is protected by its own Mutex
3322 // lock, which is also used in other contexts to protect thread
3323 // operations from having the thread being operated on from exiting
3324 // and going away unexpectedly (e.g., safepoint synchronization)
3325 
3326 JavaThread* Threads::_thread_list = NULL;
3327 int         Threads::_number_of_threads = 0;
3328 int         Threads::_number_of_non_daemon_threads = 0;
3329 int         Threads::_return_code = 0;
3330 int         Threads::_thread_claim_parity = 0;
3331 size_t      JavaThread::_stack_size_at_create = 0;
3332 #ifdef ASSERT
3333 bool        Threads::_vm_complete = false;
3334 #endif
3335 
3336 // All JavaThreads
3337 #define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next())
3338 
3339 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
3340 void Threads::threads_do(ThreadClosure* tc) {
3341   assert_locked_or_safepoint(Threads_lock);
3342   // ALL_JAVA_THREADS iterates through all JavaThreads
3343   ALL_JAVA_THREADS(p) {
3344     tc->do_thread(p);
3345   }
3346   // Someday we could have a table or list of all non-JavaThreads.
3347   // For now, just manually iterate through them.
3348   tc->do_thread(VMThread::vm_thread());
3349   Universe::heap()->gc_threads_do(tc);
3350   WatcherThread *wt = WatcherThread::watcher_thread();
3351   // Strictly speaking, the following NULL check isn't sufficient to make sure
3352   // the data for WatcherThread is still valid upon being examined. However,
3353   // considering that WatchThread terminates when the VM is on the way to
3354   // exit at safepoint, the chance of the above is extremely small. The right
3355   // way to prevent termination of WatcherThread would be to acquire
3356   // Terminator_lock, but we can't do that without violating the lock rank
3357   // checking in some cases.
3358   if (wt != NULL) {
3359     tc->do_thread(wt);
3360   }
3361 
3362   // If CompilerThreads ever become non-JavaThreads, add them here
3363 }
3364 
3365 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) {
3366   int cp = Threads::thread_claim_parity();
3367   ALL_JAVA_THREADS(p) {
3368     if (p->claim_oops_do(is_par, cp)) {
3369       tc->do_thread(p);
3370     }
3371   }
3372   VMThread* vmt = VMThread::vm_thread();
3373   if (vmt->claim_oops_do(is_par, cp)) {
3374     tc->do_thread(vmt);
3375   }
3376 }
3377 
3378 // The system initialization in the library has three phases.
3379 //
3380 // Phase 1: java.lang.System class initialization
3381 //     java.lang.System is a primordial class loaded and initialized
3382 //     by the VM early during startup.  java.lang.System.<clinit>
3383 //     only does registerNatives and keeps the rest of the class
3384 //     initialization work later until thread initialization completes.
3385 //
3386 //     System.initPhase1 initializes the system properties, the static
3387 //     fields in, out, and err. Set up java signal handlers, OS-specific
3388 //     system settings, and thread group of the main thread.
3389 static void call_initPhase1(TRAPS) {
3390   Klass* klass =  SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3391   JavaValue result(T_VOID);
3392   JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(),
3393                                          vmSymbols::void_method_signature(), CHECK);
3394 }
3395 
3396 // Phase 2. Module system initialization
3397 //     This will initialize the module system.  Only java.base classes
3398 //     can be loaded until phase 2 completes.
3399 //
3400 //     Call System.initPhase2 after the compiler initialization and jsr292
3401 //     classes get initialized because module initialization runs a lot of java
3402 //     code, that for performance reasons, should be compiled.  Also, this will
3403 //     enable the startup code to use lambda and other language features in this
3404 //     phase and onward.
3405 //
3406 //     After phase 2, The VM will begin search classes from -Xbootclasspath/a.
3407 static void call_initPhase2(TRAPS) {
3408   TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
3409 
3410   Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3411 
3412   JavaValue result(T_INT);
3413   JavaCallArguments args;
3414   args.push_int(DisplayVMOutputToStderr);
3415   args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
3416   JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
3417                                          vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
3418   if (result.get_jint() != JNI_OK) {
3419     vm_exit_during_initialization(); // no message or exception
3420   }
3421 
3422   universe_post_module_init();
3423 }
3424 
3425 // Phase 3. final setup - set security manager, system class loader and TCCL
3426 //
3427 //     This will instantiate and set the security manager, set the system class
3428 //     loader as well as the thread context class loader.  The security manager
3429 //     and system class loader may be a custom class loaded from -Xbootclasspath/a,
3430 //     other modules or the application's classpath.
3431 static void call_initPhase3(TRAPS) {
3432   Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3433   JavaValue result(T_VOID);
3434   JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
3435                                          vmSymbols::void_method_signature(), CHECK);
3436 }
3437 
3438 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
3439   TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
3440 
3441   if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
3442     create_vm_init_libraries();
3443   }
3444 
3445   initialize_class(vmSymbols::java_lang_String(), CHECK);
3446 
3447   // Inject CompactStrings value after the static initializers for String ran.
3448   java_lang_String::set_compact_strings(CompactStrings);
3449 
3450   // Initialize java_lang.System (needed before creating the thread)
3451   initialize_class(vmSymbols::java_lang_System(), CHECK);
3452   // The VM creates & returns objects of this class. Make sure it's initialized.
3453   initialize_class(vmSymbols::java_lang_Class(), CHECK);
3454   initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
3455   Handle thread_group = create_initial_thread_group(CHECK);
3456   Universe::set_main_thread_group(thread_group());
3457   initialize_class(vmSymbols::java_lang_Thread(), CHECK);
3458   oop thread_object = create_initial_thread(thread_group, main_thread, CHECK);
3459   main_thread->set_threadObj(thread_object);
3460   // Set thread status to running since main thread has
3461   // been started and running.
3462   java_lang_Thread::set_thread_status(thread_object,
3463                                       java_lang_Thread::RUNNABLE);
3464 
3465   // The VM creates objects of this class.
3466   initialize_class(vmSymbols::java_lang_Module(), CHECK);
3467 
3468   // The VM preresolves methods to these classes. Make sure that they get initialized
3469   initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
3470   initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
3471 
3472   // Phase 1 of the system initialization in the library, java.lang.System class initialization
3473   call_initPhase1(CHECK);
3474 
3475   // get the Java runtime name after java.lang.System is initialized
3476   JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
3477   JDK_Version::set_runtime_version(get_java_runtime_version(THREAD));
3478 
3479   // an instance of OutOfMemory exception has been allocated earlier
3480   initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
3481   initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
3482   initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
3483   initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
3484   initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
3485   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
3486   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
3487   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
3488 }
3489 
3490 void Threads::initialize_jsr292_core_classes(TRAPS) {
3491   TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
3492 
3493   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
3494   initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
3495   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
3496   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
3497 }
3498 
3499 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
3500   extern void JDK_Version_init();
3501 
3502   // Preinitialize version info.
3503   VM_Version::early_initialize();
3504 
3505   // Check version
3506   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
3507 
3508   // Initialize library-based TLS
3509   ThreadLocalStorage::init();
3510 
3511   // Initialize the output stream module
3512   ostream_init();
3513 
3514   // Process java launcher properties.
3515   Arguments::process_sun_java_launcher_properties(args);
3516 
3517   // Initialize the os module
3518   os::init();
3519 
3520   // Record VM creation timing statistics
3521   TraceVmCreationTime create_vm_timer;
3522   create_vm_timer.start();
3523 
3524   // Initialize system properties.
3525   Arguments::init_system_properties();
3526 
3527   // So that JDK version can be used as a discriminator when parsing arguments
3528   JDK_Version_init();
3529 
3530   // Update/Initialize System properties after JDK version number is known
3531   Arguments::init_version_specific_system_properties();
3532 
3533   // Make sure to initialize log configuration *before* parsing arguments
3534   LogConfiguration::initialize(create_vm_timer.begin_time());
3535 
3536   // Parse arguments
3537   jint parse_result = Arguments::parse(args);
3538   if (parse_result != JNI_OK) return parse_result;
3539 
3540   os::init_before_ergo();
3541 
3542   jint ergo_result = Arguments::apply_ergo();
3543   if (ergo_result != JNI_OK) return ergo_result;
3544 
3545   // Final check of all ranges after ergonomics which may change values.
3546   if (!CommandLineFlagRangeList::check_ranges()) {
3547     return JNI_EINVAL;
3548   }
3549 
3550   // Final check of all 'AfterErgo' constraints after ergonomics which may change values.
3551   bool constraint_result = CommandLineFlagConstraintList::check_constraints(CommandLineFlagConstraint::AfterErgo);
3552   if (!constraint_result) {
3553     return JNI_EINVAL;
3554   }
3555 
3556   CommandLineFlagWriteableList::mark_startup();
3557 
3558   if (PauseAtStartup) {
3559     os::pause();
3560   }
3561 
3562   HOTSPOT_VM_INIT_BEGIN();
3563 
3564   // Timing (must come after argument parsing)
3565   TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime));
3566 
3567   SafepointMechanism::initialize();
3568 
3569   // Initialize the os module after parsing the args
3570   jint os_init_2_result = os::init_2();
3571   if (os_init_2_result != JNI_OK) return os_init_2_result;
3572 
3573   jint adjust_after_os_result = Arguments::adjust_after_os();
3574   if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
3575 
3576   // Initialize output stream logging
3577   ostream_init_log();
3578 
3579   // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
3580   // Must be before create_vm_init_agents()
3581   if (Arguments::init_libraries_at_startup()) {
3582     convert_vm_init_libraries_to_agents();
3583   }
3584 
3585   // Launch -agentlib/-agentpath and converted -Xrun agents
3586   if (Arguments::init_agents_at_startup()) {
3587     create_vm_init_agents();
3588   }
3589 
3590   // Initialize Threads state
3591   _thread_list = NULL;
3592   _number_of_threads = 0;
3593   _number_of_non_daemon_threads = 0;
3594 
3595   // Initialize global data structures and create system classes in heap
3596   vm_init_globals();
3597 
3598 #if INCLUDE_JVMCI
3599   if (JVMCICounterSize > 0) {
3600     JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal);
3601     memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
3602   } else {
3603     JavaThread::_jvmci_old_thread_counters = NULL;
3604   }
3605 #endif // INCLUDE_JVMCI
3606 
3607   // Attach the main thread to this os thread
3608   JavaThread* main_thread = new JavaThread();
3609   main_thread->set_thread_state(_thread_in_vm);
3610   main_thread->initialize_thread_current();
3611   // must do this before set_active_handles
3612   main_thread->record_stack_base_and_size();
3613   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
3614 
3615   if (!main_thread->set_as_starting_thread()) {
3616     vm_shutdown_during_initialization(
3617                                       "Failed necessary internal allocation. Out of swap space");
3618     delete main_thread;
3619     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3620     return JNI_ENOMEM;
3621   }
3622 
3623   // Enable guard page *after* os::create_main_thread(), otherwise it would
3624   // crash Linux VM, see notes in os_linux.cpp.
3625   main_thread->create_stack_guard_pages();
3626 
3627   // Initialize Java-Level synchronization subsystem
3628   ObjectMonitor::Initialize();
3629 
3630   // Initialize global modules
3631   jint status = init_globals();
3632   if (status != JNI_OK) {
3633     delete main_thread;
3634     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3635     return status;
3636   }
3637 
3638   if (TRACE_INITIALIZE() != JNI_OK) {
3639     vm_exit_during_initialization("Failed to initialize tracing backend");
3640   }
3641 
3642   // Should be done after the heap is fully created
3643   main_thread->cache_global_variables();
3644 
3645   HandleMark hm;
3646 
3647   { MutexLocker mu(Threads_lock);
3648     Threads::add(main_thread);
3649   }
3650 
3651   // Any JVMTI raw monitors entered in onload will transition into
3652   // real raw monitor. VM is setup enough here for raw monitor enter.
3653   JvmtiExport::transition_pending_onload_raw_monitors();
3654 
3655   // Create the VMThread
3656   { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime));
3657 
3658   VMThread::create();
3659     Thread* vmthread = VMThread::vm_thread();
3660 
3661     if (!os::create_thread(vmthread, os::vm_thread)) {
3662       vm_exit_during_initialization("Cannot create VM thread. "
3663                                     "Out of system resources.");
3664     }
3665 
3666     // Wait for the VM thread to become ready, and VMThread::run to initialize
3667     // Monitors can have spurious returns, must always check another state flag
3668     {
3669       MutexLocker ml(Notify_lock);
3670       os::start_thread(vmthread);
3671       while (vmthread->active_handles() == NULL) {
3672         Notify_lock->wait();
3673       }
3674     }
3675   }
3676 
3677   assert(Universe::is_fully_initialized(), "not initialized");
3678   if (VerifyDuringStartup) {
3679     // Make sure we're starting with a clean slate.
3680     VM_Verify verify_op;
3681     VMThread::execute(&verify_op);
3682   }
3683 
3684   Thread* THREAD = Thread::current();
3685 
3686   // Always call even when there are not JVMTI environments yet, since environments
3687   // may be attached late and JVMTI must track phases of VM execution
3688   JvmtiExport::enter_early_start_phase();
3689 
3690   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
3691   JvmtiExport::post_early_vm_start();
3692 
3693   initialize_java_lang_classes(main_thread, CHECK_JNI_ERR);
3694 
3695   // We need this for ClassDataSharing - the initial vm.info property is set
3696   // with the default value of CDS "sharing" which may be reset through
3697   // command line options.
3698   reset_vm_info_property(CHECK_JNI_ERR);
3699 
3700   quicken_jni_functions();
3701 
3702   // No more stub generation allowed after that point.
3703   StubCodeDesc::freeze();
3704 
3705   // Set flag that basic initialization has completed. Used by exceptions and various
3706   // debug stuff, that does not work until all basic classes have been initialized.
3707   set_init_completed();
3708 
3709   LogConfiguration::post_initialize();
3710   Metaspace::post_initialize();
3711 
3712   HOTSPOT_VM_INIT_END();
3713 
3714   // record VM initialization completion time
3715 #if INCLUDE_MANAGEMENT
3716   Management::record_vm_init_completed();
3717 #endif // INCLUDE_MANAGEMENT
3718 
3719   // Signal Dispatcher needs to be started before VMInit event is posted
3720   os::signal_init(CHECK_JNI_ERR);
3721 
3722   // Start Attach Listener if +StartAttachListener or it can't be started lazily
3723   if (!DisableAttachMechanism) {
3724     AttachListener::vm_start();
3725     if (StartAttachListener || AttachListener::init_at_startup()) {
3726       AttachListener::init();
3727     }
3728   }
3729 
3730   // Launch -Xrun agents
3731   // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3732   // back-end can launch with -Xdebug -Xrunjdwp.
3733   if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3734     create_vm_init_libraries();
3735   }
3736 
3737   if (CleanChunkPoolAsync) {
3738     Chunk::start_chunk_pool_cleaner_task();
3739   }
3740 
3741   // initialize compiler(s)
3742 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
3743   CompileBroker::compilation_init(CHECK_JNI_ERR);
3744 #endif
3745 
3746   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
3747   // It is done after compilers are initialized, because otherwise compilations of
3748   // signature polymorphic MH intrinsics can be missed
3749   // (see SystemDictionary::find_method_handle_intrinsic).
3750   initialize_jsr292_core_classes(CHECK_JNI_ERR);
3751 
3752   // This will initialize the module system.  Only java.base classes can be
3753   // loaded until phase 2 completes
3754   call_initPhase2(CHECK_JNI_ERR);
3755 
3756   // Always call even when there are not JVMTI environments yet, since environments
3757   // may be attached late and JVMTI must track phases of VM execution
3758   JvmtiExport::enter_start_phase();
3759 
3760   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
3761   JvmtiExport::post_vm_start();
3762 
3763   // Final system initialization including security manager and system class loader
3764   call_initPhase3(CHECK_JNI_ERR);
3765 
3766   // cache the system and platform class loaders
3767   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
3768 
3769 #if INCLUDE_JVMCI
3770   if (EnableJVMCI) {
3771     // Initialize JVMCI eagerly if JVMCIPrintProperties is enabled.
3772     // The JVMCI Java initialization code will read this flag and
3773     // do the printing if it's set.
3774     bool init = JVMCIPrintProperties;
3775 
3776     if (!init) {
3777       // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking
3778       // compilations via JVMCI will not actually block until JVMCI is initialized.
3779       init = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation);
3780     }
3781 
3782     if (init) {
3783       JVMCIRuntime::force_initialization(CHECK_JNI_ERR);
3784     }
3785   }
3786 #endif
3787 
3788   // Always call even when there are not JVMTI environments yet, since environments
3789   // may be attached late and JVMTI must track phases of VM execution
3790   JvmtiExport::enter_live_phase();
3791 
3792   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3793   JvmtiExport::post_vm_initialized();
3794 
3795   if (TRACE_START() != JNI_OK) {
3796     vm_exit_during_initialization("Failed to start tracing backend.");
3797   }
3798 
3799 #if INCLUDE_MANAGEMENT
3800   Management::initialize(THREAD);
3801 
3802   if (HAS_PENDING_EXCEPTION) {
3803     // management agent fails to start possibly due to
3804     // configuration problem and is responsible for printing
3805     // stack trace if appropriate. Simply exit VM.
3806     vm_exit(1);
3807   }
3808 #endif // INCLUDE_MANAGEMENT
3809 
3810   if (MemProfiling)                   MemProfiler::engage();
3811   StatSampler::engage();
3812   if (CheckJNICalls)                  JniPeriodicChecker::engage();
3813 
3814   BiasedLocking::init();
3815 
3816 #if INCLUDE_RTM_OPT
3817   RTMLockingCounters::init();
3818 #endif
3819 
3820   if (JDK_Version::current().post_vm_init_hook_enabled()) {
3821     call_postVMInitHook(THREAD);
3822     // The Java side of PostVMInitHook.run must deal with all
3823     // exceptions and provide means of diagnosis.
3824     if (HAS_PENDING_EXCEPTION) {
3825       CLEAR_PENDING_EXCEPTION;
3826     }
3827   }
3828 
3829   {
3830     MutexLocker ml(PeriodicTask_lock);
3831     // Make sure the WatcherThread can be started by WatcherThread::start()
3832     // or by dynamic enrollment.
3833     WatcherThread::make_startable();
3834     // Start up the WatcherThread if there are any periodic tasks
3835     // NOTE:  All PeriodicTasks should be registered by now. If they
3836     //   aren't, late joiners might appear to start slowly (we might
3837     //   take a while to process their first tick).
3838     if (PeriodicTask::num_tasks() > 0) {
3839       WatcherThread::start();
3840     }
3841   }
3842 
3843   create_vm_timer.end();
3844 #ifdef ASSERT
3845   _vm_complete = true;
3846 #endif
3847 
3848   if (DumpSharedSpaces) {
3849     MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
3850     ShouldNotReachHere();
3851   }
3852 
3853   return JNI_OK;
3854 }
3855 
3856 // type for the Agent_OnLoad and JVM_OnLoad entry points
3857 extern "C" {
3858   typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
3859 }
3860 // Find a command line agent library and return its entry point for
3861 //         -agentlib:  -agentpath:   -Xrun
3862 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
3863 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent,
3864                                     const char *on_load_symbols[],
3865                                     size_t num_symbol_entries) {
3866   OnLoadEntry_t on_load_entry = NULL;
3867   void *library = NULL;
3868 
3869   if (!agent->valid()) {
3870     char buffer[JVM_MAXPATHLEN];
3871     char ebuf[1024] = "";
3872     const char *name = agent->name();
3873     const char *msg = "Could not find agent library ";
3874 
3875     // First check to see if agent is statically linked into executable
3876     if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) {
3877       library = agent->os_lib();
3878     } else if (agent->is_absolute_path()) {
3879       library = os::dll_load(name, ebuf, sizeof ebuf);
3880       if (library == NULL) {
3881         const char *sub_msg = " in absolute path, with error: ";
3882         size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
3883         char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
3884         jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
3885         // If we can't find the agent, exit.
3886         vm_exit_during_initialization(buf, NULL);
3887         FREE_C_HEAP_ARRAY(char, buf);
3888       }
3889     } else {
3890       // Try to load the agent from the standard dll directory
3891       if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
3892                              name)) {
3893         library = os::dll_load(buffer, ebuf, sizeof ebuf);
3894       }
3895       if (library == NULL) { // Try the library path directory.
3896         if (os::dll_build_name(buffer, sizeof(buffer), name)) {
3897           library = os::dll_load(buffer, ebuf, sizeof ebuf);
3898         }
3899         if (library == NULL) {
3900           const char *sub_msg = " on the library path, with error: ";
3901           size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
3902           char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
3903           jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
3904           // If we can't find the agent, exit.
3905           vm_exit_during_initialization(buf, NULL);
3906           FREE_C_HEAP_ARRAY(char, buf);
3907         }
3908       }
3909     }
3910     agent->set_os_lib(library);
3911     agent->set_valid();
3912   }
3913 
3914   // Find the OnLoad function.
3915   on_load_entry =
3916     CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent,
3917                                                           false,
3918                                                           on_load_symbols,
3919                                                           num_symbol_entries));
3920   return on_load_entry;
3921 }
3922 
3923 // Find the JVM_OnLoad entry point
3924 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
3925   const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
3926   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
3927 }
3928 
3929 // Find the Agent_OnLoad entry point
3930 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
3931   const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
3932   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
3933 }
3934 
3935 // For backwards compatibility with -Xrun
3936 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
3937 // treated like -agentpath:
3938 // Must be called before agent libraries are created
3939 void Threads::convert_vm_init_libraries_to_agents() {
3940   AgentLibrary* agent;
3941   AgentLibrary* next;
3942 
3943   for (agent = Arguments::libraries(); agent != NULL; agent = next) {
3944     next = agent->next();  // cache the next agent now as this agent may get moved off this list
3945     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
3946 
3947     // If there is an JVM_OnLoad function it will get called later,
3948     // otherwise see if there is an Agent_OnLoad
3949     if (on_load_entry == NULL) {
3950       on_load_entry = lookup_agent_on_load(agent);
3951       if (on_load_entry != NULL) {
3952         // switch it to the agent list -- so that Agent_OnLoad will be called,
3953         // JVM_OnLoad won't be attempted and Agent_OnUnload will
3954         Arguments::convert_library_to_agent(agent);
3955       } else {
3956         vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
3957       }
3958     }
3959   }
3960 }
3961 
3962 // Create agents for -agentlib:  -agentpath:  and converted -Xrun
3963 // Invokes Agent_OnLoad
3964 // Called very early -- before JavaThreads exist
3965 void Threads::create_vm_init_agents() {
3966   extern struct JavaVM_ main_vm;
3967   AgentLibrary* agent;
3968 
3969   JvmtiExport::enter_onload_phase();
3970 
3971   for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
3972     OnLoadEntry_t  on_load_entry = lookup_agent_on_load(agent);
3973 
3974     if (on_load_entry != NULL) {
3975       // Invoke the Agent_OnLoad function
3976       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
3977       if (err != JNI_OK) {
3978         vm_exit_during_initialization("agent library failed to init", agent->name());
3979       }
3980     } else {
3981       vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
3982     }
3983   }
3984   JvmtiExport::enter_primordial_phase();
3985 }
3986 
3987 extern "C" {
3988   typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
3989 }
3990 
3991 void Threads::shutdown_vm_agents() {
3992   // Send any Agent_OnUnload notifications
3993   const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
3994   size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols);
3995   extern struct JavaVM_ main_vm;
3996   for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
3997 
3998     // Find the Agent_OnUnload function.
3999     Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
4000                                                    os::find_agent_function(agent,
4001                                                    false,
4002                                                    on_unload_symbols,
4003                                                    num_symbol_entries));
4004 
4005     // Invoke the Agent_OnUnload function
4006     if (unload_entry != NULL) {
4007       JavaThread* thread = JavaThread::current();
4008       ThreadToNativeFromVM ttn(thread);
4009       HandleMark hm(thread);
4010       (*unload_entry)(&main_vm);
4011     }
4012   }
4013 }
4014 
4015 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
4016 // Invokes JVM_OnLoad
4017 void Threads::create_vm_init_libraries() {
4018   extern struct JavaVM_ main_vm;
4019   AgentLibrary* agent;
4020 
4021   for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
4022     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
4023 
4024     if (on_load_entry != NULL) {
4025       // Invoke the JVM_OnLoad function
4026       JavaThread* thread = JavaThread::current();
4027       ThreadToNativeFromVM ttn(thread);
4028       HandleMark hm(thread);
4029       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
4030       if (err != JNI_OK) {
4031         vm_exit_during_initialization("-Xrun library failed to init", agent->name());
4032       }
4033     } else {
4034       vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
4035     }
4036   }
4037 }
4038 
4039 JavaThread* Threads::find_java_thread_from_java_tid(jlong java_tid) {
4040   assert(Threads_lock->owned_by_self(), "Must hold Threads_lock");
4041 
4042   JavaThread* java_thread = NULL;
4043   // Sequential search for now.  Need to do better optimization later.
4044   for (JavaThread* thread = Threads::first(); thread != NULL; thread = thread->next()) {
4045     oop tobj = thread->threadObj();
4046     if (!thread->is_exiting() &&
4047         tobj != NULL &&
4048         java_tid == java_lang_Thread::thread_id(tobj)) {
4049       java_thread = thread;
4050       break;
4051     }
4052   }
4053   return java_thread;
4054 }
4055 
4056 
4057 // Last thread running calls java.lang.Shutdown.shutdown()
4058 void JavaThread::invoke_shutdown_hooks() {
4059   HandleMark hm(this);
4060 
4061   // We could get here with a pending exception, if so clear it now.
4062   if (this->has_pending_exception()) {
4063     this->clear_pending_exception();
4064   }
4065 
4066   EXCEPTION_MARK;
4067   Klass* shutdown_klass =
4068     SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
4069                                       THREAD);
4070   if (shutdown_klass != NULL) {
4071     // SystemDictionary::resolve_or_null will return null if there was
4072     // an exception.  If we cannot load the Shutdown class, just don't
4073     // call Shutdown.shutdown() at all.  This will mean the shutdown hooks
4074     // and finalizers (if runFinalizersOnExit is set) won't be run.
4075     // Note that if a shutdown hook was registered or runFinalizersOnExit
4076     // was called, the Shutdown class would have already been loaded
4077     // (Runtime.addShutdownHook and runFinalizersOnExit will load it).
4078     JavaValue result(T_VOID);
4079     JavaCalls::call_static(&result,
4080                            shutdown_klass,
4081                            vmSymbols::shutdown_method_name(),
4082                            vmSymbols::void_method_signature(),
4083                            THREAD);
4084   }
4085   CLEAR_PENDING_EXCEPTION;
4086 }
4087 
4088 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
4089 // the program falls off the end of main(). Another VM exit path is through
4090 // vm_exit() when the program calls System.exit() to return a value or when
4091 // there is a serious error in VM. The two shutdown paths are not exactly
4092 // the same, but they share Shutdown.shutdown() at Java level and before_exit()
4093 // and VM_Exit op at VM level.
4094 //
4095 // Shutdown sequence:
4096 //   + Shutdown native memory tracking if it is on
4097 //   + Wait until we are the last non-daemon thread to execute
4098 //     <-- every thing is still working at this moment -->
4099 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
4100 //        shutdown hooks, run finalizers if finalization-on-exit
4101 //   + Call before_exit(), prepare for VM exit
4102 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),
4103 //        currently the only user of this mechanism is File.deleteOnExit())
4104 //      > stop StatSampler, watcher thread, CMS threads,
4105 //        post thread end and vm death events to JVMTI,
4106 //        stop signal thread
4107 //   + Call JavaThread::exit(), it will:
4108 //      > release JNI handle blocks, remove stack guard pages
4109 //      > remove this thread from Threads list
4110 //     <-- no more Java code from this thread after this point -->
4111 //   + Stop VM thread, it will bring the remaining VM to a safepoint and stop
4112 //     the compiler threads at safepoint
4113 //     <-- do not use anything that could get blocked by Safepoint -->
4114 //   + Disable tracing at JNI/JVM barriers
4115 //   + Set _vm_exited flag for threads that are still running native code
4116 //   + Delete this thread
4117 //   + Call exit_globals()
4118 //      > deletes tty
4119 //      > deletes PerfMemory resources
4120 //   + Return to caller
4121 
4122 bool Threads::destroy_vm() {
4123   JavaThread* thread = JavaThread::current();
4124 
4125 #ifdef ASSERT
4126   _vm_complete = false;
4127 #endif
4128   // Wait until we are the last non-daemon thread to execute
4129   { MutexLocker nu(Threads_lock);
4130     while (Threads::number_of_non_daemon_threads() > 1)
4131       // This wait should make safepoint checks, wait without a timeout,
4132       // and wait as a suspend-equivalent condition.
4133       Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
4134                          Mutex::_as_suspend_equivalent_flag);
4135   }
4136 
4137   // Hang forever on exit if we are reporting an error.
4138   if (ShowMessageBoxOnError && VMError::is_error_reported()) {
4139     os::infinite_sleep();
4140   }
4141   os::wait_for_keypress_at_exit();
4142 
4143   // run Java level shutdown hooks
4144   thread->invoke_shutdown_hooks();
4145 
4146   before_exit(thread);
4147 
4148   thread->exit(true);
4149 
4150   // Stop VM thread.
4151   {
4152     // 4945125 The vm thread comes to a safepoint during exit.
4153     // GC vm_operations can get caught at the safepoint, and the
4154     // heap is unparseable if they are caught. Grab the Heap_lock
4155     // to prevent this. The GC vm_operations will not be able to
4156     // queue until after the vm thread is dead. After this point,
4157     // we'll never emerge out of the safepoint before the VM exits.
4158 
4159     MutexLocker ml(Heap_lock);
4160 
4161     VMThread::wait_for_vm_thread_exit();
4162     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
4163     VMThread::destroy();
4164   }
4165 
4166   // clean up ideal graph printers
4167 #if defined(COMPILER2) && !defined(PRODUCT)
4168   IdealGraphPrinter::clean_up();
4169 #endif
4170 
4171   // Now, all Java threads are gone except daemon threads. Daemon threads
4172   // running Java code or in VM are stopped by the Safepoint. However,
4173   // daemon threads executing native code are still running.  But they
4174   // will be stopped at native=>Java/VM barriers. Note that we can't
4175   // simply kill or suspend them, as it is inherently deadlock-prone.
4176 
4177   VM_Exit::set_vm_exited();
4178 
4179   notify_vm_shutdown();
4180 
4181   delete thread;
4182 
4183 #if INCLUDE_JVMCI
4184   if (JVMCICounterSize > 0) {
4185     FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
4186   }
4187 #endif
4188 
4189   // exit_globals() will delete tty
4190   exit_globals();
4191 
4192   LogConfiguration::finalize();
4193 
4194   return true;
4195 }
4196 
4197 
4198 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
4199   if (version == JNI_VERSION_1_1) return JNI_TRUE;
4200   return is_supported_jni_version(version);
4201 }
4202 
4203 
4204 jboolean Threads::is_supported_jni_version(jint version) {
4205   if (version == JNI_VERSION_1_2) return JNI_TRUE;
4206   if (version == JNI_VERSION_1_4) return JNI_TRUE;
4207   if (version == JNI_VERSION_1_6) return JNI_TRUE;
4208   if (version == JNI_VERSION_1_8) return JNI_TRUE;
4209   if (version == JNI_VERSION_9) return JNI_TRUE;
4210   if (version == JNI_VERSION_10) return JNI_TRUE;
4211   return JNI_FALSE;
4212 }
4213 
4214 
4215 void Threads::add(JavaThread* p, bool force_daemon) {
4216   // The threads lock must be owned at this point
4217   assert_locked_or_safepoint(Threads_lock);
4218 
4219   // See the comment for this method in thread.hpp for its purpose and
4220   // why it is called here.
4221   p->initialize_queues();
4222   p->set_next(_thread_list);
4223   _thread_list = p;
4224   _number_of_threads++;
4225   oop threadObj = p->threadObj();
4226   bool daemon = true;
4227   // Bootstrapping problem: threadObj can be null for initial
4228   // JavaThread (or for threads attached via JNI)
4229   if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) {
4230     _number_of_non_daemon_threads++;
4231     daemon = false;
4232   }
4233 
4234   ThreadService::add_thread(p, daemon);
4235 
4236   // Possible GC point.
4237   Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p));
4238 }
4239 
4240 void Threads::remove(JavaThread* p) {
4241 
4242   // Reclaim the objectmonitors from the omInUseList and omFreeList of the moribund thread.
4243   ObjectSynchronizer::omFlush(p);
4244 
4245   // Extra scope needed for Thread_lock, so we can check
4246   // that we do not remove thread without safepoint code notice
4247   { MutexLocker ml(Threads_lock);
4248 
4249     assert(includes(p), "p must be present");
4250 
4251     JavaThread* current = _thread_list;
4252     JavaThread* prev    = NULL;
4253 
4254     while (current != p) {
4255       prev    = current;
4256       current = current->next();
4257     }
4258 
4259     if (prev) {
4260       prev->set_next(current->next());
4261     } else {
4262       _thread_list = p->next();
4263     }
4264     _number_of_threads--;
4265     oop threadObj = p->threadObj();
4266     bool daemon = true;
4267     if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
4268       _number_of_non_daemon_threads--;
4269       daemon = false;
4270 
4271       // Only one thread left, do a notify on the Threads_lock so a thread waiting
4272       // on destroy_vm will wake up.
4273       if (number_of_non_daemon_threads() == 1) {
4274         Threads_lock->notify_all();
4275       }
4276     }
4277     ThreadService::remove_thread(p, daemon);
4278 
4279     // Make sure that safepoint code disregard this thread. This is needed since
4280     // the thread might mess around with locks after this point. This can cause it
4281     // to do callbacks into the safepoint code. However, the safepoint code is not aware
4282     // of this thread since it is removed from the queue.
4283     p->set_terminated_value();
4284   } // unlock Threads_lock
4285 
4286   // Since Events::log uses a lock, we grab it outside the Threads_lock
4287   Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p));
4288 }
4289 
4290 // Threads_lock must be held when this is called (or must be called during a safepoint)
4291 bool Threads::includes(JavaThread* p) {
4292   assert(Threads_lock->is_locked(), "sanity check");
4293   ALL_JAVA_THREADS(q) {
4294     if (q == p) {
4295       return true;
4296     }
4297   }
4298   return false;
4299 }
4300 
4301 // Operations on the Threads list for GC.  These are not explicitly locked,
4302 // but the garbage collector must provide a safe context for them to run.
4303 // In particular, these things should never be called when the Threads_lock
4304 // is held by some other thread. (Note: the Safepoint abstraction also
4305 // uses the Threads_lock to guarantee this property. It also makes sure that
4306 // all threads gets blocked when exiting or starting).
4307 
4308 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) {
4309   ALL_JAVA_THREADS(p) {
4310     p->oops_do(f, cf);
4311   }
4312   VMThread::vm_thread()->oops_do(f, cf);
4313 }
4314 
4315 void Threads::change_thread_claim_parity() {
4316   // Set the new claim parity.
4317   assert(_thread_claim_parity >= 0 && _thread_claim_parity <= 2,
4318          "Not in range.");
4319   _thread_claim_parity++;
4320   if (_thread_claim_parity == 3) _thread_claim_parity = 1;
4321   assert(_thread_claim_parity >= 1 && _thread_claim_parity <= 2,
4322          "Not in range.");
4323 }
4324 
4325 #ifdef ASSERT
4326 void Threads::assert_all_threads_claimed() {
4327   ALL_JAVA_THREADS(p) {
4328     const int thread_parity = p->oops_do_parity();
4329     assert((thread_parity == _thread_claim_parity),
4330            "Thread " PTR_FORMAT " has incorrect parity %d != %d", p2i(p), thread_parity, _thread_claim_parity);
4331   }
4332   VMThread* vmt = VMThread::vm_thread();
4333   const int thread_parity = vmt->oops_do_parity();
4334   assert((thread_parity == _thread_claim_parity),
4335          "VMThread " PTR_FORMAT " has incorrect parity %d != %d", p2i(vmt), thread_parity, _thread_claim_parity);
4336 }
4337 #endif // ASSERT
4338 
4339 class ParallelOopsDoThreadClosure : public ThreadClosure {
4340 private:
4341   OopClosure* _f;
4342   CodeBlobClosure* _cf;
4343 public:
4344   ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {}
4345   void do_thread(Thread* t) {
4346     t->oops_do(_f, _cf);
4347   }
4348 };
4349 
4350 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) {
4351   ParallelOopsDoThreadClosure tc(f, cf);
4352   possibly_parallel_threads_do(is_par, &tc);
4353 }
4354 
4355 #if INCLUDE_ALL_GCS
4356 // Used by ParallelScavenge
4357 void Threads::create_thread_roots_tasks(GCTaskQueue* q) {
4358   ALL_JAVA_THREADS(p) {
4359     q->enqueue(new ThreadRootsTask(p));
4360   }
4361   q->enqueue(new ThreadRootsTask(VMThread::vm_thread()));
4362 }
4363 
4364 // Used by Parallel Old
4365 void Threads::create_thread_roots_marking_tasks(GCTaskQueue* q) {
4366   ALL_JAVA_THREADS(p) {
4367     q->enqueue(new ThreadRootsMarkingTask(p));
4368   }
4369   q->enqueue(new ThreadRootsMarkingTask(VMThread::vm_thread()));
4370 }
4371 #endif // INCLUDE_ALL_GCS
4372 
4373 void Threads::nmethods_do(CodeBlobClosure* cf) {
4374   ALL_JAVA_THREADS(p) {
4375     // This is used by the code cache sweeper to mark nmethods that are active
4376     // on the stack of a Java thread. Ignore the sweeper thread itself to avoid
4377     // marking CodeCacheSweeperThread::_scanned_compiled_method as active.
4378     if(!p->is_Code_cache_sweeper_thread()) {
4379       p->nmethods_do(cf);
4380     }
4381   }
4382 }
4383 
4384 void Threads::metadata_do(void f(Metadata*)) {
4385   ALL_JAVA_THREADS(p) {
4386     p->metadata_do(f);
4387   }
4388 }
4389 
4390 class ThreadHandlesClosure : public ThreadClosure {
4391   void (*_f)(Metadata*);
4392  public:
4393   ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
4394   virtual void do_thread(Thread* thread) {
4395     thread->metadata_handles_do(_f);
4396   }
4397 };
4398 
4399 void Threads::metadata_handles_do(void f(Metadata*)) {
4400   // Only walk the Handles in Thread.
4401   ThreadHandlesClosure handles_closure(f);
4402   threads_do(&handles_closure);
4403 }
4404 
4405 void Threads::deoptimized_wrt_marked_nmethods() {
4406   ALL_JAVA_THREADS(p) {
4407     p->deoptimized_wrt_marked_nmethods();
4408   }
4409 }
4410 
4411 
4412 // Get count Java threads that are waiting to enter the specified monitor.
4413 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
4414                                                          address monitor,
4415                                                          bool doLock) {
4416   assert(doLock || SafepointSynchronize::is_at_safepoint(),
4417          "must grab Threads_lock or be at safepoint");
4418   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
4419 
4420   int i = 0;
4421   {
4422     MutexLockerEx ml(doLock ? Threads_lock : NULL);
4423     ALL_JAVA_THREADS(p) {
4424       if (!p->can_call_java()) continue;
4425 
4426       address pending = (address)p->current_pending_monitor();
4427       if (pending == monitor) {             // found a match
4428         if (i < count) result->append(p);   // save the first count matches
4429         i++;
4430       }
4431     }
4432   }
4433   return result;
4434 }
4435 
4436 
4437 JavaThread *Threads::owning_thread_from_monitor_owner(address owner,
4438                                                       bool doLock) {
4439   assert(doLock ||
4440          Threads_lock->owned_by_self() ||
4441          SafepointSynchronize::is_at_safepoint(),
4442          "must grab Threads_lock or be at safepoint");
4443 
4444   // NULL owner means not locked so we can skip the search
4445   if (owner == NULL) return NULL;
4446 
4447   {
4448     MutexLockerEx ml(doLock ? Threads_lock : NULL);
4449     ALL_JAVA_THREADS(p) {
4450       // first, see if owner is the address of a Java thread
4451       if (owner == (address)p) return p;
4452     }
4453   }
4454   // Cannot assert on lack of success here since this function may be
4455   // used by code that is trying to report useful problem information
4456   // like deadlock detection.
4457   if (UseHeavyMonitors) return NULL;
4458 
4459   // If we didn't find a matching Java thread and we didn't force use of
4460   // heavyweight monitors, then the owner is the stack address of the
4461   // Lock Word in the owning Java thread's stack.
4462   //
4463   JavaThread* the_owner = NULL;
4464   {
4465     MutexLockerEx ml(doLock ? Threads_lock : NULL);
4466     ALL_JAVA_THREADS(q) {
4467       if (q->is_lock_owned(owner)) {
4468         the_owner = q;
4469         break;
4470       }
4471     }
4472   }
4473   // cannot assert on lack of success here; see above comment
4474   return the_owner;
4475 }
4476 
4477 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
4478 void Threads::print_on(outputStream* st, bool print_stacks,
4479                        bool internal_format, bool print_concurrent_locks) {
4480   char buf[32];
4481   st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
4482 
4483   st->print_cr("Full thread dump %s (%s %s):",
4484                Abstract_VM_Version::vm_name(),
4485                Abstract_VM_Version::vm_release(),
4486                Abstract_VM_Version::vm_info_string());
4487   st->cr();
4488 
4489 #if INCLUDE_SERVICES
4490   // Dump concurrent locks
4491   ConcurrentLocksDump concurrent_locks;
4492   if (print_concurrent_locks) {
4493     concurrent_locks.dump_at_safepoint();
4494   }
4495 #endif // INCLUDE_SERVICES
4496 
4497   ALL_JAVA_THREADS(p) {
4498     ResourceMark rm;
4499     p->print_on(st);
4500     if (print_stacks) {
4501       if (internal_format) {
4502         p->trace_stack();
4503       } else {
4504         p->print_stack_on(st);
4505       }
4506     }
4507     st->cr();
4508 #if INCLUDE_SERVICES
4509     if (print_concurrent_locks) {
4510       concurrent_locks.print_locks_on(p, st);
4511     }
4512 #endif // INCLUDE_SERVICES
4513   }
4514 
4515   VMThread::vm_thread()->print_on(st);
4516   st->cr();
4517   Universe::heap()->print_gc_threads_on(st);
4518   WatcherThread* wt = WatcherThread::watcher_thread();
4519   if (wt != NULL) {
4520     wt->print_on(st);
4521     st->cr();
4522   }
4523   st->flush();
4524 }
4525 
4526 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
4527                              int buflen, bool* found_current) {
4528   if (this_thread != NULL) {
4529     bool is_current = (current == this_thread);
4530     *found_current = *found_current || is_current;
4531     st->print("%s", is_current ? "=>" : "  ");
4532 
4533     st->print(PTR_FORMAT, p2i(this_thread));
4534     st->print(" ");
4535     this_thread->print_on_error(st, buf, buflen);
4536     st->cr();
4537   }
4538 }
4539 
4540 class PrintOnErrorClosure : public ThreadClosure {
4541   outputStream* _st;
4542   Thread* _current;
4543   char* _buf;
4544   int _buflen;
4545   bool* _found_current;
4546  public:
4547   PrintOnErrorClosure(outputStream* st, Thread* current, char* buf,
4548                       int buflen, bool* found_current) :
4549    _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {}
4550 
4551   virtual void do_thread(Thread* thread) {
4552     Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current);
4553   }
4554 };
4555 
4556 // Threads::print_on_error() is called by fatal error handler. It's possible
4557 // that VM is not at safepoint and/or current thread is inside signal handler.
4558 // Don't print stack trace, as the stack may not be walkable. Don't allocate
4559 // memory (even in resource area), it might deadlock the error handler.
4560 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
4561                              int buflen) {
4562   bool found_current = false;
4563   st->print_cr("Java Threads: ( => current thread )");
4564   ALL_JAVA_THREADS(thread) {
4565     print_on_error(thread, st, current, buf, buflen, &found_current);
4566   }
4567   st->cr();
4568 
4569   st->print_cr("Other Threads:");
4570   print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current);
4571   print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current);
4572 
4573   PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
4574   Universe::heap()->gc_threads_do(&print_closure);
4575 
4576   if (!found_current) {
4577     st->cr();
4578     st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
4579     current->print_on_error(st, buf, buflen);
4580     st->cr();
4581   }
4582   st->cr();
4583   st->print_cr("Threads with active compile tasks:");
4584   print_threads_compiling(st, buf, buflen);
4585 }
4586 
4587 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen) {
4588   ALL_JAVA_THREADS(thread) {
4589     if (thread->is_Compiler_thread()) {
4590       CompilerThread* ct = (CompilerThread*) thread;
4591       if (ct->task() != NULL) {
4592         thread->print_name_on_error(st, buf, buflen);
4593         ct->task()->print(st, NULL, true, true);
4594       }
4595     }
4596   }
4597 }
4598 
4599 
4600 // Internal SpinLock and Mutex
4601 // Based on ParkEvent
4602 
4603 // Ad-hoc mutual exclusion primitives: SpinLock and Mux
4604 //
4605 // We employ SpinLocks _only for low-contention, fixed-length
4606 // short-duration critical sections where we're concerned
4607 // about native mutex_t or HotSpot Mutex:: latency.
4608 // The mux construct provides a spin-then-block mutual exclusion
4609 // mechanism.
4610 //
4611 // Testing has shown that contention on the ListLock guarding gFreeList
4612 // is common.  If we implement ListLock as a simple SpinLock it's common
4613 // for the JVM to devolve to yielding with little progress.  This is true
4614 // despite the fact that the critical sections protected by ListLock are
4615 // extremely short.
4616 //
4617 // TODO-FIXME: ListLock should be of type SpinLock.
4618 // We should make this a 1st-class type, integrated into the lock
4619 // hierarchy as leaf-locks.  Critically, the SpinLock structure
4620 // should have sufficient padding to avoid false-sharing and excessive
4621 // cache-coherency traffic.
4622 
4623 
4624 typedef volatile int SpinLockT;
4625 
4626 void Thread::SpinAcquire(volatile int * adr, const char * LockName) {
4627   if (Atomic::cmpxchg (1, adr, 0) == 0) {
4628     return;   // normal fast-path return
4629   }
4630 
4631   // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
4632   TEVENT(SpinAcquire - ctx);
4633   int ctr = 0;
4634   int Yields = 0;
4635   for (;;) {
4636     while (*adr != 0) {
4637       ++ctr;
4638       if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
4639         if (Yields > 5) {
4640           os::naked_short_sleep(1);
4641         } else {
4642           os::naked_yield();
4643           ++Yields;
4644         }
4645       } else {
4646         SpinPause();
4647       }
4648     }
4649     if (Atomic::cmpxchg(1, adr, 0) == 0) return;
4650   }
4651 }
4652 
4653 void Thread::SpinRelease(volatile int * adr) {
4654   assert(*adr != 0, "invariant");
4655   OrderAccess::fence();      // guarantee at least release consistency.
4656   // Roach-motel semantics.
4657   // It's safe if subsequent LDs and STs float "up" into the critical section,
4658   // but prior LDs and STs within the critical section can't be allowed
4659   // to reorder or float past the ST that releases the lock.
4660   // Loads and stores in the critical section - which appear in program
4661   // order before the store that releases the lock - must also appear
4662   // before the store that releases the lock in memory visibility order.
4663   // Conceptually we need a #loadstore|#storestore "release" MEMBAR before
4664   // the ST of 0 into the lock-word which releases the lock, so fence
4665   // more than covers this on all platforms.
4666   *adr = 0;
4667 }
4668 
4669 // muxAcquire and muxRelease:
4670 //
4671 // *  muxAcquire and muxRelease support a single-word lock-word construct.
4672 //    The LSB of the word is set IFF the lock is held.
4673 //    The remainder of the word points to the head of a singly-linked list
4674 //    of threads blocked on the lock.
4675 //
4676 // *  The current implementation of muxAcquire-muxRelease uses its own
4677 //    dedicated Thread._MuxEvent instance.  If we're interested in
4678 //    minimizing the peak number of extant ParkEvent instances then
4679 //    we could eliminate _MuxEvent and "borrow" _ParkEvent as long
4680 //    as certain invariants were satisfied.  Specifically, care would need
4681 //    to be taken with regards to consuming unpark() "permits".
4682 //    A safe rule of thumb is that a thread would never call muxAcquire()
4683 //    if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently
4684 //    park().  Otherwise the _ParkEvent park() operation in muxAcquire() could
4685 //    consume an unpark() permit intended for monitorenter, for instance.
4686 //    One way around this would be to widen the restricted-range semaphore
4687 //    implemented in park().  Another alternative would be to provide
4688 //    multiple instances of the PlatformEvent() for each thread.  One
4689 //    instance would be dedicated to muxAcquire-muxRelease, for instance.
4690 //
4691 // *  Usage:
4692 //    -- Only as leaf locks
4693 //    -- for short-term locking only as muxAcquire does not perform
4694 //       thread state transitions.
4695 //
4696 // Alternatives:
4697 // *  We could implement muxAcquire and muxRelease with MCS or CLH locks
4698 //    but with parking or spin-then-park instead of pure spinning.
4699 // *  Use Taura-Oyama-Yonenzawa locks.
4700 // *  It's possible to construct a 1-0 lock if we encode the lockword as
4701 //    (List,LockByte).  Acquire will CAS the full lockword while Release
4702 //    will STB 0 into the LockByte.  The 1-0 scheme admits stranding, so
4703 //    acquiring threads use timers (ParkTimed) to detect and recover from
4704 //    the stranding window.  Thread/Node structures must be aligned on 256-byte
4705 //    boundaries by using placement-new.
4706 // *  Augment MCS with advisory back-link fields maintained with CAS().
4707 //    Pictorially:  LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner.
4708 //    The validity of the backlinks must be ratified before we trust the value.
4709 //    If the backlinks are invalid the exiting thread must back-track through the
4710 //    the forward links, which are always trustworthy.
4711 // *  Add a successor indication.  The LockWord is currently encoded as
4712 //    (List, LOCKBIT:1).  We could also add a SUCCBIT or an explicit _succ variable
4713 //    to provide the usual futile-wakeup optimization.
4714 //    See RTStt for details.
4715 // *  Consider schedctl.sc_nopreempt to cover the critical section.
4716 //
4717 
4718 
4719 const intptr_t LOCKBIT = 1;
4720 
4721 void Thread::muxAcquire(volatile intptr_t * Lock, const char * LockName) {
4722   intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0);
4723   if (w == 0) return;
4724   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4725     return;
4726   }
4727 
4728   TEVENT(muxAcquire - Contention);
4729   ParkEvent * const Self = Thread::current()->_MuxEvent;
4730   assert((intptr_t(Self) & LOCKBIT) == 0, "invariant");
4731   for (;;) {
4732     int its = (os::is_MP() ? 100 : 0) + 1;
4733 
4734     // Optional spin phase: spin-then-park strategy
4735     while (--its >= 0) {
4736       w = *Lock;
4737       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4738         return;
4739       }
4740     }
4741 
4742     Self->reset();
4743     Self->OnList = intptr_t(Lock);
4744     // The following fence() isn't _strictly necessary as the subsequent
4745     // CAS() both serializes execution and ratifies the fetched *Lock value.
4746     OrderAccess::fence();
4747     for (;;) {
4748       w = *Lock;
4749       if ((w & LOCKBIT) == 0) {
4750         if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4751           Self->OnList = 0;   // hygiene - allows stronger asserts
4752           return;
4753         }
4754         continue;      // Interference -- *Lock changed -- Just retry
4755       }
4756       assert(w & LOCKBIT, "invariant");
4757       Self->ListNext = (ParkEvent *) (w & ~LOCKBIT);
4758       if (Atomic::cmpxchg(intptr_t(Self)|LOCKBIT, Lock, w) == w) break;
4759     }
4760 
4761     while (Self->OnList != 0) {
4762       Self->park();
4763     }
4764   }
4765 }
4766 
4767 void Thread::muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev) {
4768   intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0);
4769   if (w == 0) return;
4770   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4771     return;
4772   }
4773 
4774   TEVENT(muxAcquire - Contention);
4775   ParkEvent * ReleaseAfter = NULL;
4776   if (ev == NULL) {
4777     ev = ReleaseAfter = ParkEvent::Allocate(NULL);
4778   }
4779   assert((intptr_t(ev) & LOCKBIT) == 0, "invariant");
4780   for (;;) {
4781     guarantee(ev->OnList == 0, "invariant");
4782     int its = (os::is_MP() ? 100 : 0) + 1;
4783 
4784     // Optional spin phase: spin-then-park strategy
4785     while (--its >= 0) {
4786       w = *Lock;
4787       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4788         if (ReleaseAfter != NULL) {
4789           ParkEvent::Release(ReleaseAfter);
4790         }
4791         return;
4792       }
4793     }
4794 
4795     ev->reset();
4796     ev->OnList = intptr_t(Lock);
4797     // The following fence() isn't _strictly necessary as the subsequent
4798     // CAS() both serializes execution and ratifies the fetched *Lock value.
4799     OrderAccess::fence();
4800     for (;;) {
4801       w = *Lock;
4802       if ((w & LOCKBIT) == 0) {
4803         if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4804           ev->OnList = 0;
4805           // We call ::Release while holding the outer lock, thus
4806           // artificially lengthening the critical section.
4807           // Consider deferring the ::Release() until the subsequent unlock(),
4808           // after we've dropped the outer lock.
4809           if (ReleaseAfter != NULL) {
4810             ParkEvent::Release(ReleaseAfter);
4811           }
4812           return;
4813         }
4814         continue;      // Interference -- *Lock changed -- Just retry
4815       }
4816       assert(w & LOCKBIT, "invariant");
4817       ev->ListNext = (ParkEvent *) (w & ~LOCKBIT);
4818       if (Atomic::cmpxchg(intptr_t(ev)|LOCKBIT, Lock, w) == w) break;
4819     }
4820 
4821     while (ev->OnList != 0) {
4822       ev->park();
4823     }
4824   }
4825 }
4826 
4827 // Release() must extract a successor from the list and then wake that thread.
4828 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme
4829 // similar to that used by ParkEvent::Allocate() and ::Release().  DMR-based
4830 // Release() would :
4831 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list.
4832 // (B) Extract a successor from the private list "in-hand"
4833 // (C) attempt to CAS() the residual back into *Lock over null.
4834 //     If there were any newly arrived threads and the CAS() would fail.
4835 //     In that case Release() would detach the RATs, re-merge the list in-hand
4836 //     with the RATs and repeat as needed.  Alternately, Release() might
4837 //     detach and extract a successor, but then pass the residual list to the wakee.
4838 //     The wakee would be responsible for reattaching and remerging before it
4839 //     competed for the lock.
4840 //
4841 // Both "pop" and DMR are immune from ABA corruption -- there can be
4842 // multiple concurrent pushers, but only one popper or detacher.
4843 // This implementation pops from the head of the list.  This is unfair,
4844 // but tends to provide excellent throughput as hot threads remain hot.
4845 // (We wake recently run threads first).
4846 //
4847 // All paths through muxRelease() will execute a CAS.
4848 // Release consistency -- We depend on the CAS in muxRelease() to provide full
4849 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations
4850 // executed within the critical section are complete and globally visible before the
4851 // store (CAS) to the lock-word that releases the lock becomes globally visible.
4852 void Thread::muxRelease(volatile intptr_t * Lock)  {
4853   for (;;) {
4854     const intptr_t w = Atomic::cmpxchg((intptr_t)0, Lock, LOCKBIT);
4855     assert(w & LOCKBIT, "invariant");
4856     if (w == LOCKBIT) return;
4857     ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT);
4858     assert(List != NULL, "invariant");
4859     assert(List->OnList == intptr_t(Lock), "invariant");
4860     ParkEvent * const nxt = List->ListNext;
4861     guarantee((intptr_t(nxt) & LOCKBIT) == 0, "invariant");
4862 
4863     // The following CAS() releases the lock and pops the head element.
4864     // The CAS() also ratifies the previously fetched lock-word value.
4865     if (Atomic::cmpxchg(intptr_t(nxt), Lock, w) != w) {
4866       continue;
4867     }
4868     List->OnList = 0;
4869     OrderAccess::fence();
4870     List->unpark();
4871     return;
4872   }
4873 }
4874 
4875 
4876 void Threads::verify() {
4877   ALL_JAVA_THREADS(p) {
4878     p->verify();
4879   }
4880   VMThread* thread = VMThread::vm_thread();
4881   if (thread != NULL) thread->verify();
4882 }