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