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