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