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