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