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/gcLocker.inline.hpp"
  35 #include "gc/shared/workgroup.hpp"
  36 #include "interpreter/interpreter.hpp"
  37 #include "interpreter/linkResolver.hpp"
  38 #include "interpreter/oopMapCache.hpp"
  39 #include "jvmtifiles/jvmtiEnv.hpp"
  40 #include "memory/metaspaceShared.hpp"
  41 #include "memory/oopFactory.hpp"
  42 #include "memory/universe.inline.hpp"
  43 #include "oops/instanceKlass.hpp"
  44 #include "oops/objArrayOop.hpp"
  45 #include "oops/oop.inline.hpp"
  46 #include "oops/symbol.hpp"
  47 #include "oops/verifyOopClosure.hpp"
  48 #include "prims/jvm_misc.hpp"
  49 #include "prims/jvmtiExport.hpp"
  50 #include "prims/jvmtiThreadState.hpp"
  51 #include "prims/privilegedStack.hpp"
  52 #include "runtime/arguments.hpp"
  53 #include "runtime/atomic.inline.hpp"
  54 #include "runtime/biasedLocking.hpp"
  55 #include "runtime/commandLineFlagConstraintList.hpp"
  56 #include "runtime/commandLineFlagRangeList.hpp"
  57 #include "runtime/deoptimization.hpp"
  58 #include "runtime/fprofiler.hpp"
  59 #include "runtime/frame.inline.hpp"
  60 #include "runtime/globals.hpp"
  61 #include "runtime/init.hpp"
  62 #include "runtime/interfaceSupport.hpp"
  63 #include "runtime/java.hpp"
  64 #include "runtime/javaCalls.hpp"
  65 #include "runtime/jniPeriodicChecker.hpp"
  66 #include "runtime/memprofiler.hpp"
  67 #include "runtime/mutexLocker.hpp"
  68 #include "runtime/objectMonitor.hpp"
  69 #include "runtime/orderAccess.inline.hpp"
  70 #include "runtime/osThread.hpp"
  71 #include "runtime/safepoint.hpp"
  72 #include "runtime/sharedRuntime.hpp"
  73 #include "runtime/statSampler.hpp"
  74 #include "runtime/stubRoutines.hpp"
  75 #include "runtime/sweeper.hpp"
  76 #include "runtime/task.hpp"
  77 #include "runtime/thread.inline.hpp"
  78 #include "runtime/threadCritical.hpp"
  79 #include "runtime/threadLocalStorage.hpp"
  80 #include "runtime/vframe.hpp"
  81 #include "runtime/vframeArray.hpp"
  82 #include "runtime/vframe_hp.hpp"
  83 #include "runtime/vmThread.hpp"
  84 #include "runtime/vm_operations.hpp"
  85 #include "runtime/vm_version.hpp"
  86 #include "services/attachListener.hpp"
  87 #include "services/management.hpp"
  88 #include "services/memTracker.hpp"
  89 #include "services/threadService.hpp"
  90 #include "trace/traceMacros.hpp"
  91 #include "trace/tracing.hpp"
  92 #include "utilities/defaultStream.hpp"
  93 #include "utilities/dtrace.hpp"
  94 #include "utilities/events.hpp"
  95 #include "utilities/macros.hpp"
  96 #include "utilities/preserveException.hpp"
  97 #if INCLUDE_ALL_GCS
  98 #include "gc/cms/concurrentMarkSweepThread.hpp"
  99 #include "gc/g1/concurrentMarkThread.inline.hpp"
 100 #include "gc/parallel/pcTasks.hpp"
 101 #endif // INCLUDE_ALL_GCS




 102 #ifdef COMPILER1
 103 #include "c1/c1_Compiler.hpp"
 104 #endif
 105 #ifdef COMPILER2
 106 #include "opto/c2compiler.hpp"
 107 #include "opto/idealGraphPrinter.hpp"
 108 #endif
 109 #if INCLUDE_RTM_OPT
 110 #include "runtime/rtmLocking.hpp"
 111 #endif
 112 
 113 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
 114 
 115 #ifdef DTRACE_ENABLED
 116 
 117 // Only bother with this argument setup if dtrace is available
 118 
 119   #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
 120   #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
 121 
 122   #define DTRACE_THREAD_PROBE(probe, javathread)                           \
 123     {                                                                      \
 124       ResourceMark rm(this);                                               \
 125       int len = 0;                                                         \
 126       const char* name = (javathread)->get_thread_name();                  \
 127       len = strlen(name);                                                  \
 128       HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */               \
 129         (char *) name, len,                                                \
 130         java_lang_Thread::thread_id((javathread)->threadObj()),            \
 131         (uintptr_t) (javathread)->osthread()->thread_id(),                 \
 132         java_lang_Thread::is_daemon((javathread)->threadObj()));           \
 133     }
 134 
 135 #else //  ndef DTRACE_ENABLED
 136 
 137   #define DTRACE_THREAD_PROBE(probe, javathread)
 138 
 139 #endif // ndef DTRACE_ENABLED
 140 
 141 
 142 // Class hierarchy
 143 // - Thread
 144 //   - VMThread
 145 //   - WatcherThread
 146 //   - ConcurrentMarkSweepThread
 147 //   - JavaThread
 148 //     - CompilerThread
 149 
 150 // ======= Thread ========
 151 // Support for forcing alignment of thread objects for biased locking
 152 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
 153   if (UseBiasedLocking) {
 154     const int alignment = markOopDesc::biased_lock_alignment;
 155     size_t aligned_size = size + (alignment - sizeof(intptr_t));
 156     void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC)
 157                                           : AllocateHeap(aligned_size, flags, CURRENT_PC,
 158                                                          AllocFailStrategy::RETURN_NULL);
 159     void* aligned_addr     = (void*) align_size_up((intptr_t) real_malloc_addr, alignment);
 160     assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
 161            ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
 162            "JavaThread alignment code overflowed allocated storage");
 163     if (TraceBiasedLocking) {
 164       if (aligned_addr != real_malloc_addr) {
 165         tty->print_cr("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
 166                       real_malloc_addr, aligned_addr);
 167       }
 168     }
 169     ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
 170     return aligned_addr;
 171   } else {
 172     return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
 173                        : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
 174   }
 175 }
 176 
 177 void Thread::operator delete(void* p) {
 178   if (UseBiasedLocking) {
 179     void* real_malloc_addr = ((Thread*) p)->_real_malloc_address;
 180     FreeHeap(real_malloc_addr);
 181   } else {
 182     FreeHeap(p);
 183   }
 184 }
 185 
 186 
 187 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
 188 // JavaThread
 189 
 190 
 191 Thread::Thread() {
 192   // stack and get_thread
 193   set_stack_base(NULL);
 194   set_stack_size(0);
 195   set_self_raw_id(0);
 196   set_lgrp_id(-1);
 197   DEBUG_ONLY(clear_suspendible_thread();)
 198 
 199   // allocated data structures
 200   set_osthread(NULL);
 201   set_resource_area(new (mtThread)ResourceArea());
 202   DEBUG_ONLY(_current_resource_mark = NULL;)
 203   set_handle_area(new (mtThread) HandleArea(NULL));
 204   set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
 205   set_active_handles(NULL);
 206   set_free_handle_block(NULL);
 207   set_last_handle_mark(NULL);
 208 
 209   // This initial value ==> never claimed.
 210   _oops_do_parity = 0;
 211 
 212   // the handle mark links itself to last_handle_mark
 213   new HandleMark(this);
 214 
 215   // plain initialization
 216   debug_only(_owned_locks = NULL;)
 217   debug_only(_allow_allocation_count = 0;)
 218   NOT_PRODUCT(_allow_safepoint_count = 0;)
 219   NOT_PRODUCT(_skip_gcalot = false;)
 220   _jvmti_env_iteration_count = 0;
 221   set_allocated_bytes(0);
 222   _vm_operation_started_count = 0;
 223   _vm_operation_completed_count = 0;
 224   _current_pending_monitor = NULL;
 225   _current_pending_monitor_is_from_java = true;
 226   _current_waiting_monitor = NULL;
 227   _num_nested_signal = 0;
 228   omFreeList = NULL;
 229   omFreeCount = 0;
 230   omFreeProvision = 32;
 231   omInUseList = NULL;
 232   omInUseCount = 0;
 233 
 234 #ifdef ASSERT
 235   _visited_for_critical_count = false;
 236 #endif
 237 
 238   _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true,
 239                          Monitor::_safepoint_check_sometimes);
 240   _suspend_flags = 0;
 241 
 242   // thread-specific hashCode stream generator state - Marsaglia shift-xor form
 243   _hashStateX = os::random();
 244   _hashStateY = 842502087;
 245   _hashStateZ = 0x8767;    // (int)(3579807591LL & 0xffff) ;
 246   _hashStateW = 273326509;
 247 
 248   _OnTrap   = 0;
 249   _schedctl = NULL;
 250   _Stalled  = 0;
 251   _TypeTag  = 0x2BAD;
 252 
 253   // Many of the following fields are effectively final - immutable
 254   // Note that nascent threads can't use the Native Monitor-Mutex
 255   // construct until the _MutexEvent is initialized ...
 256   // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
 257   // we might instead use a stack of ParkEvents that we could provision on-demand.
 258   // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
 259   // and ::Release()
 260   _ParkEvent   = ParkEvent::Allocate(this);
 261   _SleepEvent  = ParkEvent::Allocate(this);
 262   _MutexEvent  = ParkEvent::Allocate(this);
 263   _MuxEvent    = ParkEvent::Allocate(this);
 264 
 265 #ifdef CHECK_UNHANDLED_OOPS
 266   if (CheckUnhandledOops) {
 267     _unhandled_oops = new UnhandledOops(this);
 268   }
 269 #endif // CHECK_UNHANDLED_OOPS
 270 #ifdef ASSERT
 271   if (UseBiasedLocking) {
 272     assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
 273     assert(this == _real_malloc_address ||
 274            this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
 275            "bug in forced alignment of thread objects");
 276   }
 277 #endif // ASSERT
 278 }
 279 
 280 // Non-inlined version to be used where thread.inline.hpp shouldn't be included.
 281 Thread* Thread::current_noinline() {
 282   return Thread::current();
 283 }
 284 
 285 void Thread::initialize_thread_local_storage() {
 286   // Note: Make sure this method only calls
 287   // non-blocking operations. Otherwise, it might not work
 288   // with the thread-startup/safepoint interaction.
 289 
 290   // During Java thread startup, safepoint code should allow this
 291   // method to complete because it may need to allocate memory to
 292   // store information for the new thread.
 293 
 294   // initialize structure dependent on thread local storage
 295   ThreadLocalStorage::set_thread(this);
 296 }
 297 
 298 void Thread::record_stack_base_and_size() {
 299   set_stack_base(os::current_stack_base());
 300   set_stack_size(os::current_stack_size());
 301   if (is_Java_thread()) {
 302     ((JavaThread*) this)->set_stack_overflow_limit();
 303   }
 304   // CR 7190089: on Solaris, primordial thread's stack is adjusted
 305   // in initialize_thread(). Without the adjustment, stack size is
 306   // incorrect if stack is set to unlimited (ulimit -s unlimited).
 307   // So far, only Solaris has real implementation of initialize_thread().
 308   //
 309   // set up any platform-specific state.
 310   os::initialize_thread(this);
 311 
 312 #if INCLUDE_NMT
 313   // record thread's native stack, stack grows downward
 314   address stack_low_addr = stack_base() - stack_size();
 315   MemTracker::record_thread_stack(stack_low_addr, stack_size());
 316 #endif // INCLUDE_NMT
 317 }
 318 
 319 
 320 Thread::~Thread() {
 321   // Reclaim the objectmonitors from the omFreeList of the moribund thread.
 322   ObjectSynchronizer::omFlush(this);
 323 
 324   EVENT_THREAD_DESTRUCT(this);
 325 
 326   // stack_base can be NULL if the thread is never started or exited before
 327   // record_stack_base_and_size called. Although, we would like to ensure
 328   // that all started threads do call record_stack_base_and_size(), there is
 329   // not proper way to enforce that.
 330 #if INCLUDE_NMT
 331   if (_stack_base != NULL) {
 332     address low_stack_addr = stack_base() - stack_size();
 333     MemTracker::release_thread_stack(low_stack_addr, stack_size());
 334 #ifdef ASSERT
 335     set_stack_base(NULL);
 336 #endif
 337   }
 338 #endif // INCLUDE_NMT
 339 
 340   // deallocate data structures
 341   delete resource_area();
 342   // since the handle marks are using the handle area, we have to deallocated the root
 343   // handle mark before deallocating the thread's handle area,
 344   assert(last_handle_mark() != NULL, "check we have an element");
 345   delete last_handle_mark();
 346   assert(last_handle_mark() == NULL, "check we have reached the end");
 347 
 348   // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
 349   // We NULL out the fields for good hygiene.
 350   ParkEvent::Release(_ParkEvent); _ParkEvent   = NULL;
 351   ParkEvent::Release(_SleepEvent); _SleepEvent  = NULL;
 352   ParkEvent::Release(_MutexEvent); _MutexEvent  = NULL;
 353   ParkEvent::Release(_MuxEvent); _MuxEvent    = NULL;
 354 
 355   delete handle_area();
 356   delete metadata_handles();
 357 
 358   // osthread() can be NULL, if creation of thread failed.
 359   if (osthread() != NULL) os::free_thread(osthread());
 360 
 361   delete _SR_lock;
 362 
 363   // clear thread local storage if the Thread is deleting itself
 364   if (this == Thread::current()) {
 365     ThreadLocalStorage::set_thread(NULL);
 366   } else {
 367     // In the case where we're not the current thread, invalidate all the
 368     // caches in case some code tries to get the current thread or the
 369     // thread that was destroyed, and gets stale information.
 370     ThreadLocalStorage::invalidate_all();
 371   }
 372   CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
 373 }
 374 
 375 // NOTE: dummy function for assertion purpose.
 376 void Thread::run() {
 377   ShouldNotReachHere();
 378 }
 379 
 380 #ifdef ASSERT
 381 // Private method to check for dangling thread pointer
 382 void check_for_dangling_thread_pointer(Thread *thread) {
 383   assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
 384          "possibility of dangling Thread pointer");
 385 }
 386 #endif
 387 
 388 ThreadPriority Thread::get_priority(const Thread* const thread) {
 389   ThreadPriority priority;
 390   // Can return an error!
 391   (void)os::get_priority(thread, priority);
 392   assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
 393   return priority;
 394 }
 395 
 396 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
 397   debug_only(check_for_dangling_thread_pointer(thread);)
 398   // Can return an error!
 399   (void)os::set_priority(thread, priority);
 400 }
 401 
 402 
 403 void Thread::start(Thread* thread) {
 404   // Start is different from resume in that its safety is guaranteed by context or
 405   // being called from a Java method synchronized on the Thread object.
 406   if (!DisableStartThread) {
 407     if (thread->is_Java_thread()) {
 408       // Initialize the thread state to RUNNABLE before starting this thread.
 409       // Can not set it after the thread started because we do not know the
 410       // exact thread state at that time. It could be in MONITOR_WAIT or
 411       // in SLEEPING or some other state.
 412       java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
 413                                           java_lang_Thread::RUNNABLE);
 414     }
 415     os::start_thread(thread);
 416   }
 417 }
 418 
 419 // Enqueue a VM_Operation to do the job for us - sometime later
 420 void Thread::send_async_exception(oop java_thread, oop java_throwable) {
 421   VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable);
 422   VMThread::execute(vm_stop);
 423 }
 424 
 425 
 426 // Check if an external suspend request has completed (or has been
 427 // cancelled). Returns true if the thread is externally suspended and
 428 // false otherwise.
 429 //
 430 // The bits parameter returns information about the code path through
 431 // the routine. Useful for debugging:
 432 //
 433 // set in is_ext_suspend_completed():
 434 // 0x00000001 - routine was entered
 435 // 0x00000010 - routine return false at end
 436 // 0x00000100 - thread exited (return false)
 437 // 0x00000200 - suspend request cancelled (return false)
 438 // 0x00000400 - thread suspended (return true)
 439 // 0x00001000 - thread is in a suspend equivalent state (return true)
 440 // 0x00002000 - thread is native and walkable (return true)
 441 // 0x00004000 - thread is native_trans and walkable (needed retry)
 442 //
 443 // set in wait_for_ext_suspend_completion():
 444 // 0x00010000 - routine was entered
 445 // 0x00020000 - suspend request cancelled before loop (return false)
 446 // 0x00040000 - thread suspended before loop (return true)
 447 // 0x00080000 - suspend request cancelled in loop (return false)
 448 // 0x00100000 - thread suspended in loop (return true)
 449 // 0x00200000 - suspend not completed during retry loop (return false)
 450 
 451 // Helper class for tracing suspend wait debug bits.
 452 //
 453 // 0x00000100 indicates that the target thread exited before it could
 454 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
 455 // 0x00080000 each indicate a cancelled suspend request so they don't
 456 // count as wait failures either.
 457 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000)
 458 
 459 class TraceSuspendDebugBits : public StackObj {
 460  private:
 461   JavaThread * jt;
 462   bool         is_wait;
 463   bool         called_by_wait;  // meaningful when !is_wait
 464   uint32_t *   bits;
 465 
 466  public:
 467   TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait,
 468                         uint32_t *_bits) {
 469     jt             = _jt;
 470     is_wait        = _is_wait;
 471     called_by_wait = _called_by_wait;
 472     bits           = _bits;
 473   }
 474 
 475   ~TraceSuspendDebugBits() {
 476     if (!is_wait) {
 477 #if 1
 478       // By default, don't trace bits for is_ext_suspend_completed() calls.
 479       // That trace is very chatty.
 480       return;
 481 #else
 482       if (!called_by_wait) {
 483         // If tracing for is_ext_suspend_completed() is enabled, then only
 484         // trace calls to it from wait_for_ext_suspend_completion()
 485         return;
 486       }
 487 #endif
 488     }
 489 
 490     if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) {
 491       if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) {
 492         MutexLocker ml(Threads_lock);  // needed for get_thread_name()
 493         ResourceMark rm;
 494 
 495         tty->print_cr(
 496                       "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
 497                       jt->get_thread_name(), *bits);
 498 
 499         guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed");
 500       }
 501     }
 502   }
 503 };
 504 #undef DEBUG_FALSE_BITS
 505 
 506 
 507 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay,
 508                                           uint32_t *bits) {
 509   TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
 510 
 511   bool did_trans_retry = false;  // only do thread_in_native_trans retry once
 512   bool do_trans_retry;           // flag to force the retry
 513 
 514   *bits |= 0x00000001;
 515 
 516   do {
 517     do_trans_retry = false;
 518 
 519     if (is_exiting()) {
 520       // Thread is in the process of exiting. This is always checked
 521       // first to reduce the risk of dereferencing a freed JavaThread.
 522       *bits |= 0x00000100;
 523       return false;
 524     }
 525 
 526     if (!is_external_suspend()) {
 527       // Suspend request is cancelled. This is always checked before
 528       // is_ext_suspended() to reduce the risk of a rogue resume
 529       // confusing the thread that made the suspend request.
 530       *bits |= 0x00000200;
 531       return false;
 532     }
 533 
 534     if (is_ext_suspended()) {
 535       // thread is suspended
 536       *bits |= 0x00000400;
 537       return true;
 538     }
 539 
 540     // Now that we no longer do hard suspends of threads running
 541     // native code, the target thread can be changing thread state
 542     // while we are in this routine:
 543     //
 544     //   _thread_in_native -> _thread_in_native_trans -> _thread_blocked
 545     //
 546     // We save a copy of the thread state as observed at this moment
 547     // and make our decision about suspend completeness based on the
 548     // copy. This closes the race where the thread state is seen as
 549     // _thread_in_native_trans in the if-thread_blocked check, but is
 550     // seen as _thread_blocked in if-thread_in_native_trans check.
 551     JavaThreadState save_state = thread_state();
 552 
 553     if (save_state == _thread_blocked && is_suspend_equivalent()) {
 554       // If the thread's state is _thread_blocked and this blocking
 555       // condition is known to be equivalent to a suspend, then we can
 556       // consider the thread to be externally suspended. This means that
 557       // the code that sets _thread_blocked has been modified to do
 558       // self-suspension if the blocking condition releases. We also
 559       // used to check for CONDVAR_WAIT here, but that is now covered by
 560       // the _thread_blocked with self-suspension check.
 561       //
 562       // Return true since we wouldn't be here unless there was still an
 563       // external suspend request.
 564       *bits |= 0x00001000;
 565       return true;
 566     } else if (save_state == _thread_in_native && frame_anchor()->walkable()) {
 567       // Threads running native code will self-suspend on native==>VM/Java
 568       // transitions. If its stack is walkable (should always be the case
 569       // unless this function is called before the actual java_suspend()
 570       // call), then the wait is done.
 571       *bits |= 0x00002000;
 572       return true;
 573     } else if (!called_by_wait && !did_trans_retry &&
 574                save_state == _thread_in_native_trans &&
 575                frame_anchor()->walkable()) {
 576       // The thread is transitioning from thread_in_native to another
 577       // thread state. check_safepoint_and_suspend_for_native_trans()
 578       // will force the thread to self-suspend. If it hasn't gotten
 579       // there yet we may have caught the thread in-between the native
 580       // code check above and the self-suspend. Lucky us. If we were
 581       // called by wait_for_ext_suspend_completion(), then it
 582       // will be doing the retries so we don't have to.
 583       //
 584       // Since we use the saved thread state in the if-statement above,
 585       // there is a chance that the thread has already transitioned to
 586       // _thread_blocked by the time we get here. In that case, we will
 587       // make a single unnecessary pass through the logic below. This
 588       // doesn't hurt anything since we still do the trans retry.
 589 
 590       *bits |= 0x00004000;
 591 
 592       // Once the thread leaves thread_in_native_trans for another
 593       // thread state, we break out of this retry loop. We shouldn't
 594       // need this flag to prevent us from getting back here, but
 595       // sometimes paranoia is good.
 596       did_trans_retry = true;
 597 
 598       // We wait for the thread to transition to a more usable state.
 599       for (int i = 1; i <= SuspendRetryCount; i++) {
 600         // We used to do an "os::yield_all(i)" call here with the intention
 601         // that yielding would increase on each retry. However, the parameter
 602         // is ignored on Linux which means the yield didn't scale up. Waiting
 603         // on the SR_lock below provides a much more predictable scale up for
 604         // the delay. It also provides a simple/direct point to check for any
 605         // safepoint requests from the VMThread
 606 
 607         // temporarily drops SR_lock while doing wait with safepoint check
 608         // (if we're a JavaThread - the WatcherThread can also call this)
 609         // and increase delay with each retry
 610         SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
 611 
 612         // check the actual thread state instead of what we saved above
 613         if (thread_state() != _thread_in_native_trans) {
 614           // the thread has transitioned to another thread state so
 615           // try all the checks (except this one) one more time.
 616           do_trans_retry = true;
 617           break;
 618         }
 619       } // end retry loop
 620 
 621 
 622     }
 623   } while (do_trans_retry);
 624 
 625   *bits |= 0x00000010;
 626   return false;
 627 }
 628 
 629 // Wait for an external suspend request to complete (or be cancelled).
 630 // Returns true if the thread is externally suspended and false otherwise.
 631 //
 632 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
 633                                                  uint32_t *bits) {
 634   TraceSuspendDebugBits tsdb(this, true /* is_wait */,
 635                              false /* !called_by_wait */, bits);
 636 
 637   // local flag copies to minimize SR_lock hold time
 638   bool is_suspended;
 639   bool pending;
 640   uint32_t reset_bits;
 641 
 642   // set a marker so is_ext_suspend_completed() knows we are the caller
 643   *bits |= 0x00010000;
 644 
 645   // We use reset_bits to reinitialize the bits value at the top of
 646   // each retry loop. This allows the caller to make use of any
 647   // unused bits for their own marking purposes.
 648   reset_bits = *bits;
 649 
 650   {
 651     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
 652     is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
 653                                             delay, bits);
 654     pending = is_external_suspend();
 655   }
 656   // must release SR_lock to allow suspension to complete
 657 
 658   if (!pending) {
 659     // A cancelled suspend request is the only false return from
 660     // is_ext_suspend_completed() that keeps us from entering the
 661     // retry loop.
 662     *bits |= 0x00020000;
 663     return false;
 664   }
 665 
 666   if (is_suspended) {
 667     *bits |= 0x00040000;
 668     return true;
 669   }
 670 
 671   for (int i = 1; i <= retries; i++) {
 672     *bits = reset_bits;  // reinit to only track last retry
 673 
 674     // We used to do an "os::yield_all(i)" call here with the intention
 675     // that yielding would increase on each retry. However, the parameter
 676     // is ignored on Linux which means the yield didn't scale up. Waiting
 677     // on the SR_lock below provides a much more predictable scale up for
 678     // the delay. It also provides a simple/direct point to check for any
 679     // safepoint requests from the VMThread
 680 
 681     {
 682       MutexLocker ml(SR_lock());
 683       // wait with safepoint check (if we're a JavaThread - the WatcherThread
 684       // can also call this)  and increase delay with each retry
 685       SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
 686 
 687       is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
 688                                               delay, bits);
 689 
 690       // It is possible for the external suspend request to be cancelled
 691       // (by a resume) before the actual suspend operation is completed.
 692       // Refresh our local copy to see if we still need to wait.
 693       pending = is_external_suspend();
 694     }
 695 
 696     if (!pending) {
 697       // A cancelled suspend request is the only false return from
 698       // is_ext_suspend_completed() that keeps us from staying in the
 699       // retry loop.
 700       *bits |= 0x00080000;
 701       return false;
 702     }
 703 
 704     if (is_suspended) {
 705       *bits |= 0x00100000;
 706       return true;
 707     }
 708   } // end retry loop
 709 
 710   // thread did not suspend after all our retries
 711   *bits |= 0x00200000;
 712   return false;
 713 }
 714 
 715 #ifndef PRODUCT
 716 void JavaThread::record_jump(address target, address instr, const char* file,
 717                              int line) {
 718 
 719   // This should not need to be atomic as the only way for simultaneous
 720   // updates is via interrupts. Even then this should be rare or non-existent
 721   // and we don't care that much anyway.
 722 
 723   int index = _jmp_ring_index;
 724   _jmp_ring_index = (index + 1) & (jump_ring_buffer_size - 1);
 725   _jmp_ring[index]._target = (intptr_t) target;
 726   _jmp_ring[index]._instruction = (intptr_t) instr;
 727   _jmp_ring[index]._file = file;
 728   _jmp_ring[index]._line = line;
 729 }
 730 #endif // PRODUCT
 731 
 732 // Called by flat profiler
 733 // Callers have already called wait_for_ext_suspend_completion
 734 // The assertion for that is currently too complex to put here:
 735 bool JavaThread::profile_last_Java_frame(frame* _fr) {
 736   bool gotframe = false;
 737   // self suspension saves needed state.
 738   if (has_last_Java_frame() && _anchor.walkable()) {
 739     *_fr = pd_last_frame();
 740     gotframe = true;
 741   }
 742   return gotframe;
 743 }
 744 
 745 void Thread::interrupt(Thread* thread) {
 746   debug_only(check_for_dangling_thread_pointer(thread);)
 747   os::interrupt(thread);
 748 }
 749 
 750 bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) {
 751   debug_only(check_for_dangling_thread_pointer(thread);)
 752   // Note:  If clear_interrupted==false, this simply fetches and
 753   // returns the value of the field osthread()->interrupted().
 754   return os::is_interrupted(thread, clear_interrupted);
 755 }
 756 
 757 
 758 // GC Support
 759 bool Thread::claim_oops_do_par_case(int strong_roots_parity) {
 760   jint thread_parity = _oops_do_parity;
 761   if (thread_parity != strong_roots_parity) {
 762     jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity);
 763     if (res == thread_parity) {
 764       return true;
 765     } else {
 766       guarantee(res == strong_roots_parity, "Or else what?");
 767       return false;
 768     }
 769   }
 770   return false;
 771 }
 772 
 773 void Thread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
 774   active_handles()->oops_do(f);
 775   // Do oop for ThreadShadow
 776   f->do_oop((oop*)&_pending_exception);
 777   handle_area()->oops_do(f);
 778 }
 779 
 780 void Thread::nmethods_do(CodeBlobClosure* cf) {
 781   // no nmethods in a generic thread...
 782 }
 783 
 784 void Thread::metadata_handles_do(void f(Metadata*)) {
 785   // Only walk the Handles in Thread.
 786   if (metadata_handles() != NULL) {
 787     for (int i = 0; i< metadata_handles()->length(); i++) {
 788       f(metadata_handles()->at(i));
 789     }
 790   }
 791 }
 792 
 793 void Thread::print_on(outputStream* st) const {
 794   // get_priority assumes osthread initialized
 795   if (osthread() != NULL) {
 796     int os_prio;
 797     if (os::get_native_priority(this, &os_prio) == OS_OK) {
 798       st->print("os_prio=%d ", os_prio);
 799     }
 800     st->print("tid=" INTPTR_FORMAT " ", this);
 801     ext().print_on(st);
 802     osthread()->print_on(st);
 803   }
 804   debug_only(if (WizardMode) print_owned_locks_on(st);)
 805 }
 806 
 807 // Thread::print_on_error() is called by fatal error handler. Don't use
 808 // any lock or allocate memory.
 809 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
 810   if (is_VM_thread())                 st->print("VMThread");
 811   else if (is_Compiler_thread())      st->print("CompilerThread");
 812   else if (is_Java_thread())          st->print("JavaThread");
 813   else if (is_GC_task_thread())       st->print("GCTaskThread");
 814   else if (is_Watcher_thread())       st->print("WatcherThread");
 815   else if (is_ConcurrentGC_thread())  st->print("ConcurrentGCThread");
 816   else                                st->print("Thread");
 817 
 818   st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
 819             _stack_base - _stack_size, _stack_base);
 820 
 821   if (osthread()) {
 822     st->print(" [id=%d]", osthread()->thread_id());
 823   }
 824 }
 825 
 826 #ifdef ASSERT
 827 void Thread::print_owned_locks_on(outputStream* st) const {
 828   Monitor *cur = _owned_locks;
 829   if (cur == NULL) {
 830     st->print(" (no locks) ");
 831   } else {
 832     st->print_cr(" Locks owned:");
 833     while (cur) {
 834       cur->print_on(st);
 835       cur = cur->next();
 836     }
 837   }
 838 }
 839 
 840 static int ref_use_count  = 0;
 841 
 842 bool Thread::owns_locks_but_compiled_lock() const {
 843   for (Monitor *cur = _owned_locks; cur; cur = cur->next()) {
 844     if (cur != Compile_lock) return true;
 845   }
 846   return false;
 847 }
 848 
 849 
 850 #endif
 851 
 852 #ifndef PRODUCT
 853 
 854 // The flag: potential_vm_operation notifies if this particular safepoint state could potential
 855 // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that
 856 // no threads which allow_vm_block's are held
 857 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
 858   // Check if current thread is allowed to block at a safepoint
 859   if (!(_allow_safepoint_count == 0)) {
 860     fatal("Possible safepoint reached by thread that does not allow it");
 861   }
 862   if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
 863     fatal("LEAF method calling lock?");
 864   }
 865 
 866 #ifdef ASSERT
 867   if (potential_vm_operation && is_Java_thread()
 868       && !Universe::is_bootstrapping()) {
 869     // Make sure we do not hold any locks that the VM thread also uses.
 870     // This could potentially lead to deadlocks
 871     for (Monitor *cur = _owned_locks; cur; cur = cur->next()) {
 872       // Threads_lock is special, since the safepoint synchronization will not start before this is
 873       // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock,
 874       // since it is used to transfer control between JavaThreads and the VMThread
 875       // Do not *exclude* any locks unless you are absolutely sure it is correct. Ask someone else first!
 876       if ((cur->allow_vm_block() &&
 877            cur != Threads_lock &&
 878            cur != Compile_lock &&               // Temporary: should not be necessary when we get separate compilation
 879            cur != VMOperationRequest_lock &&
 880            cur != VMOperationQueue_lock) ||
 881            cur->rank() == Mutex::special) {
 882         fatal(err_msg("Thread holding lock at safepoint that vm can block on: %s", cur->name()));
 883       }
 884     }
 885   }
 886 
 887   if (GCALotAtAllSafepoints) {
 888     // We could enter a safepoint here and thus have a gc
 889     InterfaceSupport::check_gc_alot();
 890   }
 891 #endif
 892 }
 893 #endif
 894 
 895 bool Thread::is_in_stack(address adr) const {
 896   assert(Thread::current() == this, "is_in_stack can only be called from current thread");
 897   address end = os::current_stack_pointer();
 898   // Allow non Java threads to call this without stack_base
 899   if (_stack_base == NULL) return true;
 900   if (stack_base() >= adr && adr >= end) return true;
 901 
 902   return false;
 903 }
 904 
 905 
 906 bool Thread::is_in_usable_stack(address adr) const {
 907   size_t stack_guard_size = os::uses_stack_guard_pages() ? (StackYellowPages + StackRedPages) * os::vm_page_size() : 0;
 908   size_t usable_stack_size = _stack_size - stack_guard_size;
 909 
 910   return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size));
 911 }
 912 
 913 
 914 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
 915 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
 916 // used for compilation in the future. If that change is made, the need for these methods
 917 // should be revisited, and they should be removed if possible.
 918 
 919 bool Thread::is_lock_owned(address adr) const {
 920   return on_local_stack(adr);
 921 }
 922 
 923 bool Thread::set_as_starting_thread() {
 924   // NOTE: this must be called inside the main thread.
 925   return os::create_main_thread((JavaThread*)this);
 926 }
 927 
 928 static void initialize_class(Symbol* class_name, TRAPS) {
 929   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
 930   InstanceKlass::cast(klass)->initialize(CHECK);
 931 }
 932 
 933 
 934 // Creates the initial ThreadGroup
 935 static Handle create_initial_thread_group(TRAPS) {
 936   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ThreadGroup(), true, CHECK_NH);
 937   instanceKlassHandle klass (THREAD, k);
 938 
 939   Handle system_instance = klass->allocate_instance_handle(CHECK_NH);
 940   {
 941     JavaValue result(T_VOID);
 942     JavaCalls::call_special(&result,
 943                             system_instance,
 944                             klass,
 945                             vmSymbols::object_initializer_name(),
 946                             vmSymbols::void_method_signature(),
 947                             CHECK_NH);
 948   }
 949   Universe::set_system_thread_group(system_instance());
 950 
 951   Handle main_instance = klass->allocate_instance_handle(CHECK_NH);
 952   {
 953     JavaValue result(T_VOID);
 954     Handle string = java_lang_String::create_from_str("main", CHECK_NH);
 955     JavaCalls::call_special(&result,
 956                             main_instance,
 957                             klass,
 958                             vmSymbols::object_initializer_name(),
 959                             vmSymbols::threadgroup_string_void_signature(),
 960                             system_instance,
 961                             string,
 962                             CHECK_NH);
 963   }
 964   return main_instance;
 965 }
 966 
 967 // Creates the initial Thread
 968 static oop create_initial_thread(Handle thread_group, JavaThread* thread,
 969                                  TRAPS) {
 970   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_NULL);
 971   instanceKlassHandle klass (THREAD, k);
 972   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL);
 973 
 974   java_lang_Thread::set_thread(thread_oop(), thread);
 975   java_lang_Thread::set_priority(thread_oop(), NormPriority);
 976   thread->set_threadObj(thread_oop());
 977 
 978   Handle string = java_lang_String::create_from_str("main", CHECK_NULL);
 979 
 980   JavaValue result(T_VOID);
 981   JavaCalls::call_special(&result, thread_oop,
 982                           klass,
 983                           vmSymbols::object_initializer_name(),
 984                           vmSymbols::threadgroup_string_void_signature(),
 985                           thread_group,
 986                           string,
 987                           CHECK_NULL);
 988   return thread_oop();
 989 }
 990 
 991 static void call_initializeSystemClass(TRAPS) {
 992   Klass* k =  SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
 993   instanceKlassHandle klass (THREAD, k);
 994 
 995   JavaValue result(T_VOID);
 996   JavaCalls::call_static(&result, klass, vmSymbols::initializeSystemClass_name(),
 997                          vmSymbols::void_method_signature(), CHECK);
 998 }
 999 
1000 char java_runtime_name[128] = "";
1001 char java_runtime_version[128] = "";
1002 
1003 // extract the JRE name from sun.misc.Version.java_runtime_name
1004 static const char* get_java_runtime_name(TRAPS) {
1005   Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(),
1006                                     Handle(), Handle(), CHECK_AND_CLEAR_NULL);
1007   fieldDescriptor fd;
1008   bool found = k != NULL &&
1009                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(),
1010                                                         vmSymbols::string_signature(), &fd);
1011   if (found) {
1012     oop name_oop = k->java_mirror()->obj_field(fd.offset());
1013     if (name_oop == NULL) {
1014       return NULL;
1015     }
1016     const char* name = java_lang_String::as_utf8_string(name_oop,
1017                                                         java_runtime_name,
1018                                                         sizeof(java_runtime_name));
1019     return name;
1020   } else {
1021     return NULL;
1022   }
1023 }
1024 
1025 // extract the JRE version from sun.misc.Version.java_runtime_version
1026 static const char* get_java_runtime_version(TRAPS) {
1027   Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(),
1028                                     Handle(), Handle(), CHECK_AND_CLEAR_NULL);
1029   fieldDescriptor fd;
1030   bool found = k != NULL &&
1031                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(),
1032                                                         vmSymbols::string_signature(), &fd);
1033   if (found) {
1034     oop name_oop = k->java_mirror()->obj_field(fd.offset());
1035     if (name_oop == NULL) {
1036       return NULL;
1037     }
1038     const char* name = java_lang_String::as_utf8_string(name_oop,
1039                                                         java_runtime_version,
1040                                                         sizeof(java_runtime_version));
1041     return name;
1042   } else {
1043     return NULL;
1044   }
1045 }
1046 
1047 // General purpose hook into Java code, run once when the VM is initialized.
1048 // The Java library method itself may be changed independently from the VM.
1049 static void call_postVMInitHook(TRAPS) {
1050   Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_PostVMInitHook(), THREAD);
1051   instanceKlassHandle klass (THREAD, k);
1052   if (klass.not_null()) {
1053     JavaValue result(T_VOID);
1054     JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
1055                            vmSymbols::void_method_signature(),
1056                            CHECK);
1057   }
1058 }
1059 
1060 static void reset_vm_info_property(TRAPS) {
1061   // the vm info string
1062   ResourceMark rm(THREAD);
1063   const char *vm_info = VM_Version::vm_info_string();
1064 
1065   // java.lang.System class
1066   Klass* k =  SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
1067   instanceKlassHandle klass (THREAD, k);
1068 
1069   // setProperty arguments
1070   Handle key_str    = java_lang_String::create_from_str("java.vm.info", CHECK);
1071   Handle value_str  = java_lang_String::create_from_str(vm_info, CHECK);
1072 
1073   // return value
1074   JavaValue r(T_OBJECT);
1075 
1076   // public static String setProperty(String key, String value);
1077   JavaCalls::call_static(&r,
1078                          klass,
1079                          vmSymbols::setProperty_name(),
1080                          vmSymbols::string_string_string_signature(),
1081                          key_str,
1082                          value_str,
1083                          CHECK);
1084 }
1085 
1086 
1087 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
1088                                     bool daemon, TRAPS) {
1089   assert(thread_group.not_null(), "thread group should be specified");
1090   assert(threadObj() == NULL, "should only create Java thread object once");
1091 
1092   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
1093   instanceKlassHandle klass (THREAD, k);
1094   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
1095 
1096   java_lang_Thread::set_thread(thread_oop(), this);
1097   java_lang_Thread::set_priority(thread_oop(), NormPriority);
1098   set_threadObj(thread_oop());
1099 
1100   JavaValue result(T_VOID);
1101   if (thread_name != NULL) {
1102     Handle name = java_lang_String::create_from_str(thread_name, CHECK);
1103     // Thread gets assigned specified name and null target
1104     JavaCalls::call_special(&result,
1105                             thread_oop,
1106                             klass,
1107                             vmSymbols::object_initializer_name(),
1108                             vmSymbols::threadgroup_string_void_signature(),
1109                             thread_group, // Argument 1
1110                             name,         // Argument 2
1111                             THREAD);
1112   } else {
1113     // Thread gets assigned name "Thread-nnn" and null target
1114     // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
1115     JavaCalls::call_special(&result,
1116                             thread_oop,
1117                             klass,
1118                             vmSymbols::object_initializer_name(),
1119                             vmSymbols::threadgroup_runnable_void_signature(),
1120                             thread_group, // Argument 1
1121                             Handle(),     // Argument 2
1122                             THREAD);
1123   }
1124 
1125 
1126   if (daemon) {
1127     java_lang_Thread::set_daemon(thread_oop());
1128   }
1129 
1130   if (HAS_PENDING_EXCEPTION) {
1131     return;
1132   }
1133 
1134   KlassHandle group(THREAD, SystemDictionary::ThreadGroup_klass());
1135   Handle threadObj(THREAD, this->threadObj());
1136 
1137   JavaCalls::call_special(&result,
1138                           thread_group,
1139                           group,
1140                           vmSymbols::add_method_name(),
1141                           vmSymbols::thread_void_signature(),
1142                           threadObj,          // Arg 1
1143                           THREAD);
1144 }
1145 
1146 // NamedThread --  non-JavaThread subclasses with multiple
1147 // uniquely named instances should derive from this.
1148 NamedThread::NamedThread() : Thread() {
1149   _name = NULL;
1150   _processed_thread = NULL;
1151 }
1152 
1153 NamedThread::~NamedThread() {
1154   if (_name != NULL) {
1155     FREE_C_HEAP_ARRAY(char, _name);
1156     _name = NULL;
1157   }
1158 }
1159 
1160 void NamedThread::set_name(const char* format, ...) {
1161   guarantee(_name == NULL, "Only get to set name once.");
1162   _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
1163   guarantee(_name != NULL, "alloc failure");
1164   va_list ap;
1165   va_start(ap, format);
1166   jio_vsnprintf(_name, max_name_len, format, ap);
1167   va_end(ap);
1168 }
1169 
1170 void NamedThread::initialize_named_thread() {
1171   set_native_thread_name(name());
1172 }
1173 
1174 void NamedThread::print_on(outputStream* st) const {
1175   st->print("\"%s\" ", name());
1176   Thread::print_on(st);
1177   st->cr();
1178 }
1179 
1180 
1181 // ======= WatcherThread ========
1182 
1183 // The watcher thread exists to simulate timer interrupts.  It should
1184 // be replaced by an abstraction over whatever native support for
1185 // timer interrupts exists on the platform.
1186 
1187 WatcherThread* WatcherThread::_watcher_thread   = NULL;
1188 bool WatcherThread::_startable = false;
1189 volatile bool  WatcherThread::_should_terminate = false;
1190 
1191 WatcherThread::WatcherThread() : Thread(), _crash_protection(NULL) {
1192   assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
1193   if (os::create_thread(this, os::watcher_thread)) {
1194     _watcher_thread = this;
1195 
1196     // Set the watcher thread to the highest OS priority which should not be
1197     // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY
1198     // is created. The only normal thread using this priority is the reference
1199     // handler thread, which runs for very short intervals only.
1200     // If the VMThread's priority is not lower than the WatcherThread profiling
1201     // will be inaccurate.
1202     os::set_priority(this, MaxPriority);
1203     if (!DisableStartThread) {
1204       os::start_thread(this);
1205     }
1206   }
1207 }
1208 
1209 int WatcherThread::sleep() const {
1210   // The WatcherThread does not participate in the safepoint protocol
1211   // for the PeriodicTask_lock because it is not a JavaThread.
1212   MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
1213 
1214   if (_should_terminate) {
1215     // check for termination before we do any housekeeping or wait
1216     return 0;  // we did not sleep.
1217   }
1218 
1219   // remaining will be zero if there are no tasks,
1220   // causing the WatcherThread to sleep until a task is
1221   // enrolled
1222   int remaining = PeriodicTask::time_to_wait();
1223   int time_slept = 0;
1224 
1225   // we expect this to timeout - we only ever get unparked when
1226   // we should terminate or when a new task has been enrolled
1227   OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
1228 
1229   jlong time_before_loop = os::javaTimeNanos();
1230 
1231   while (true) {
1232     bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag,
1233                                             remaining);
1234     jlong now = os::javaTimeNanos();
1235 
1236     if (remaining == 0) {
1237       // if we didn't have any tasks we could have waited for a long time
1238       // consider the time_slept zero and reset time_before_loop
1239       time_slept = 0;
1240       time_before_loop = now;
1241     } else {
1242       // need to recalculate since we might have new tasks in _tasks
1243       time_slept = (int) ((now - time_before_loop) / 1000000);
1244     }
1245 
1246     // Change to task list or spurious wakeup of some kind
1247     if (timedout || _should_terminate) {
1248       break;
1249     }
1250 
1251     remaining = PeriodicTask::time_to_wait();
1252     if (remaining == 0) {
1253       // Last task was just disenrolled so loop around and wait until
1254       // another task gets enrolled
1255       continue;
1256     }
1257 
1258     remaining -= time_slept;
1259     if (remaining <= 0) {
1260       break;
1261     }
1262   }
1263 
1264   return time_slept;
1265 }
1266 
1267 void WatcherThread::run() {
1268   assert(this == watcher_thread(), "just checking");
1269 
1270   this->record_stack_base_and_size();
1271   this->initialize_thread_local_storage();
1272   this->set_native_thread_name(this->name());
1273   this->set_active_handles(JNIHandleBlock::allocate_block());
1274   while (true) {
1275     assert(watcher_thread() == Thread::current(), "thread consistency check");
1276     assert(watcher_thread() == this, "thread consistency check");
1277 
1278     // Calculate how long it'll be until the next PeriodicTask work
1279     // should be done, and sleep that amount of time.
1280     int time_waited = sleep();
1281 
1282     if (is_error_reported()) {
1283       // A fatal error has happened, the error handler(VMError::report_and_die)
1284       // should abort JVM after creating an error log file. However in some
1285       // rare cases, the error handler itself might deadlock. Here we try to
1286       // kill JVM if the fatal error handler fails to abort in 2 minutes.
1287       //
1288       // This code is in WatcherThread because WatcherThread wakes up
1289       // periodically so the fatal error handler doesn't need to do anything;
1290       // also because the WatcherThread is less likely to crash than other
1291       // threads.
1292 
1293       for (;;) {
1294         if (!ShowMessageBoxOnError
1295             && (OnError == NULL || OnError[0] == '\0')
1296             && Arguments::abort_hook() == NULL) {
1297           os::sleep(this, ErrorLogTimeout * 60 * 1000, false);
1298           fdStream err(defaultStream::output_fd());
1299           err.print_raw_cr("# [ timer expired, abort... ]");
1300           // skip atexit/vm_exit/vm_abort hooks
1301           os::die();
1302         }
1303 
1304         // Wake up 5 seconds later, the fatal handler may reset OnError or
1305         // ShowMessageBoxOnError when it is ready to abort.
1306         os::sleep(this, 5 * 1000, false);
1307       }
1308     }
1309 
1310     if (_should_terminate) {
1311       // check for termination before posting the next tick
1312       break;
1313     }
1314 
1315     PeriodicTask::real_time_tick(time_waited);
1316   }
1317 
1318   // Signal that it is terminated
1319   {
1320     MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag);
1321     _watcher_thread = NULL;
1322     Terminator_lock->notify();
1323   }
1324 
1325   // Thread destructor usually does this..
1326   ThreadLocalStorage::set_thread(NULL);
1327 }
1328 
1329 void WatcherThread::start() {
1330   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1331 
1332   if (watcher_thread() == NULL && _startable) {
1333     _should_terminate = false;
1334     // Create the single instance of WatcherThread
1335     new WatcherThread();
1336   }
1337 }
1338 
1339 void WatcherThread::make_startable() {
1340   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1341   _startable = true;
1342 }
1343 
1344 void WatcherThread::stop() {
1345   {
1346     // Follow normal safepoint aware lock enter protocol since the
1347     // WatcherThread is stopped by another JavaThread.
1348     MutexLocker ml(PeriodicTask_lock);
1349     _should_terminate = true;
1350 
1351     WatcherThread* watcher = watcher_thread();
1352     if (watcher != NULL) {
1353       // unpark the WatcherThread so it can see that it should terminate
1354       watcher->unpark();
1355     }
1356   }
1357 
1358   MutexLocker mu(Terminator_lock);
1359 
1360   while (watcher_thread() != NULL) {
1361     // This wait should make safepoint checks, wait without a timeout,
1362     // and wait as a suspend-equivalent condition.
1363     //
1364     // Note: If the FlatProfiler is running, then this thread is waiting
1365     // for the WatcherThread to terminate and the WatcherThread, via the
1366     // FlatProfiler task, is waiting for the external suspend request on
1367     // this thread to complete. wait_for_ext_suspend_completion() will
1368     // eventually timeout, but that takes time. Making this wait a
1369     // suspend-equivalent condition solves that timeout problem.
1370     //
1371     Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
1372                           Mutex::_as_suspend_equivalent_flag);
1373   }
1374 }
1375 
1376 void WatcherThread::unpark() {
1377   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1378   PeriodicTask_lock->notify();
1379 }
1380 
1381 void WatcherThread::print_on(outputStream* st) const {
1382   st->print("\"%s\" ", name());
1383   Thread::print_on(st);
1384   st->cr();
1385 }
1386 
1387 // ======= JavaThread ========
1388 



























1389 // A JavaThread is a normal Java thread
1390 
1391 void JavaThread::initialize() {
1392   // Initialize fields
1393 
1394   // Set the claimed par_id to UINT_MAX (ie not claiming any par_ids)
1395   set_claimed_par_id(UINT_MAX);
1396 
1397   set_saved_exception_pc(NULL);
1398   set_threadObj(NULL);
1399   _anchor.clear();
1400   set_entry_point(NULL);
1401   set_jni_functions(jni_functions());
1402   set_callee_target(NULL);
1403   set_vm_result(NULL);
1404   set_vm_result_2(NULL);
1405   set_vframe_array_head(NULL);
1406   set_vframe_array_last(NULL);
1407   set_deferred_locals(NULL);
1408   set_deopt_mark(NULL);
1409   set_deopt_nmethod(NULL);
1410   clear_must_deopt_id();
1411   set_monitor_chunks(NULL);
1412   set_next(NULL);
1413   set_thread_state(_thread_new);
1414   _terminated = _not_terminated;
1415   _privileged_stack_top = NULL;
1416   _array_for_gc = NULL;
1417   _suspend_equivalent = false;
1418   _in_deopt_handler = 0;
1419   _doing_unsafe_access = false;
1420   _stack_guard_state = stack_guard_unused;














1421   (void)const_cast<oop&>(_exception_oop = oop(NULL));
1422   _exception_pc  = 0;
1423   _exception_handler_pc = 0;
1424   _is_method_handle_return = 0;
1425   _jvmti_thread_state= NULL;
1426   _should_post_on_exceptions_flag = JNI_FALSE;
1427   _jvmti_get_loaded_classes_closure = NULL;
1428   _interp_only_mode    = 0;
1429   _special_runtime_exit_condition = _no_async_condition;
1430   _pending_async_exception = NULL;
1431   _thread_stat = NULL;
1432   _thread_stat = new ThreadStatistics();
1433   _blocked_on_compilation = false;
1434   _jni_active_critical = 0;
1435   _pending_jni_exception_check_fn = NULL;
1436   _do_not_unlock_if_synchronized = false;
1437   _cached_monitor_info = NULL;
1438   _parker = Parker::Allocate(this);
1439 
1440 #ifndef PRODUCT
1441   _jmp_ring_index = 0;
1442   for (int ji = 0; ji < jump_ring_buffer_size; ji++) {
1443     record_jump(NULL, NULL, NULL, 0);
1444   }
1445 #endif // PRODUCT
1446 
1447   set_thread_profiler(NULL);
1448   if (FlatProfiler::is_active()) {
1449     // This is where we would decide to either give each thread it's own profiler
1450     // or use one global one from FlatProfiler,
1451     // or up to some count of the number of profiled threads, etc.
1452     ThreadProfiler* pp = new ThreadProfiler();
1453     pp->engage();
1454     set_thread_profiler(pp);
1455   }
1456 
1457   // Setup safepoint state info for this thread
1458   ThreadSafepointState::create(this);
1459 
1460   debug_only(_java_call_counter = 0);
1461 
1462   // JVMTI PopFrame support
1463   _popframe_condition = popframe_inactive;
1464   _popframe_preserved_args = NULL;
1465   _popframe_preserved_args_size = 0;
1466   _frames_to_pop_failed_realloc = 0;
1467 
1468   pd_initialize();
1469 }
1470 
1471 #if INCLUDE_ALL_GCS
1472 SATBMarkQueueSet JavaThread::_satb_mark_queue_set;
1473 DirtyCardQueueSet JavaThread::_dirty_card_queue_set;
1474 #endif // INCLUDE_ALL_GCS
1475 
1476 JavaThread::JavaThread(bool is_attaching_via_jni) :
1477                        Thread()
1478 #if INCLUDE_ALL_GCS
1479                        , _satb_mark_queue(&_satb_mark_queue_set),
1480                        _dirty_card_queue(&_dirty_card_queue_set)
1481 #endif // INCLUDE_ALL_GCS
1482 {
1483   initialize();
1484   if (is_attaching_via_jni) {
1485     _jni_attach_state = _attaching_via_jni;
1486   } else {
1487     _jni_attach_state = _not_attaching_via_jni;
1488   }
1489   assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
1490 }
1491 
1492 bool JavaThread::reguard_stack(address cur_sp) {
1493   if (_stack_guard_state != stack_guard_yellow_disabled) {
1494     return true; // Stack already guarded or guard pages not needed.
1495   }
1496 
1497   if (register_stack_overflow()) {
1498     // For those architectures which have separate register and
1499     // memory stacks, we must check the register stack to see if
1500     // it has overflowed.
1501     return false;
1502   }
1503 
1504   // Java code never executes within the yellow zone: the latter is only
1505   // there to provoke an exception during stack banging.  If java code
1506   // is executing there, either StackShadowPages should be larger, or
1507   // some exception code in c1, c2 or the interpreter isn't unwinding
1508   // when it should.
1509   guarantee(cur_sp > stack_yellow_zone_base(), "not enough space to reguard - increase StackShadowPages");
1510 
1511   enable_stack_yellow_zone();
1512   return true;
1513 }
1514 
1515 bool JavaThread::reguard_stack(void) {
1516   return reguard_stack(os::current_stack_pointer());
1517 }
1518 
1519 
1520 void JavaThread::block_if_vm_exited() {
1521   if (_terminated == _vm_exited) {
1522     // _vm_exited is set at safepoint, and Threads_lock is never released
1523     // we will block here forever
1524     Threads_lock->lock_without_safepoint_check();
1525     ShouldNotReachHere();
1526   }
1527 }
1528 
1529 
1530 // Remove this ifdef when C1 is ported to the compiler interface.
1531 static void compiler_thread_entry(JavaThread* thread, TRAPS);
1532 static void sweeper_thread_entry(JavaThread* thread, TRAPS);
1533 
1534 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
1535                        Thread()
1536 #if INCLUDE_ALL_GCS
1537                        , _satb_mark_queue(&_satb_mark_queue_set),
1538                        _dirty_card_queue(&_dirty_card_queue_set)
1539 #endif // INCLUDE_ALL_GCS
1540 {
1541   initialize();
1542   _jni_attach_state = _not_attaching_via_jni;
1543   set_entry_point(entry_point);
1544   // Create the native thread itself.
1545   // %note runtime_23
1546   os::ThreadType thr_type = os::java_thread;
1547   thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
1548                                                      os::java_thread;
1549   os::create_thread(this, thr_type, stack_sz);
1550   // The _osthread may be NULL here because we ran out of memory (too many threads active).
1551   // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
1552   // may hold a lock and all locks must be unlocked before throwing the exception (throwing
1553   // the exception consists of creating the exception object & initializing it, initialization
1554   // will leave the VM via a JavaCall and then all locks must be unlocked).
1555   //
1556   // The thread is still suspended when we reach here. Thread must be explicit started
1557   // by creator! Furthermore, the thread must also explicitly be added to the Threads list
1558   // by calling Threads:add. The reason why this is not done here, is because the thread
1559   // object must be fully initialized (take a look at JVM_Start)
1560 }
1561 
1562 JavaThread::~JavaThread() {
1563 
1564   // JSR166 -- return the parker to the free list
1565   Parker::Release(_parker);
1566   _parker = NULL;
1567 
1568   // Free any remaining  previous UnrollBlock
1569   vframeArray* old_array = vframe_array_last();
1570 
1571   if (old_array != NULL) {
1572     Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
1573     old_array->set_unroll_block(NULL);
1574     delete old_info;
1575     delete old_array;
1576   }
1577 
1578   GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals();
1579   if (deferred != NULL) {
1580     // This can only happen if thread is destroyed before deoptimization occurs.
1581     assert(deferred->length() != 0, "empty array!");
1582     do {
1583       jvmtiDeferredLocalVariableSet* dlv = deferred->at(0);
1584       deferred->remove_at(0);
1585       // individual jvmtiDeferredLocalVariableSet are CHeapObj's
1586       delete dlv;
1587     } while (deferred->length() != 0);
1588     delete deferred;
1589   }
1590 
1591   // All Java related clean up happens in exit
1592   ThreadSafepointState::destroy(this);
1593   if (_thread_profiler != NULL) delete _thread_profiler;
1594   if (_thread_stat != NULL) delete _thread_stat;











1595 }
1596 
1597 
1598 // The first routine called by a new Java thread
1599 void JavaThread::run() {
1600   // initialize thread-local alloc buffer related fields
1601   this->initialize_tlab();
1602 
1603   // used to test validity of stack trace backs
1604   this->record_base_of_stack_pointer();
1605 
1606   // Record real stack base and size.
1607   this->record_stack_base_and_size();
1608 
1609   // Initialize thread local storage; set before calling MutexLocker
1610   this->initialize_thread_local_storage();
1611 
1612   this->create_stack_guard_pages();
1613 
1614   this->cache_global_variables();
1615 
1616   // Thread is now sufficient initialized to be handled by the safepoint code as being
1617   // in the VM. Change thread state from _thread_new to _thread_in_vm
1618   ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
1619 
1620   assert(JavaThread::current() == this, "sanity check");
1621   assert(!Thread::current()->owns_locks(), "sanity check");
1622 
1623   DTRACE_THREAD_PROBE(start, this);
1624 
1625   // This operation might block. We call that after all safepoint checks for a new thread has
1626   // been completed.
1627   this->set_active_handles(JNIHandleBlock::allocate_block());
1628 
1629   if (JvmtiExport::should_post_thread_life()) {
1630     JvmtiExport::post_thread_start(this);
1631   }
1632 
1633   EventThreadStart event;
1634   if (event.should_commit()) {
1635     event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj()));
1636     event.commit();
1637   }
1638 
1639   // We call another function to do the rest so we are sure that the stack addresses used
1640   // from there will be lower than the stack base just computed
1641   thread_main_inner();
1642 
1643   // Note, thread is no longer valid at this point!
1644 }
1645 
1646 
1647 void JavaThread::thread_main_inner() {
1648   assert(JavaThread::current() == this, "sanity check");
1649   assert(this->threadObj() != NULL, "just checking");
1650 
1651   // Execute thread entry point unless this thread has a pending exception
1652   // or has been stopped before starting.
1653   // Note: Due to JVM_StopThread we can have pending exceptions already!
1654   if (!this->has_pending_exception() &&
1655       !java_lang_Thread::is_stillborn(this->threadObj())) {
1656     {
1657       ResourceMark rm(this);
1658       this->set_native_thread_name(this->get_thread_name());
1659     }
1660     HandleMark hm(this);
1661     this->entry_point()(this, this);
1662   }
1663 
1664   DTRACE_THREAD_PROBE(stop, this);
1665 
1666   this->exit(false);
1667   delete this;
1668 }
1669 
1670 
1671 static void ensure_join(JavaThread* thread) {
1672   // We do not need to grap the Threads_lock, since we are operating on ourself.
1673   Handle threadObj(thread, thread->threadObj());
1674   assert(threadObj.not_null(), "java thread object must exist");
1675   ObjectLocker lock(threadObj, thread);
1676   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1677   thread->clear_pending_exception();
1678   // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
1679   java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1680   // Clear the native thread instance - this makes isAlive return false and allows the join()
1681   // to complete once we've done the notify_all below
1682   java_lang_Thread::set_thread(threadObj(), NULL);
1683   lock.notify_all(thread);
1684   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1685   thread->clear_pending_exception();
1686 }
1687 
1688 
1689 // For any new cleanup additions, please check to see if they need to be applied to
1690 // cleanup_failed_attach_current_thread as well.
1691 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
1692   assert(this == JavaThread::current(), "thread consistency check");
1693 
1694   HandleMark hm(this);
1695   Handle uncaught_exception(this, this->pending_exception());
1696   this->clear_pending_exception();
1697   Handle threadObj(this, this->threadObj());
1698   assert(threadObj.not_null(), "Java thread object should be created");
1699 
1700   if (get_thread_profiler() != NULL) {
1701     get_thread_profiler()->disengage();
1702     ResourceMark rm;
1703     get_thread_profiler()->print(get_thread_name());
1704   }
1705 
1706 
1707   // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place
1708   {
1709     EXCEPTION_MARK;
1710 
1711     CLEAR_PENDING_EXCEPTION;
1712   }
1713   if (!destroy_vm) {
1714     if (uncaught_exception.not_null()) {
1715       EXCEPTION_MARK;
1716       // Call method Thread.dispatchUncaughtException().
1717       KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
1718       JavaValue result(T_VOID);
1719       JavaCalls::call_virtual(&result,
1720                               threadObj, thread_klass,
1721                               vmSymbols::dispatchUncaughtException_name(),
1722                               vmSymbols::throwable_void_signature(),
1723                               uncaught_exception,
1724                               THREAD);
1725       if (HAS_PENDING_EXCEPTION) {
1726         ResourceMark rm(this);
1727         jio_fprintf(defaultStream::error_stream(),
1728                     "\nException: %s thrown from the UncaughtExceptionHandler"
1729                     " in thread \"%s\"\n",
1730                     pending_exception()->klass()->external_name(),
1731                     get_thread_name());
1732         CLEAR_PENDING_EXCEPTION;
1733       }
1734     }
1735 
1736     // Called before the java thread exit since we want to read info
1737     // from java_lang_Thread object
1738     EventThreadEnd event;
1739     if (event.should_commit()) {
1740       event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj()));
1741       event.commit();
1742     }
1743 
1744     // Call after last event on thread
1745     EVENT_THREAD_EXIT(this);
1746 
1747     // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
1748     // the execution of the method. If that is not enough, then we don't really care. Thread.stop
1749     // is deprecated anyhow.
1750     if (!is_Compiler_thread()) {
1751       int count = 3;
1752       while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
1753         EXCEPTION_MARK;
1754         JavaValue result(T_VOID);
1755         KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
1756         JavaCalls::call_virtual(&result,
1757                                 threadObj, thread_klass,
1758                                 vmSymbols::exit_method_name(),
1759                                 vmSymbols::void_method_signature(),
1760                                 THREAD);
1761         CLEAR_PENDING_EXCEPTION;
1762       }
1763     }
1764     // notify JVMTI
1765     if (JvmtiExport::should_post_thread_life()) {
1766       JvmtiExport::post_thread_end(this);
1767     }
1768 
1769     // We have notified the agents that we are exiting, before we go on,
1770     // we must check for a pending external suspend request and honor it
1771     // in order to not surprise the thread that made the suspend request.
1772     while (true) {
1773       {
1774         MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1775         if (!is_external_suspend()) {
1776           set_terminated(_thread_exiting);
1777           ThreadService::current_thread_exiting(this);
1778           break;
1779         }
1780         // Implied else:
1781         // Things get a little tricky here. We have a pending external
1782         // suspend request, but we are holding the SR_lock so we
1783         // can't just self-suspend. So we temporarily drop the lock
1784         // and then self-suspend.
1785       }
1786 
1787       ThreadBlockInVM tbivm(this);
1788       java_suspend_self();
1789 
1790       // We're done with this suspend request, but we have to loop around
1791       // and check again. Eventually we will get SR_lock without a pending
1792       // external suspend request and will be able to mark ourselves as
1793       // exiting.
1794     }
1795     // no more external suspends are allowed at this point
1796   } else {
1797     // before_exit() has already posted JVMTI THREAD_END events
1798   }
1799 
1800   // Notify waiters on thread object. This has to be done after exit() is called
1801   // on the thread (if the thread is the last thread in a daemon ThreadGroup the
1802   // group should have the destroyed bit set before waiters are notified).
1803   ensure_join(this);
1804   assert(!this->has_pending_exception(), "ensure_join should have cleared");
1805 
1806   // 6282335 JNI DetachCurrentThread spec states that all Java monitors
1807   // held by this thread must be released. The spec does not distinguish
1808   // between JNI-acquired and regular Java monitors. We can only see
1809   // regular Java monitors here if monitor enter-exit matching is broken.
1810   //
1811   // Optionally release any monitors for regular JavaThread exits. This
1812   // is provided as a work around for any bugs in monitor enter-exit
1813   // matching. This can be expensive so it is not enabled by default.
1814   // ObjectMonitor::Knob_ExitRelease is a superset of the
1815   // JNIDetachReleasesMonitors option.
1816   //
1817   // ensure_join() ignores IllegalThreadStateExceptions, and so does
1818   // ObjectSynchronizer::release_monitors_owned_by_thread().
1819   if ((exit_type == jni_detach && JNIDetachReleasesMonitors) ||
1820       ObjectMonitor::Knob_ExitRelease) {
1821     // Sanity check even though JNI DetachCurrentThread() would have
1822     // returned JNI_ERR if there was a Java frame. JavaThread exit
1823     // should be done executing Java code by the time we get here.
1824     assert(!this->has_last_Java_frame(),
1825            "should not have a Java frame when detaching or exiting");
1826     ObjectSynchronizer::release_monitors_owned_by_thread(this);
1827     assert(!this->has_pending_exception(), "release_monitors should have cleared");
1828   }
1829 
1830   // These things needs to be done while we are still a Java Thread. Make sure that thread
1831   // is in a consistent state, in case GC happens
1832   assert(_privileged_stack_top == NULL, "must be NULL when we get here");
1833 
1834   if (active_handles() != NULL) {
1835     JNIHandleBlock* block = active_handles();
1836     set_active_handles(NULL);
1837     JNIHandleBlock::release_block(block);
1838   }
1839 
1840   if (free_handle_block() != NULL) {
1841     JNIHandleBlock* block = free_handle_block();
1842     set_free_handle_block(NULL);
1843     JNIHandleBlock::release_block(block);
1844   }
1845 
1846   // These have to be removed while this is still a valid thread.
1847   remove_stack_guard_pages();
1848 
1849   if (UseTLAB) {
1850     tlab().make_parsable(true);  // retire TLAB
1851   }
1852 
1853   if (JvmtiEnv::environments_might_exist()) {
1854     JvmtiExport::cleanup_thread(this);
1855   }
1856 
1857   // We must flush any deferred card marks before removing a thread from
1858   // the list of active threads.
1859   Universe::heap()->flush_deferred_store_barrier(this);
1860   assert(deferred_card_mark().is_empty(), "Should have been flushed");
1861 
1862 #if INCLUDE_ALL_GCS
1863   // We must flush the G1-related buffers before removing a thread
1864   // from the list of active threads. We must do this after any deferred
1865   // card marks have been flushed (above) so that any entries that are
1866   // added to the thread's dirty card queue as a result are not lost.
1867   if (UseG1GC) {
1868     flush_barrier_queues();
1869   }
1870 #endif // INCLUDE_ALL_GCS
1871 
1872   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
1873   Threads::remove(this);
1874 }
1875 
1876 #if INCLUDE_ALL_GCS
1877 // Flush G1-related queues.
1878 void JavaThread::flush_barrier_queues() {
1879   satb_mark_queue().flush();
1880   dirty_card_queue().flush();
1881 }
1882 
1883 void JavaThread::initialize_queues() {
1884   assert(!SafepointSynchronize::is_at_safepoint(),
1885          "we should not be at a safepoint");
1886 
1887   ObjPtrQueue& satb_queue = satb_mark_queue();
1888   SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set();
1889   // The SATB queue should have been constructed with its active
1890   // field set to false.
1891   assert(!satb_queue.is_active(), "SATB queue should not be active");
1892   assert(satb_queue.is_empty(), "SATB queue should be empty");
1893   // If we are creating the thread during a marking cycle, we should
1894   // set the active field of the SATB queue to true.
1895   if (satb_queue_set.is_active()) {
1896     satb_queue.set_active(true);
1897   }
1898 
1899   DirtyCardQueue& dirty_queue = dirty_card_queue();
1900   // The dirty card queue should have been constructed with its
1901   // active field set to true.
1902   assert(dirty_queue.is_active(), "dirty card queue should be active");
1903 }
1904 #endif // INCLUDE_ALL_GCS
1905 
1906 void JavaThread::cleanup_failed_attach_current_thread() {
1907   if (get_thread_profiler() != NULL) {
1908     get_thread_profiler()->disengage();
1909     ResourceMark rm;
1910     get_thread_profiler()->print(get_thread_name());
1911   }
1912 
1913   if (active_handles() != NULL) {
1914     JNIHandleBlock* block = active_handles();
1915     set_active_handles(NULL);
1916     JNIHandleBlock::release_block(block);
1917   }
1918 
1919   if (free_handle_block() != NULL) {
1920     JNIHandleBlock* block = free_handle_block();
1921     set_free_handle_block(NULL);
1922     JNIHandleBlock::release_block(block);
1923   }
1924 
1925   // These have to be removed while this is still a valid thread.
1926   remove_stack_guard_pages();
1927 
1928   if (UseTLAB) {
1929     tlab().make_parsable(true);  // retire TLAB, if any
1930   }
1931 
1932 #if INCLUDE_ALL_GCS
1933   if (UseG1GC) {
1934     flush_barrier_queues();
1935   }
1936 #endif // INCLUDE_ALL_GCS
1937 
1938   Threads::remove(this);
1939   delete this;
1940 }
1941 
1942 
1943 
1944 
1945 JavaThread* JavaThread::active() {
1946   Thread* thread = ThreadLocalStorage::thread();
1947   assert(thread != NULL, "just checking");
1948   if (thread->is_Java_thread()) {
1949     return (JavaThread*) thread;
1950   } else {
1951     assert(thread->is_VM_thread(), "this must be a vm thread");
1952     VM_Operation* op = ((VMThread*) thread)->vm_operation();
1953     JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
1954     assert(ret->is_Java_thread(), "must be a Java thread");
1955     return ret;
1956   }
1957 }
1958 
1959 bool JavaThread::is_lock_owned(address adr) const {
1960   if (Thread::is_lock_owned(adr)) return true;
1961 
1962   for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
1963     if (chunk->contains(adr)) return true;
1964   }
1965 
1966   return false;
1967 }
1968 
1969 
1970 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
1971   chunk->set_next(monitor_chunks());
1972   set_monitor_chunks(chunk);
1973 }
1974 
1975 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
1976   guarantee(monitor_chunks() != NULL, "must be non empty");
1977   if (monitor_chunks() == chunk) {
1978     set_monitor_chunks(chunk->next());
1979   } else {
1980     MonitorChunk* prev = monitor_chunks();
1981     while (prev->next() != chunk) prev = prev->next();
1982     prev->set_next(chunk->next());
1983   }
1984 }
1985 
1986 // JVM support.
1987 
1988 // Note: this function shouldn't block if it's called in
1989 // _thread_in_native_trans state (such as from
1990 // check_special_condition_for_native_trans()).
1991 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) {
1992 
1993   if (has_last_Java_frame() && has_async_condition()) {
1994     // If we are at a polling page safepoint (not a poll return)
1995     // then we must defer async exception because live registers
1996     // will be clobbered by the exception path. Poll return is
1997     // ok because the call we a returning from already collides
1998     // with exception handling registers and so there is no issue.
1999     // (The exception handling path kills call result registers but
2000     //  this is ok since the exception kills the result anyway).
2001 
2002     if (is_at_poll_safepoint()) {
2003       // if the code we are returning to has deoptimized we must defer
2004       // the exception otherwise live registers get clobbered on the
2005       // exception path before deoptimization is able to retrieve them.
2006       //
2007       RegisterMap map(this, false);
2008       frame caller_fr = last_frame().sender(&map);
2009       assert(caller_fr.is_compiled_frame(), "what?");
2010       if (caller_fr.is_deoptimized_frame()) {
2011         if (TraceExceptions) {
2012           ResourceMark rm;
2013           tty->print_cr("deferred async exception at compiled safepoint");
2014         }
2015         return;
2016       }
2017     }
2018   }
2019 
2020   JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition();
2021   if (condition == _no_async_condition) {
2022     // Conditions have changed since has_special_runtime_exit_condition()
2023     // was called:
2024     // - if we were here only because of an external suspend request,
2025     //   then that was taken care of above (or cancelled) so we are done
2026     // - if we were here because of another async request, then it has
2027     //   been cleared between the has_special_runtime_exit_condition()
2028     //   and now so again we are done
2029     return;
2030   }
2031 
2032   // Check for pending async. exception
2033   if (_pending_async_exception != NULL) {
2034     // Only overwrite an already pending exception, if it is not a threadDeath.
2035     if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) {
2036 
2037       // We cannot call Exceptions::_throw(...) here because we cannot block
2038       set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
2039 
2040       if (TraceExceptions) {
2041         ResourceMark rm;
2042         tty->print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", this);
2043         if (has_last_Java_frame()) {
2044           frame f = last_frame();
2045           tty->print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", f.pc(), f.sp());
2046         }
2047         tty->print_cr(" of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name());
2048       }
2049       _pending_async_exception = NULL;
2050       clear_has_async_exception();
2051     }
2052   }
2053 
2054   if (check_unsafe_error &&
2055       condition == _async_unsafe_access_error && !has_pending_exception()) {
2056     condition = _no_async_condition;  // done
2057     switch (thread_state()) {
2058     case _thread_in_vm: {
2059       JavaThread* THREAD = this;
2060       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
2061     }
2062     case _thread_in_native: {
2063       ThreadInVMfromNative tiv(this);
2064       JavaThread* THREAD = this;
2065       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
2066     }
2067     case _thread_in_Java: {
2068       ThreadInVMfromJava tiv(this);
2069       JavaThread* THREAD = this;
2070       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
2071     }
2072     default:
2073       ShouldNotReachHere();
2074     }
2075   }
2076 
2077   assert(condition == _no_async_condition || has_pending_exception() ||
2078          (!check_unsafe_error && condition == _async_unsafe_access_error),
2079          "must have handled the async condition, if no exception");
2080 }
2081 
2082 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
2083   //
2084   // Check for pending external suspend. Internal suspend requests do
2085   // not use handle_special_runtime_exit_condition().
2086   // If JNIEnv proxies are allowed, don't self-suspend if the target
2087   // thread is not the current thread. In older versions of jdbx, jdbx
2088   // threads could call into the VM with another thread's JNIEnv so we
2089   // can be here operating on behalf of a suspended thread (4432884).
2090   bool do_self_suspend = is_external_suspend_with_lock();
2091   if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) {
2092     //
2093     // Because thread is external suspended the safepoint code will count
2094     // thread as at a safepoint. This can be odd because we can be here
2095     // as _thread_in_Java which would normally transition to _thread_blocked
2096     // at a safepoint. We would like to mark the thread as _thread_blocked
2097     // before calling java_suspend_self like all other callers of it but
2098     // we must then observe proper safepoint protocol. (We can't leave
2099     // _thread_blocked with a safepoint in progress). However we can be
2100     // here as _thread_in_native_trans so we can't use a normal transition
2101     // constructor/destructor pair because they assert on that type of
2102     // transition. We could do something like:
2103     //
2104     // JavaThreadState state = thread_state();
2105     // set_thread_state(_thread_in_vm);
2106     // {
2107     //   ThreadBlockInVM tbivm(this);
2108     //   java_suspend_self()
2109     // }
2110     // set_thread_state(_thread_in_vm_trans);
2111     // if (safepoint) block;
2112     // set_thread_state(state);
2113     //
2114     // but that is pretty messy. Instead we just go with the way the
2115     // code has worked before and note that this is the only path to
2116     // java_suspend_self that doesn't put the thread in _thread_blocked
2117     // mode.
2118 
2119     frame_anchor()->make_walkable(this);
2120     java_suspend_self();
2121 
2122     // We might be here for reasons in addition to the self-suspend request
2123     // so check for other async requests.
2124   }
2125 
2126   if (check_asyncs) {
2127     check_and_handle_async_exceptions();
2128   }
2129 }
2130 
2131 void JavaThread::send_thread_stop(oop java_throwable)  {
2132   assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
2133   assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
2134   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
2135 
2136   // Do not throw asynchronous exceptions against the compiler thread
2137   // (the compiler thread should not be a Java thread -- fix in 1.4.2)
2138   if (is_Compiler_thread()) return;
2139 
2140   {
2141     // Actually throw the Throwable against the target Thread - however
2142     // only if there is no thread death exception installed already.
2143     if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
2144       // If the topmost frame is a runtime stub, then we are calling into
2145       // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
2146       // must deoptimize the caller before continuing, as the compiled  exception handler table
2147       // may not be valid
2148       if (has_last_Java_frame()) {
2149         frame f = last_frame();
2150         if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
2151           // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2152           RegisterMap reg_map(this, UseBiasedLocking);
2153           frame compiled_frame = f.sender(&reg_map);
2154           if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
2155             Deoptimization::deoptimize(this, compiled_frame, &reg_map);
2156           }
2157         }
2158       }
2159 
2160       // Set async. pending exception in thread.
2161       set_pending_async_exception(java_throwable);
2162 
2163       if (TraceExceptions) {
2164         ResourceMark rm;
2165         tty->print_cr("Pending Async. exception installed of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name());
2166       }
2167       // for AbortVMOnException flag
2168       NOT_PRODUCT(Exceptions::debug_check_abort(InstanceKlass::cast(_pending_async_exception->klass())->external_name()));
2169     }
2170   }
2171 
2172 
2173   // Interrupt thread so it will wake up from a potential wait()
2174   Thread::interrupt(this);
2175 }
2176 
2177 // External suspension mechanism.
2178 //
2179 // Tell the VM to suspend a thread when ever it knows that it does not hold on
2180 // to any VM_locks and it is at a transition
2181 // Self-suspension will happen on the transition out of the vm.
2182 // Catch "this" coming in from JNIEnv pointers when the thread has been freed
2183 //
2184 // Guarantees on return:
2185 //   + Target thread will not execute any new bytecode (that's why we need to
2186 //     force a safepoint)
2187 //   + Target thread will not enter any new monitors
2188 //
2189 void JavaThread::java_suspend() {
2190   { MutexLocker mu(Threads_lock);
2191     if (!Threads::includes(this) || is_exiting() || this->threadObj() == NULL) {
2192       return;
2193     }
2194   }
2195 
2196   { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2197     if (!is_external_suspend()) {
2198       // a racing resume has cancelled us; bail out now
2199       return;
2200     }
2201 
2202     // suspend is done
2203     uint32_t debug_bits = 0;
2204     // Warning: is_ext_suspend_completed() may temporarily drop the
2205     // SR_lock to allow the thread to reach a stable thread state if
2206     // it is currently in a transient thread state.
2207     if (is_ext_suspend_completed(false /* !called_by_wait */,
2208                                  SuspendRetryDelay, &debug_bits)) {
2209       return;
2210     }
2211   }
2212 
2213   VM_ForceSafepoint vm_suspend;
2214   VMThread::execute(&vm_suspend);
2215 }
2216 
2217 // Part II of external suspension.
2218 // A JavaThread self suspends when it detects a pending external suspend
2219 // request. This is usually on transitions. It is also done in places
2220 // where continuing to the next transition would surprise the caller,
2221 // e.g., monitor entry.
2222 //
2223 // Returns the number of times that the thread self-suspended.
2224 //
2225 // Note: DO NOT call java_suspend_self() when you just want to block current
2226 //       thread. java_suspend_self() is the second stage of cooperative
2227 //       suspension for external suspend requests and should only be used
2228 //       to complete an external suspend request.
2229 //
2230 int JavaThread::java_suspend_self() {
2231   int ret = 0;
2232 
2233   // we are in the process of exiting so don't suspend
2234   if (is_exiting()) {
2235     clear_external_suspend();
2236     return ret;
2237   }
2238 
2239   assert(_anchor.walkable() ||
2240          (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()),
2241          "must have walkable stack");
2242 
2243   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2244 
2245   assert(!this->is_ext_suspended(),
2246          "a thread trying to self-suspend should not already be suspended");
2247 
2248   if (this->is_suspend_equivalent()) {
2249     // If we are self-suspending as a result of the lifting of a
2250     // suspend equivalent condition, then the suspend_equivalent
2251     // flag is not cleared until we set the ext_suspended flag so
2252     // that wait_for_ext_suspend_completion() returns consistent
2253     // results.
2254     this->clear_suspend_equivalent();
2255   }
2256 
2257   // A racing resume may have cancelled us before we grabbed SR_lock
2258   // above. Or another external suspend request could be waiting for us
2259   // by the time we return from SR_lock()->wait(). The thread
2260   // that requested the suspension may already be trying to walk our
2261   // stack and if we return now, we can change the stack out from under
2262   // it. This would be a "bad thing (TM)" and cause the stack walker
2263   // to crash. We stay self-suspended until there are no more pending
2264   // external suspend requests.
2265   while (is_external_suspend()) {
2266     ret++;
2267     this->set_ext_suspended();
2268 
2269     // _ext_suspended flag is cleared by java_resume()
2270     while (is_ext_suspended()) {
2271       this->SR_lock()->wait(Mutex::_no_safepoint_check_flag);
2272     }
2273   }
2274 
2275   return ret;
2276 }
2277 
2278 #ifdef ASSERT
2279 // verify the JavaThread has not yet been published in the Threads::list, and
2280 // hence doesn't need protection from concurrent access at this stage
2281 void JavaThread::verify_not_published() {
2282   if (!Threads_lock->owned_by_self()) {
2283     MutexLockerEx ml(Threads_lock,  Mutex::_no_safepoint_check_flag);
2284     assert(!Threads::includes(this),
2285            "java thread shouldn't have been published yet!");
2286   } else {
2287     assert(!Threads::includes(this),
2288            "java thread shouldn't have been published yet!");
2289   }
2290 }
2291 #endif
2292 
2293 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2294 // progress or when _suspend_flags is non-zero.
2295 // Current thread needs to self-suspend if there is a suspend request and/or
2296 // block if a safepoint is in progress.
2297 // Async exception ISN'T checked.
2298 // Note only the ThreadInVMfromNative transition can call this function
2299 // directly and when thread state is _thread_in_native_trans
2300 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
2301   assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
2302 
2303   JavaThread *curJT = JavaThread::current();
2304   bool do_self_suspend = thread->is_external_suspend();
2305 
2306   assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
2307 
2308   // If JNIEnv proxies are allowed, don't self-suspend if the target
2309   // thread is not the current thread. In older versions of jdbx, jdbx
2310   // threads could call into the VM with another thread's JNIEnv so we
2311   // can be here operating on behalf of a suspended thread (4432884).
2312   if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) {
2313     JavaThreadState state = thread->thread_state();
2314 
2315     // We mark this thread_blocked state as a suspend-equivalent so
2316     // that a caller to is_ext_suspend_completed() won't be confused.
2317     // The suspend-equivalent state is cleared by java_suspend_self().
2318     thread->set_suspend_equivalent();
2319 
2320     // If the safepoint code sees the _thread_in_native_trans state, it will
2321     // wait until the thread changes to other thread state. There is no
2322     // guarantee on how soon we can obtain the SR_lock and complete the
2323     // self-suspend request. It would be a bad idea to let safepoint wait for
2324     // too long. Temporarily change the state to _thread_blocked to
2325     // let the VM thread know that this thread is ready for GC. The problem
2326     // of changing thread state is that safepoint could happen just after
2327     // java_suspend_self() returns after being resumed, and VM thread will
2328     // see the _thread_blocked state. We must check for safepoint
2329     // after restoring the state and make sure we won't leave while a safepoint
2330     // is in progress.
2331     thread->set_thread_state(_thread_blocked);
2332     thread->java_suspend_self();
2333     thread->set_thread_state(state);
2334     // Make sure new state is seen by VM thread
2335     if (os::is_MP()) {
2336       if (UseMembar) {
2337         // Force a fence between the write above and read below
2338         OrderAccess::fence();
2339       } else {
2340         // Must use this rather than serialization page in particular on Windows
2341         InterfaceSupport::serialize_memory(thread);
2342       }
2343     }
2344   }
2345 
2346   if (SafepointSynchronize::do_call_back()) {
2347     // If we are safepointing, then block the caller which may not be
2348     // the same as the target thread (see above).
2349     SafepointSynchronize::block(curJT);
2350   }
2351 
2352   if (thread->is_deopt_suspend()) {
2353     thread->clear_deopt_suspend();
2354     RegisterMap map(thread, false);
2355     frame f = thread->last_frame();
2356     while (f.id() != thread->must_deopt_id() && ! f.is_first_frame()) {
2357       f = f.sender(&map);
2358     }
2359     if (f.id() == thread->must_deopt_id()) {
2360       thread->clear_must_deopt_id();
2361       f.deoptimize(thread);
2362     } else {
2363       fatal("missed deoptimization!");
2364     }
2365   }
2366 }
2367 
2368 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2369 // progress or when _suspend_flags is non-zero.
2370 // Current thread needs to self-suspend if there is a suspend request and/or
2371 // block if a safepoint is in progress.
2372 // Also check for pending async exception (not including unsafe access error).
2373 // Note only the native==>VM/Java barriers can call this function and when
2374 // thread state is _thread_in_native_trans.
2375 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
2376   check_safepoint_and_suspend_for_native_trans(thread);
2377 
2378   if (thread->has_async_exception()) {
2379     // We are in _thread_in_native_trans state, don't handle unsafe
2380     // access error since that may block.
2381     thread->check_and_handle_async_exceptions(false);
2382   }
2383 }
2384 
2385 // This is a variant of the normal
2386 // check_special_condition_for_native_trans with slightly different
2387 // semantics for use by critical native wrappers.  It does all the
2388 // normal checks but also performs the transition back into
2389 // thread_in_Java state.  This is required so that critical natives
2390 // can potentially block and perform a GC if they are the last thread
2391 // exiting the GC_locker.
2392 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) {
2393   check_special_condition_for_native_trans(thread);
2394 
2395   // Finish the transition
2396   thread->set_thread_state(_thread_in_Java);
2397 
2398   if (thread->do_critical_native_unlock()) {
2399     ThreadInVMfromJavaNoAsyncException tiv(thread);
2400     GC_locker::unlock_critical(thread);
2401     thread->clear_critical_native_unlock();
2402   }
2403 }
2404 
2405 // We need to guarantee the Threads_lock here, since resumes are not
2406 // allowed during safepoint synchronization
2407 // Can only resume from an external suspension
2408 void JavaThread::java_resume() {
2409   assert_locked_or_safepoint(Threads_lock);
2410 
2411   // Sanity check: thread is gone, has started exiting or the thread
2412   // was not externally suspended.
2413   if (!Threads::includes(this) || is_exiting() || !is_external_suspend()) {
2414     return;
2415   }
2416 
2417   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2418 
2419   clear_external_suspend();
2420 
2421   if (is_ext_suspended()) {
2422     clear_ext_suspended();
2423     SR_lock()->notify_all();
2424   }
2425 }
2426 
2427 void JavaThread::create_stack_guard_pages() {
2428   if (! os::uses_stack_guard_pages() || _stack_guard_state != stack_guard_unused) return;
2429   address low_addr = stack_base() - stack_size();
2430   size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
2431 
2432   int allocate = os::allocate_stack_guard_pages();
2433   // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len);
2434 
2435   if (allocate && !os::create_stack_guard_pages((char *) low_addr, len)) {
2436     warning("Attempt to allocate stack guard pages failed.");
2437     return;
2438   }
2439 
2440   if (os::guard_memory((char *) low_addr, len)) {
2441     _stack_guard_state = stack_guard_enabled;
2442   } else {
2443     warning("Attempt to protect stack guard pages failed.");
2444     if (os::uncommit_memory((char *) low_addr, len)) {
2445       warning("Attempt to deallocate stack guard pages failed.");
2446     }
2447   }
2448 }
2449 
2450 void JavaThread::remove_stack_guard_pages() {
2451   assert(Thread::current() == this, "from different thread");
2452   if (_stack_guard_state == stack_guard_unused) return;
2453   address low_addr = stack_base() - stack_size();
2454   size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
2455 
2456   if (os::allocate_stack_guard_pages()) {
2457     if (os::remove_stack_guard_pages((char *) low_addr, len)) {
2458       _stack_guard_state = stack_guard_unused;
2459     } else {
2460       warning("Attempt to deallocate stack guard pages failed.");
2461     }
2462   } else {
2463     if (_stack_guard_state == stack_guard_unused) return;
2464     if (os::unguard_memory((char *) low_addr, len)) {
2465       _stack_guard_state = stack_guard_unused;
2466     } else {
2467       warning("Attempt to unprotect stack guard pages failed.");
2468     }
2469   }
2470 }
2471 
2472 void JavaThread::enable_stack_yellow_zone() {
2473   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2474   assert(_stack_guard_state != stack_guard_enabled, "already enabled");
2475 
2476   // The base notation is from the stacks point of view, growing downward.
2477   // We need to adjust it to work correctly with guard_memory()
2478   address base = stack_yellow_zone_base() - stack_yellow_zone_size();
2479 
2480   guarantee(base < stack_base(), "Error calculating stack yellow zone");
2481   guarantee(base < os::current_stack_pointer(), "Error calculating stack yellow zone");
2482 
2483   if (os::guard_memory((char *) base, stack_yellow_zone_size())) {
2484     _stack_guard_state = stack_guard_enabled;
2485   } else {
2486     warning("Attempt to guard stack yellow zone failed.");
2487   }
2488   enable_register_stack_guard();
2489 }
2490 
2491 void JavaThread::disable_stack_yellow_zone() {
2492   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2493   assert(_stack_guard_state != stack_guard_yellow_disabled, "already disabled");
2494 
2495   // Simply return if called for a thread that does not use guard pages.
2496   if (_stack_guard_state == stack_guard_unused) return;
2497 
2498   // The base notation is from the stacks point of view, growing downward.
2499   // We need to adjust it to work correctly with guard_memory()
2500   address base = stack_yellow_zone_base() - stack_yellow_zone_size();
2501 
2502   if (os::unguard_memory((char *)base, stack_yellow_zone_size())) {
2503     _stack_guard_state = stack_guard_yellow_disabled;
2504   } else {
2505     warning("Attempt to unguard stack yellow zone failed.");
2506   }
2507   disable_register_stack_guard();
2508 }
2509 
2510 void JavaThread::enable_stack_red_zone() {
2511   // The base notation is from the stacks point of view, growing downward.
2512   // We need to adjust it to work correctly with guard_memory()
2513   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2514   address base = stack_red_zone_base() - stack_red_zone_size();
2515 
2516   guarantee(base < stack_base(), "Error calculating stack red zone");
2517   guarantee(base < os::current_stack_pointer(), "Error calculating stack red zone");
2518 
2519   if (!os::guard_memory((char *) base, stack_red_zone_size())) {
2520     warning("Attempt to guard stack red zone failed.");
2521   }
2522 }
2523 
2524 void JavaThread::disable_stack_red_zone() {
2525   // The base notation is from the stacks point of view, growing downward.
2526   // We need to adjust it to work correctly with guard_memory()
2527   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2528   address base = stack_red_zone_base() - stack_red_zone_size();
2529   if (!os::unguard_memory((char *)base, stack_red_zone_size())) {
2530     warning("Attempt to unguard stack red zone failed.");
2531   }
2532 }
2533 
2534 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
2535   // ignore is there is no stack
2536   if (!has_last_Java_frame()) return;
2537   // traverse the stack frames. Starts from top frame.
2538   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2539     frame* fr = fst.current();
2540     f(fr, fst.register_map());
2541   }
2542 }
2543 
2544 
2545 #ifndef PRODUCT
2546 // Deoptimization
2547 // Function for testing deoptimization
2548 void JavaThread::deoptimize() {
2549   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2550   StackFrameStream fst(this, UseBiasedLocking);
2551   bool deopt = false;           // Dump stack only if a deopt actually happens.
2552   bool only_at = strlen(DeoptimizeOnlyAt) > 0;
2553   // Iterate over all frames in the thread and deoptimize
2554   for (; !fst.is_done(); fst.next()) {
2555     if (fst.current()->can_be_deoptimized()) {
2556 
2557       if (only_at) {
2558         // Deoptimize only at particular bcis.  DeoptimizeOnlyAt
2559         // consists of comma or carriage return separated numbers so
2560         // search for the current bci in that string.
2561         address pc = fst.current()->pc();
2562         nmethod* nm =  (nmethod*) fst.current()->cb();
2563         ScopeDesc* sd = nm->scope_desc_at(pc);
2564         char buffer[8];
2565         jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
2566         size_t len = strlen(buffer);
2567         const char * found = strstr(DeoptimizeOnlyAt, buffer);
2568         while (found != NULL) {
2569           if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
2570               (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
2571             // Check that the bci found is bracketed by terminators.
2572             break;
2573           }
2574           found = strstr(found + 1, buffer);
2575         }
2576         if (!found) {
2577           continue;
2578         }
2579       }
2580 
2581       if (DebugDeoptimization && !deopt) {
2582         deopt = true; // One-time only print before deopt
2583         tty->print_cr("[BEFORE Deoptimization]");
2584         trace_frames();
2585         trace_stack();
2586       }
2587       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2588     }
2589   }
2590 
2591   if (DebugDeoptimization && deopt) {
2592     tty->print_cr("[AFTER Deoptimization]");
2593     trace_frames();
2594   }
2595 }
2596 
2597 
2598 // Make zombies
2599 void JavaThread::make_zombies() {
2600   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2601     if (fst.current()->can_be_deoptimized()) {
2602       // it is a Java nmethod
2603       nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
2604       nm->make_not_entrant();
2605     }
2606   }
2607 }
2608 #endif // PRODUCT
2609 
2610 
2611 void JavaThread::deoptimized_wrt_marked_nmethods() {
2612   if (!has_last_Java_frame()) return;
2613   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2614   StackFrameStream fst(this, UseBiasedLocking);
2615   for (; !fst.is_done(); fst.next()) {
2616     if (fst.current()->should_be_deoptimized()) {
2617       if (LogCompilation && xtty != NULL) {
2618         nmethod* nm = fst.current()->cb()->as_nmethod_or_null();
2619         xtty->elem("deoptimized thread='" UINTX_FORMAT "' compile_id='%d'",
2620                    this->name(), nm != NULL ? nm->compile_id() : -1);
2621       }
2622 
2623       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2624     }
2625   }
2626 }
2627 
2628 
2629 // If the caller is a NamedThread, then remember, in the current scope,
2630 // the given JavaThread in its _processed_thread field.
2631 class RememberProcessedThread: public StackObj {
2632   NamedThread* _cur_thr;
2633  public:
2634   RememberProcessedThread(JavaThread* jthr) {
2635     Thread* thread = Thread::current();
2636     if (thread->is_Named_thread()) {
2637       _cur_thr = (NamedThread *)thread;
2638       _cur_thr->set_processed_thread(jthr);
2639     } else {
2640       _cur_thr = NULL;
2641     }
2642   }
2643 
2644   ~RememberProcessedThread() {
2645     if (_cur_thr) {
2646       _cur_thr->set_processed_thread(NULL);
2647     }
2648   }
2649 };
2650 
2651 void JavaThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
2652   // Verify that the deferred card marks have been flushed.
2653   assert(deferred_card_mark().is_empty(), "Should be empty during GC");
2654 
2655   // The ThreadProfiler oops_do is done from FlatProfiler::oops_do
2656   // since there may be more than one thread using each ThreadProfiler.
2657 
2658   // Traverse the GCHandles
2659   Thread::oops_do(f, cld_f, cf);
2660 


2661   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2662          (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2663 
2664   if (has_last_Java_frame()) {
2665     // Record JavaThread to GC thread
2666     RememberProcessedThread rpt(this);
2667 
2668     // Traverse the privileged stack
2669     if (_privileged_stack_top != NULL) {
2670       _privileged_stack_top->oops_do(f);
2671     }
2672 
2673     // traverse the registered growable array
2674     if (_array_for_gc != NULL) {
2675       for (int index = 0; index < _array_for_gc->length(); index++) {
2676         f->do_oop(_array_for_gc->adr_at(index));
2677       }
2678     }
2679 
2680     // Traverse the monitor chunks
2681     for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2682       chunk->oops_do(f);
2683     }
2684 
2685     // Traverse the execution stack
2686     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2687       fst.current()->oops_do(f, cld_f, cf, fst.register_map());
2688     }
2689   }
2690 
2691   // callee_target is never live across a gc point so NULL it here should
2692   // it still contain a methdOop.
2693 
2694   set_callee_target(NULL);
2695 
2696   assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
2697   // If we have deferred set_locals there might be oops waiting to be
2698   // written
2699   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals();
2700   if (list != NULL) {
2701     for (int i = 0; i < list->length(); i++) {
2702       list->at(i)->oops_do(f);
2703     }
2704   }
2705 
2706   // Traverse instance variables at the end since the GC may be moving things
2707   // around using this function
2708   f->do_oop((oop*) &_threadObj);
2709   f->do_oop((oop*) &_vm_result);
2710   f->do_oop((oop*) &_exception_oop);
2711   f->do_oop((oop*) &_pending_async_exception);
2712 
2713   if (jvmti_thread_state() != NULL) {
2714     jvmti_thread_state()->oops_do(f);
2715   }
2716 }
2717 
2718 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
2719   Thread::nmethods_do(cf);  // (super method is a no-op)
2720 
2721   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2722          (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2723 
2724   if (has_last_Java_frame()) {
2725     // Traverse the execution stack
2726     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2727       fst.current()->nmethods_do(cf);
2728     }
2729   }
2730 }
2731 
2732 void JavaThread::metadata_do(void f(Metadata*)) {
2733   if (has_last_Java_frame()) {
2734     // Traverse the execution stack to call f() on the methods in the stack
2735     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2736       fst.current()->metadata_do(f);
2737     }
2738   } else if (is_Compiler_thread()) {
2739     // need to walk ciMetadata in current compile tasks to keep alive.
2740     CompilerThread* ct = (CompilerThread*)this;
2741     if (ct->env() != NULL) {
2742       ct->env()->metadata_do(f);
2743     }
2744     if (ct->task() != NULL) {
2745       ct->task()->metadata_do(f);
2746     }
2747   }
2748 }
2749 
2750 // Printing
2751 const char* _get_thread_state_name(JavaThreadState _thread_state) {
2752   switch (_thread_state) {
2753   case _thread_uninitialized:     return "_thread_uninitialized";
2754   case _thread_new:               return "_thread_new";
2755   case _thread_new_trans:         return "_thread_new_trans";
2756   case _thread_in_native:         return "_thread_in_native";
2757   case _thread_in_native_trans:   return "_thread_in_native_trans";
2758   case _thread_in_vm:             return "_thread_in_vm";
2759   case _thread_in_vm_trans:       return "_thread_in_vm_trans";
2760   case _thread_in_Java:           return "_thread_in_Java";
2761   case _thread_in_Java_trans:     return "_thread_in_Java_trans";
2762   case _thread_blocked:           return "_thread_blocked";
2763   case _thread_blocked_trans:     return "_thread_blocked_trans";
2764   default:                        return "unknown thread state";
2765   }
2766 }
2767 
2768 #ifndef PRODUCT
2769 void JavaThread::print_thread_state_on(outputStream *st) const {
2770   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
2771 };
2772 void JavaThread::print_thread_state() const {
2773   print_thread_state_on(tty);
2774 }
2775 #endif // PRODUCT
2776 
2777 // Called by Threads::print() for VM_PrintThreads operation
2778 void JavaThread::print_on(outputStream *st) const {
2779   st->print("\"%s\" ", get_thread_name());
2780   oop thread_oop = threadObj();
2781   if (thread_oop != NULL) {
2782     st->print("#" INT64_FORMAT " ", java_lang_Thread::thread_id(thread_oop));
2783     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
2784     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
2785   }
2786   Thread::print_on(st);
2787   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
2788   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
2789   if (thread_oop != NULL) {
2790     st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
2791   }
2792 #ifndef PRODUCT
2793   print_thread_state_on(st);
2794   _safepoint_state->print_on(st);
2795 #endif // PRODUCT
2796 }
2797 
2798 // Called by fatal error handler. The difference between this and
2799 // JavaThread::print() is that we can't grab lock or allocate memory.
2800 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
2801   st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
2802   oop thread_obj = threadObj();
2803   if (thread_obj != NULL) {
2804     if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
2805   }
2806   st->print(" [");
2807   st->print("%s", _get_thread_state_name(_thread_state));
2808   if (osthread()) {
2809     st->print(", id=%d", osthread()->thread_id());
2810   }
2811   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
2812             _stack_base - _stack_size, _stack_base);
2813   st->print("]");
2814   return;
2815 }
2816 
2817 // Verification
2818 
2819 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
2820 
2821 void JavaThread::verify() {
2822   // Verify oops in the thread.
2823   oops_do(&VerifyOopClosure::verify_oop, NULL, NULL);
2824 
2825   // Verify the stack frames.
2826   frames_do(frame_verify);
2827 }
2828 
2829 // CR 6300358 (sub-CR 2137150)
2830 // Most callers of this method assume that it can't return NULL but a
2831 // thread may not have a name whilst it is in the process of attaching to
2832 // the VM - see CR 6412693, and there are places where a JavaThread can be
2833 // seen prior to having it's threadObj set (eg JNI attaching threads and
2834 // if vm exit occurs during initialization). These cases can all be accounted
2835 // for such that this method never returns NULL.
2836 const char* JavaThread::get_thread_name() const {
2837 #ifdef ASSERT
2838   // early safepoints can hit while current thread does not yet have TLS
2839   if (!SafepointSynchronize::is_at_safepoint()) {
2840     Thread *cur = Thread::current();
2841     if (!(cur->is_Java_thread() && cur == this)) {
2842       // Current JavaThreads are allowed to get their own name without
2843       // the Threads_lock.
2844       assert_locked_or_safepoint(Threads_lock);
2845     }
2846   }
2847 #endif // ASSERT
2848   return get_thread_name_string();
2849 }
2850 
2851 // Returns a non-NULL representation of this thread's name, or a suitable
2852 // descriptive string if there is no set name
2853 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
2854   const char* name_str;
2855   oop thread_obj = threadObj();
2856   if (thread_obj != NULL) {
2857     oop name = java_lang_Thread::name(thread_obj);
2858     if (name != NULL) {
2859       if (buf == NULL) {
2860         name_str = java_lang_String::as_utf8_string(name);
2861       } else {
2862         name_str = java_lang_String::as_utf8_string(name, buf, buflen);
2863       }
2864     } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
2865       name_str = "<no-name - thread is attaching>";
2866     } else {
2867       name_str = Thread::name();
2868     }
2869   } else {
2870     name_str = Thread::name();
2871   }
2872   assert(name_str != NULL, "unexpected NULL thread name");
2873   return name_str;
2874 }
2875 
2876 
2877 const char* JavaThread::get_threadgroup_name() const {
2878   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
2879   oop thread_obj = threadObj();
2880   if (thread_obj != NULL) {
2881     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
2882     if (thread_group != NULL) {
2883       typeArrayOop name = java_lang_ThreadGroup::name(thread_group);
2884       // ThreadGroup.name can be null
2885       if (name != NULL) {
2886         const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
2887         return str;
2888       }
2889     }
2890   }
2891   return NULL;
2892 }
2893 
2894 const char* JavaThread::get_parent_name() const {
2895   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
2896   oop thread_obj = threadObj();
2897   if (thread_obj != NULL) {
2898     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
2899     if (thread_group != NULL) {
2900       oop parent = java_lang_ThreadGroup::parent(thread_group);
2901       if (parent != NULL) {
2902         typeArrayOop name = java_lang_ThreadGroup::name(parent);
2903         // ThreadGroup.name can be null
2904         if (name != NULL) {
2905           const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
2906           return str;
2907         }
2908       }
2909     }
2910   }
2911   return NULL;
2912 }
2913 
2914 ThreadPriority JavaThread::java_priority() const {
2915   oop thr_oop = threadObj();
2916   if (thr_oop == NULL) return NormPriority; // Bootstrapping
2917   ThreadPriority priority = java_lang_Thread::priority(thr_oop);
2918   assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
2919   return priority;
2920 }
2921 
2922 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
2923 
2924   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2925   // Link Java Thread object <-> C++ Thread
2926 
2927   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
2928   // and put it into a new Handle.  The Handle "thread_oop" can then
2929   // be used to pass the C++ thread object to other methods.
2930 
2931   // Set the Java level thread object (jthread) field of the
2932   // new thread (a JavaThread *) to C++ thread object using the
2933   // "thread_oop" handle.
2934 
2935   // Set the thread field (a JavaThread *) of the
2936   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
2937 
2938   Handle thread_oop(Thread::current(),
2939                     JNIHandles::resolve_non_null(jni_thread));
2940   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
2941          "must be initialized");
2942   set_threadObj(thread_oop());
2943   java_lang_Thread::set_thread(thread_oop(), this);
2944 
2945   if (prio == NoPriority) {
2946     prio = java_lang_Thread::priority(thread_oop());
2947     assert(prio != NoPriority, "A valid priority should be present");
2948   }
2949 
2950   // Push the Java priority down to the native thread; needs Threads_lock
2951   Thread::set_priority(this, prio);
2952 
2953   prepare_ext();
2954 
2955   // Add the new thread to the Threads list and set it in motion.
2956   // We must have threads lock in order to call Threads::add.
2957   // It is crucial that we do not block before the thread is
2958   // added to the Threads list for if a GC happens, then the java_thread oop
2959   // will not be visited by GC.
2960   Threads::add(this);
2961 }
2962 
2963 oop JavaThread::current_park_blocker() {
2964   // Support for JSR-166 locks
2965   oop thread_oop = threadObj();
2966   if (thread_oop != NULL &&
2967       JDK_Version::current().supports_thread_park_blocker()) {
2968     return java_lang_Thread::park_blocker(thread_oop);
2969   }
2970   return NULL;
2971 }
2972 
2973 
2974 void JavaThread::print_stack_on(outputStream* st) {
2975   if (!has_last_Java_frame()) return;
2976   ResourceMark rm;
2977   HandleMark   hm;
2978 
2979   RegisterMap reg_map(this);
2980   vframe* start_vf = last_java_vframe(&reg_map);
2981   int count = 0;
2982   for (vframe* f = start_vf; f; f = f->sender()) {
2983     if (f->is_java_frame()) {
2984       javaVFrame* jvf = javaVFrame::cast(f);
2985       java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
2986 
2987       // Print out lock information
2988       if (JavaMonitorsInStackTrace) {
2989         jvf->print_lock_info_on(st, count);
2990       }
2991     } else {
2992       // Ignore non-Java frames
2993     }
2994 
2995     // Bail-out case for too deep stacks
2996     count++;
2997     if (MaxJavaStackTraceDepth == count) return;
2998   }
2999 }
3000 
3001 
3002 // JVMTI PopFrame support
3003 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
3004   assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
3005   if (in_bytes(size_in_bytes) != 0) {
3006     _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
3007     _popframe_preserved_args_size = in_bytes(size_in_bytes);
3008     Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
3009   }
3010 }
3011 
3012 void* JavaThread::popframe_preserved_args() {
3013   return _popframe_preserved_args;
3014 }
3015 
3016 ByteSize JavaThread::popframe_preserved_args_size() {
3017   return in_ByteSize(_popframe_preserved_args_size);
3018 }
3019 
3020 WordSize JavaThread::popframe_preserved_args_size_in_words() {
3021   int sz = in_bytes(popframe_preserved_args_size());
3022   assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
3023   return in_WordSize(sz / wordSize);
3024 }
3025 
3026 void JavaThread::popframe_free_preserved_args() {
3027   assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
3028   FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args);
3029   _popframe_preserved_args = NULL;
3030   _popframe_preserved_args_size = 0;
3031 }
3032 
3033 #ifndef PRODUCT
3034 
3035 void JavaThread::trace_frames() {
3036   tty->print_cr("[Describe stack]");
3037   int frame_no = 1;
3038   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
3039     tty->print("  %d. ", frame_no++);
3040     fst.current()->print_value_on(tty, this);
3041     tty->cr();
3042   }
3043 }
3044 
3045 class PrintAndVerifyOopClosure: public OopClosure {
3046  protected:
3047   template <class T> inline void do_oop_work(T* p) {
3048     oop obj = oopDesc::load_decode_heap_oop(p);
3049     if (obj == NULL) return;
3050     tty->print(INTPTR_FORMAT ": ", p);
3051     if (obj->is_oop_or_null()) {
3052       if (obj->is_objArray()) {
3053         tty->print_cr("valid objArray: " INTPTR_FORMAT, (oopDesc*) obj);
3054       } else {
3055         obj->print();
3056       }
3057     } else {
3058       tty->print_cr("invalid oop: " INTPTR_FORMAT, (oopDesc*) obj);
3059     }
3060     tty->cr();
3061   }
3062  public:
3063   virtual void do_oop(oop* p) { do_oop_work(p); }
3064   virtual void do_oop(narrowOop* p)  { do_oop_work(p); }
3065 };
3066 
3067 
3068 static void oops_print(frame* f, const RegisterMap *map) {
3069   PrintAndVerifyOopClosure print;
3070   f->print_value();
3071   f->oops_do(&print, NULL, NULL, (RegisterMap*)map);
3072 }
3073 
3074 // Print our all the locations that contain oops and whether they are
3075 // valid or not.  This useful when trying to find the oldest frame
3076 // where an oop has gone bad since the frame walk is from youngest to
3077 // oldest.
3078 void JavaThread::trace_oops() {
3079   tty->print_cr("[Trace oops]");
3080   frames_do(oops_print);
3081 }
3082 
3083 
3084 #ifdef ASSERT
3085 // Print or validate the layout of stack frames
3086 void JavaThread::print_frame_layout(int depth, bool validate_only) {
3087   ResourceMark rm;
3088   PRESERVE_EXCEPTION_MARK;
3089   FrameValues values;
3090   int frame_no = 0;
3091   for (StackFrameStream fst(this, false); !fst.is_done(); fst.next()) {
3092     fst.current()->describe(values, ++frame_no);
3093     if (depth == frame_no) break;
3094   }
3095   if (validate_only) {
3096     values.validate();
3097   } else {
3098     tty->print_cr("[Describe stack layout]");
3099     values.print(this);
3100   }
3101 }
3102 #endif
3103 
3104 void JavaThread::trace_stack_from(vframe* start_vf) {
3105   ResourceMark rm;
3106   int vframe_no = 1;
3107   for (vframe* f = start_vf; f; f = f->sender()) {
3108     if (f->is_java_frame()) {
3109       javaVFrame::cast(f)->print_activation(vframe_no++);
3110     } else {
3111       f->print();
3112     }
3113     if (vframe_no > StackPrintLimit) {
3114       tty->print_cr("...<more frames>...");
3115       return;
3116     }
3117   }
3118 }
3119 
3120 
3121 void JavaThread::trace_stack() {
3122   if (!has_last_Java_frame()) return;
3123   ResourceMark rm;
3124   HandleMark   hm;
3125   RegisterMap reg_map(this);
3126   trace_stack_from(last_java_vframe(&reg_map));
3127 }
3128 
3129 
3130 #endif // PRODUCT
3131 
3132 
3133 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
3134   assert(reg_map != NULL, "a map must be given");
3135   frame f = last_frame();
3136   for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) {
3137     if (vf->is_java_frame()) return javaVFrame::cast(vf);
3138   }
3139   return NULL;
3140 }
3141 
3142 
3143 Klass* JavaThread::security_get_caller_class(int depth) {
3144   vframeStream vfst(this);
3145   vfst.security_get_caller_frame(depth);
3146   if (!vfst.at_end()) {
3147     return vfst.method()->method_holder();
3148   }
3149   return NULL;
3150 }
3151 
3152 static void compiler_thread_entry(JavaThread* thread, TRAPS) {
3153   assert(thread->is_Compiler_thread(), "must be compiler thread");
3154   CompileBroker::compiler_thread_loop();
3155 }
3156 
3157 static void sweeper_thread_entry(JavaThread* thread, TRAPS) {
3158   NMethodSweeper::sweeper_loop();
3159 }
3160 
3161 // Create a CompilerThread
3162 CompilerThread::CompilerThread(CompileQueue* queue,
3163                                CompilerCounters* counters)
3164                                : JavaThread(&compiler_thread_entry) {
3165   _env   = NULL;
3166   _log   = NULL;
3167   _task  = NULL;
3168   _queue = queue;
3169   _counters = counters;
3170   _buffer_blob = NULL;
3171   _compiler = NULL;
3172 
3173 #ifndef PRODUCT
3174   _ideal_graph_printer = NULL;
3175 #endif
3176 }
3177 




3178 // Create sweeper thread
3179 CodeCacheSweeperThread::CodeCacheSweeperThread()
3180 : JavaThread(&sweeper_thread_entry) {
3181   _scanned_nmethod = NULL;
3182 }
3183 void CodeCacheSweeperThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
3184   JavaThread::oops_do(f, cld_f, cf);
3185   if (_scanned_nmethod != NULL && cf != NULL) {
3186     // Safepoints can occur when the sweeper is scanning an nmethod so
3187     // process it here to make sure it isn't unloaded in the middle of
3188     // a scan.
3189     cf->do_code_blob(_scanned_nmethod);
3190   }
3191 }
3192 
3193 
3194 // ======= Threads ========
3195 
3196 // The Threads class links together all active threads, and provides
3197 // operations over all threads.  It is protected by its own Mutex
3198 // lock, which is also used in other contexts to protect thread
3199 // operations from having the thread being operated on from exiting
3200 // and going away unexpectedly (e.g., safepoint synchronization)
3201 
3202 JavaThread* Threads::_thread_list = NULL;
3203 int         Threads::_number_of_threads = 0;
3204 int         Threads::_number_of_non_daemon_threads = 0;
3205 int         Threads::_return_code = 0;
3206 int         Threads::_thread_claim_parity = 0;
3207 size_t      JavaThread::_stack_size_at_create = 0;
3208 #ifdef ASSERT
3209 bool        Threads::_vm_complete = false;
3210 #endif
3211 
3212 // All JavaThreads
3213 #define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next())
3214 
3215 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
3216 void Threads::threads_do(ThreadClosure* tc) {
3217   assert_locked_or_safepoint(Threads_lock);
3218   // ALL_JAVA_THREADS iterates through all JavaThreads
3219   ALL_JAVA_THREADS(p) {
3220     tc->do_thread(p);
3221   }
3222   // Someday we could have a table or list of all non-JavaThreads.
3223   // For now, just manually iterate through them.
3224   tc->do_thread(VMThread::vm_thread());
3225   Universe::heap()->gc_threads_do(tc);
3226   WatcherThread *wt = WatcherThread::watcher_thread();
3227   // Strictly speaking, the following NULL check isn't sufficient to make sure
3228   // the data for WatcherThread is still valid upon being examined. However,
3229   // considering that WatchThread terminates when the VM is on the way to
3230   // exit at safepoint, the chance of the above is extremely small. The right
3231   // way to prevent termination of WatcherThread would be to acquire
3232   // Terminator_lock, but we can't do that without violating the lock rank
3233   // checking in some cases.
3234   if (wt != NULL) {
3235     tc->do_thread(wt);
3236   }
3237 
3238   // If CompilerThreads ever become non-JavaThreads, add them here
3239 }
3240 
3241 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
3242   TraceTime timer("Initialize java.lang classes", TraceStartupTime);
3243 
3244   if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
3245     create_vm_init_libraries();
3246   }
3247 
3248   initialize_class(vmSymbols::java_lang_String(), CHECK);
3249 
3250   // Initialize java_lang.System (needed before creating the thread)
3251   initialize_class(vmSymbols::java_lang_System(), CHECK);
3252   // The VM creates & returns objects of this class. Make sure it's initialized.
3253   initialize_class(vmSymbols::java_lang_Class(), CHECK);
3254   initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
3255   Handle thread_group = create_initial_thread_group(CHECK);
3256   Universe::set_main_thread_group(thread_group());
3257   initialize_class(vmSymbols::java_lang_Thread(), CHECK);
3258   oop thread_object = create_initial_thread(thread_group, main_thread, CHECK);
3259   main_thread->set_threadObj(thread_object);
3260   // Set thread status to running since main thread has
3261   // been started and running.
3262   java_lang_Thread::set_thread_status(thread_object,
3263                                       java_lang_Thread::RUNNABLE);
3264 
3265   // The VM preresolves methods to these classes. Make sure that they get initialized
3266   initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
3267   initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
3268   call_initializeSystemClass(CHECK);
3269 
3270   // get the Java runtime name after java.lang.System is initialized
3271   JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
3272   JDK_Version::set_runtime_version(get_java_runtime_version(THREAD));
3273 
3274   // an instance of OutOfMemory exception has been allocated earlier
3275   initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
3276   initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
3277   initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
3278   initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
3279   initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
3280   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
3281   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
3282   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
3283 }
3284 
3285 void Threads::initialize_jsr292_core_classes(TRAPS) {
3286   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
3287   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
3288   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
3289 }
3290 
3291 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
3292   extern void JDK_Version_init();
3293 
3294   // Preinitialize version info.
3295   VM_Version::early_initialize();
3296 
3297   // Check version
3298   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
3299 
3300   // Initialize the output stream module
3301   ostream_init();
3302 
3303   // Process java launcher properties.
3304   Arguments::process_sun_java_launcher_properties(args);
3305 
3306   // Initialize the os module before using TLS
3307   os::init();
3308 
3309   // Initialize system properties.
3310   Arguments::init_system_properties();
3311 
3312   // So that JDK version can be used as a discriminator when parsing arguments
3313   JDK_Version_init();
3314 
3315   // Update/Initialize System properties after JDK version number is known
3316   Arguments::init_version_specific_system_properties();
3317 
3318   // Parse arguments
3319   jint parse_result = Arguments::parse(args);
3320   if (parse_result != JNI_OK) return parse_result;
3321 
3322   os::init_before_ergo();
3323 
3324   jint ergo_result = Arguments::apply_ergo();
3325   if (ergo_result != JNI_OK) return ergo_result;
3326 
3327   // Final check of all ranges after ergonomics which may change values.
3328   if (!CommandLineFlagRangeList::check_ranges()) {
3329     return JNI_EINVAL;
3330   }
3331 
3332   // Final check of all 'AfterErgo' constraints after ergonomics which may change values.
3333   bool constraint_result = CommandLineFlagConstraintList::check_constraints(CommandLineFlagConstraint::AfterErgo);
3334   if (!constraint_result) {
3335     return JNI_EINVAL;
3336   }
3337 
3338   if (PauseAtStartup) {
3339     os::pause();
3340   }
3341 
3342   HOTSPOT_VM_INIT_BEGIN();
3343 
3344   // Record VM creation timing statistics
3345   TraceVmCreationTime create_vm_timer;
3346   create_vm_timer.start();
3347 
3348   // Timing (must come after argument parsing)
3349   TraceTime timer("Create VM", TraceStartupTime);
3350 
3351   // Initialize the os module after parsing the args
3352   jint os_init_2_result = os::init_2();
3353   if (os_init_2_result != JNI_OK) return os_init_2_result;
3354 
3355   jint adjust_after_os_result = Arguments::adjust_after_os();
3356   if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
3357 
3358   // initialize TLS
3359   ThreadLocalStorage::init();
3360 
3361   // Initialize output stream logging
3362   ostream_init_log();
3363 
3364   // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
3365   // Must be before create_vm_init_agents()
3366   if (Arguments::init_libraries_at_startup()) {
3367     convert_vm_init_libraries_to_agents();
3368   }
3369 
3370   // Launch -agentlib/-agentpath and converted -Xrun agents
3371   if (Arguments::init_agents_at_startup()) {
3372     create_vm_init_agents();
3373   }
3374 
3375   // Initialize Threads state
3376   _thread_list = NULL;
3377   _number_of_threads = 0;
3378   _number_of_non_daemon_threads = 0;
3379 
3380   // Initialize global data structures and create system classes in heap
3381   vm_init_globals();
3382 









3383   // Attach the main thread to this os thread
3384   JavaThread* main_thread = new JavaThread();
3385   main_thread->set_thread_state(_thread_in_vm);
3386   // must do this before set_active_handles and initialize_thread_local_storage
3387   // Note: on solaris initialize_thread_local_storage() will (indirectly)
3388   // change the stack size recorded here to one based on the java thread
3389   // stacksize. This adjusted size is what is used to figure the placement
3390   // of the guard pages.
3391   main_thread->record_stack_base_and_size();
3392   main_thread->initialize_thread_local_storage();
3393 
3394   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
3395 
3396   if (!main_thread->set_as_starting_thread()) {
3397     vm_shutdown_during_initialization(
3398                                       "Failed necessary internal allocation. Out of swap space");
3399     delete main_thread;
3400     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3401     return JNI_ENOMEM;
3402   }
3403 
3404   // Enable guard page *after* os::create_main_thread(), otherwise it would
3405   // crash Linux VM, see notes in os_linux.cpp.
3406   main_thread->create_stack_guard_pages();
3407 
3408   // Initialize Java-Level synchronization subsystem
3409   ObjectMonitor::Initialize();
3410 
3411   // Initialize global modules
3412   jint status = init_globals();
3413   if (status != JNI_OK) {
3414     delete main_thread;
3415     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3416     return status;
3417   }
3418 
3419   // Should be done after the heap is fully created
3420   main_thread->cache_global_variables();
3421 
3422   HandleMark hm;
3423 
3424   { MutexLocker mu(Threads_lock);
3425     Threads::add(main_thread);
3426   }
3427 
3428   // Any JVMTI raw monitors entered in onload will transition into
3429   // real raw monitor. VM is setup enough here for raw monitor enter.
3430   JvmtiExport::transition_pending_onload_raw_monitors();
3431 
3432   // Create the VMThread
3433   { TraceTime timer("Start VMThread", TraceStartupTime);
3434     VMThread::create();
3435     Thread* vmthread = VMThread::vm_thread();
3436 
3437     if (!os::create_thread(vmthread, os::vm_thread)) {
3438       vm_exit_during_initialization("Cannot create VM thread. "
3439                                     "Out of system resources.");
3440     }
3441 
3442     // Wait for the VM thread to become ready, and VMThread::run to initialize
3443     // Monitors can have spurious returns, must always check another state flag
3444     {
3445       MutexLocker ml(Notify_lock);
3446       os::start_thread(vmthread);
3447       while (vmthread->active_handles() == NULL) {
3448         Notify_lock->wait();
3449       }
3450     }
3451   }
3452 
3453   assert(Universe::is_fully_initialized(), "not initialized");
3454   if (VerifyDuringStartup) {
3455     // Make sure we're starting with a clean slate.
3456     VM_Verify verify_op;
3457     VMThread::execute(&verify_op);
3458   }
3459 
3460   Thread* THREAD = Thread::current();
3461 
3462   // At this point, the Universe is initialized, but we have not executed
3463   // any byte code.  Now is a good time (the only time) to dump out the
3464   // internal state of the JVM for sharing.
3465   if (DumpSharedSpaces) {
3466     MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
3467     ShouldNotReachHere();
3468   }
3469 
3470   // Always call even when there are not JVMTI environments yet, since environments
3471   // may be attached late and JVMTI must track phases of VM execution
3472   JvmtiExport::enter_start_phase();
3473 
3474   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
3475   JvmtiExport::post_vm_start();
3476 
3477   initialize_java_lang_classes(main_thread, CHECK_JNI_ERR);
3478 
3479   // We need this for ClassDataSharing - the initial vm.info property is set
3480   // with the default value of CDS "sharing" which may be reset through
3481   // command line options.
3482   reset_vm_info_property(CHECK_JNI_ERR);
3483 
3484   quicken_jni_functions();
3485 
3486   // Must be run after init_ft which initializes ft_enabled
3487   if (TRACE_INITIALIZE() != JNI_OK) {
3488     vm_exit_during_initialization("Failed to initialize tracing backend");
3489   }
3490 
3491   // Set flag that basic initialization has completed. Used by exceptions and various
3492   // debug stuff, that does not work until all basic classes have been initialized.
3493   set_init_completed();
3494 
3495   Metaspace::post_initialize();
3496 
3497   HOTSPOT_VM_INIT_END();
3498 
3499   // record VM initialization completion time
3500 #if INCLUDE_MANAGEMENT
3501   Management::record_vm_init_completed();
3502 #endif // INCLUDE_MANAGEMENT
3503 
3504   // Compute system loader. Note that this has to occur after set_init_completed, since
3505   // valid exceptions may be thrown in the process.
3506   // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
3507   // set_init_completed has just been called, causing exceptions not to be shortcut
3508   // anymore. We call vm_exit_during_initialization directly instead.
3509   SystemDictionary::compute_java_system_loader(CHECK_JNI_ERR);
3510 
3511 #if INCLUDE_ALL_GCS
3512   // Support for ConcurrentMarkSweep. This should be cleaned up
3513   // and better encapsulated. The ugly nested if test would go away
3514   // once things are properly refactored. XXX YSR
3515   if (UseConcMarkSweepGC || UseG1GC) {
3516     if (UseConcMarkSweepGC) {
3517       ConcurrentMarkSweepThread::makeSurrogateLockerThread(CHECK_JNI_ERR);
3518     } else {
3519       ConcurrentMarkThread::makeSurrogateLockerThread(CHECK_JNI_ERR);
3520     }
3521   }
3522 #endif // INCLUDE_ALL_GCS
3523 
3524   // Always call even when there are not JVMTI environments yet, since environments
3525   // may be attached late and JVMTI must track phases of VM execution
3526   JvmtiExport::enter_live_phase();
3527 
3528   // Signal Dispatcher needs to be started before VMInit event is posted
3529   os::signal_init();
3530 
3531   // Start Attach Listener if +StartAttachListener or it can't be started lazily
3532   if (!DisableAttachMechanism) {
3533     AttachListener::vm_start();
3534     if (StartAttachListener || AttachListener::init_at_startup()) {
3535       AttachListener::init();
3536     }
3537   }
3538 
3539   // Launch -Xrun agents
3540   // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3541   // back-end can launch with -Xdebug -Xrunjdwp.
3542   if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3543     create_vm_init_libraries();
3544   }
3545 
3546   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3547   JvmtiExport::post_vm_initialized();
3548 
3549   if (TRACE_START() != JNI_OK) {
3550     vm_exit_during_initialization("Failed to start tracing backend.");
3551   }
3552 
3553   if (CleanChunkPoolAsync) {
3554     Chunk::start_chunk_pool_cleaner_task();
3555   }
3556 









3557   // initialize compiler(s)
3558 #if defined(COMPILER1) || defined(COMPILER2) || defined(SHARK)
3559   CompileBroker::compilation_init();
3560 #endif
3561 
3562   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
3563   // It is done after compilers are initialized, because otherwise compilations of
3564   // signature polymorphic MH intrinsics can be missed
3565   // (see SystemDictionary::find_method_handle_intrinsic).
3566   initialize_jsr292_core_classes(CHECK_JNI_ERR);
3567 
3568 #if INCLUDE_MANAGEMENT
3569   Management::initialize(THREAD);
3570 
3571   if (HAS_PENDING_EXCEPTION) {
3572     // management agent fails to start possibly due to
3573     // configuration problem and is responsible for printing
3574     // stack trace if appropriate. Simply exit VM.
3575     vm_exit(1);
3576   }
3577 #endif // INCLUDE_MANAGEMENT
3578 
3579   if (Arguments::has_profile())       FlatProfiler::engage(main_thread, true);
3580   if (MemProfiling)                   MemProfiler::engage();
3581   StatSampler::engage();
3582   if (CheckJNICalls)                  JniPeriodicChecker::engage();
3583 
3584   BiasedLocking::init();
3585 
3586 #if INCLUDE_RTM_OPT
3587   RTMLockingCounters::init();
3588 #endif
3589 
3590   if (JDK_Version::current().post_vm_init_hook_enabled()) {
3591     call_postVMInitHook(THREAD);
3592     // The Java side of PostVMInitHook.run must deal with all
3593     // exceptions and provide means of diagnosis.
3594     if (HAS_PENDING_EXCEPTION) {
3595       CLEAR_PENDING_EXCEPTION;
3596     }
3597   }
3598 
3599   {
3600     MutexLocker ml(PeriodicTask_lock);
3601     // Make sure the WatcherThread can be started by WatcherThread::start()
3602     // or by dynamic enrollment.
3603     WatcherThread::make_startable();
3604     // Start up the WatcherThread if there are any periodic tasks
3605     // NOTE:  All PeriodicTasks should be registered by now. If they
3606     //   aren't, late joiners might appear to start slowly (we might
3607     //   take a while to process their first tick).
3608     if (PeriodicTask::num_tasks() > 0) {
3609       WatcherThread::start();
3610     }
3611   }
3612 
3613   CodeCacheExtensions::complete_step(CodeCacheExtensionsSteps::CreateVM);
3614 
3615   create_vm_timer.end();
3616 #ifdef ASSERT
3617   _vm_complete = true;
3618 #endif
3619   return JNI_OK;
3620 }
3621 
3622 // type for the Agent_OnLoad and JVM_OnLoad entry points
3623 extern "C" {
3624   typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
3625 }
3626 // Find a command line agent library and return its entry point for
3627 //         -agentlib:  -agentpath:   -Xrun
3628 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
3629 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent,
3630                                     const char *on_load_symbols[],
3631                                     size_t num_symbol_entries) {
3632   OnLoadEntry_t on_load_entry = NULL;
3633   void *library = NULL;
3634 
3635   if (!agent->valid()) {
3636     char buffer[JVM_MAXPATHLEN];
3637     char ebuf[1024] = "";
3638     const char *name = agent->name();
3639     const char *msg = "Could not find agent library ";
3640 
3641     // First check to see if agent is statically linked into executable
3642     if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) {
3643       library = agent->os_lib();
3644     } else if (agent->is_absolute_path()) {
3645       library = os::dll_load(name, ebuf, sizeof ebuf);
3646       if (library == NULL) {
3647         const char *sub_msg = " in absolute path, with error: ";
3648         size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
3649         char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
3650         jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
3651         // If we can't find the agent, exit.
3652         vm_exit_during_initialization(buf, NULL);
3653         FREE_C_HEAP_ARRAY(char, buf);
3654       }
3655     } else {
3656       // Try to load the agent from the standard dll directory
3657       if (os::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
3658                              name)) {
3659         library = os::dll_load(buffer, ebuf, sizeof ebuf);
3660       }
3661       if (library == NULL) { // Try the local directory
3662         char ns[1] = {0};
3663         if (os::dll_build_name(buffer, sizeof(buffer), ns, name)) {
3664           library = os::dll_load(buffer, ebuf, sizeof ebuf);
3665         }
3666         if (library == NULL) {
3667           const char *sub_msg = " on the library path, with error: ";
3668           size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
3669           char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
3670           jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
3671           // If we can't find the agent, exit.
3672           vm_exit_during_initialization(buf, NULL);
3673           FREE_C_HEAP_ARRAY(char, buf);
3674         }
3675       }
3676     }
3677     agent->set_os_lib(library);
3678     agent->set_valid();
3679   }
3680 
3681   // Find the OnLoad function.
3682   on_load_entry =
3683     CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent,
3684                                                           false,
3685                                                           on_load_symbols,
3686                                                           num_symbol_entries));
3687   return on_load_entry;
3688 }
3689 
3690 // Find the JVM_OnLoad entry point
3691 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
3692   const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
3693   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
3694 }
3695 
3696 // Find the Agent_OnLoad entry point
3697 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
3698   const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
3699   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
3700 }
3701 
3702 // For backwards compatibility with -Xrun
3703 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
3704 // treated like -agentpath:
3705 // Must be called before agent libraries are created
3706 void Threads::convert_vm_init_libraries_to_agents() {
3707   AgentLibrary* agent;
3708   AgentLibrary* next;
3709 
3710   for (agent = Arguments::libraries(); agent != NULL; agent = next) {
3711     next = agent->next();  // cache the next agent now as this agent may get moved off this list
3712     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
3713 
3714     // If there is an JVM_OnLoad function it will get called later,
3715     // otherwise see if there is an Agent_OnLoad
3716     if (on_load_entry == NULL) {
3717       on_load_entry = lookup_agent_on_load(agent);
3718       if (on_load_entry != NULL) {
3719         // switch it to the agent list -- so that Agent_OnLoad will be called,
3720         // JVM_OnLoad won't be attempted and Agent_OnUnload will
3721         Arguments::convert_library_to_agent(agent);
3722       } else {
3723         vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
3724       }
3725     }
3726   }
3727 }
3728 
3729 // Create agents for -agentlib:  -agentpath:  and converted -Xrun
3730 // Invokes Agent_OnLoad
3731 // Called very early -- before JavaThreads exist
3732 void Threads::create_vm_init_agents() {
3733   extern struct JavaVM_ main_vm;
3734   AgentLibrary* agent;
3735 
3736   JvmtiExport::enter_onload_phase();
3737 
3738   for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
3739     OnLoadEntry_t  on_load_entry = lookup_agent_on_load(agent);
3740 
3741     if (on_load_entry != NULL) {
3742       // Invoke the Agent_OnLoad function
3743       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
3744       if (err != JNI_OK) {
3745         vm_exit_during_initialization("agent library failed to init", agent->name());
3746       }
3747     } else {
3748       vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
3749     }
3750   }
3751   JvmtiExport::enter_primordial_phase();
3752 }
3753 
3754 extern "C" {
3755   typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
3756 }
3757 
3758 void Threads::shutdown_vm_agents() {
3759   // Send any Agent_OnUnload notifications
3760   const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
3761   size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols);
3762   extern struct JavaVM_ main_vm;
3763   for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
3764 
3765     // Find the Agent_OnUnload function.
3766     Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
3767                                                    os::find_agent_function(agent,
3768                                                    false,
3769                                                    on_unload_symbols,
3770                                                    num_symbol_entries));
3771 
3772     // Invoke the Agent_OnUnload function
3773     if (unload_entry != NULL) {
3774       JavaThread* thread = JavaThread::current();
3775       ThreadToNativeFromVM ttn(thread);
3776       HandleMark hm(thread);
3777       (*unload_entry)(&main_vm);
3778     }
3779   }
3780 }
3781 
3782 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
3783 // Invokes JVM_OnLoad
3784 void Threads::create_vm_init_libraries() {
3785   extern struct JavaVM_ main_vm;
3786   AgentLibrary* agent;
3787 
3788   for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
3789     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
3790 
3791     if (on_load_entry != NULL) {
3792       // Invoke the JVM_OnLoad function
3793       JavaThread* thread = JavaThread::current();
3794       ThreadToNativeFromVM ttn(thread);
3795       HandleMark hm(thread);
3796       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
3797       if (err != JNI_OK) {
3798         vm_exit_during_initialization("-Xrun library failed to init", agent->name());
3799       }
3800     } else {
3801       vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
3802     }
3803   }
3804 }
3805 
3806 JavaThread* Threads::find_java_thread_from_java_tid(jlong java_tid) {
3807   assert(Threads_lock->owned_by_self(), "Must hold Threads_lock");
3808 
3809   JavaThread* java_thread = NULL;
3810   // Sequential search for now.  Need to do better optimization later.
3811   for (JavaThread* thread = Threads::first(); thread != NULL; thread = thread->next()) {
3812     oop tobj = thread->threadObj();
3813     if (!thread->is_exiting() &&
3814         tobj != NULL &&
3815         java_tid == java_lang_Thread::thread_id(tobj)) {
3816       java_thread = thread;
3817       break;
3818     }
3819   }
3820   return java_thread;
3821 }
3822 
3823 
3824 // Last thread running calls java.lang.Shutdown.shutdown()
3825 void JavaThread::invoke_shutdown_hooks() {
3826   HandleMark hm(this);
3827 
3828   // We could get here with a pending exception, if so clear it now.
3829   if (this->has_pending_exception()) {
3830     this->clear_pending_exception();
3831   }
3832 
3833   EXCEPTION_MARK;
3834   Klass* k =
3835     SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
3836                                       THREAD);
3837   if (k != NULL) {
3838     // SystemDictionary::resolve_or_null will return null if there was
3839     // an exception.  If we cannot load the Shutdown class, just don't
3840     // call Shutdown.shutdown() at all.  This will mean the shutdown hooks
3841     // and finalizers (if runFinalizersOnExit is set) won't be run.
3842     // Note that if a shutdown hook was registered or runFinalizersOnExit
3843     // was called, the Shutdown class would have already been loaded
3844     // (Runtime.addShutdownHook and runFinalizersOnExit will load it).
3845     instanceKlassHandle shutdown_klass (THREAD, k);
3846     JavaValue result(T_VOID);
3847     JavaCalls::call_static(&result,
3848                            shutdown_klass,
3849                            vmSymbols::shutdown_method_name(),
3850                            vmSymbols::void_method_signature(),
3851                            THREAD);
3852   }
3853   CLEAR_PENDING_EXCEPTION;
3854 }
3855 
3856 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
3857 // the program falls off the end of main(). Another VM exit path is through
3858 // vm_exit() when the program calls System.exit() to return a value or when
3859 // there is a serious error in VM. The two shutdown paths are not exactly
3860 // the same, but they share Shutdown.shutdown() at Java level and before_exit()
3861 // and VM_Exit op at VM level.
3862 //
3863 // Shutdown sequence:
3864 //   + Shutdown native memory tracking if it is on
3865 //   + Wait until we are the last non-daemon thread to execute
3866 //     <-- every thing is still working at this moment -->
3867 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
3868 //        shutdown hooks, run finalizers if finalization-on-exit
3869 //   + Call before_exit(), prepare for VM exit
3870 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),
3871 //        currently the only user of this mechanism is File.deleteOnExit())
3872 //      > stop flat profiler, StatSampler, watcher thread, CMS threads,
3873 //        post thread end and vm death events to JVMTI,
3874 //        stop signal thread
3875 //   + Call JavaThread::exit(), it will:
3876 //      > release JNI handle blocks, remove stack guard pages
3877 //      > remove this thread from Threads list
3878 //     <-- no more Java code from this thread after this point -->
3879 //   + Stop VM thread, it will bring the remaining VM to a safepoint and stop
3880 //     the compiler threads at safepoint
3881 //     <-- do not use anything that could get blocked by Safepoint -->
3882 //   + Disable tracing at JNI/JVM barriers
3883 //   + Set _vm_exited flag for threads that are still running native code
3884 //   + Delete this thread
3885 //   + Call exit_globals()
3886 //      > deletes tty
3887 //      > deletes PerfMemory resources
3888 //   + Return to caller
3889 
3890 bool Threads::destroy_vm() {
3891   JavaThread* thread = JavaThread::current();
3892 
3893 #ifdef ASSERT
3894   _vm_complete = false;
3895 #endif
3896   // Wait until we are the last non-daemon thread to execute
3897   { MutexLocker nu(Threads_lock);
3898     while (Threads::number_of_non_daemon_threads() > 1)
3899       // This wait should make safepoint checks, wait without a timeout,
3900       // and wait as a suspend-equivalent condition.
3901       //
3902       // Note: If the FlatProfiler is running and this thread is waiting
3903       // for another non-daemon thread to finish, then the FlatProfiler
3904       // is waiting for the external suspend request on this thread to
3905       // complete. wait_for_ext_suspend_completion() will eventually
3906       // timeout, but that takes time. Making this wait a suspend-
3907       // equivalent condition solves that timeout problem.
3908       //
3909       Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
3910                          Mutex::_as_suspend_equivalent_flag);
3911   }
3912 
3913   // Hang forever on exit if we are reporting an error.
3914   if (ShowMessageBoxOnError && is_error_reported()) {
3915     os::infinite_sleep();
3916   }
3917   os::wait_for_keypress_at_exit();
3918 
3919   // run Java level shutdown hooks
3920   thread->invoke_shutdown_hooks();
3921 
3922   before_exit(thread);
3923 
3924   thread->exit(true);
3925 
3926   // Stop VM thread.
3927   {
3928     // 4945125 The vm thread comes to a safepoint during exit.
3929     // GC vm_operations can get caught at the safepoint, and the
3930     // heap is unparseable if they are caught. Grab the Heap_lock
3931     // to prevent this. The GC vm_operations will not be able to
3932     // queue until after the vm thread is dead. After this point,
3933     // we'll never emerge out of the safepoint before the VM exits.
3934 
3935     MutexLocker ml(Heap_lock);
3936 
3937     VMThread::wait_for_vm_thread_exit();
3938     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
3939     VMThread::destroy();
3940   }
3941 
3942   // clean up ideal graph printers
3943 #if defined(COMPILER2) && !defined(PRODUCT)
3944   IdealGraphPrinter::clean_up();
3945 #endif
3946 
3947   // Now, all Java threads are gone except daemon threads. Daemon threads
3948   // running Java code or in VM are stopped by the Safepoint. However,
3949   // daemon threads executing native code are still running.  But they
3950   // will be stopped at native=>Java/VM barriers. Note that we can't
3951   // simply kill or suspend them, as it is inherently deadlock-prone.
3952 
3953 #ifndef PRODUCT
3954   // disable function tracing at JNI/JVM barriers
3955   TraceJNICalls = false;
3956   TraceJVMCalls = false;
3957   TraceRuntimeCalls = false;
3958 #endif
3959 
3960   VM_Exit::set_vm_exited();
3961 
3962   notify_vm_shutdown();
3963 
3964   delete thread;
3965 






3966   // exit_globals() will delete tty
3967   exit_globals();
3968 
3969   return true;
3970 }
3971 
3972 
3973 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
3974   if (version == JNI_VERSION_1_1) return JNI_TRUE;
3975   return is_supported_jni_version(version);
3976 }
3977 
3978 
3979 jboolean Threads::is_supported_jni_version(jint version) {
3980   if (version == JNI_VERSION_1_2) return JNI_TRUE;
3981   if (version == JNI_VERSION_1_4) return JNI_TRUE;
3982   if (version == JNI_VERSION_1_6) return JNI_TRUE;
3983   if (version == JNI_VERSION_1_8) return JNI_TRUE;
3984   return JNI_FALSE;
3985 }
3986 
3987 
3988 void Threads::add(JavaThread* p, bool force_daemon) {
3989   // The threads lock must be owned at this point
3990   assert_locked_or_safepoint(Threads_lock);
3991 
3992   // See the comment for this method in thread.hpp for its purpose and
3993   // why it is called here.
3994   p->initialize_queues();
3995   p->set_next(_thread_list);
3996   _thread_list = p;
3997   _number_of_threads++;
3998   oop threadObj = p->threadObj();
3999   bool daemon = true;
4000   // Bootstrapping problem: threadObj can be null for initial
4001   // JavaThread (or for threads attached via JNI)
4002   if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) {
4003     _number_of_non_daemon_threads++;
4004     daemon = false;
4005   }
4006 
4007   ThreadService::add_thread(p, daemon);
4008 
4009   // Possible GC point.
4010   Events::log(p, "Thread added: " INTPTR_FORMAT, p);
4011 }
4012 
4013 void Threads::remove(JavaThread* p) {
4014   // Extra scope needed for Thread_lock, so we can check
4015   // that we do not remove thread without safepoint code notice
4016   { MutexLocker ml(Threads_lock);
4017 
4018     assert(includes(p), "p must be present");
4019 
4020     JavaThread* current = _thread_list;
4021     JavaThread* prev    = NULL;
4022 
4023     while (current != p) {
4024       prev    = current;
4025       current = current->next();
4026     }
4027 
4028     if (prev) {
4029       prev->set_next(current->next());
4030     } else {
4031       _thread_list = p->next();
4032     }
4033     _number_of_threads--;
4034     oop threadObj = p->threadObj();
4035     bool daemon = true;
4036     if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
4037       _number_of_non_daemon_threads--;
4038       daemon = false;
4039 
4040       // Only one thread left, do a notify on the Threads_lock so a thread waiting
4041       // on destroy_vm will wake up.
4042       if (number_of_non_daemon_threads() == 1) {
4043         Threads_lock->notify_all();
4044       }
4045     }
4046     ThreadService::remove_thread(p, daemon);
4047 
4048     // Make sure that safepoint code disregard this thread. This is needed since
4049     // the thread might mess around with locks after this point. This can cause it
4050     // to do callbacks into the safepoint code. However, the safepoint code is not aware
4051     // of this thread since it is removed from the queue.
4052     p->set_terminated_value();
4053   } // unlock Threads_lock
4054 
4055   // Since Events::log uses a lock, we grab it outside the Threads_lock
4056   Events::log(p, "Thread exited: " INTPTR_FORMAT, p);
4057 }
4058 
4059 // Threads_lock must be held when this is called (or must be called during a safepoint)
4060 bool Threads::includes(JavaThread* p) {
4061   assert(Threads_lock->is_locked(), "sanity check");
4062   ALL_JAVA_THREADS(q) {
4063     if (q == p) {
4064       return true;
4065     }
4066   }
4067   return false;
4068 }
4069 
4070 // Operations on the Threads list for GC.  These are not explicitly locked,
4071 // but the garbage collector must provide a safe context for them to run.
4072 // In particular, these things should never be called when the Threads_lock
4073 // is held by some other thread. (Note: the Safepoint abstraction also
4074 // uses the Threads_lock to guarantee this property. It also makes sure that
4075 // all threads gets blocked when exiting or starting).
4076 
4077 void Threads::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
4078   ALL_JAVA_THREADS(p) {
4079     p->oops_do(f, cld_f, cf);
4080   }
4081   VMThread::vm_thread()->oops_do(f, cld_f, cf);
4082 }
4083 
4084 void Threads::change_thread_claim_parity() {
4085   // Set the new claim parity.
4086   assert(_thread_claim_parity >= 0 && _thread_claim_parity <= 2,
4087          "Not in range.");
4088   _thread_claim_parity++;
4089   if (_thread_claim_parity == 3) _thread_claim_parity = 1;
4090   assert(_thread_claim_parity >= 1 && _thread_claim_parity <= 2,
4091          "Not in range.");
4092 }
4093 
4094 #ifdef ASSERT
4095 void Threads::assert_all_threads_claimed() {
4096   ALL_JAVA_THREADS(p) {
4097     const int thread_parity = p->oops_do_parity();
4098     assert((thread_parity == _thread_claim_parity),
4099         err_msg("Thread " PTR_FORMAT " has incorrect parity %d != %d", p2i(p), thread_parity, _thread_claim_parity));
4100   }
4101 }
4102 #endif // ASSERT
4103 
4104 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
4105   int cp = Threads::thread_claim_parity();
4106   ALL_JAVA_THREADS(p) {
4107     if (p->claim_oops_do(is_par, cp)) {
4108       p->oops_do(f, cld_f, cf);
4109     }
4110   }
4111   VMThread* vmt = VMThread::vm_thread();
4112   if (vmt->claim_oops_do(is_par, cp)) {
4113     vmt->oops_do(f, cld_f, cf);
4114   }
4115 }
4116 
4117 #if INCLUDE_ALL_GCS
4118 // Used by ParallelScavenge
4119 void Threads::create_thread_roots_tasks(GCTaskQueue* q) {
4120   ALL_JAVA_THREADS(p) {
4121     q->enqueue(new ThreadRootsTask(p));
4122   }
4123   q->enqueue(new ThreadRootsTask(VMThread::vm_thread()));
4124 }
4125 
4126 // Used by Parallel Old
4127 void Threads::create_thread_roots_marking_tasks(GCTaskQueue* q) {
4128   ALL_JAVA_THREADS(p) {
4129     q->enqueue(new ThreadRootsMarkingTask(p));
4130   }
4131   q->enqueue(new ThreadRootsMarkingTask(VMThread::vm_thread()));
4132 }
4133 #endif // INCLUDE_ALL_GCS
4134 
4135 void Threads::nmethods_do(CodeBlobClosure* cf) {
4136   ALL_JAVA_THREADS(p) {
4137     p->nmethods_do(cf);
4138   }
4139   VMThread::vm_thread()->nmethods_do(cf);
4140 }
4141 
4142 void Threads::metadata_do(void f(Metadata*)) {
4143   ALL_JAVA_THREADS(p) {
4144     p->metadata_do(f);
4145   }
4146 }
4147 
4148 class ThreadHandlesClosure : public ThreadClosure {
4149   void (*_f)(Metadata*);
4150  public:
4151   ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
4152   virtual void do_thread(Thread* thread) {
4153     thread->metadata_handles_do(_f);
4154   }
4155 };
4156 
4157 void Threads::metadata_handles_do(void f(Metadata*)) {
4158   // Only walk the Handles in Thread.
4159   ThreadHandlesClosure handles_closure(f);
4160   threads_do(&handles_closure);
4161 }
4162 
4163 void Threads::deoptimized_wrt_marked_nmethods() {
4164   ALL_JAVA_THREADS(p) {
4165     p->deoptimized_wrt_marked_nmethods();
4166   }
4167 }
4168 
4169 
4170 // Get count Java threads that are waiting to enter the specified monitor.
4171 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
4172                                                          address monitor,
4173                                                          bool doLock) {
4174   assert(doLock || SafepointSynchronize::is_at_safepoint(),
4175          "must grab Threads_lock or be at safepoint");
4176   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
4177 
4178   int i = 0;
4179   {
4180     MutexLockerEx ml(doLock ? Threads_lock : NULL);
4181     ALL_JAVA_THREADS(p) {
4182       if (p->is_Compiler_thread()) continue;
4183 
4184       address pending = (address)p->current_pending_monitor();
4185       if (pending == monitor) {             // found a match
4186         if (i < count) result->append(p);   // save the first count matches
4187         i++;
4188       }
4189     }
4190   }
4191   return result;
4192 }
4193 
4194 
4195 JavaThread *Threads::owning_thread_from_monitor_owner(address owner,
4196                                                       bool doLock) {
4197   assert(doLock ||
4198          Threads_lock->owned_by_self() ||
4199          SafepointSynchronize::is_at_safepoint(),
4200          "must grab Threads_lock or be at safepoint");
4201 
4202   // NULL owner means not locked so we can skip the search
4203   if (owner == NULL) return NULL;
4204 
4205   {
4206     MutexLockerEx ml(doLock ? Threads_lock : NULL);
4207     ALL_JAVA_THREADS(p) {
4208       // first, see if owner is the address of a Java thread
4209       if (owner == (address)p) return p;
4210     }
4211   }
4212   // Cannot assert on lack of success here since this function may be
4213   // used by code that is trying to report useful problem information
4214   // like deadlock detection.
4215   if (UseHeavyMonitors) return NULL;
4216 
4217   // If we didn't find a matching Java thread and we didn't force use of
4218   // heavyweight monitors, then the owner is the stack address of the
4219   // Lock Word in the owning Java thread's stack.
4220   //
4221   JavaThread* the_owner = NULL;
4222   {
4223     MutexLockerEx ml(doLock ? Threads_lock : NULL);
4224     ALL_JAVA_THREADS(q) {
4225       if (q->is_lock_owned(owner)) {
4226         the_owner = q;
4227         break;
4228       }
4229     }
4230   }
4231   // cannot assert on lack of success here; see above comment
4232   return the_owner;
4233 }
4234 
4235 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
4236 void Threads::print_on(outputStream* st, bool print_stacks,
4237                        bool internal_format, bool print_concurrent_locks) {
4238   char buf[32];
4239   st->print_cr("%s", os::local_time_string(buf, sizeof(buf)));
4240 
4241   st->print_cr("Full thread dump %s (%s %s):",
4242                Abstract_VM_Version::vm_name(),
4243                Abstract_VM_Version::vm_release(),
4244                Abstract_VM_Version::vm_info_string());
4245   st->cr();
4246 
4247 #if INCLUDE_SERVICES
4248   // Dump concurrent locks
4249   ConcurrentLocksDump concurrent_locks;
4250   if (print_concurrent_locks) {
4251     concurrent_locks.dump_at_safepoint();
4252   }
4253 #endif // INCLUDE_SERVICES
4254 
4255   ALL_JAVA_THREADS(p) {
4256     ResourceMark rm;
4257     p->print_on(st);
4258     if (print_stacks) {
4259       if (internal_format) {
4260         p->trace_stack();
4261       } else {
4262         p->print_stack_on(st);
4263       }
4264     }
4265     st->cr();
4266 #if INCLUDE_SERVICES
4267     if (print_concurrent_locks) {
4268       concurrent_locks.print_locks_on(p, st);
4269     }
4270 #endif // INCLUDE_SERVICES
4271   }
4272 
4273   VMThread::vm_thread()->print_on(st);
4274   st->cr();
4275   Universe::heap()->print_gc_threads_on(st);
4276   WatcherThread* wt = WatcherThread::watcher_thread();
4277   if (wt != NULL) {
4278     wt->print_on(st);
4279     st->cr();
4280   }
4281   CompileBroker::print_compiler_threads_on(st);
4282   st->flush();
4283 }
4284 
4285 // Threads::print_on_error() is called by fatal error handler. It's possible
4286 // that VM is not at safepoint and/or current thread is inside signal handler.
4287 // Don't print stack trace, as the stack may not be walkable. Don't allocate
4288 // memory (even in resource area), it might deadlock the error handler.
4289 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
4290                              int buflen) {
4291   bool found_current = false;
4292   st->print_cr("Java Threads: ( => current thread )");
4293   ALL_JAVA_THREADS(thread) {
4294     bool is_current = (current == thread);
4295     found_current = found_current || is_current;
4296 
4297     st->print("%s", is_current ? "=>" : "  ");
4298 
4299     st->print(PTR_FORMAT, thread);
4300     st->print(" ");
4301     thread->print_on_error(st, buf, buflen);
4302     st->cr();
4303   }
4304   st->cr();
4305 
4306   st->print_cr("Other Threads:");
4307   if (VMThread::vm_thread()) {
4308     bool is_current = (current == VMThread::vm_thread());
4309     found_current = found_current || is_current;
4310     st->print("%s", current == VMThread::vm_thread() ? "=>" : "  ");
4311 
4312     st->print(PTR_FORMAT, VMThread::vm_thread());
4313     st->print(" ");
4314     VMThread::vm_thread()->print_on_error(st, buf, buflen);
4315     st->cr();
4316   }
4317   WatcherThread* wt = WatcherThread::watcher_thread();
4318   if (wt != NULL) {
4319     bool is_current = (current == wt);
4320     found_current = found_current || is_current;
4321     st->print("%s", is_current ? "=>" : "  ");
4322 
4323     st->print(PTR_FORMAT, wt);
4324     st->print(" ");
4325     wt->print_on_error(st, buf, buflen);
4326     st->cr();
4327   }
4328   if (!found_current) {
4329     st->cr();
4330     st->print("=>" PTR_FORMAT " (exited) ", current);
4331     current->print_on_error(st, buf, buflen);
4332     st->cr();
4333   }
4334 }
4335 
4336 // Internal SpinLock and Mutex
4337 // Based on ParkEvent
4338 
4339 // Ad-hoc mutual exclusion primitives: SpinLock and Mux
4340 //
4341 // We employ SpinLocks _only for low-contention, fixed-length
4342 // short-duration critical sections where we're concerned
4343 // about native mutex_t or HotSpot Mutex:: latency.
4344 // The mux construct provides a spin-then-block mutual exclusion
4345 // mechanism.
4346 //
4347 // Testing has shown that contention on the ListLock guarding gFreeList
4348 // is common.  If we implement ListLock as a simple SpinLock it's common
4349 // for the JVM to devolve to yielding with little progress.  This is true
4350 // despite the fact that the critical sections protected by ListLock are
4351 // extremely short.
4352 //
4353 // TODO-FIXME: ListLock should be of type SpinLock.
4354 // We should make this a 1st-class type, integrated into the lock
4355 // hierarchy as leaf-locks.  Critically, the SpinLock structure
4356 // should have sufficient padding to avoid false-sharing and excessive
4357 // cache-coherency traffic.
4358 
4359 
4360 typedef volatile int SpinLockT;
4361 
4362 void Thread::SpinAcquire(volatile int * adr, const char * LockName) {
4363   if (Atomic::cmpxchg (1, adr, 0) == 0) {
4364     return;   // normal fast-path return
4365   }
4366 
4367   // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
4368   TEVENT(SpinAcquire - ctx);
4369   int ctr = 0;
4370   int Yields = 0;
4371   for (;;) {
4372     while (*adr != 0) {
4373       ++ctr;
4374       if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
4375         if (Yields > 5) {
4376           os::naked_short_sleep(1);
4377         } else {
4378           os::naked_yield();
4379           ++Yields;
4380         }
4381       } else {
4382         SpinPause();
4383       }
4384     }
4385     if (Atomic::cmpxchg(1, adr, 0) == 0) return;
4386   }
4387 }
4388 
4389 void Thread::SpinRelease(volatile int * adr) {
4390   assert(*adr != 0, "invariant");
4391   OrderAccess::fence();      // guarantee at least release consistency.
4392   // Roach-motel semantics.
4393   // It's safe if subsequent LDs and STs float "up" into the critical section,
4394   // but prior LDs and STs within the critical section can't be allowed
4395   // to reorder or float past the ST that releases the lock.
4396   // Loads and stores in the critical section - which appear in program
4397   // order before the store that releases the lock - must also appear
4398   // before the store that releases the lock in memory visibility order.
4399   // Conceptually we need a #loadstore|#storestore "release" MEMBAR before
4400   // the ST of 0 into the lock-word which releases the lock, so fence
4401   // more than covers this on all platforms.
4402   *adr = 0;
4403 }
4404 
4405 // muxAcquire and muxRelease:
4406 //
4407 // *  muxAcquire and muxRelease support a single-word lock-word construct.
4408 //    The LSB of the word is set IFF the lock is held.
4409 //    The remainder of the word points to the head of a singly-linked list
4410 //    of threads blocked on the lock.
4411 //
4412 // *  The current implementation of muxAcquire-muxRelease uses its own
4413 //    dedicated Thread._MuxEvent instance.  If we're interested in
4414 //    minimizing the peak number of extant ParkEvent instances then
4415 //    we could eliminate _MuxEvent and "borrow" _ParkEvent as long
4416 //    as certain invariants were satisfied.  Specifically, care would need
4417 //    to be taken with regards to consuming unpark() "permits".
4418 //    A safe rule of thumb is that a thread would never call muxAcquire()
4419 //    if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently
4420 //    park().  Otherwise the _ParkEvent park() operation in muxAcquire() could
4421 //    consume an unpark() permit intended for monitorenter, for instance.
4422 //    One way around this would be to widen the restricted-range semaphore
4423 //    implemented in park().  Another alternative would be to provide
4424 //    multiple instances of the PlatformEvent() for each thread.  One
4425 //    instance would be dedicated to muxAcquire-muxRelease, for instance.
4426 //
4427 // *  Usage:
4428 //    -- Only as leaf locks
4429 //    -- for short-term locking only as muxAcquire does not perform
4430 //       thread state transitions.
4431 //
4432 // Alternatives:
4433 // *  We could implement muxAcquire and muxRelease with MCS or CLH locks
4434 //    but with parking or spin-then-park instead of pure spinning.
4435 // *  Use Taura-Oyama-Yonenzawa locks.
4436 // *  It's possible to construct a 1-0 lock if we encode the lockword as
4437 //    (List,LockByte).  Acquire will CAS the full lockword while Release
4438 //    will STB 0 into the LockByte.  The 1-0 scheme admits stranding, so
4439 //    acquiring threads use timers (ParkTimed) to detect and recover from
4440 //    the stranding window.  Thread/Node structures must be aligned on 256-byte
4441 //    boundaries by using placement-new.
4442 // *  Augment MCS with advisory back-link fields maintained with CAS().
4443 //    Pictorially:  LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner.
4444 //    The validity of the backlinks must be ratified before we trust the value.
4445 //    If the backlinks are invalid the exiting thread must back-track through the
4446 //    the forward links, which are always trustworthy.
4447 // *  Add a successor indication.  The LockWord is currently encoded as
4448 //    (List, LOCKBIT:1).  We could also add a SUCCBIT or an explicit _succ variable
4449 //    to provide the usual futile-wakeup optimization.
4450 //    See RTStt for details.
4451 // *  Consider schedctl.sc_nopreempt to cover the critical section.
4452 //
4453 
4454 
4455 typedef volatile intptr_t MutexT;      // Mux Lock-word
4456 enum MuxBits { LOCKBIT = 1 };
4457 
4458 void Thread::muxAcquire(volatile intptr_t * Lock, const char * LockName) {
4459   intptr_t w = Atomic::cmpxchg_ptr(LOCKBIT, Lock, 0);
4460   if (w == 0) return;
4461   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4462     return;
4463   }
4464 
4465   TEVENT(muxAcquire - Contention);
4466   ParkEvent * const Self = Thread::current()->_MuxEvent;
4467   assert((intptr_t(Self) & LOCKBIT) == 0, "invariant");
4468   for (;;) {
4469     int its = (os::is_MP() ? 100 : 0) + 1;
4470 
4471     // Optional spin phase: spin-then-park strategy
4472     while (--its >= 0) {
4473       w = *Lock;
4474       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4475         return;
4476       }
4477     }
4478 
4479     Self->reset();
4480     Self->OnList = intptr_t(Lock);
4481     // The following fence() isn't _strictly necessary as the subsequent
4482     // CAS() both serializes execution and ratifies the fetched *Lock value.
4483     OrderAccess::fence();
4484     for (;;) {
4485       w = *Lock;
4486       if ((w & LOCKBIT) == 0) {
4487         if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4488           Self->OnList = 0;   // hygiene - allows stronger asserts
4489           return;
4490         }
4491         continue;      // Interference -- *Lock changed -- Just retry
4492       }
4493       assert(w & LOCKBIT, "invariant");
4494       Self->ListNext = (ParkEvent *) (w & ~LOCKBIT);
4495       if (Atomic::cmpxchg_ptr(intptr_t(Self)|LOCKBIT, Lock, w) == w) break;
4496     }
4497 
4498     while (Self->OnList != 0) {
4499       Self->park();
4500     }
4501   }
4502 }
4503 
4504 void Thread::muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev) {
4505   intptr_t w = Atomic::cmpxchg_ptr(LOCKBIT, Lock, 0);
4506   if (w == 0) return;
4507   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4508     return;
4509   }
4510 
4511   TEVENT(muxAcquire - Contention);
4512   ParkEvent * ReleaseAfter = NULL;
4513   if (ev == NULL) {
4514     ev = ReleaseAfter = ParkEvent::Allocate(NULL);
4515   }
4516   assert((intptr_t(ev) & LOCKBIT) == 0, "invariant");
4517   for (;;) {
4518     guarantee(ev->OnList == 0, "invariant");
4519     int its = (os::is_MP() ? 100 : 0) + 1;
4520 
4521     // Optional spin phase: spin-then-park strategy
4522     while (--its >= 0) {
4523       w = *Lock;
4524       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4525         if (ReleaseAfter != NULL) {
4526           ParkEvent::Release(ReleaseAfter);
4527         }
4528         return;
4529       }
4530     }
4531 
4532     ev->reset();
4533     ev->OnList = intptr_t(Lock);
4534     // The following fence() isn't _strictly necessary as the subsequent
4535     // CAS() both serializes execution and ratifies the fetched *Lock value.
4536     OrderAccess::fence();
4537     for (;;) {
4538       w = *Lock;
4539       if ((w & LOCKBIT) == 0) {
4540         if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
4541           ev->OnList = 0;
4542           // We call ::Release while holding the outer lock, thus
4543           // artificially lengthening the critical section.
4544           // Consider deferring the ::Release() until the subsequent unlock(),
4545           // after we've dropped the outer lock.
4546           if (ReleaseAfter != NULL) {
4547             ParkEvent::Release(ReleaseAfter);
4548           }
4549           return;
4550         }
4551         continue;      // Interference -- *Lock changed -- Just retry
4552       }
4553       assert(w & LOCKBIT, "invariant");
4554       ev->ListNext = (ParkEvent *) (w & ~LOCKBIT);
4555       if (Atomic::cmpxchg_ptr(intptr_t(ev)|LOCKBIT, Lock, w) == w) break;
4556     }
4557 
4558     while (ev->OnList != 0) {
4559       ev->park();
4560     }
4561   }
4562 }
4563 
4564 // Release() must extract a successor from the list and then wake that thread.
4565 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme
4566 // similar to that used by ParkEvent::Allocate() and ::Release().  DMR-based
4567 // Release() would :
4568 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list.
4569 // (B) Extract a successor from the private list "in-hand"
4570 // (C) attempt to CAS() the residual back into *Lock over null.
4571 //     If there were any newly arrived threads and the CAS() would fail.
4572 //     In that case Release() would detach the RATs, re-merge the list in-hand
4573 //     with the RATs and repeat as needed.  Alternately, Release() might
4574 //     detach and extract a successor, but then pass the residual list to the wakee.
4575 //     The wakee would be responsible for reattaching and remerging before it
4576 //     competed for the lock.
4577 //
4578 // Both "pop" and DMR are immune from ABA corruption -- there can be
4579 // multiple concurrent pushers, but only one popper or detacher.
4580 // This implementation pops from the head of the list.  This is unfair,
4581 // but tends to provide excellent throughput as hot threads remain hot.
4582 // (We wake recently run threads first).
4583 //
4584 // All paths through muxRelease() will execute a CAS.
4585 // Release consistency -- We depend on the CAS in muxRelease() to provide full
4586 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations
4587 // executed within the critical section are complete and globally visible before the
4588 // store (CAS) to the lock-word that releases the lock becomes globally visible.
4589 void Thread::muxRelease(volatile intptr_t * Lock)  {
4590   for (;;) {
4591     const intptr_t w = Atomic::cmpxchg_ptr(0, Lock, LOCKBIT);
4592     assert(w & LOCKBIT, "invariant");
4593     if (w == LOCKBIT) return;
4594     ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT);
4595     assert(List != NULL, "invariant");
4596     assert(List->OnList == intptr_t(Lock), "invariant");
4597     ParkEvent * const nxt = List->ListNext;
4598     guarantee((intptr_t(nxt) & LOCKBIT) == 0, "invariant");
4599 
4600     // The following CAS() releases the lock and pops the head element.
4601     // The CAS() also ratifies the previously fetched lock-word value.
4602     if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) {
4603       continue;
4604     }
4605     List->OnList = 0;
4606     OrderAccess::fence();
4607     List->unpark();
4608     return;
4609   }
4610 }
4611 
4612 
4613 void Threads::verify() {
4614   ALL_JAVA_THREADS(p) {
4615     p->verify();
4616   }
4617   VMThread* thread = VMThread::vm_thread();
4618   if (thread != NULL) thread->verify();
4619 }
--- EOF ---