annotate src/share/vm/runtime/thread.cpp @ 4570:ae4adc1492d1

Added tag jdk7u40-b30 for changeset 24f785f94d2f
author katleman
date Fri, 21 Jun 2013 11:18:38 -0700
parents 12494ffb721b
children 370cbb35dbca fc4660f7922c
rev   line source
duke@0 1 /*
zgu@4170 2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
duke@0 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
duke@0 4 *
duke@0 5 * This code is free software; you can redistribute it and/or modify it
duke@0 6 * under the terms of the GNU General Public License version 2 only, as
duke@0 7 * published by the Free Software Foundation.
duke@0 8 *
duke@0 9 * This code is distributed in the hope that it will be useful, but WITHOUT
duke@0 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
duke@0 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
duke@0 12 * version 2 for more details (a copy is included in the LICENSE file that
duke@0 13 * accompanied this code).
duke@0 14 *
duke@0 15 * You should have received a copy of the GNU General Public License version
duke@0 16 * 2 along with this work; if not, write to the Free Software Foundation,
duke@0 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
duke@0 18 *
trims@1472 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
trims@1472 20 * or visit www.oracle.com if you need additional information or have any
trims@1472 21 * questions.
duke@0 22 *
duke@0 23 */
duke@0 24
stefank@1879 25 #include "precompiled.hpp"
stefank@1879 26 #include "classfile/classLoader.hpp"
stefank@1879 27 #include "classfile/javaClasses.hpp"
stefank@1879 28 #include "classfile/systemDictionary.hpp"
stefank@1879 29 #include "classfile/vmSymbols.hpp"
stefank@1879 30 #include "code/scopeDesc.hpp"
stefank@1879 31 #include "compiler/compileBroker.hpp"
stefank@1879 32 #include "interpreter/interpreter.hpp"
stefank@1879 33 #include "interpreter/linkResolver.hpp"
never@2433 34 #include "interpreter/oopMapCache.hpp"
kamg@2011 35 #include "jvmtifiles/jvmtiEnv.hpp"
never@3158 36 #include "memory/gcLocker.inline.hpp"
stefank@1879 37 #include "memory/oopFactory.hpp"
stefank@1879 38 #include "memory/universe.inline.hpp"
stefank@1879 39 #include "oops/instanceKlass.hpp"
stefank@1879 40 #include "oops/objArrayOop.hpp"
stefank@1879 41 #include "oops/oop.inline.hpp"
coleenp@2062 42 #include "oops/symbol.hpp"
stefank@1879 43 #include "prims/jvm_misc.hpp"
stefank@1879 44 #include "prims/jvmtiExport.hpp"
stefank@1879 45 #include "prims/jvmtiThreadState.hpp"
stefank@1879 46 #include "prims/privilegedStack.hpp"
stefank@1879 47 #include "runtime/aprofiler.hpp"
stefank@1879 48 #include "runtime/arguments.hpp"
stefank@1879 49 #include "runtime/biasedLocking.hpp"
stefank@1879 50 #include "runtime/deoptimization.hpp"
stefank@1879 51 #include "runtime/fprofiler.hpp"
stefank@1879 52 #include "runtime/frame.inline.hpp"
stefank@1879 53 #include "runtime/init.hpp"
stefank@1879 54 #include "runtime/interfaceSupport.hpp"
stefank@1879 55 #include "runtime/java.hpp"
stefank@1879 56 #include "runtime/javaCalls.hpp"
stefank@1879 57 #include "runtime/jniPeriodicChecker.hpp"
stefank@1879 58 #include "runtime/memprofiler.hpp"
stefank@1879 59 #include "runtime/mutexLocker.hpp"
stefank@1879 60 #include "runtime/objectMonitor.hpp"
stefank@1879 61 #include "runtime/osThread.hpp"
stefank@1879 62 #include "runtime/safepoint.hpp"
stefank@1879 63 #include "runtime/sharedRuntime.hpp"
stefank@1879 64 #include "runtime/statSampler.hpp"
stefank@1879 65 #include "runtime/stubRoutines.hpp"
stefank@1879 66 #include "runtime/task.hpp"
stefank@1879 67 #include "runtime/threadCritical.hpp"
stefank@1879 68 #include "runtime/threadLocalStorage.hpp"
stefank@1879 69 #include "runtime/vframe.hpp"
stefank@1879 70 #include "runtime/vframeArray.hpp"
stefank@1879 71 #include "runtime/vframe_hp.hpp"
stefank@1879 72 #include "runtime/vmThread.hpp"
stefank@1879 73 #include "runtime/vm_operations.hpp"
stefank@1879 74 #include "services/attachListener.hpp"
stefank@1879 75 #include "services/management.hpp"
zgu@3863 76 #include "services/memTracker.hpp"
stefank@1879 77 #include "services/threadService.hpp"
sla@4141 78 #include "trace/tracing.hpp"
sla@4141 79 #include "trace/traceMacros.hpp"
stefank@1879 80 #include "utilities/defaultStream.hpp"
stefank@1879 81 #include "utilities/dtrace.hpp"
stefank@1879 82 #include "utilities/events.hpp"
stefank@1879 83 #include "utilities/preserveException.hpp"
stefank@1879 84 #ifdef TARGET_OS_FAMILY_linux
stefank@1879 85 # include "os_linux.inline.hpp"
stefank@1879 86 # include "thread_linux.inline.hpp"
stefank@1879 87 #endif
stefank@1879 88 #ifdef TARGET_OS_FAMILY_solaris
stefank@1879 89 # include "os_solaris.inline.hpp"
stefank@1879 90 # include "thread_solaris.inline.hpp"
stefank@1879 91 #endif
stefank@1879 92 #ifdef TARGET_OS_FAMILY_windows
stefank@1879 93 # include "os_windows.inline.hpp"
stefank@1879 94 # include "thread_windows.inline.hpp"
stefank@1879 95 #endif
never@2796 96 #ifdef TARGET_OS_FAMILY_bsd
never@2796 97 # include "os_bsd.inline.hpp"
never@2796 98 # include "thread_bsd.inline.hpp"
never@2796 99 #endif
stefank@1879 100 #ifndef SERIALGC
stefank@1879 101 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
stefank@1879 102 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
stefank@1879 103 #include "gc_implementation/parallelScavenge/pcTasks.hpp"
stefank@1879 104 #endif
stefank@1879 105 #ifdef COMPILER1
stefank@1879 106 #include "c1/c1_Compiler.hpp"
stefank@1879 107 #endif
stefank@1879 108 #ifdef COMPILER2
stefank@1879 109 #include "opto/c2compiler.hpp"
stefank@1879 110 #include "opto/idealGraphPrinter.hpp"
stefank@1879 111 #endif
duke@0 112
duke@0 113 #ifdef DTRACE_ENABLED
duke@0 114
duke@0 115 // Only bother with this argument setup if dtrace is available
duke@0 116
dcubed@2842 117 #ifndef USDT2
duke@0 118 HS_DTRACE_PROBE_DECL(hotspot, vm__init__begin);
duke@0 119 HS_DTRACE_PROBE_DECL(hotspot, vm__init__end);
duke@0 120 HS_DTRACE_PROBE_DECL5(hotspot, thread__start, char*, intptr_t,
duke@0 121 intptr_t, intptr_t, bool);
duke@0 122 HS_DTRACE_PROBE_DECL5(hotspot, thread__stop, char*, intptr_t,
duke@0 123 intptr_t, intptr_t, bool);
duke@0 124
duke@0 125 #define DTRACE_THREAD_PROBE(probe, javathread) \
duke@0 126 { \
duke@0 127 ResourceMark rm(this); \
duke@0 128 int len = 0; \
duke@0 129 const char* name = (javathread)->get_thread_name(); \
duke@0 130 len = strlen(name); \
duke@0 131 HS_DTRACE_PROBE5(hotspot, thread__##probe, \
duke@0 132 name, len, \
duke@0 133 java_lang_Thread::thread_id((javathread)->threadObj()), \
duke@0 134 (javathread)->osthread()->thread_id(), \
duke@0 135 java_lang_Thread::is_daemon((javathread)->threadObj())); \
duke@0 136 }
duke@0 137
dcubed@2842 138 #else /* USDT2 */
dcubed@2842 139
dcubed@2842 140 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_PROBE_START
dcubed@2842 141 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_PROBE_STOP
dcubed@2842 142
dcubed@2842 143 #define DTRACE_THREAD_PROBE(probe, javathread) \
dcubed@2842 144 { \
dcubed@2842 145 ResourceMark rm(this); \
dcubed@2842 146 int len = 0; \
dcubed@2842 147 const char* name = (javathread)->get_thread_name(); \
dcubed@2842 148 len = strlen(name); \
dcubed@2842 149 HOTSPOT_THREAD_PROBE_##probe( /* probe = start, stop */ \
dcubed@2842 150 (char *) name, len, \
dcubed@2842 151 java_lang_Thread::thread_id((javathread)->threadObj()), \
dcubed@2842 152 (uintptr_t) (javathread)->osthread()->thread_id(), \
dcubed@2842 153 java_lang_Thread::is_daemon((javathread)->threadObj())); \
dcubed@2842 154 }
dcubed@2842 155
dcubed@2842 156 #endif /* USDT2 */
dcubed@2842 157
duke@0 158 #else // ndef DTRACE_ENABLED
duke@0 159
duke@0 160 #define DTRACE_THREAD_PROBE(probe, javathread)
duke@0 161
duke@0 162 #endif // ndef DTRACE_ENABLED
duke@0 163
zgu@3863 164
duke@0 165 // Class hierarchy
duke@0 166 // - Thread
duke@0 167 // - VMThread
duke@0 168 // - WatcherThread
duke@0 169 // - ConcurrentMarkSweepThread
duke@0 170 // - JavaThread
duke@0 171 // - CompilerThread
duke@0 172
duke@0 173 // ======= Thread ========
duke@0 174 // Support for forcing alignment of thread objects for biased locking
zgu@3863 175 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
duke@0 176 if (UseBiasedLocking) {
duke@0 177 const int alignment = markOopDesc::biased_lock_alignment;
duke@0 178 size_t aligned_size = size + (alignment - sizeof(intptr_t));
zgu@3863 179 void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC)
zgu@3863 180 : os::malloc(aligned_size, flags, CURRENT_PC);
duke@0 181 void* aligned_addr = (void*) align_size_up((intptr_t) real_malloc_addr, alignment);
duke@0 182 assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
duke@0 183 ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
duke@0 184 "JavaThread alignment code overflowed allocated storage");
duke@0 185 if (TraceBiasedLocking) {
duke@0 186 if (aligned_addr != real_malloc_addr)
duke@0 187 tty->print_cr("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
duke@0 188 real_malloc_addr, aligned_addr);
duke@0 189 }
duke@0 190 ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
duke@0 191 return aligned_addr;
duke@0 192 } else {
zgu@3863 193 return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
zgu@3863 194 : os::malloc(size, flags, CURRENT_PC);
duke@0 195 }
duke@0 196 }
duke@0 197
duke@0 198 void Thread::operator delete(void* p) {
duke@0 199 if (UseBiasedLocking) {
duke@0 200 void* real_malloc_addr = ((Thread*) p)->_real_malloc_address;
zgu@3863 201 FreeHeap(real_malloc_addr, mtThread);
duke@0 202 } else {
zgu@3863 203 FreeHeap(p, mtThread);
duke@0 204 }
duke@0 205 }
duke@0 206
duke@0 207
duke@0 208 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
duke@0 209 // JavaThread
duke@0 210
duke@0 211
duke@0 212 Thread::Thread() {
phh@1988 213 // stack and get_thread
phh@1988 214 set_stack_base(NULL);
phh@1988 215 set_stack_size(0);
phh@1988 216 set_self_raw_id(0);
phh@1988 217 set_lgrp_id(-1);
duke@0 218
duke@0 219 // allocated data structures
phh@1988 220 set_osthread(NULL);
zgu@3863 221 set_resource_area(new (mtThread)ResourceArea());
zgu@3863 222 set_handle_area(new (mtThread) HandleArea(NULL));
duke@0 223 set_active_handles(NULL);
duke@0 224 set_free_handle_block(NULL);
duke@0 225 set_last_handle_mark(NULL);
duke@0 226
duke@0 227 // This initial value ==> never claimed.
duke@0 228 _oops_do_parity = 0;
duke@0 229
duke@0 230 // the handle mark links itself to last_handle_mark
duke@0 231 new HandleMark(this);
duke@0 232
duke@0 233 // plain initialization
duke@0 234 debug_only(_owned_locks = NULL;)
duke@0 235 debug_only(_allow_allocation_count = 0;)
duke@0 236 NOT_PRODUCT(_allow_safepoint_count = 0;)
ysr@806 237 NOT_PRODUCT(_skip_gcalot = false;)
duke@0 238 CHECK_UNHANDLED_OOPS_ONLY(_gc_locked_out_count = 0;)
duke@0 239 _jvmti_env_iteration_count = 0;
phh@1988 240 set_allocated_bytes(0);
duke@0 241 _vm_operation_started_count = 0;
duke@0 242 _vm_operation_completed_count = 0;
duke@0 243 _current_pending_monitor = NULL;
duke@0 244 _current_pending_monitor_is_from_java = true;
duke@0 245 _current_waiting_monitor = NULL;
duke@0 246 _num_nested_signal = 0;
duke@0 247 omFreeList = NULL ;
duke@0 248 omFreeCount = 0 ;
duke@0 249 omFreeProvision = 32 ;
acorn@1507 250 omInUseList = NULL ;
acorn@1507 251 omInUseCount = 0 ;
duke@0 252
never@3264 253 #ifdef ASSERT
never@3264 254 _visited_for_critical_count = false;
never@3264 255 #endif
never@3264 256
duke@0 257 _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true);
duke@0 258 _suspend_flags = 0;
duke@0 259
duke@0 260 // thread-specific hashCode stream generator state - Marsaglia shift-xor form
duke@0 261 _hashStateX = os::random() ;
duke@0 262 _hashStateY = 842502087 ;
duke@0 263 _hashStateZ = 0x8767 ; // (int)(3579807591LL & 0xffff) ;
duke@0 264 _hashStateW = 273326509 ;
duke@0 265
duke@0 266 _OnTrap = 0 ;
duke@0 267 _schedctl = NULL ;
duke@0 268 _Stalled = 0 ;
duke@0 269 _TypeTag = 0x2BAD ;
duke@0 270
duke@0 271 // Many of the following fields are effectively final - immutable
duke@0 272 // Note that nascent threads can't use the Native Monitor-Mutex
duke@0 273 // construct until the _MutexEvent is initialized ...
duke@0 274 // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
duke@0 275 // we might instead use a stack of ParkEvents that we could provision on-demand.
duke@0 276 // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
duke@0 277 // and ::Release()
duke@0 278 _ParkEvent = ParkEvent::Allocate (this) ;
duke@0 279 _SleepEvent = ParkEvent::Allocate (this) ;
duke@0 280 _MutexEvent = ParkEvent::Allocate (this) ;
duke@0 281 _MuxEvent = ParkEvent::Allocate (this) ;
duke@0 282
duke@0 283 #ifdef CHECK_UNHANDLED_OOPS
duke@0 284 if (CheckUnhandledOops) {
duke@0 285 _unhandled_oops = new UnhandledOops(this);
duke@0 286 }
duke@0 287 #endif // CHECK_UNHANDLED_OOPS
duke@0 288 #ifdef ASSERT
duke@0 289 if (UseBiasedLocking) {
duke@0 290 assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
duke@0 291 assert(this == _real_malloc_address ||
duke@0 292 this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
duke@0 293 "bug in forced alignment of thread objects");
duke@0 294 }
duke@0 295 #endif /* ASSERT */
duke@0 296 }
duke@0 297
duke@0 298 void Thread::initialize_thread_local_storage() {
duke@0 299 // Note: Make sure this method only calls
duke@0 300 // non-blocking operations. Otherwise, it might not work
duke@0 301 // with the thread-startup/safepoint interaction.
duke@0 302
duke@0 303 // During Java thread startup, safepoint code should allow this
duke@0 304 // method to complete because it may need to allocate memory to
duke@0 305 // store information for the new thread.
duke@0 306
duke@0 307 // initialize structure dependent on thread local storage
duke@0 308 ThreadLocalStorage::set_thread(this);
duke@0 309 }
duke@0 310
duke@0 311 void Thread::record_stack_base_and_size() {
duke@0 312 set_stack_base(os::current_stack_base());
duke@0 313 set_stack_size(os::current_stack_size());
zgu@4060 314 // CR 7190089: on Solaris, primordial thread's stack is adjusted
zgu@4060 315 // in initialize_thread(). Without the adjustment, stack size is
zgu@4060 316 // incorrect if stack is set to unlimited (ulimit -s unlimited).
zgu@4060 317 // So far, only Solaris has real implementation of initialize_thread().
zgu@4060 318 //
zgu@4060 319 // set up any platform-specific state.
zgu@4060 320 os::initialize_thread(this);
zgu@4060 321
zgu@4060 322 // record thread's native stack, stack grows downward
zgu@4060 323 if (MemTracker::is_on()) {
zgu@4060 324 address stack_low_addr = stack_base() - stack_size();
zgu@4060 325 MemTracker::record_thread_stack(stack_low_addr, stack_size(), this,
zgu@4060 326 CURRENT_PC);
zgu@4060 327 }
duke@0 328 }
duke@0 329
duke@0 330
duke@0 331 Thread::~Thread() {
duke@0 332 // Reclaim the objectmonitors from the omFreeList of the moribund thread.
duke@0 333 ObjectSynchronizer::omFlush (this) ;
duke@0 334
zgu@4059 335 // stack_base can be NULL if the thread is never started or exited before
zgu@4059 336 // record_stack_base_and_size called. Although, we would like to ensure
zgu@4059 337 // that all started threads do call record_stack_base_and_size(), there is
zgu@4059 338 // not proper way to enforce that.
zgu@4059 339 if (_stack_base != NULL) {
zgu@4059 340 address low_stack_addr = stack_base() - stack_size();
zgu@4059 341 MemTracker::release_thread_stack(low_stack_addr, stack_size(), this);
zgu@4064 342 #ifdef ASSERT
zgu@4064 343 set_stack_base(NULL);
zgu@4064 344 #endif
zgu@4059 345 }
zgu@3863 346
duke@0 347 // deallocate data structures
duke@0 348 delete resource_area();
duke@0 349 // since the handle marks are using the handle area, we have to deallocated the root
duke@0 350 // handle mark before deallocating the thread's handle area,
duke@0 351 assert(last_handle_mark() != NULL, "check we have an element");
duke@0 352 delete last_handle_mark();
duke@0 353 assert(last_handle_mark() == NULL, "check we have reached the end");
duke@0 354
duke@0 355 // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
duke@0 356 // We NULL out the fields for good hygiene.
duke@0 357 ParkEvent::Release (_ParkEvent) ; _ParkEvent = NULL ;
duke@0 358 ParkEvent::Release (_SleepEvent) ; _SleepEvent = NULL ;
duke@0 359 ParkEvent::Release (_MutexEvent) ; _MutexEvent = NULL ;
duke@0 360 ParkEvent::Release (_MuxEvent) ; _MuxEvent = NULL ;
duke@0 361
duke@0 362 delete handle_area();
duke@0 363
duke@0 364 // osthread() can be NULL, if creation of thread failed.
duke@0 365 if (osthread() != NULL) os::free_thread(osthread());
duke@0 366
duke@0 367 delete _SR_lock;
duke@0 368
duke@0 369 // clear thread local storage if the Thread is deleting itself
duke@0 370 if (this == Thread::current()) {
duke@0 371 ThreadLocalStorage::set_thread(NULL);
duke@0 372 } else {
duke@0 373 // In the case where we're not the current thread, invalidate all the
duke@0 374 // caches in case some code tries to get the current thread or the
duke@0 375 // thread that was destroyed, and gets stale information.
duke@0 376 ThreadLocalStorage::invalidate_all();
duke@0 377 }
duke@0 378 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
duke@0 379 }
duke@0 380
duke@0 381 // NOTE: dummy function for assertion purpose.
duke@0 382 void Thread::run() {
duke@0 383 ShouldNotReachHere();
duke@0 384 }
duke@0 385
duke@0 386 #ifdef ASSERT
duke@0 387 // Private method to check for dangling thread pointer
duke@0 388 void check_for_dangling_thread_pointer(Thread *thread) {
duke@0 389 assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
duke@0 390 "possibility of dangling Thread pointer");
duke@0 391 }
duke@0 392 #endif
duke@0 393
duke@0 394
duke@0 395 #ifndef PRODUCT
duke@0 396 // Tracing method for basic thread operations
duke@0 397 void Thread::trace(const char* msg, const Thread* const thread) {
duke@0 398 if (!TraceThreadEvents) return;
duke@0 399 ResourceMark rm;
duke@0 400 ThreadCritical tc;
duke@0 401 const char *name = "non-Java thread";
duke@0 402 int prio = -1;
duke@0 403 if (thread->is_Java_thread()
duke@0 404 && !thread->is_Compiler_thread()) {
duke@0 405 // The Threads_lock must be held to get information about
duke@0 406 // this thread but may not be in some situations when
duke@0 407 // tracing thread events.
duke@0 408 bool release_Threads_lock = false;
duke@0 409 if (!Threads_lock->owned_by_self()) {
duke@0 410 Threads_lock->lock();
duke@0 411 release_Threads_lock = true;
duke@0 412 }
duke@0 413 JavaThread* jt = (JavaThread *)thread;
duke@0 414 name = (char *)jt->get_thread_name();
duke@0 415 oop thread_oop = jt->threadObj();
duke@0 416 if (thread_oop != NULL) {
duke@0 417 prio = java_lang_Thread::priority(thread_oop);
duke@0 418 }
duke@0 419 if (release_Threads_lock) {
duke@0 420 Threads_lock->unlock();
duke@0 421 }
duke@0 422 }
duke@0 423 tty->print_cr("Thread::%s " INTPTR_FORMAT " [%lx] %s (prio: %d)", msg, thread, thread->osthread()->thread_id(), name, prio);
duke@0 424 }
duke@0 425 #endif
duke@0 426
duke@0 427
duke@0 428 ThreadPriority Thread::get_priority(const Thread* const thread) {
duke@0 429 trace("get priority", thread);
duke@0 430 ThreadPriority priority;
duke@0 431 // Can return an error!
duke@0 432 (void)os::get_priority(thread, priority);
duke@0 433 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
duke@0 434 return priority;
duke@0 435 }
duke@0 436
duke@0 437 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
duke@0 438 trace("set priority", thread);
duke@0 439 debug_only(check_for_dangling_thread_pointer(thread);)
duke@0 440 // Can return an error!
duke@0 441 (void)os::set_priority(thread, priority);
duke@0 442 }
duke@0 443
duke@0 444
duke@0 445 void Thread::start(Thread* thread) {
duke@0 446 trace("start", thread);
duke@0 447 // Start is different from resume in that its safety is guaranteed by context or
duke@0 448 // being called from a Java method synchronized on the Thread object.
duke@0 449 if (!DisableStartThread) {
duke@0 450 if (thread->is_Java_thread()) {
duke@0 451 // Initialize the thread state to RUNNABLE before starting this thread.
duke@0 452 // Can not set it after the thread started because we do not know the
duke@0 453 // exact thread state at that time. It could be in MONITOR_WAIT or
duke@0 454 // in SLEEPING or some other state.
duke@0 455 java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
duke@0 456 java_lang_Thread::RUNNABLE);
duke@0 457 }
duke@0 458 os::start_thread(thread);
duke@0 459 }
duke@0 460 }
duke@0 461
duke@0 462 // Enqueue a VM_Operation to do the job for us - sometime later
duke@0 463 void Thread::send_async_exception(oop java_thread, oop java_throwable) {
duke@0 464 VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable);
duke@0 465 VMThread::execute(vm_stop);
duke@0 466 }
duke@0 467
duke@0 468
duke@0 469 //
duke@0 470 // Check if an external suspend request has completed (or has been
duke@0 471 // cancelled). Returns true if the thread is externally suspended and
duke@0 472 // false otherwise.
duke@0 473 //
duke@0 474 // The bits parameter returns information about the code path through
duke@0 475 // the routine. Useful for debugging:
duke@0 476 //
duke@0 477 // set in is_ext_suspend_completed():
duke@0 478 // 0x00000001 - routine was entered
duke@0 479 // 0x00000010 - routine return false at end
duke@0 480 // 0x00000100 - thread exited (return false)
duke@0 481 // 0x00000200 - suspend request cancelled (return false)
duke@0 482 // 0x00000400 - thread suspended (return true)
duke@0 483 // 0x00001000 - thread is in a suspend equivalent state (return true)
duke@0 484 // 0x00002000 - thread is native and walkable (return true)
duke@0 485 // 0x00004000 - thread is native_trans and walkable (needed retry)
duke@0 486 //
duke@0 487 // set in wait_for_ext_suspend_completion():
duke@0 488 // 0x00010000 - routine was entered
duke@0 489 // 0x00020000 - suspend request cancelled before loop (return false)
duke@0 490 // 0x00040000 - thread suspended before loop (return true)
duke@0 491 // 0x00080000 - suspend request cancelled in loop (return false)
duke@0 492 // 0x00100000 - thread suspended in loop (return true)
duke@0 493 // 0x00200000 - suspend not completed during retry loop (return false)
duke@0 494 //
duke@0 495
duke@0 496 // Helper class for tracing suspend wait debug bits.
duke@0 497 //
duke@0 498 // 0x00000100 indicates that the target thread exited before it could
duke@0 499 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
duke@0 500 // 0x00080000 each indicate a cancelled suspend request so they don't
duke@0 501 // count as wait failures either.
duke@0 502 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000)
duke@0 503
duke@0 504 class TraceSuspendDebugBits : public StackObj {
duke@0 505 private:
duke@0 506 JavaThread * jt;
duke@0 507 bool is_wait;
duke@0 508 bool called_by_wait; // meaningful when !is_wait
duke@0 509 uint32_t * bits;
duke@0 510
duke@0 511 public:
duke@0 512 TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait,
duke@0 513 uint32_t *_bits) {
duke@0 514 jt = _jt;
duke@0 515 is_wait = _is_wait;
duke@0 516 called_by_wait = _called_by_wait;
duke@0 517 bits = _bits;
duke@0 518 }
duke@0 519
duke@0 520 ~TraceSuspendDebugBits() {
duke@0 521 if (!is_wait) {
duke@0 522 #if 1
duke@0 523 // By default, don't trace bits for is_ext_suspend_completed() calls.
duke@0 524 // That trace is very chatty.
duke@0 525 return;
duke@0 526 #else
duke@0 527 if (!called_by_wait) {
duke@0 528 // If tracing for is_ext_suspend_completed() is enabled, then only
duke@0 529 // trace calls to it from wait_for_ext_suspend_completion()
duke@0 530 return;
duke@0 531 }
duke@0 532 #endif
duke@0 533 }
duke@0 534
duke@0 535 if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) {
duke@0 536 if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) {
duke@0 537 MutexLocker ml(Threads_lock); // needed for get_thread_name()
duke@0 538 ResourceMark rm;
duke@0 539
duke@0 540 tty->print_cr(
duke@0 541 "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
duke@0 542 jt->get_thread_name(), *bits);
duke@0 543
duke@0 544 guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed");
duke@0 545 }
duke@0 546 }
duke@0 547 }
duke@0 548 };
duke@0 549 #undef DEBUG_FALSE_BITS
duke@0 550
duke@0 551
duke@0 552 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits) {
duke@0 553 TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
duke@0 554
duke@0 555 bool did_trans_retry = false; // only do thread_in_native_trans retry once
duke@0 556 bool do_trans_retry; // flag to force the retry
duke@0 557
duke@0 558 *bits |= 0x00000001;
duke@0 559
duke@0 560 do {
duke@0 561 do_trans_retry = false;
duke@0 562
duke@0 563 if (is_exiting()) {
duke@0 564 // Thread is in the process of exiting. This is always checked
duke@0 565 // first to reduce the risk of dereferencing a freed JavaThread.
duke@0 566 *bits |= 0x00000100;
duke@0 567 return false;
duke@0 568 }
duke@0 569
duke@0 570 if (!is_external_suspend()) {
duke@0 571 // Suspend request is cancelled. This is always checked before
duke@0 572 // is_ext_suspended() to reduce the risk of a rogue resume
duke@0 573 // confusing the thread that made the suspend request.
duke@0 574 *bits |= 0x00000200;
duke@0 575 return false;
duke@0 576 }
duke@0 577
duke@0 578 if (is_ext_suspended()) {
duke@0 579 // thread is suspended
duke@0 580 *bits |= 0x00000400;
duke@0 581 return true;
duke@0 582 }
duke@0 583
duke@0 584 // Now that we no longer do hard suspends of threads running
duke@0 585 // native code, the target thread can be changing thread state
duke@0 586 // while we are in this routine:
duke@0 587 //
duke@0 588 // _thread_in_native -> _thread_in_native_trans -> _thread_blocked
duke@0 589 //
duke@0 590 // We save a copy of the thread state as observed at this moment
duke@0 591 // and make our decision about suspend completeness based on the
duke@0 592 // copy. This closes the race where the thread state is seen as
duke@0 593 // _thread_in_native_trans in the if-thread_blocked check, but is
duke@0 594 // seen as _thread_blocked in if-thread_in_native_trans check.
duke@0 595 JavaThreadState save_state = thread_state();
duke@0 596
duke@0 597 if (save_state == _thread_blocked && is_suspend_equivalent()) {
duke@0 598 // If the thread's state is _thread_blocked and this blocking
duke@0 599 // condition is known to be equivalent to a suspend, then we can
duke@0 600 // consider the thread to be externally suspended. This means that
duke@0 601 // the code that sets _thread_blocked has been modified to do
duke@0 602 // self-suspension if the blocking condition releases. We also
duke@0 603 // used to check for CONDVAR_WAIT here, but that is now covered by
duke@0 604 // the _thread_blocked with self-suspension check.
duke@0 605 //
duke@0 606 // Return true since we wouldn't be here unless there was still an
duke@0 607 // external suspend request.
duke@0 608 *bits |= 0x00001000;
duke@0 609 return true;
duke@0 610 } else if (save_state == _thread_in_native && frame_anchor()->walkable()) {
duke@0 611 // Threads running native code will self-suspend on native==>VM/Java
duke@0 612 // transitions. If its stack is walkable (should always be the case
duke@0 613 // unless this function is called before the actual java_suspend()
duke@0 614 // call), then the wait is done.
duke@0 615 *bits |= 0x00002000;
duke@0 616 return true;
duke@0 617 } else if (!called_by_wait && !did_trans_retry &&
duke@0 618 save_state == _thread_in_native_trans &&
duke@0 619 frame_anchor()->walkable()) {
duke@0 620 // The thread is transitioning from thread_in_native to another
duke@0 621 // thread state. check_safepoint_and_suspend_for_native_trans()
duke@0 622 // will force the thread to self-suspend. If it hasn't gotten
duke@0 623 // there yet we may have caught the thread in-between the native
duke@0 624 // code check above and the self-suspend. Lucky us. If we were
duke@0 625 // called by wait_for_ext_suspend_completion(), then it
duke@0 626 // will be doing the retries so we don't have to.
duke@0 627 //
duke@0 628 // Since we use the saved thread state in the if-statement above,
duke@0 629 // there is a chance that the thread has already transitioned to
duke@0 630 // _thread_blocked by the time we get here. In that case, we will
duke@0 631 // make a single unnecessary pass through the logic below. This
duke@0 632 // doesn't hurt anything since we still do the trans retry.
duke@0 633
duke@0 634 *bits |= 0x00004000;
duke@0 635
duke@0 636 // Once the thread leaves thread_in_native_trans for another
duke@0 637 // thread state, we break out of this retry loop. We shouldn't
duke@0 638 // need this flag to prevent us from getting back here, but
duke@0 639 // sometimes paranoia is good.
duke@0 640 did_trans_retry = true;
duke@0 641
duke@0 642 // We wait for the thread to transition to a more usable state.
duke@0 643 for (int i = 1; i <= SuspendRetryCount; i++) {
duke@0 644 // We used to do an "os::yield_all(i)" call here with the intention
duke@0 645 // that yielding would increase on each retry. However, the parameter
duke@0 646 // is ignored on Linux which means the yield didn't scale up. Waiting
duke@0 647 // on the SR_lock below provides a much more predictable scale up for
duke@0 648 // the delay. It also provides a simple/direct point to check for any
duke@0 649 // safepoint requests from the VMThread
duke@0 650
duke@0 651 // temporarily drops SR_lock while doing wait with safepoint check
duke@0 652 // (if we're a JavaThread - the WatcherThread can also call this)
duke@0 653 // and increase delay with each retry
duke@0 654 SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
duke@0 655
duke@0 656 // check the actual thread state instead of what we saved above
duke@0 657 if (thread_state() != _thread_in_native_trans) {
duke@0 658 // the thread has transitioned to another thread state so
duke@0 659 // try all the checks (except this one) one more time.
duke@0 660 do_trans_retry = true;
duke@0 661 break;
duke@0 662 }
duke@0 663 } // end retry loop
duke@0 664
duke@0 665
duke@0 666 }
duke@0 667 } while (do_trans_retry);
duke@0 668
duke@0 669 *bits |= 0x00000010;
duke@0 670 return false;
duke@0 671 }
duke@0 672
duke@0 673 //
duke@0 674 // Wait for an external suspend request to complete (or be cancelled).
duke@0 675 // Returns true if the thread is externally suspended and false otherwise.
duke@0 676 //
duke@0 677 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
duke@0 678 uint32_t *bits) {
duke@0 679 TraceSuspendDebugBits tsdb(this, true /* is_wait */,
duke@0 680 false /* !called_by_wait */, bits);
duke@0 681
duke@0 682 // local flag copies to minimize SR_lock hold time
duke@0 683 bool is_suspended;
duke@0 684 bool pending;
duke@0 685 uint32_t reset_bits;
duke@0 686
duke@0 687 // set a marker so is_ext_suspend_completed() knows we are the caller
duke@0 688 *bits |= 0x00010000;
duke@0 689
duke@0 690 // We use reset_bits to reinitialize the bits value at the top of
duke@0 691 // each retry loop. This allows the caller to make use of any
duke@0 692 // unused bits for their own marking purposes.
duke@0 693 reset_bits = *bits;
duke@0 694
duke@0 695 {
duke@0 696 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
duke@0 697 is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
duke@0 698 delay, bits);
duke@0 699 pending = is_external_suspend();
duke@0 700 }
duke@0 701 // must release SR_lock to allow suspension to complete
duke@0 702
duke@0 703 if (!pending) {
duke@0 704 // A cancelled suspend request is the only false return from
duke@0 705 // is_ext_suspend_completed() that keeps us from entering the
duke@0 706 // retry loop.
duke@0 707 *bits |= 0x00020000;
duke@0 708 return false;
duke@0 709 }
duke@0 710
duke@0 711 if (is_suspended) {
duke@0 712 *bits |= 0x00040000;
duke@0 713 return true;
duke@0 714 }
duke@0 715
duke@0 716 for (int i = 1; i <= retries; i++) {
duke@0 717 *bits = reset_bits; // reinit to only track last retry
duke@0 718
duke@0 719 // We used to do an "os::yield_all(i)" call here with the intention
duke@0 720 // that yielding would increase on each retry. However, the parameter
duke@0 721 // is ignored on Linux which means the yield didn't scale up. Waiting
duke@0 722 // on the SR_lock below provides a much more predictable scale up for
duke@0 723 // the delay. It also provides a simple/direct point to check for any
duke@0 724 // safepoint requests from the VMThread
duke@0 725
duke@0 726 {
duke@0 727 MutexLocker ml(SR_lock());
duke@0 728 // wait with safepoint check (if we're a JavaThread - the WatcherThread
duke@0 729 // can also call this) and increase delay with each retry
duke@0 730 SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
duke@0 731
duke@0 732 is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
duke@0 733 delay, bits);
duke@0 734
duke@0 735 // It is possible for the external suspend request to be cancelled
duke@0 736 // (by a resume) before the actual suspend operation is completed.
duke@0 737 // Refresh our local copy to see if we still need to wait.
duke@0 738 pending = is_external_suspend();
duke@0 739 }
duke@0 740
duke@0 741 if (!pending) {
duke@0 742 // A cancelled suspend request is the only false return from
duke@0 743 // is_ext_suspend_completed() that keeps us from staying in the
duke@0 744 // retry loop.
duke@0 745 *bits |= 0x00080000;
duke@0 746 return false;
duke@0 747 }
duke@0 748
duke@0 749 if (is_suspended) {
duke@0 750 *bits |= 0x00100000;
duke@0 751 return true;
duke@0 752 }
duke@0 753 } // end retry loop
duke@0 754
duke@0 755 // thread did not suspend after all our retries
duke@0 756 *bits |= 0x00200000;
duke@0 757 return false;
duke@0 758 }
duke@0 759
duke@0 760 #ifndef PRODUCT
duke@0 761 void JavaThread::record_jump(address target, address instr, const char* file, int line) {
duke@0 762
duke@0 763 // This should not need to be atomic as the only way for simultaneous
duke@0 764 // updates is via interrupts. Even then this should be rare or non-existant
duke@0 765 // and we don't care that much anyway.
duke@0 766
duke@0 767 int index = _jmp_ring_index;
duke@0 768 _jmp_ring_index = (index + 1 ) & (jump_ring_buffer_size - 1);
duke@0 769 _jmp_ring[index]._target = (intptr_t) target;
duke@0 770 _jmp_ring[index]._instruction = (intptr_t) instr;
duke@0 771 _jmp_ring[index]._file = file;
duke@0 772 _jmp_ring[index]._line = line;
duke@0 773 }
duke@0 774 #endif /* PRODUCT */
duke@0 775
duke@0 776 // Called by flat profiler
duke@0 777 // Callers have already called wait_for_ext_suspend_completion
duke@0 778 // The assertion for that is currently too complex to put here:
duke@0 779 bool JavaThread::profile_last_Java_frame(frame* _fr) {
duke@0 780 bool gotframe = false;
duke@0 781 // self suspension saves needed state.
duke@0 782 if (has_last_Java_frame() && _anchor.walkable()) {
duke@0 783 *_fr = pd_last_frame();
duke@0 784 gotframe = true;
duke@0 785 }
duke@0 786 return gotframe;
duke@0 787 }
duke@0 788
duke@0 789 void Thread::interrupt(Thread* thread) {
duke@0 790 trace("interrupt", thread);
duke@0 791 debug_only(check_for_dangling_thread_pointer(thread);)
duke@0 792 os::interrupt(thread);
duke@0 793 }
duke@0 794
duke@0 795 bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) {
duke@0 796 trace("is_interrupted", thread);
duke@0 797 debug_only(check_for_dangling_thread_pointer(thread);)
duke@0 798 // Note: If clear_interrupted==false, this simply fetches and
duke@0 799 // returns the value of the field osthread()->interrupted().
duke@0 800 return os::is_interrupted(thread, clear_interrupted);
duke@0 801 }
duke@0 802
duke@0 803
duke@0 804 // GC Support
duke@0 805 bool Thread::claim_oops_do_par_case(int strong_roots_parity) {
duke@0 806 jint thread_parity = _oops_do_parity;
duke@0 807 if (thread_parity != strong_roots_parity) {
duke@0 808 jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity);
johnc@2815 809 if (res == thread_parity) {
johnc@2815 810 return true;
johnc@2815 811 } else {
duke@0 812 guarantee(res == strong_roots_parity, "Or else what?");
jmasa@2941 813 assert(SharedHeap::heap()->workers()->active_workers() > 0,
jmasa@2941 814 "Should only fail when parallel.");
duke@0 815 return false;
duke@0 816 }
duke@0 817 }
jmasa@2941 818 assert(SharedHeap::heap()->workers()->active_workers() > 0,
duke@0 819 "Should only fail when parallel.");
duke@0 820 return false;
duke@0 821 }
duke@0 822
jrose@989 823 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
duke@0 824 active_handles()->oops_do(f);
duke@0 825 // Do oop for ThreadShadow
duke@0 826 f->do_oop((oop*)&_pending_exception);
duke@0 827 handle_area()->oops_do(f);
duke@0 828 }
duke@0 829
jrose@989 830 void Thread::nmethods_do(CodeBlobClosure* cf) {
jrose@989 831 // no nmethods in a generic thread...
duke@0 832 }
duke@0 833
duke@0 834 void Thread::print_on(outputStream* st) const {
duke@0 835 // get_priority assumes osthread initialized
duke@0 836 if (osthread() != NULL) {
duke@0 837 st->print("prio=%d tid=" INTPTR_FORMAT " ", get_priority(this), this);
duke@0 838 osthread()->print_on(st);
duke@0 839 }
duke@0 840 debug_only(if (WizardMode) print_owned_locks_on(st);)
duke@0 841 }
duke@0 842
duke@0 843 // Thread::print_on_error() is called by fatal error handler. Don't use
duke@0 844 // any lock or allocate memory.
duke@0 845 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
duke@0 846 if (is_VM_thread()) st->print("VMThread");
duke@0 847 else if (is_Compiler_thread()) st->print("CompilerThread");
duke@0 848 else if (is_Java_thread()) st->print("JavaThread");
duke@0 849 else if (is_GC_task_thread()) st->print("GCTaskThread");
duke@0 850 else if (is_Watcher_thread()) st->print("WatcherThread");
duke@0 851 else if (is_ConcurrentGC_thread()) st->print("ConcurrentGCThread");
duke@0 852 else st->print("Thread");
duke@0 853
duke@0 854 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
duke@0 855 _stack_base - _stack_size, _stack_base);
duke@0 856
duke@0 857 if (osthread()) {
duke@0 858 st->print(" [id=%d]", osthread()->thread_id());
duke@0 859 }
duke@0 860 }
duke@0 861
duke@0 862 #ifdef ASSERT
duke@0 863 void Thread::print_owned_locks_on(outputStream* st) const {
duke@0 864 Monitor *cur = _owned_locks;
duke@0 865 if (cur == NULL) {
duke@0 866 st->print(" (no locks) ");
duke@0 867 } else {
duke@0 868 st->print_cr(" Locks owned:");
duke@0 869 while(cur) {
duke@0 870 cur->print_on(st);
duke@0 871 cur = cur->next();
duke@0 872 }
duke@0 873 }
duke@0 874 }
duke@0 875
duke@0 876 static int ref_use_count = 0;
duke@0 877
duke@0 878 bool Thread::owns_locks_but_compiled_lock() const {
duke@0 879 for(Monitor *cur = _owned_locks; cur; cur = cur->next()) {
duke@0 880 if (cur != Compile_lock) return true;
duke@0 881 }
duke@0 882 return false;
duke@0 883 }
duke@0 884
duke@0 885
duke@0 886 #endif
duke@0 887
duke@0 888 #ifndef PRODUCT
duke@0 889
duke@0 890 // The flag: potential_vm_operation notifies if this particular safepoint state could potential
duke@0 891 // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that
duke@0 892 // no threads which allow_vm_block's are held
duke@0 893 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
duke@0 894 // Check if current thread is allowed to block at a safepoint
duke@0 895 if (!(_allow_safepoint_count == 0))
duke@0 896 fatal("Possible safepoint reached by thread that does not allow it");
duke@0 897 if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
duke@0 898 fatal("LEAF method calling lock?");
duke@0 899 }
duke@0 900
duke@0 901 #ifdef ASSERT
duke@0 902 if (potential_vm_operation && is_Java_thread()
duke@0 903 && !Universe::is_bootstrapping()) {
duke@0 904 // Make sure we do not hold any locks that the VM thread also uses.
duke@0 905 // This could potentially lead to deadlocks
duke@0 906 for(Monitor *cur = _owned_locks; cur; cur = cur->next()) {
duke@0 907 // Threads_lock is special, since the safepoint synchronization will not start before this is
duke@0 908 // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock,
duke@0 909 // since it is used to transfer control between JavaThreads and the VMThread
duke@0 910 // Do not *exclude* any locks unless you are absolutly sure it is correct. Ask someone else first!
duke@0 911 if ( (cur->allow_vm_block() &&
duke@0 912 cur != Threads_lock &&
duke@0 913 cur != Compile_lock && // Temporary: should not be necessary when we get spearate compilation
duke@0 914 cur != VMOperationRequest_lock &&
duke@0 915 cur != VMOperationQueue_lock) ||
duke@0 916 cur->rank() == Mutex::special) {
duke@0 917 warning("Thread holding lock at safepoint that vm can block on: %s", cur->name());
duke@0 918 }
duke@0 919 }
duke@0 920 }
duke@0 921
duke@0 922 if (GCALotAtAllSafepoints) {
duke@0 923 // We could enter a safepoint here and thus have a gc
duke@0 924 InterfaceSupport::check_gc_alot();
duke@0 925 }
duke@0 926 #endif
duke@0 927 }
duke@0 928 #endif
duke@0 929
duke@0 930 bool Thread::is_in_stack(address adr) const {
duke@0 931 assert(Thread::current() == this, "is_in_stack can only be called from current thread");
duke@0 932 address end = os::current_stack_pointer();
duke@0 933 if (stack_base() >= adr && adr >= end) return true;
duke@0 934
duke@0 935 return false;
duke@0 936 }
duke@0 937
duke@0 938
duke@0 939 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
duke@0 940 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
duke@0 941 // used for compilation in the future. If that change is made, the need for these methods
duke@0 942 // should be revisited, and they should be removed if possible.
duke@0 943
duke@0 944 bool Thread::is_lock_owned(address adr) const {
kvn@1608 945 return on_local_stack(adr);
duke@0 946 }
duke@0 947
duke@0 948 bool Thread::set_as_starting_thread() {
duke@0 949 // NOTE: this must be called inside the main thread.
duke@0 950 return os::create_main_thread((JavaThread*)this);
duke@0 951 }
duke@0 952
coleenp@2062 953 static void initialize_class(Symbol* class_name, TRAPS) {
duke@0 954 klassOop klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
duke@0 955 instanceKlass::cast(klass)->initialize(CHECK);
duke@0 956 }
duke@0 957
duke@0 958
duke@0 959 // Creates the initial ThreadGroup
duke@0 960 static Handle create_initial_thread_group(TRAPS) {
coleenp@2062 961 klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ThreadGroup(), true, CHECK_NH);
duke@0 962 instanceKlassHandle klass (THREAD, k);
duke@0 963
duke@0 964 Handle system_instance = klass->allocate_instance_handle(CHECK_NH);
duke@0 965 {
duke@0 966 JavaValue result(T_VOID);
duke@0 967 JavaCalls::call_special(&result,
duke@0 968 system_instance,
duke@0 969 klass,
coleenp@2062 970 vmSymbols::object_initializer_name(),
coleenp@2062 971 vmSymbols::void_method_signature(),
duke@0 972 CHECK_NH);
duke@0 973 }
duke@0 974 Universe::set_system_thread_group(system_instance());
duke@0 975
duke@0 976 Handle main_instance = klass->allocate_instance_handle(CHECK_NH);
duke@0 977 {
duke@0 978 JavaValue result(T_VOID);
duke@0 979 Handle string = java_lang_String::create_from_str("main", CHECK_NH);
duke@0 980 JavaCalls::call_special(&result,
duke@0 981 main_instance,
duke@0 982 klass,
coleenp@2062 983 vmSymbols::object_initializer_name(),
coleenp@2062 984 vmSymbols::threadgroup_string_void_signature(),
duke@0 985 system_instance,
duke@0 986 string,
duke@0 987 CHECK_NH);
duke@0 988 }
duke@0 989 return main_instance;
duke@0 990 }
duke@0 991
duke@0 992 // Creates the initial Thread
duke@0 993 static oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) {
coleenp@2062 994 klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_NULL);
duke@0 995 instanceKlassHandle klass (THREAD, k);
duke@0 996 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL);
duke@0 997
duke@0 998 java_lang_Thread::set_thread(thread_oop(), thread);
duke@0 999 java_lang_Thread::set_priority(thread_oop(), NormPriority);
duke@0 1000 thread->set_threadObj(thread_oop());
duke@0 1001
duke@0 1002 Handle string = java_lang_String::create_from_str("main", CHECK_NULL);
duke@0 1003
duke@0 1004 JavaValue result(T_VOID);
duke@0 1005 JavaCalls::call_special(&result, thread_oop,
duke@0 1006 klass,
coleenp@2062 1007 vmSymbols::object_initializer_name(),
coleenp@2062 1008 vmSymbols::threadgroup_string_void_signature(),
duke@0 1009 thread_group,
duke@0 1010 string,
duke@0 1011 CHECK_NULL);
duke@0 1012 return thread_oop();
duke@0 1013 }
duke@0 1014
duke@0 1015 static void call_initializeSystemClass(TRAPS) {
coleenp@2062 1016 klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
duke@0 1017 instanceKlassHandle klass (THREAD, k);
duke@0 1018
duke@0 1019 JavaValue result(T_VOID);
coleenp@2062 1020 JavaCalls::call_static(&result, klass, vmSymbols::initializeSystemClass_name(),
coleenp@2062 1021 vmSymbols::void_method_signature(), CHECK);
duke@0 1022 }
duke@0 1023
twisti@3847 1024 char java_runtime_name[128] = "";
sla@4063 1025 char java_runtime_version[128] = "";
twisti@3847 1026
twisti@3847 1027 // extract the JRE name from sun.misc.Version.java_runtime_name
twisti@3847 1028 static const char* get_java_runtime_name(TRAPS) {
twisti@3847 1029 klassOop k = SystemDictionary::find(vmSymbols::sun_misc_Version(),
twisti@3847 1030 Handle(), Handle(), CHECK_AND_CLEAR_NULL);
twisti@3847 1031 fieldDescriptor fd;
twisti@3847 1032 bool found = k != NULL &&
twisti@3847 1033 instanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(),
twisti@3847 1034 vmSymbols::string_signature(), &fd);
twisti@3847 1035 if (found) {
twisti@3847 1036 oop name_oop = k->java_mirror()->obj_field(fd.offset());
twisti@3847 1037 if (name_oop == NULL)
twisti@3847 1038 return NULL;
twisti@3847 1039 const char* name = java_lang_String::as_utf8_string(name_oop,
twisti@3847 1040 java_runtime_name,
twisti@3847 1041 sizeof(java_runtime_name));
twisti@3847 1042 return name;
twisti@3847 1043 } else {
twisti@3847 1044 return NULL;
twisti@3847 1045 }
twisti@3847 1046 }
twisti@3847 1047
sla@4063 1048 // extract the JRE version from sun.misc.Version.java_runtime_version
sla@4063 1049 static const char* get_java_runtime_version(TRAPS) {
sla@4063 1050 klassOop k = SystemDictionary::find(vmSymbols::sun_misc_Version(),
sla@4063 1051 Handle(), Handle(), CHECK_AND_CLEAR_NULL);
sla@4063 1052 fieldDescriptor fd;
sla@4063 1053 bool found = k != NULL &&
sla@4063 1054 instanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(),
sla@4063 1055 vmSymbols::string_signature(), &fd);
sla@4063 1056 if (found) {
sla@4063 1057 oop name_oop = k->java_mirror()->obj_field(fd.offset());
sla@4063 1058 if (name_oop == NULL)
sla@4063 1059 return NULL;
sla@4063 1060 const char* name = java_lang_String::as_utf8_string(name_oop,
sla@4063 1061 java_runtime_version,
sla@4063 1062 sizeof(java_runtime_version));
sla@4063 1063 return name;
sla@4063 1064 } else {
sla@4063 1065 return NULL;
sla@4063 1066 }
sla@4063 1067 }
sla@4063 1068
kevinw@2014 1069 // General purpose hook into Java code, run once when the VM is initialized.
kevinw@2014 1070 // The Java library method itself may be changed independently from the VM.
kevinw@2014 1071 static void call_postVMInitHook(TRAPS) {
never@2771 1072 klassOop k = SystemDictionary::PostVMInitHook_klass();
kevinw@2014 1073 instanceKlassHandle klass (THREAD, k);
kevinw@2014 1074 if (klass.not_null()) {
kevinw@2014 1075 JavaValue result(T_VOID);
coleenp@2062 1076 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
coleenp@2062 1077 vmSymbols::void_method_signature(),
kevinw@2014 1078 CHECK);
kevinw@2014 1079 }
kevinw@2014 1080 }
kevinw@2014 1081
duke@0 1082 static void reset_vm_info_property(TRAPS) {
duke@0 1083 // the vm info string
duke@0 1084 ResourceMark rm(THREAD);
duke@0 1085 const char *vm_info = VM_Version::vm_info_string();
duke@0 1086
duke@0 1087 // java.lang.System class
coleenp@2062 1088 klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
duke@0 1089 instanceKlassHandle klass (THREAD, k);
duke@0 1090
duke@0 1091 // setProperty arguments
duke@0 1092 Handle key_str = java_lang_String::create_from_str("java.vm.info", CHECK);
duke@0 1093 Handle value_str = java_lang_String::create_from_str(vm_info, CHECK);
duke@0 1094
duke@0 1095 // return value
duke@0 1096 JavaValue r(T_OBJECT);
duke@0 1097
duke@0 1098 // public static String setProperty(String key, String value);
duke@0 1099 JavaCalls::call_static(&r,
duke@0 1100 klass,
coleenp@2062 1101 vmSymbols::setProperty_name(),
coleenp@2062 1102 vmSymbols::string_string_string_signature(),
duke@0 1103 key_str,
duke@0 1104 value_str,
duke@0 1105 CHECK);
duke@0 1106 }
duke@0 1107
duke@0 1108
duke@0 1109 void JavaThread::allocate_threadObj(Handle thread_group, char* thread_name, bool daemon, TRAPS) {
duke@0 1110 assert(thread_group.not_null(), "thread group should be specified");
duke@0 1111 assert(threadObj() == NULL, "should only create Java thread object once");
duke@0 1112
coleenp@2062 1113 klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
duke@0 1114 instanceKlassHandle klass (THREAD, k);
duke@0 1115 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
duke@0 1116
duke@0 1117 java_lang_Thread::set_thread(thread_oop(), this);
duke@0 1118 java_lang_Thread::set_priority(thread_oop(), NormPriority);
duke@0 1119 set_threadObj(thread_oop());
duke@0 1120
duke@0 1121 JavaValue result(T_VOID);
duke@0 1122 if (thread_name != NULL) {
duke@0 1123 Handle name = java_lang_String::create_from_str(thread_name, CHECK);
duke@0 1124 // Thread gets assigned specified name and null target
duke@0 1125 JavaCalls::call_special(&result,
duke@0 1126 thread_oop,
duke@0 1127 klass,
coleenp@2062 1128 vmSymbols::object_initializer_name(),
coleenp@2062 1129 vmSymbols::threadgroup_string_void_signature(),
duke@0 1130 thread_group, // Argument 1
duke@0 1131 name, // Argument 2
duke@0 1132 THREAD);
duke@0 1133 } else {
duke@0 1134 // Thread gets assigned name "Thread-nnn" and null target
duke@0 1135 // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
duke@0 1136 JavaCalls::call_special(&result,
duke@0 1137 thread_oop,
duke@0 1138 klass,
coleenp@2062 1139 vmSymbols::object_initializer_name(),
coleenp@2062 1140 vmSymbols::threadgroup_runnable_void_signature(),
duke@0 1141 thread_group, // Argument 1
duke@0 1142 Handle(), // Argument 2
duke@0 1143 THREAD);
duke@0 1144 }
duke@0 1145
duke@0 1146
duke@0 1147 if (daemon) {
duke@0 1148 java_lang_Thread::set_daemon(thread_oop());
duke@0 1149 }
duke@0 1150
duke@0 1151 if (HAS_PENDING_EXCEPTION) {
duke@0 1152 return;
duke@0 1153 }
duke@0 1154
never@1142 1155 KlassHandle group(this, SystemDictionary::ThreadGroup_klass());
duke@0 1156 Handle threadObj(this, this->threadObj());
duke@0 1157
duke@0 1158 JavaCalls::call_special(&result,
duke@0 1159 thread_group,
duke@0 1160 group,
coleenp@2062 1161 vmSymbols::add_method_name(),
coleenp@2062 1162 vmSymbols::thread_void_signature(),
duke@0 1163 threadObj, // Arg 1
duke@0 1164 THREAD);
duke@0 1165
duke@0 1166
duke@0 1167 }
duke@0 1168
duke@0 1169 // NamedThread -- non-JavaThread subclasses with multiple
duke@0 1170 // uniquely named instances should derive from this.
duke@0 1171 NamedThread::NamedThread() : Thread() {
duke@0 1172 _name = NULL;
minqi@1119 1173 _processed_thread = NULL;
duke@0 1174 }
duke@0 1175
duke@0 1176 NamedThread::~NamedThread() {
duke@0 1177 if (_name != NULL) {
zgu@3863 1178 FREE_C_HEAP_ARRAY(char, _name, mtThread);
duke@0 1179 _name = NULL;
duke@0 1180 }
duke@0 1181 }
duke@0 1182
duke@0 1183 void NamedThread::set_name(const char* format, ...) {
duke@0 1184 guarantee(_name == NULL, "Only get to set name once.");
zgu@3863 1185 _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
duke@0 1186 guarantee(_name != NULL, "alloc failure");
duke@0 1187 va_list ap;
duke@0 1188 va_start(ap, format);
duke@0 1189 jio_vsnprintf(_name, max_name_len, format, ap);
duke@0 1190 va_end(ap);
duke@0 1191 }
duke@0 1192
duke@0 1193 // ======= WatcherThread ========
duke@0 1194
duke@0 1195 // The watcher thread exists to simulate timer interrupts. It should
duke@0 1196 // be replaced by an abstraction over whatever native support for
duke@0 1197 // timer interrupts exists on the platform.
duke@0 1198
duke@0 1199 WatcherThread* WatcherThread::_watcher_thread = NULL;
rbackman@4046 1200 bool WatcherThread::_startable = false;
bobv@1601 1201 volatile bool WatcherThread::_should_terminate = false;
duke@0 1202
duke@0 1203 WatcherThread::WatcherThread() : Thread() {
duke@0 1204 assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
duke@0 1205 if (os::create_thread(this, os::watcher_thread)) {
duke@0 1206 _watcher_thread = this;
duke@0 1207
duke@0 1208 // Set the watcher thread to the highest OS priority which should not be
duke@0 1209 // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY
duke@0 1210 // is created. The only normal thread using this priority is the reference
duke@0 1211 // handler thread, which runs for very short intervals only.
duke@0 1212 // If the VMThread's priority is not lower than the WatcherThread profiling
duke@0 1213 // will be inaccurate.
duke@0 1214 os::set_priority(this, MaxPriority);
duke@0 1215 if (!DisableStartThread) {
duke@0 1216 os::start_thread(this);
duke@0 1217 }
duke@0 1218 }
duke@0 1219 }
duke@0 1220
rbackman@4046 1221 int WatcherThread::sleep() const {
rbackman@4046 1222 MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
rbackman@4046 1223
rbackman@4046 1224 // remaining will be zero if there are no tasks,
rbackman@4046 1225 // causing the WatcherThread to sleep until a task is
rbackman@4046 1226 // enrolled
rbackman@4046 1227 int remaining = PeriodicTask::time_to_wait();
rbackman@4046 1228 int time_slept = 0;
rbackman@4046 1229
rbackman@4046 1230 // we expect this to timeout - we only ever get unparked when
rbackman@4046 1231 // we should terminate or when a new task has been enrolled
rbackman@4046 1232 OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
rbackman@4046 1233
rbackman@4046 1234 jlong time_before_loop = os::javaTimeNanos();
rbackman@4046 1235
rbackman@4046 1236 for (;;) {
rbackman@4046 1237 bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag, remaining);
rbackman@4046 1238 jlong now = os::javaTimeNanos();
rbackman@4046 1239
rbackman@4046 1240 if (remaining == 0) {
rbackman@4046 1241 // if we didn't have any tasks we could have waited for a long time
rbackman@4046 1242 // consider the time_slept zero and reset time_before_loop
rbackman@4046 1243 time_slept = 0;
rbackman@4046 1244 time_before_loop = now;
rbackman@4046 1245 } else {
rbackman@4046 1246 // need to recalulate since we might have new tasks in _tasks
rbackman@4046 1247 time_slept = (int) ((now - time_before_loop) / 1000000);
rbackman@4046 1248 }
rbackman@4046 1249
rbackman@4046 1250 // Change to task list or spurious wakeup of some kind
rbackman@4046 1251 if (timedout || _should_terminate) {
rbackman@4046 1252 break;
rbackman@4046 1253 }
rbackman@4046 1254
rbackman@4046 1255 remaining = PeriodicTask::time_to_wait();
rbackman@4046 1256 if (remaining == 0) {
rbackman@4046 1257 // Last task was just disenrolled so loop around and wait until
rbackman@4046 1258 // another task gets enrolled
rbackman@4046 1259 continue;
rbackman@4046 1260 }
rbackman@4046 1261
rbackman@4046 1262 remaining -= time_slept;
rbackman@4046 1263 if (remaining <= 0)
rbackman@4046 1264 break;
rbackman@4046 1265 }
rbackman@4046 1266
rbackman@4046 1267 return time_slept;
rbackman@4046 1268 }
rbackman@4046 1269
duke@0 1270 void WatcherThread::run() {
duke@0 1271 assert(this == watcher_thread(), "just checking");
duke@0 1272
duke@0 1273 this->record_stack_base_and_size();
duke@0 1274 this->initialize_thread_local_storage();
duke@0 1275 this->set_active_handles(JNIHandleBlock::allocate_block());
duke@0 1276 while(!_should_terminate) {
duke@0 1277 assert(watcher_thread() == Thread::current(), "thread consistency check");
duke@0 1278 assert(watcher_thread() == this, "thread consistency check");
duke@0 1279
duke@0 1280 // Calculate how long it'll be until the next PeriodicTask work
duke@0 1281 // should be done, and sleep that amount of time.
rbackman@4046 1282 int time_waited = sleep();
duke@0 1283
duke@0 1284 if (is_error_reported()) {
duke@0 1285 // A fatal error has happened, the error handler(VMError::report_and_die)
duke@0 1286 // should abort JVM after creating an error log file. However in some
duke@0 1287 // rare cases, the error handler itself might deadlock. Here we try to
duke@0 1288 // kill JVM if the fatal error handler fails to abort in 2 minutes.
duke@0 1289 //
duke@0 1290 // This code is in WatcherThread because WatcherThread wakes up
duke@0 1291 // periodically so the fatal error handler doesn't need to do anything;
duke@0 1292 // also because the WatcherThread is less likely to crash than other
duke@0 1293 // threads.
duke@0 1294
duke@0 1295 for (;;) {
duke@0 1296 if (!ShowMessageBoxOnError
duke@0 1297 && (OnError == NULL || OnError[0] == '\0')
duke@0 1298 && Arguments::abort_hook() == NULL) {
duke@0 1299 os::sleep(this, 2 * 60 * 1000, false);
duke@0 1300 fdStream err(defaultStream::output_fd());
duke@0 1301 err.print_raw_cr("# [ timer expired, abort... ]");
duke@0 1302 // skip atexit/vm_exit/vm_abort hooks
duke@0 1303 os::die();
duke@0 1304 }
duke@0 1305
duke@0 1306 // Wake up 5 seconds later, the fatal handler may reset OnError or
duke@0 1307 // ShowMessageBoxOnError when it is ready to abort.
duke@0 1308 os::sleep(this, 5 * 1000, false);
duke@0 1309 }
duke@0 1310 }
duke@0 1311
rbackman@4046 1312 PeriodicTask::real_time_tick(time_waited);
duke@0 1313 }
duke@0 1314
duke@0 1315 // Signal that it is terminated
duke@0 1316 {
duke@0 1317 MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag);
duke@0 1318 _watcher_thread = NULL;
duke@0 1319 Terminator_lock->notify();
duke@0 1320 }
duke@0 1321
duke@0 1322 // Thread destructor usually does this..
duke@0 1323 ThreadLocalStorage::set_thread(NULL);
duke@0 1324 }
duke@0 1325
duke@0 1326 void WatcherThread::start() {
rbackman@4046 1327 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
rbackman@4046 1328
rbackman@4046 1329 if (watcher_thread() == NULL && _startable) {
duke@0 1330 _should_terminate = false;
duke@0 1331 // Create the single instance of WatcherThread
duke@0 1332 new WatcherThread();
duke@0 1333 }
duke@0 1334 }
duke@0 1335
rbackman@4046 1336 void WatcherThread::make_startable() {
rbackman@4046 1337 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
rbackman@4046 1338 _startable = true;
rbackman@4046 1339 }
rbackman@4046 1340
duke@0 1341 void WatcherThread::stop() {
rbackman@4046 1342 {
rbackman@4046 1343 MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
rbackman@4046 1344 _should_terminate = true;
rbackman@4046 1345 OrderAccess::fence(); // ensure WatcherThread sees update in main loop
rbackman@4046 1346
rbackman@4046 1347 WatcherThread* watcher = watcher_thread();
rbackman@4046 1348 if (watcher != NULL)
rbackman@4046 1349 watcher->unpark();
rbackman@4046 1350 }
rbackman@4046 1351
duke@0 1352 // it is ok to take late safepoints here, if needed
duke@0 1353 MutexLocker mu(Terminator_lock);
bobv@1601 1354
duke@0 1355 while(watcher_thread() != NULL) {
duke@0 1356 // This wait should make safepoint checks, wait without a timeout,
duke@0 1357 // and wait as a suspend-equivalent condition.
duke@0 1358 //
duke@0 1359 // Note: If the FlatProfiler is running, then this thread is waiting
duke@0 1360 // for the WatcherThread to terminate and the WatcherThread, via the
duke@0 1361 // FlatProfiler task, is waiting for the external suspend request on
duke@0 1362 // this thread to complete. wait_for_ext_suspend_completion() will
duke@0 1363 // eventually timeout, but that takes time. Making this wait a
duke@0 1364 // suspend-equivalent condition solves that timeout problem.
duke@0 1365 //
duke@0 1366 Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
duke@0 1367 Mutex::_as_suspend_equivalent_flag);
duke@0 1368 }
duke@0 1369 }
duke@0 1370
rbackman@4046 1371 void WatcherThread::unpark() {
rbackman@4046 1372 MutexLockerEx ml(PeriodicTask_lock->owned_by_self() ? NULL : PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
rbackman@4046 1373 PeriodicTask_lock->notify();
rbackman@4046 1374 }
rbackman@4046 1375
duke@0 1376 void WatcherThread::print_on(outputStream* st) const {
duke@0 1377 st->print("\"%s\" ", name());
duke@0 1378 Thread::print_on(st);
duke@0 1379 st->cr();
duke@0 1380 }
duke@0 1381
duke@0 1382 // ======= JavaThread ========
duke@0 1383
duke@0 1384 // A JavaThread is a normal Java thread
duke@0 1385
duke@0 1386 void JavaThread::initialize() {
duke@0 1387 // Initialize fields
ysr@342 1388
ysr@342 1389 // Set the claimed par_id to -1 (ie not claiming any par_ids)
ysr@342 1390 set_claimed_par_id(-1);
ysr@342 1391
duke@0 1392 set_saved_exception_pc(NULL);
duke@0 1393 set_threadObj(NULL);
duke@0 1394 _anchor.clear();
duke@0 1395 set_entry_point(NULL);
duke@0 1396 set_jni_functions(jni_functions());
duke@0 1397 set_callee_target(NULL);
duke@0 1398 set_vm_result(NULL);
duke@0 1399 set_vm_result_2(NULL);
duke@0 1400 set_vframe_array_head(NULL);
duke@0 1401 set_vframe_array_last(NULL);
duke@0 1402 set_deferred_locals(NULL);
duke@0 1403 set_deopt_mark(NULL);
iveresov@1734 1404 set_deopt_nmethod(NULL);
duke@0 1405 clear_must_deopt_id();
duke@0 1406 set_monitor_chunks(NULL);
duke@0 1407 set_next(NULL);
duke@0 1408 set_thread_state(_thread_new);
zgu@3863 1409 set_recorder(NULL);
duke@0 1410 _terminated = _not_terminated;
duke@0 1411 _privileged_stack_top = NULL;
duke@0 1412 _array_for_gc = NULL;
duke@0 1413 _suspend_equivalent = false;
duke@0 1414 _in_deopt_handler = 0;
duke@0 1415 _doing_unsafe_access = false;
duke@0 1416 _stack_guard_state = stack_guard_unused;
duke@0 1417 _exception_oop = NULL;
duke@0 1418 _exception_pc = 0;
duke@0 1419 _exception_handler_pc = 0;
twisti@1823 1420 _is_method_handle_return = 0;
duke@0 1421 _jvmti_thread_state= NULL;
dcubed@1213 1422 _should_post_on_exceptions_flag = JNI_FALSE;
duke@0 1423 _jvmti_get_loaded_classes_closure = NULL;
duke@0 1424 _interp_only_mode = 0;
duke@0 1425 _special_runtime_exit_condition = _no_async_condition;
duke@0 1426 _pending_async_exception = NULL;
duke@0 1427 _is_compiling = false;
duke@0 1428 _thread_stat = NULL;
duke@0 1429 _thread_stat = new ThreadStatistics();
duke@0 1430 _blocked_on_compilation = false;
duke@0 1431 _jni_active_critical = 0;
duke@0 1432 _do_not_unlock_if_synchronized = false;
duke@0 1433 _cached_monitor_info = NULL;
duke@0 1434 _parker = Parker::Allocate(this) ;
duke@0 1435
duke@0 1436 #ifndef PRODUCT
duke@0 1437 _jmp_ring_index = 0;
duke@0 1438 for (int ji = 0 ; ji < jump_ring_buffer_size ; ji++ ) {
duke@0 1439 record_jump(NULL, NULL, NULL, 0);
duke@0 1440 }
duke@0 1441 #endif /* PRODUCT */
duke@0 1442
duke@0 1443 set_thread_profiler(NULL);
duke@0 1444 if (FlatProfiler::is_active()) {
duke@0 1445 // This is where we would decide to either give each thread it's own profiler
duke@0 1446 // or use one global one from FlatProfiler,
duke@0 1447 // or up to some count of the number of profiled threads, etc.
duke@0 1448 ThreadProfiler* pp = new ThreadProfiler();
duke@0 1449 pp->engage();
duke@0 1450 set_thread_profiler(pp);
duke@0 1451 }
duke@0 1452
duke@0 1453 // Setup safepoint state info for this thread
duke@0 1454 ThreadSafepointState::create(this);
duke@0 1455
duke@0 1456 debug_only(_java_call_counter = 0);
duke@0 1457
duke@0 1458 // JVMTI PopFrame support
duke@0 1459 _popframe_condition = popframe_inactive;
duke@0 1460 _popframe_preserved_args = NULL;
duke@0 1461 _popframe_preserved_args_size = 0;
duke@0 1462
duke@0 1463 pd_initialize();
duke@0 1464 }
duke@0 1465
ysr@342 1466 #ifndef SERIALGC
ysr@342 1467 SATBMarkQueueSet JavaThread::_satb_mark_queue_set;
ysr@342 1468 DirtyCardQueueSet JavaThread::_dirty_card_queue_set;
ysr@342 1469 #endif // !SERIALGC
ysr@342 1470
dcubed@2842 1471 JavaThread::JavaThread(bool is_attaching_via_jni) :
ysr@342 1472 Thread()
ysr@342 1473 #ifndef SERIALGC
ysr@342 1474 , _satb_mark_queue(&_satb_mark_queue_set),
ysr@342 1475 _dirty_card_queue(&_dirty_card_queue_set)
ysr@342 1476 #endif // !SERIALGC
ysr@342 1477 {
duke@0 1478 initialize();
dcubed@2842 1479 if (is_attaching_via_jni) {
dcubed@2842 1480 _jni_attach_state = _attaching_via_jni;
dcubed@2842 1481 } else {
dcubed@2842 1482 _jni_attach_state = _not_attaching_via_jni;
dcubed@2842 1483 }
johnc@4275 1484 assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
zgu@3863 1485 _safepoint_visible = false;
duke@0 1486 }
duke@0 1487
duke@0 1488 bool JavaThread::reguard_stack(address cur_sp) {
duke@0 1489 if (_stack_guard_state != stack_guard_yellow_disabled) {
duke@0 1490 return true; // Stack already guarded or guard pages not needed.
duke@0 1491 }
duke@0 1492
duke@0 1493 if (register_stack_overflow()) {
duke@0 1494 // For those architectures which have separate register and
duke@0 1495 // memory stacks, we must check the register stack to see if
duke@0 1496 // it has overflowed.
duke@0 1497 return false;
duke@0 1498 }
duke@0 1499
duke@0 1500 // Java code never executes within the yellow zone: the latter is only
duke@0 1501 // there to provoke an exception during stack banging. If java code
duke@0 1502 // is executing there, either StackShadowPages should be larger, or
duke@0 1503 // some exception code in c1, c2 or the interpreter isn't unwinding
duke@0 1504 // when it should.
duke@0 1505 guarantee(cur_sp > stack_yellow_zone_base(), "not enough space to reguard - increase StackShadowPages");
duke@0 1506
duke@0 1507 enable_stack_yellow_zone();
duke@0 1508 return true;
duke@0 1509 }
duke@0 1510
duke@0 1511 bool JavaThread::reguard_stack(void) {
duke@0 1512 return reguard_stack(os::current_stack_pointer());
duke@0 1513 }
duke@0 1514
duke@0 1515
duke@0 1516 void JavaThread::block_if_vm_exited() {
duke@0 1517 if (_terminated == _vm_exited) {
duke@0 1518 // _vm_exited is set at safepoint, and Threads_lock is never released
duke@0 1519 // we will block here forever
duke@0 1520 Threads_lock->lock_without_safepoint_check();
duke@0 1521 ShouldNotReachHere();
duke@0 1522 }
duke@0 1523 }
duke@0 1524
duke@0 1525
duke@0 1526 // Remove this ifdef when C1 is ported to the compiler interface.
duke@0 1527 static void compiler_thread_entry(JavaThread* thread, TRAPS);
duke@0 1528
ysr@342 1529 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
ysr@342 1530 Thread()
ysr@342 1531 #ifndef SERIALGC
ysr@342 1532 , _satb_mark_queue(&_satb_mark_queue_set),
ysr@342 1533 _dirty_card_queue(&_dirty_card_queue_set)
ysr@342 1534 #endif // !SERIALGC
ysr@342 1535 {
duke@0 1536 if (TraceThreadEvents) {
duke@0 1537 tty->print_cr("creating thread %p", this);
duke@0 1538 }
duke@0 1539 initialize();
dcubed@2842 1540 _jni_attach_state = _not_attaching_via_jni;
duke@0 1541 set_entry_point(entry_point);
duke@0 1542 // Create the native thread itself.
duke@0 1543 // %note runtime_23
duke@0 1544 os::ThreadType thr_type = os::java_thread;
duke@0 1545 thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
duke@0 1546 os::java_thread;
duke@0 1547 os::create_thread(this, thr_type, stack_sz);
zgu@3863 1548 _safepoint_visible = false;
duke@0 1549 // The _osthread may be NULL here because we ran out of memory (too many threads active).
duke@0 1550 // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
duke@0 1551 // may hold a lock and all locks must be unlocked before throwing the exception (throwing
duke@0 1552 // the exception consists of creating the exception object & initializing it, initialization
duke@0 1553 // will leave the VM via a JavaCall and then all locks must be unlocked).
duke@0 1554 //
duke@0 1555 // The thread is still suspended when we reach here. Thread must be explicit started
duke@0 1556 // by creator! Furthermore, the thread must also explicitly be added to the Threads list
duke@0 1557 // by calling Threads:add. The reason why this is not done here, is because the thread
duke@0 1558 // object must be fully initialized (take a look at JVM_Start)
duke@0 1559 }
duke@0 1560
duke@0 1561 JavaThread::~JavaThread() {
duke@0 1562 if (TraceThreadEvents) {
duke@0 1563 tty->print_cr("terminate thread %p", this);
duke@0 1564 }
duke@0 1565
zgu@4064 1566 // By now, this thread should already be invisible to safepoint,
zgu@4064 1567 // and its per-thread recorder also collected.
zgu@3863 1568 assert(!is_safepoint_visible(), "wrong state");
zgu@4064 1569 #if INCLUDE_NMT
zgu@4064 1570 assert(get_recorder() == NULL, "Already collected");
zgu@4064 1571 #endif // INCLUDE_NMT
zgu@3863 1572
duke@0 1573 // JSR166 -- return the parker to the free list
duke@0 1574 Parker::Release(_parker);
duke@0 1575 _parker = NULL ;
duke@0 1576
duke@0 1577 // Free any remaining previous UnrollBlock
duke@0 1578 vframeArray* old_array = vframe_array_last();
duke@0 1579
duke@0 1580 if (old_array != NULL) {
duke@0 1581 Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
duke@0 1582 old_array->set_unroll_block(NULL);
duke@0 1583 delete old_info;
duke@0 1584 delete old_array;
duke@0 1585 }
duke@0 1586
duke@0 1587 GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals();
duke@0 1588 if (deferred != NULL) {
duke@0 1589 // This can only happen if thread is destroyed before deoptimization occurs.
duke@0 1590 assert(deferred->length() != 0, "empty array!");
duke@0 1591 do {
duke@0 1592 jvmtiDeferredLocalVariableSet* dlv = deferred->at(0);
duke@0 1593 deferred->remove_at(0);
duke@0 1594 // individual jvmtiDeferredLocalVariableSet are CHeapObj's
duke@0 1595 delete dlv;
duke@0 1596 } while (deferred->length() != 0);
duke@0 1597 delete deferred;
duke@0 1598 }
duke@0 1599
duke@0 1600 // All Java related clean up happens in exit
duke@0 1601 ThreadSafepointState::destroy(this);
duke@0 1602 if (_thread_profiler != NULL) delete _thread_profiler;
duke@0 1603 if (_thread_stat != NULL) delete _thread_stat;
duke@0 1604 }
duke@0 1605
duke@0 1606
duke@0 1607 // The first routine called by a new Java thread
duke@0 1608 void JavaThread::run() {
duke@0 1609 // initialize thread-local alloc buffer related fields
duke@0 1610 this->initialize_tlab();
duke@0 1611
duke@0 1612 // used to test validitity of stack trace backs
duke@0 1613 this->record_base_of_stack_pointer();
duke@0 1614
duke@0 1615 // Record real stack base and size.
duke@0 1616 this->record_stack_base_and_size();
duke@0 1617
duke@0 1618 // Initialize thread local storage; set before calling MutexLocker
duke@0 1619 this->initialize_thread_local_storage();
duke@0 1620
duke@0 1621 this->create_stack_guard_pages();
duke@0 1622
bobv@1601 1623 this->cache_global_variables();
bobv@1601 1624
duke@0 1625 // Thread is now sufficient initialized to be handled by the safepoint code as being
duke@0 1626 // in the VM. Change thread state from _thread_new to _thread_in_vm
duke@0 1627 ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
duke@0 1628
duke@0 1629 assert(JavaThread::current() == this, "sanity check");
duke@0 1630 assert(!Thread::current()->owns_locks(), "sanity check");
duke@0 1631
duke@0 1632 DTRACE_THREAD_PROBE(start, this);
duke@0 1633
duke@0 1634 // This operation might block. We call that after all safepoint checks for a new thread has
duke@0 1635 // been completed.
duke@0 1636 this->set_active_handles(JNIHandleBlock::allocate_block());
duke@0 1637
duke@0 1638 if (JvmtiExport::should_post_thread_life()) {
duke@0 1639 JvmtiExport::post_thread_start(this);
duke@0 1640 }
duke@0 1641
sla@4141 1642 EventThreadStart event;
sla@4141 1643 if (event.should_commit()) {
sla@4141 1644 event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj()));
sla@4141 1645 event.commit();
sla@4141 1646 }
phh@3081 1647
duke@0 1648 // We call another function to do the rest so we are sure that the stack addresses used
duke@0 1649 // from there will be lower than the stack base just computed
duke@0 1650 thread_main_inner();
duke@0 1651
duke@0 1652 // Note, thread is no longer valid at this point!
duke@0 1653 }
duke@0 1654
duke@0 1655
duke@0 1656 void JavaThread::thread_main_inner() {
duke@0 1657 assert(JavaThread::current() == this, "sanity check");
duke@0 1658 assert(this->threadObj() != NULL, "just checking");
duke@0 1659
dholmes@2047 1660 // Execute thread entry point unless this thread has a pending exception
dholmes@2047 1661 // or has been stopped before starting.
duke@0 1662 // Note: Due to JVM_StopThread we can have pending exceptions already!
dholmes@2047 1663 if (!this->has_pending_exception() &&
dholmes@2047 1664 !java_lang_Thread::is_stillborn(this->threadObj())) {
dcubed@2842 1665 {
dcubed@2842 1666 ResourceMark rm(this);
dcubed@2842 1667 this->set_native_thread_name(this->get_thread_name());
dcubed@2842 1668 }
duke@0 1669 HandleMark hm(this);
duke@0 1670 this->entry_point()(this, this);
duke@0 1671 }
duke@0 1672
duke@0 1673 DTRACE_THREAD_PROBE(stop, this);
duke@0 1674
duke@0 1675 this->exit(false);
duke@0 1676 delete this;
duke@0 1677 }
duke@0 1678
duke@0 1679
duke@0 1680 static void ensure_join(JavaThread* thread) {
duke@0 1681 // We do not need to grap the Threads_lock, since we are operating on ourself.
duke@0 1682 Handle threadObj(thread, thread->threadObj());
duke@0 1683 assert(threadObj.not_null(), "java thread object must exist");
duke@0 1684 ObjectLocker lock(threadObj, thread);
duke@0 1685 // Ignore pending exception (ThreadDeath), since we are exiting anyway
duke@0 1686 thread->clear_pending_exception();
duke@0 1687 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
duke@0 1688 java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
dholmes@2047 1689 // Clear the native thread instance - this makes isAlive return false and allows the join()
dholmes@2047 1690 // to complete once we've done the notify_all below
duke@0 1691 java_lang_Thread::set_thread(threadObj(), NULL);
duke@0 1692 lock.notify_all(thread);
duke@0 1693 // Ignore pending exception (ThreadDeath), since we are exiting anyway
duke@0 1694 thread->clear_pending_exception();
duke@0 1695 }
duke@0 1696
iveresov@441 1697
duke@0 1698 // For any new cleanup additions, please check to see if they need to be applied to
duke@0 1699 // cleanup_failed_attach_current_thread as well.
duke@0 1700 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
duke@0 1701 assert(this == JavaThread::current(), "thread consistency check");
duke@0 1702 if (!InitializeJavaLangSystem) return;
duke@0 1703
duke@0 1704 HandleMark hm(this);
duke@0 1705 Handle uncaught_exception(this, this->pending_exception());
duke@0 1706 this->clear_pending_exception();
duke@0 1707 Handle threadObj(this, this->threadObj());
duke@0 1708 assert(threadObj.not_null(), "Java thread object should be created");
duke@0 1709
duke@0 1710 if (get_thread_profiler() != NULL) {
duke@0 1711 get_thread_profiler()->disengage();
duke@0 1712 ResourceMark rm;
duke@0 1713 get_thread_profiler()->print(get_thread_name());
duke@0 1714 }
duke@0 1715
duke@0 1716
duke@0 1717 // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place
duke@0 1718 {
duke@0 1719 EXCEPTION_MARK;
duke@0 1720
duke@0 1721 CLEAR_PENDING_EXCEPTION;
duke@0 1722 }
duke@0 1723 // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This
duke@0 1724 // has to be fixed by a runtime query method
duke@0 1725 if (!destroy_vm || JDK_Version::is_jdk12x_version()) {
duke@0 1726 // JSR-166: change call from from ThreadGroup.uncaughtException to
duke@0 1727 // java.lang.Thread.dispatchUncaughtException
duke@0 1728 if (uncaught_exception.not_null()) {
duke@0 1729 Handle group(this, java_lang_Thread::threadGroup(threadObj()));
duke@0 1730 {
duke@0 1731 EXCEPTION_MARK;
duke@0 1732 // Check if the method Thread.dispatchUncaughtException() exists. If so
duke@0 1733 // call it. Otherwise we have an older library without the JSR-166 changes,
duke@0 1734 // so call ThreadGroup.uncaughtException()
duke@0 1735 KlassHandle recvrKlass(THREAD, threadObj->klass());
duke@0 1736 CallInfo callinfo;
never@1142 1737 KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
duke@0 1738 LinkResolver::resolve_virtual_call(callinfo, threadObj, recvrKlass, thread_klass,
coleenp@2062 1739 vmSymbols::dispatchUncaughtException_name(),
coleenp@2062 1740 vmSymbols::throwable_void_signature(),
duke@0 1741 KlassHandle(), false, false, THREAD);
duke@0 1742 CLEAR_PENDING_EXCEPTION;
duke@0 1743 methodHandle method = callinfo.selected_method();
duke@0 1744 if (method.not_null()) {
duke@0 1745 JavaValue result(T_VOID);
duke@0 1746 JavaCalls::call_virtual(&result,
duke@0 1747 threadObj, thread_klass,
coleenp@2062 1748 vmSymbols::dispatchUncaughtException_name(),
coleenp@2062 1749 vmSymbols::throwable_void_signature(),
duke@0 1750 uncaught_exception,
duke@0 1751 THREAD);
duke@0 1752 } else {
never@1142 1753 KlassHandle thread_group(THREAD, SystemDictionary::ThreadGroup_klass());
duke@0 1754 JavaValue result(T_VOID);
duke@0 1755 JavaCalls::call_virtual(&result,
duke@0 1756 group, thread_group,
coleenp@2062 1757 vmSymbols::uncaughtException_name(),
coleenp@2062 1758 vmSymbols::thread_throwable_void_signature(),
duke@0 1759 threadObj, // Arg 1
duke@0 1760 uncaught_exception, // Arg 2
duke@0 1761 THREAD);
duke@0 1762 }
coleenp@2081 1763 if (HAS_PENDING_EXCEPTION) {
coleenp@2081 1764 ResourceMark rm(this);
coleenp@2081 1765 jio_fprintf(defaultStream::error_stream(),
coleenp@2081 1766 "\nException: %s thrown from the UncaughtExceptionHandler"
coleenp@2081 1767 " in thread \"%s\"\n",
coleenp@2081 1768 Klass::cast(pending_exception()->klass())->external_name(),
coleenp@2081 1769 get_thread_name());
coleenp@2081 1770 CLEAR_PENDING_EXCEPTION;
coleenp@2081 1771 }
duke@0 1772 }
duke@0 1773 }
duke@0 1774
phh@3081 1775 // Called before the java thread exit since we want to read info
phh@3081 1776 // from java_lang_Thread object
sla@4141 1777 EventThreadEnd event;
sla@4141 1778 if (event.should_commit()) {
sla@4141 1779 event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj()));
sla@4141 1780 event.commit();
sla@4141 1781 }
phh@3081 1782
phh@3081 1783 // Call after last event on thread
phh@3081 1784 EVENT_THREAD_EXIT(this);
phh@3081 1785
duke@0 1786 // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
duke@0 1787 // the execution of the method. If that is not enough, then we don't really care. Thread.stop
duke@0 1788 // is deprecated anyhow.
duke@0 1789 { int count = 3;
duke@0 1790 while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
duke@0 1791 EXCEPTION_MARK;
duke@0 1792 JavaValue result(T_VOID);
never@1142 1793 KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
duke@0 1794 JavaCalls::call_virtual(&result,
duke@0 1795 threadObj, thread_klass,
coleenp@2062 1796 vmSymbols::exit_method_name(),
coleenp@2062 1797 vmSymbols::void_method_signature(),
duke@0 1798 THREAD);
duke@0 1799 CLEAR_PENDING_EXCEPTION;
duke@0 1800 }
duke@0 1801 }
duke@0 1802
duke@0 1803 // notify JVMTI
duke@0 1804 if (JvmtiExport::should_post_thread_life()) {
duke@0 1805 JvmtiExport::post_thread_end(this);
duke@0 1806 }
duke@0 1807
duke@0 1808 // We have notified the agents that we are exiting, before we go on,
duke@0 1809 // we must check for a pending external suspend request and honor it
duke@0 1810 // in order to not surprise the thread that made the suspend request.
duke@0 1811 while (true) {
duke@0 1812 {
duke@0 1813 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
duke@0 1814 if (!is_external_suspend()) {
duke@0 1815 set_terminated(_thread_exiting);
duke@0 1816 ThreadService::current_thread_exiting(this);
duke@0 1817 break;
duke@0 1818 }
duke@0 1819 // Implied else:
duke@0 1820 // Things get a little tricky here. We have a pending external
duke@0 1821 // suspend request, but we are holding the SR_lock so we
duke@0 1822 // can't just self-suspend. So we temporarily drop the lock
duke@0 1823 // and then self-suspend.
duke@0 1824 }
duke@0 1825
duke@0 1826 ThreadBlockInVM tbivm(this);
duke@0 1827 java_suspend_self();
duke@0 1828
duke@0 1829 // We're done with this suspend request, but we have to loop around
duke@0 1830 // and check again. Eventually we will get SR_lock without a pending
duke@0 1831 // external suspend request and will be able to mark ourselves as
duke@0 1832 // exiting.
duke@0 1833 }
duke@0 1834 // no more external suspends are allowed at this point
duke@0 1835 } else {
duke@0 1836 // before_exit() has already posted JVMTI THREAD_END events
duke@0 1837 }
duke@0 1838
duke@0 1839 // Notify waiters on thread object. This has to be done after exit() is called
duke@0 1840 // on the thread (if the thread is the last thread in a daemon ThreadGroup the
duke@0 1841 // group should have the destroyed bit set before waiters are notified).
duke@0 1842 ensure_join(this);
duke@0 1843 assert(!this->has_pending_exception(), "ensure_join should have cleared");
duke@0 1844
duke@0 1845 // 6282335 JNI DetachCurrentThread spec states that all Java monitors
duke@0 1846 // held by this thread must be released. A detach operation must only
duke@0 1847 // get here if there are no Java frames on the stack. Therefore, any
duke@0 1848 // owned monitors at this point MUST be JNI-acquired monitors which are
duke@0 1849 // pre-inflated and in the monitor cache.
duke@0 1850 //
duke@0 1851 // ensure_join() ignores IllegalThreadStateExceptions, and so does this.
duke@0 1852 if (exit_type == jni_detach && JNIDetachReleasesMonitors) {
duke@0 1853 assert(!this->has_last_Java_frame(), "detaching with Java frames?");
duke@0 1854 ObjectSynchronizer::release_monitors_owned_by_thread(this);
duke@0 1855 assert(!this->has_pending_exception(), "release_monitors should have cleared");
duke@0 1856 }
duke@0 1857
duke@0 1858 // These things needs to be done while we are still a Java Thread. Make sure that thread
duke@0 1859 // is in a consistent state, in case GC happens
duke@0 1860 assert(_privileged_stack_top == NULL, "must be NULL when we get here");
duke@0 1861
duke@0 1862 if (active_handles() != NULL) {
duke@0 1863 JNIHandleBlock* block = active_handles();
duke@0 1864 set_active_handles(NULL);
duke@0 1865 JNIHandleBlock::release_block(block);
duke@0 1866 }
duke@0 1867
duke@0 1868 if (free_handle_block() != NULL) {
duke@0 1869 JNIHandleBlock* block = free_handle_block();
duke@0 1870 set_free_handle_block(NULL);
duke@0 1871 JNIHandleBlock::release_block(block);
duke@0 1872 }
duke@0 1873
duke@0 1874 // These have to be removed while this is still a valid thread.
duke@0 1875 remove_stack_guard_pages();
duke@0 1876
duke@0 1877 if (UseTLAB) {
duke@0 1878 tlab().make_parsable(true); // retire TLAB
duke@0 1879 }
duke@0 1880
kamg@2011 1881 if (JvmtiEnv::environments_might_exist()) {
dcubed@49 1882 JvmtiExport::cleanup_thread(this);
dcubed@49 1883 }
dcubed@49 1884
johnc@4275 1885 // We must flush any deferred card marks before removing a thread from
johnc@4275 1886 // the list of active threads.
johnc@4275 1887 Universe::heap()->flush_deferred_store_barrier(this);
johnc@4275 1888 assert(deferred_card_mark().is_empty(), "Should have been flushed");
johnc@4275 1889
iveresov@441 1890 #ifndef SERIALGC
johnc@4275 1891 // We must flush the G1-related buffers before removing a thread
johnc@4275 1892 // from the list of active threads. We must do this after any deferred
johnc@4275 1893 // card marks have been flushed (above) so that any entries that are
johnc@4275 1894 // added to the thread's dirty card queue as a result are not lost.
iveresov@441 1895 if (UseG1GC) {
iveresov@441 1896 flush_barrier_queues();
iveresov@441 1897 }
iveresov@441 1898 #endif
iveresov@441 1899
duke@0 1900 // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
duke@0 1901 Threads::remove(this);
duke@0 1902 }
duke@0 1903
iveresov@441 1904 #ifndef SERIALGC
iveresov@441 1905 // Flush G1-related queues.
iveresov@441 1906 void JavaThread::flush_barrier_queues() {
iveresov@441 1907 satb_mark_queue().flush();
iveresov@441 1908 dirty_card_queue().flush();
iveresov@441 1909 }
tonyp@1762 1910
tonyp@1762 1911 void JavaThread::initialize_queues() {
tonyp@1762 1912 assert(!SafepointSynchronize::is_at_safepoint(),
tonyp@1762 1913 "we should not be at a safepoint");
tonyp@1762 1914
tonyp@1762 1915 ObjPtrQueue& satb_queue = satb_mark_queue();
tonyp@1762 1916 SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set();
tonyp@1762 1917 // The SATB queue should have been constructed with its active
tonyp@1762 1918 // field set to false.
tonyp@1762 1919 assert(!satb_queue.is_active(), "SATB queue should not be active");
tonyp@1762 1920 assert(satb_queue.is_empty(), "SATB queue should be empty");
tonyp@1762 1921 // If we are creating the thread during a marking cycle, we should
tonyp@1762 1922 // set the active field of the SATB queue to true.
tonyp@1762 1923 if (satb_queue_set.is_active()) {
tonyp@1762 1924 satb_queue.set_active(true);
tonyp@1762 1925 }
tonyp@1762 1926
tonyp@1762 1927 DirtyCardQueue& dirty_queue = dirty_card_queue();
tonyp@1762 1928 // The dirty card queue should have been constructed with its
tonyp@1762 1929 // active field set to true.
tonyp@1762 1930 assert(dirty_queue.is_active(), "dirty card queue should be active");
tonyp@1762 1931 }
tonyp@1762 1932 #endif // !SERIALGC
iveresov@441 1933
duke@0 1934 void JavaThread::cleanup_failed_attach_current_thread() {
iveresov@441 1935 if (get_thread_profiler() != NULL) {
iveresov@441 1936 get_thread_profiler()->disengage();
iveresov@441 1937 ResourceMark rm;
iveresov@441 1938 get_thread_profiler()->print(get_thread_name());
iveresov@441 1939 }
iveresov@441 1940
iveresov@441 1941 if (active_handles() != NULL) {
iveresov@441 1942 JNIHandleBlock* block = active_handles();
iveresov@441 1943 set_active_handles(NULL);
iveresov@441 1944 JNIHandleBlock::release_block(block);
iveresov@441 1945 }
iveresov@441 1946
iveresov@441 1947 if (free_handle_block() != NULL) {
iveresov@441 1948 JNIHandleBlock* block = free_handle_block();
iveresov@441 1949 set_free_handle_block(NULL);
iveresov@441 1950 JNIHandleBlock::release_block(block);
iveresov@441 1951 }
iveresov@441 1952
coleenp@1290 1953 // These have to be removed while this is still a valid thread.
coleenp@1290 1954 remove_stack_guard_pages();
coleenp@1290 1955
iveresov@441 1956 if (UseTLAB) {
iveresov@441 1957 tlab().make_parsable(true); // retire TLAB, if any
iveresov@441 1958 }
iveresov@441 1959
iveresov@441 1960 #ifndef SERIALGC
iveresov@441 1961 if (UseG1GC) {
iveresov@441 1962 flush_barrier_queues();
iveresov@441 1963 }
iveresov@441 1964 #endif
iveresov@441 1965
iveresov@441 1966 Threads::remove(this);
iveresov@441 1967 delete this;
duke@0 1968 }
duke@0 1969
duke@0 1970
iveresov@441 1971
iveresov@441 1972
duke@0 1973 JavaThread* JavaThread::active() {
duke@0 1974 Thread* thread = ThreadLocalStorage::thread();
duke@0 1975 assert(thread != NULL, "just checking");
duke@0 1976 if (thread->is_Java_thread()) {
duke@0 1977 return (JavaThread*) thread;
duke@0 1978 } else {
duke@0 1979 assert(thread->is_VM_thread(), "this must be a vm thread");
duke@0 1980 VM_Operation* op = ((VMThread*) thread)->vm_operation();
duke@0 1981 JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
duke@0 1982 assert(ret->is_Java_thread(), "must be a Java thread");
duke@0 1983 return ret;
duke@0 1984 }
duke@0 1985 }
duke@0 1986
duke@0 1987 bool JavaThread::is_lock_owned(address adr) const {
xlu@702 1988 if (Thread::is_lock_owned(adr)) return true;
duke@0 1989
duke@0 1990 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
duke@0 1991 if (chunk->contains(adr)) return true;
duke@0 1992 }
duke@0 1993
duke@0 1994 return false;
duke@0 1995 }
duke@0 1996
duke@0 1997
duke@0 1998 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
duke@0 1999 chunk->set_next(monitor_chunks());
duke@0 2000 set_monitor_chunks(chunk);
duke@0 2001 }
duke@0 2002
duke@0 2003 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
duke@0 2004 guarantee(monitor_chunks() != NULL, "must be non empty");
duke@0 2005 if (monitor_chunks() == chunk) {
duke@0 2006 set_monitor_chunks(chunk->next());
duke@0 2007 } else {
duke@0 2008 MonitorChunk* prev = monitor_chunks();
duke@0 2009 while (prev->next() != chunk) prev = prev->next();
duke@0 2010 prev->set_next(chunk->next());
duke@0 2011 }
duke@0 2012 }
duke@0 2013
duke@0 2014 // JVM support.
duke@0 2015
duke@0 2016 // Note: this function shouldn't block if it's called in
duke@0 2017 // _thread_in_native_trans state (such as from
duke@0 2018 // check_special_condition_for_native_trans()).
duke@0 2019 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) {
duke@0 2020
duke@0 2021 if (has_last_Java_frame() && has_async_condition()) {
duke@0 2022 // If we are at a polling page safepoint (not a poll return)
duke@0 2023 // then we must defer async exception because live registers
duke@0 2024 // will be clobbered by the exception path. Poll return is
duke@0 2025 // ok because the call we a returning from already collides
duke@0 2026 // with exception handling registers and so there is no issue.
duke@0 2027 // (The exception handling path kills call result registers but
duke@0 2028 // this is ok since the exception kills the result anyway).
duke@0 2029
duke@0 2030 if (is_at_poll_safepoint()) {
duke@0 2031 // if the code we are returning to has deoptimized we must defer
duke@0 2032 // the exception otherwise live registers get clobbered on the
duke@0 2033 // exception path before deoptimization is able to retrieve them.
duke@0 2034 //
duke@0 2035 RegisterMap map(this, false);
duke@0 2036 frame caller_fr = last_frame().sender(&map);
duke@0 2037 assert(caller_fr.is_compiled_frame(), "what?");
duke@0 2038 if (caller_fr.is_deoptimized_frame()) {
duke@0 2039 if (TraceExceptions) {
duke@0 2040 ResourceMark rm;
duke@0 2041 tty->print_cr("deferred async exception at compiled safepoint");
duke@0 2042 }
duke@0 2043 return;
duke@0 2044 }
duke@0 2045 }
duke@0 2046 }
duke@0 2047
duke@0 2048 JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition();
duke@0 2049 if (condition == _no_async_condition) {
duke@0 2050 // Conditions have changed since has_special_runtime_exit_condition()
duke@0 2051 // was called:
duke@0 2052 // - if we were here only because of an external suspend request,
duke@0 2053 // then that was taken care of above (or cancelled) so we are done
duke@0 2054 // - if we were here because of another async request, then it has
duke@0 2055 // been cleared between the has_special_runtime_exit_condition()
duke@0 2056 // and now so again we are done
duke@0 2057 return;
duke@0 2058 }
duke@0 2059
duke@0 2060 // Check for pending async. exception
duke@0 2061 if (_pending_async_exception != NULL) {
duke@0 2062 // Only overwrite an already pending exception, if it is not a threadDeath.
never@1142 2063 if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) {
duke@0 2064
duke@0 2065 // We cannot call Exceptions::_throw(...) here because we cannot block
duke@0 2066 set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
duke@0 2067
duke@0 2068 if (TraceExceptions) {
duke@0 2069 ResourceMark rm;
duke@0 2070 tty->print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", this);
duke@0 2071 if (has_last_Java_frame() ) {
duke@0 2072 frame f = last_frame();
duke@0 2073 tty->print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", f.pc(), f.sp());
duke@0 2074 }
duke@0 2075 tty->print_cr(" of type: %s", instanceKlass::cast(_pending_async_exception->klass())->external_name());
duke@0 2076 }
duke@0 2077 _pending_async_exception = NULL;
duke@0 2078 clear_has_async_exception();
duke@0 2079 }
duke@0 2080 }
duke@0 2081
duke@0 2082 if (check_unsafe_error &&
duke@0 2083 condition == _async_unsafe_access_error && !has_pending_exception()) {
duke@0 2084 condition = _no_async_condition; // done
duke@0 2085 switch (thread_state()) {
duke@0 2086 case _thread_in_vm:
duke@0 2087 {
duke@0 2088 JavaThread* THREAD = this;
duke@0 2089 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
duke@0 2090 }
duke@0 2091 case _thread_in_native:
duke@0 2092 {
duke@0 2093 ThreadInVMfromNative tiv(this);
duke@0 2094 JavaThread* THREAD = this;
duke@0 2095 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
duke@0 2096 }
duke@0 2097 case _thread_in_Java:
duke@0 2098 {
duke@0 2099 ThreadInVMfromJava tiv(this);
duke@0 2100 JavaThread* THREAD = this;
duke@0 2101 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
duke@0 2102 }
duke@0 2103 default:
duke@0 2104 ShouldNotReachHere();
duke@0 2105 }
duke@0 2106 }
duke@0 2107
duke@0 2108 assert(condition == _no_async_condition || has_pending_exception() ||
duke@0 2109 (!check_unsafe_error && condition == _async_unsafe_access_error),
duke@0 2110 "must have handled the async condition, if no exception");
duke@0 2111 }
duke@0 2112
duke@0 2113 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
duke@0 2114 //
duke@0 2115 // Check for pending external suspend. Internal suspend requests do
duke@0 2116 // not use handle_special_runtime_exit_condition().
duke@0 2117 // If JNIEnv proxies are allowed, don't self-suspend if the target
duke@0 2118 // thread is not the current thread. In older versions of jdbx, jdbx
duke@0 2119 // threads could call into the VM with another thread's JNIEnv so we
duke@0 2120 // can be here operating on behalf of a suspended thread (4432884).
duke@0 2121 bool do_self_suspend = is_external_suspend_with_lock();
duke@0 2122 if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) {
duke@0 2123 //
duke@0 2124 // Because thread is external suspended the safepoint code will count
duke@0 2125 // thread as at a safepoint. This can be odd because we can be here
duke@0 2126 // as _thread_in_Java which would normally transition to _thread_blocked
duke@0 2127 // at a safepoint. We would like to mark the thread as _thread_blocked
duke@0 2128 // before calling java_suspend_self like all other callers of it but
duke@0 2129 // we must then observe proper safepoint protocol. (We can't leave
duke@0 2130 // _thread_blocked with a safepoint in progress). However we can be
duke@0 2131 // here as _thread_in_native_trans so we can't use a normal transition
duke@0 2132 // constructor/destructor pair because they assert on that type of
duke@0 2133 // transition. We could do something like:
duke@0 2134 //
duke@0 2135 // JavaThreadState state = thread_state();
duke@0 2136 // set_thread_state(_thread_in_vm);
duke@0 2137 // {
duke@0 2138 // ThreadBlockInVM tbivm(this);
duke@0 2139 // java_suspend_self()
duke@0 2140 // }
duke@0 2141 // set_thread_state(_thread_in_vm_trans);
duke@0 2142 // if (safepoint) block;
duke@0 2143 // set_thread_state(state);
duke@0 2144 //
duke@0 2145 // but that is pretty messy. Instead we just go with the way the
duke@0 2146 // code has worked before and note that this is the only path to
duke@0 2147 // java_suspend_self that doesn't put the thread in _thread_blocked
duke@0 2148 // mode.
duke@0 2149
duke@0 2150 frame_anchor()->make_walkable(this);
duke@0 2151 java_suspend_self();
duke@0 2152
duke@0 2153 // We might be here for reasons in addition to the self-suspend request
duke@0 2154 // so check for other async requests.
duke@0 2155 }
duke@0 2156
duke@0 2157 if (check_asyncs) {
duke@0 2158 check_and_handle_async_exceptions();
duke@0 2159 }
duke@0 2160 }
duke@0 2161
duke@0 2162 void JavaThread::send_thread_stop(oop java_throwable) {
duke@0 2163 assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
duke@0 2164 assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
duke@0 2165 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
duke@0 2166
duke@0 2167 // Do not throw asynchronous exceptions against the compiler thread
duke@0 2168 // (the compiler thread should not be a Java thread -- fix in 1.4.2)
duke@0 2169 if (is_Compiler_thread()) return;
duke@0 2170
duke@0 2171 {
duke@0 2172 // Actually throw the Throwable against the target Thread - however
duke@0 2173 // only if there is no thread death exception installed already.
never@1142 2174 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
duke@0 2175 // If the topmost frame is a runtime stub, then we are calling into
duke@0 2176 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
duke@0 2177 // must deoptimize the caller before continuing, as the compiled exception handler table
duke@0 2178 // may not be valid
duke@0 2179 if (has_last_Java_frame()) {
duke@0 2180 frame f = last_frame();
duke@0 2181 if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
duke@0 2182 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
duke@0 2183 RegisterMap reg_map(this, UseBiasedLocking);
duke@0 2184 frame compiled_frame = f.sender(&reg_map);
kvn@4131 2185 if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
duke@0 2186 Deoptimization::deoptimize(this, compiled_frame, &reg_map);
duke@0 2187 }
duke@0 2188 }
duke@0 2189 }
duke@0 2190
duke@0 2191 // Set async. pending exception in thread.
duke@0 2192 set_pending_async_exception(java_throwable);
duke@0 2193
duke@0 2194 if (TraceExceptions) {
duke@0 2195 ResourceMark rm;
duke@0 2196 tty->print_cr("Pending Async. exception installed of type: %s", instanceKlass::cast(_pending_async_exception->klass())->external_name());
duke@0 2197 }
duke@0 2198 // for AbortVMOnException flag
duke@0 2199 NOT_PRODUCT(Exceptions::debug_check_abort(instanceKlass::cast(_pending_async_exception->klass())->external_name()));
duke@0 2200 }
duke@0 2201 }
duke@0 2202
duke@0 2203
duke@0 2204 // Interrupt thread so it will wake up from a potential wait()
duke@0 2205 Thread::interrupt(this);
duke@0 2206 }
duke@0 2207
duke@0 2208 // External suspension mechanism.
duke@0 2209 //
duke@0 2210 // Tell the VM to suspend a thread when ever it knows that it does not hold on
duke@0 2211 // to any VM_locks and it is at a transition
duke@0 2212 // Self-suspension will happen on the transition out of the vm.
duke@0 2213 // Catch "this" coming in from JNIEnv pointers when the thread has been freed
duke@0 2214 //
duke@0 2215 // Guarantees on return:
duke@0 2216 // + Target thread will not execute any new bytecode (that's why we need to
duke@0 2217 // force a safepoint)
duke@0 2218 // + Target thread will not enter any new monitors
duke@0 2219 //
duke@0 2220 void JavaThread::java_suspend() {
duke@0 2221 { MutexLocker mu(Threads_lock);
duke@0 2222 if (!Threads::includes(this) || is_exiting() || this->threadObj() == NULL) {
duke@0 2223 return;
duke@0 2224 }
duke@0 2225 }
duke@0 2226
duke@0 2227 { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
duke@0 2228 if (!is_external_suspend()) {
duke@0 2229 // a racing resume has cancelled us; bail out now
duke@0 2230 return;
duke@0 2231 }
duke@0 2232
duke@0 2233 // suspend is done
duke@0 2234 uint32_t debug_bits = 0;
duke@0 2235 // Warning: is_ext_suspend_completed() may temporarily drop the
duke@0 2236 // SR_lock to allow the thread to reach a stable thread state if
duke@0 2237 // it is currently in a transient thread state.
duke@0 2238 if (is_ext_suspend_completed(false /* !called_by_wait */,
duke@0 2239 SuspendRetryDelay, &debug_bits) ) {
duke@0 2240 return;
duke@0 2241 }
duke@0 2242 }
duke@0 2243
duke@0 2244 VM_ForceSafepoint vm_suspend;
duke@0 2245 VMThread::execute(&vm_suspend);
duke@0 2246 }
duke@0 2247
duke@0 2248 // Part II of external suspension.
duke@0 2249 // A JavaThread self suspends when it detects a pending external suspend
duke@0 2250 // request. This is usually on transitions. It is also done in places
duke@0 2251 // where continuing to the next transition would surprise the caller,
duke@0 2252 // e.g., monitor entry.
duke@0 2253 //
duke@0 2254 // Returns the number of times that the thread self-suspended.
duke@0 2255 //
duke@0 2256 // Note: DO NOT call java_suspend_self() when you just want to block current
duke@0 2257 // thread. java_suspend_self() is the second stage of cooperative
duke@0 2258 // suspension for external suspend requests and should only be used
duke@0 2259 // to complete an external suspend request.
duke@0 2260 //
duke@0 2261 int JavaThread::java_suspend_self() {
duke@0 2262 int ret = 0;
duke@0 2263
duke@0 2264 // we are in the process of exiting so don't suspend
duke@0 2265 if (is_exiting()) {
duke@0 2266 clear_external_suspend();
duke@0 2267 return ret;
duke@0 2268 }
duke@0 2269
duke@0 2270 assert(_anchor.walkable() ||
duke@0 2271 (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()),
duke@0 2272 "must have walkable stack");
duke@0 2273
duke@0 2274 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
duke@0 2275
dcubed@979 2276 assert(!this->is_ext_suspended(),
duke@0 2277 "a thread trying to self-suspend should not already be suspended");
duke@0 2278
duke@0 2279 if (this->is_suspend_equivalent()) {
duke@0 2280 // If we are self-suspending as a result of the lifting of a
duke@0 2281 // suspend equivalent condition, then the suspend_equivalent
duke@0 2282 // flag is not cleared until we set the ext_suspended flag so
duke@0 2283 // that wait_for_ext_suspend_completion() returns consistent
duke@0 2284 // results.
duke@0 2285 this->clear_suspend_equivalent();
duke@0 2286 }
duke@0 2287
duke@0 2288 // A racing resume may have cancelled us before we grabbed SR_lock
duke@0 2289 // above. Or another external suspend request could be waiting for us
duke@0 2290 // by the time we return from SR_lock()->wait(). The thread
duke@0 2291 // that requested the suspension may already be trying to walk our
duke@0 2292 // stack and if we return now, we can change the stack out from under
duke@0 2293 // it. This would be a "bad thing (TM)" and cause the stack walker
duke@0 2294 // to crash. We stay self-suspended until there are no more pending
duke@0 2295 // external suspend requests.
duke@0 2296 while (is_external_suspend()) {
duke@0 2297 ret++;
duke@0 2298 this->set_ext_suspended();
duke@0 2299
duke@0 2300 // _ext_suspended flag is cleared by java_resume()
duke@0 2301 while (is_ext_suspended()) {
duke@0 2302 this->SR_lock()->wait(Mutex::_no_safepoint_check_flag);
duke@0 2303 }
duke@0 2304 }
duke@0 2305
duke@0 2306 return ret;
duke@0 2307 }
duke@0 2308
duke@0 2309 #ifdef ASSERT
duke@0 2310 // verify the JavaThread has not yet been published in the Threads::list, and
duke@0 2311 // hence doesn't need protection from concurrent access at this stage
duke@0 2312 void JavaThread::verify_not_published() {
duke@0 2313 if (!Threads_lock->owned_by_self()) {
duke@0 2314 MutexLockerEx ml(Threads_lock, Mutex::_no_safepoint_check_flag);
duke@0 2315 assert( !Threads::includes(this),
duke@0 2316 "java thread shouldn't have been published yet!");
duke@0 2317 }
duke@0 2318 else {
duke@0 2319 assert( !Threads::includes(this),
duke@0 2320 "java thread shouldn't have been published yet!");
duke@0 2321 }
duke@0 2322 }
duke@0 2323 #endif
duke@0 2324
duke@0 2325 // Slow path when the native==>VM/Java barriers detect a safepoint is in
duke@0 2326 // progress or when _suspend_flags is non-zero.
duke@0 2327 // Current thread needs to self-suspend if there is a suspend request and/or
duke@0 2328 // block if a safepoint is in progress.
duke@0 2329 // Async exception ISN'T checked.
duke@0 2330 // Note only the ThreadInVMfromNative transition can call this function
duke@0 2331 // directly and when thread state is _thread_in_native_trans
duke@0 2332 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
duke@0 2333 assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
duke@0 2334
duke@0 2335 JavaThread *curJT = JavaThread::current();
duke@0 2336 bool do_self_suspend = thread->is_external_suspend();
duke@0 2337
duke@0 2338 assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
duke@0 2339
duke@0 2340 // If JNIEnv proxies are allowed, don't self-suspend if the target
duke@0 2341 // thread is not the current thread. In older versions of jdbx, jdbx
duke@0 2342 // threads could call into the VM with another thread's JNIEnv so we
duke@0 2343 // can be here operating on behalf of a suspended thread (4432884).
duke@0 2344 if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) {
duke@0 2345 JavaThreadState state = thread->thread_state();
duke@0 2346
duke@0 2347 // We mark this thread_blocked state as a suspend-equivalent so
duke@0 2348 // that a caller to is_ext_suspend_completed() won't be confused.
duke@0 2349 // The suspend-equivalent state is cleared by java_suspend_self().
duke@0 2350 thread->set_suspend_equivalent();
duke@0 2351
duke@0 2352 // If the safepoint code sees the _thread_in_native_trans state, it will
duke@0 2353 // wait until the thread changes to other thread state. There is no
duke@0 2354 // guarantee on how soon we can obtain the SR_lock and complete the
duke@0 2355 // self-suspend request. It would be a bad idea to let safepoint wait for
duke@0 2356 // too long. Temporarily change the state to _thread_blocked to
duke@0 2357 // let the VM thread know that this thread is ready for GC. The problem
duke@0 2358 // of changing thread state is that safepoint could happen just after
duke@0 2359 // java_suspend_self() returns after being resumed, and VM thread will
duke@0 2360 // see the _thread_blocked state. We must check for safepoint
duke@0 2361 // after restoring the state and make sure we won't leave while a safepoint
duke@0 2362 // is in progress.
duke@0 2363 thread->set_thread_state(_thread_blocked);
duke@0 2364 thread->java_suspend_self();
duke@0 2365 thread->set_thread_state(state);
duke@0 2366 // Make sure new state is seen by VM thread
duke@0 2367 if (os::is_MP()) {
duke@0 2368 if (UseMembar) {
duke@0 2369 // Force a fence between the write above and read below
duke@0 2370 OrderAccess::fence();
duke@0 2371 } else {
duke@0 2372 // Must use this rather than serialization page in particular on Windows
duke@0 2373 InterfaceSupport::serialize_memory(thread);
duke@0 2374 }
duke@0 2375 }
duke@0 2376 }
duke@0 2377
duke@0 2378 if (SafepointSynchronize::do_call_back()) {
duke@0 2379 // If we are safepointing, then block the caller which may not be
duke@0 2380 // the same as the target thread (see above).
duke@0 2381 SafepointSynchronize::block(curJT);
duke@0 2382 }
duke@0 2383
duke@0 2384 if (thread->is_deopt_suspend()) {
duke@0 2385 thread->clear_deopt_suspend();
duke@0 2386 RegisterMap map(thread, false);
duke@0 2387 frame f = thread->last_frame();
duke@0 2388 while ( f.id() != thread->must_deopt_id() && ! f.is_first_frame()) {
duke@0 2389 f = f.sender(&map);
duke@0 2390 }
duke@0 2391 if (f.id() == thread->must_deopt_id()) {
duke@0 2392 thread->clear_must_deopt_id();
never@1647 2393 f.deoptimize(thread);
duke@0 2394 } else {
duke@0 2395 fatal("missed deoptimization!");
duke@0 2396 }
duke@0 2397 }
duke@0 2398 }
duke@0 2399
duke@0 2400 // Slow path when the native==>VM/Java barriers detect a safepoint is in
duke@0 2401 // progress or when _suspend_flags is non-zero.
duke@0 2402 // Current thread needs to self-suspend if there is a suspend request and/or
duke@0 2403 // block if a safepoint is in progress.
duke@0 2404 // Also check for pending async exception (not including unsafe access error).
duke@0 2405 // Note only the native==>VM/Java barriers can call this function and when
duke@0 2406 // thread state is _thread_in_native_trans.
duke@0 2407 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
duke@0 2408 check_safepoint_and_suspend_for_native_trans(thread);
duke@0 2409
duke@0 2410 if (thread->has_async_exception()) {
duke@0 2411 // We are in _thread_in_native_trans state, don't handle unsafe
duke@0 2412 // access error since that may block.
duke@0 2413 thread->check_and_handle_async_exceptions(false);
duke@0 2414 }
duke@0 2415 }
duke@0 2416
never@3158 2417 // This is a variant of the normal
never@3158 2418 // check_special_condition_for_native_trans with slightly different
never@3158 2419 // semantics for use by critical native wrappers. It does all the
never@3158 2420 // normal checks but also performs the transition back into
never@3158 2421 // thread_in_Java state. This is required so that critical natives
never@3158 2422 // can potentially block and perform a GC if they are the last thread
never@3158 2423 // exiting the GC_locker.
never@3158 2424 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) {
never@3158 2425 check_special_condition_for_native_trans(thread);
never@3158 2426
never@3158 2427 // Finish the transition
never@3158 2428 thread->set_thread_state(_thread_in_Java);
never@3158 2429
never@3158 2430 if (thread->do_critical_native_unlock()) {
never@3158 2431 ThreadInVMfromJavaNoAsyncException tiv(thread);
never@3158 2432 GC_locker::unlock_critical(thread);
never@3158 2433 thread->clear_critical_native_unlock();
never@3158 2434 }
never@3158 2435 }
never@3158 2436
duke@0 2437 // We need to guarantee the Threads_lock here, since resumes are not
duke@0 2438 // allowed during safepoint synchronization
duke@0 2439 // Can only resume from an external suspension
duke@0 2440 void JavaThread::java_resume() {
duke@0 2441 assert_locked_or_safepoint(Threads_lock);
duke@0 2442
duke@0 2443 // Sanity check: thread is gone, has started exiting or the thread
duke@0 2444 // was not externally suspended.
duke@0 2445 if (!Threads::includes(this) || is_exiting() || !is_external_suspend()) {
duke@0 2446 return;
duke@0 2447 }
duke@0 2448
duke@0 2449 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
duke@0 2450
duke@0 2451 clear_external_suspend();
duke@0 2452
duke@0 2453 if (is_ext_suspended()) {
duke@0 2454 clear_ext_suspended();
duke@0 2455 SR_lock()->notify_all();
duke@0 2456 }
duke@0 2457 }
duke@0 2458
duke@0 2459 void JavaThread::create_stack_guard_pages() {
duke@0 2460 if (! os::uses_stack_guard_pages() || _stack_guard_state != stack_guard_unused) return;
duke@0 2461 address low_addr = stack_base() - stack_size();
duke@0 2462 size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
duke@0 2463
duke@0 2464 int allocate = os::allocate_stack_guard_pages();
duke@0 2465 // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len);
duke@0 2466
coleenp@1320 2467 if (allocate && !os::create_stack_guard_pages((char *) low_addr, len)) {
duke@0 2468 warning("Attempt to allocate stack guard pages failed.");
duke@0 2469 return;
duke@0 2470 }
duke@0 2471
duke@0 2472 if (os::guard_memory((char *) low_addr, len)) {
duke@0 2473 _stack_guard_state = stack_guard_enabled;
duke@0 2474 } else {
duke@0 2475 warning("Attempt to protect stack guard pages failed.");
duke@0 2476 if (os::uncommit_memory((char *) low_addr, len)) {
duke@0 2477 warning("Attempt to deallocate stack guard pages failed.");
duke@0 2478 }
duke@0 2479 }
duke@0 2480 }
duke@0 2481
duke@0 2482 void JavaThread::remove_stack_guard_pages() {
zgu@4064 2483 assert(Thread::current() == this, "from different thread");
duke@0 2484 if (_stack_guard_state == stack_guard_unused) return;
duke@0 2485 address low_addr = stack_base() - stack_size();
duke@0 2486 size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
duke@0 2487
duke@0 2488 if (os::allocate_stack_guard_pages()) {
coleenp@1320 2489 if (os::remove_stack_guard_pages((char *) low_addr, len)) {
duke@0 2490 _stack_guard_state = stack_guard_unused;
duke@0 2491 } else {
duke@0 2492 warning("Attempt to deallocate stack guard pages failed.");
duke@0 2493 }
duke@0 2494 } else {
duke@0 2495 if (_stack_guard_state == stack_guard_unused) return;
duke@0 2496 if (os::unguard_memory((char *) low_addr, len)) {
duke@0 2497 _stack_guard_state = stack_guard_unused;
duke@0 2498 } else {
duke@0 2499 warning("Attempt to unprotect stack guard pages failed.");
duke@0 2500 }
duke@0 2501 }
duke@0 2502 }
duke@0 2503
duke@0 2504 void JavaThread::enable_stack_yellow_zone() {
duke@0 2505 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
duke@0 2506 assert(_stack_guard_state != stack_guard_enabled, "already enabled");
duke@0 2507
duke@0 2508 // The base notation is from the stacks point of view, growing downward.
duke@0 2509 // We need to adjust it to work correctly with guard_memory()
duke@0 2510 address base = stack_yellow_zone_base() - stack_yellow_zone_size();
duke@0 2511
duke@0 2512 guarantee(base < stack_base(),"Error calculating stack yellow zone");
duke@0 2513 guarantee(base < os::current_stack_pointer(),"Error calculating stack yellow zone");
duke@0 2514
duke@0 2515 if (os::guard_memory((char *) base, stack_yellow_zone_size())) {
duke@0 2516 _stack_guard_state = stack_guard_enabled;
duke@0 2517 } else {
duke@0 2518 warning("Attempt to guard stack yellow zone failed.");
duke@0 2519 }
duke@0 2520 enable_register_stack_guard();
duke@0 2521 }
duke@0 2522
duke@0 2523 void JavaThread::disable_stack_yellow_zone() {
duke@0 2524 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
duke@0 2525 assert(_stack_guard_state != stack_guard_yellow_disabled, "already disabled");
duke@0 2526
duke@0 2527 // Simply return if called for a thread that does not use guard pages.
duke@0 2528 if (_stack_guard_state == stack_guard_unused) return;
duke@0 2529
duke@0 2530 // The base notation is from the stacks point of view, growing downward.
duke@0 2531 // We need to adjust it to work correctly with guard_memory()
duke@0 2532 address base = stack_yellow_zone_base() - stack_yellow_zone_size();
duke@0 2533
duke@0 2534 if (os::unguard_memory((char *)base, stack_yellow_zone_size())) {
duke@0 2535 _stack_guard_state = stack_guard_yellow_disabled;
duke@0 2536 } else {
duke@0 2537 warning("Attempt to unguard stack yellow zone failed.");
duke@0 2538 }
duke@0 2539 disable_register_stack_guard();
duke@0 2540 }
duke@0 2541
duke@0 2542 void JavaThread::enable_stack_red_zone() {
duke@0 2543 // The base notation is from the stacks point of view, growing downward.
duke@0 2544 // We need to adjust it to work correctly with guard_memory()
duke@0 2545 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
duke@0 2546 address base = stack_red_zone_base() - stack_red_zone_size();
duke@0 2547
duke@0 2548 guarantee(base < stack_base(),"Error calculating stack red zone");
duke@0 2549 guarantee(base < os::current_stack_pointer(),"Error calculating stack red zone");
duke@0 2550
duke@0 2551 if(!os::guard_memory((char *) base, stack_red_zone_size())) {
duke@0 2552 warning("Attempt to guard stack red zone failed.");
duke@0 2553 }
duke@0 2554 }
duke@0 2555
duke@0 2556 void JavaThread::disable_stack_red_zone() {
duke@0 2557 // The base notation is from the stacks point of view, growing downward.
duke@0 2558 // We need to adjust it to work correctly with guard_memory()
duke@0 2559 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
duke@0 2560 address base = stack_red_zone_base() - stack_red_zone_size();
duke@0 2561 if (!os::unguard_memory((char *)base, stack_red_zone_size())) {
duke@0 2562 warning("Attempt to unguard stack red zone failed.");
duke@0 2563 }
duke@0 2564 }
duke@0 2565
duke@0 2566 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
duke@0 2567 // ignore is there is no stack
duke@0 2568 if (!has_last_Java_frame()) return;
duke@0 2569 // traverse the stack frames. Starts from top frame.
duke@0 2570 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
duke@0 2571 frame* fr = fst.current();
duke@0 2572 f(fr, fst.register_map());
duke@0 2573 }
duke@0 2574 }
duke@0 2575
duke@0 2576
duke@0 2577 #ifndef PRODUCT
duke@0 2578 // Deoptimization
duke@0 2579 // Function for testing deoptimization
duke@0 2580 void JavaThread::deoptimize() {
duke@0 2581 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
duke@0 2582 StackFrameStream fst(this, UseBiasedLocking);
duke@0 2583 bool deopt = false; // Dump stack only if a deopt actually happens.
duke@0 2584 bool only_at = strlen(DeoptimizeOnlyAt) > 0;
duke@0 2585 // Iterate over all frames in the thread and deoptimize
duke@0 2586 for(; !fst.is_done(); fst.next()) {
duke@0 2587 if(fst.current()->can_be_deoptimized()) {
duke@0 2588
duke@0 2589 if (only_at) {
duke@0 2590 // Deoptimize only at particular bcis. DeoptimizeOnlyAt
duke@0 2591 // consists of comma or carriage return separated numbers so
duke@0 2592 // search for the current bci in that string.
duke@0 2593 address pc = fst.current()->pc();
duke@0 2594 nmethod* nm = (nmethod*) fst.current()->cb();
duke@0 2595 ScopeDesc* sd = nm->scope_desc_at( pc);
duke@0 2596 char buffer[8];
duke@0 2597 jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
duke@0 2598 size_t len = strlen(buffer);
duke@0 2599 const char * found = strstr(DeoptimizeOnlyAt, buffer);
duke@0 2600 while (found != NULL) {
duke@0 2601 if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
duke@0 2602 (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
duke@0 2603 // Check that the bci found is bracketed by terminators.
duke@0 2604 break;
duke@0 2605 }
duke@0 2606 found = strstr(found + 1, buffer);
duke@0 2607 }
duke@0 2608 if (!found) {
duke@0 2609 continue;
duke@0 2610 }
duke@0 2611 }
duke@0 2612
duke@0 2613 if (DebugDeoptimization && !deopt) {
duke@0 2614 deopt = true; // One-time only print before deopt
duke@0 2615 tty->print_cr("[BEFORE Deoptimization]");
duke@0 2616 trace_frames();
duke@0 2617 trace_stack();
duke@0 2618 }
duke@0 2619 Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
duke@0 2620 }
duke@0 2621 }
duke@0 2622
duke@0 2623 if (DebugDeoptimization && deopt) {
duke@0 2624 tty->print_cr("[AFTER Deoptimization]");
duke@0 2625 trace_frames();
duke@0 2626 }
duke@0 2627 }
duke@0 2628
duke@0 2629
duke@0 2630 // Make zombies
duke@0 2631 void JavaThread::make_zombies() {
duke@0 2632 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
duke@0 2633 if (fst.current()->can_be_deoptimized()) {
duke@0 2634 // it is a Java nmethod
duke@0 2635 nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
duke@0 2636 nm->make_not_entrant();
duke@0 2637 }
duke@0 2638 }
duke@0 2639 }
duke@0 2640 #endif // PRODUCT
duke@0 2641
duke@0 2642
duke@0 2643 void JavaThread::deoptimized_wrt_marked_nmethods() {
duke@0 2644 if (!has_last_Java_frame()) return;
duke@0 2645 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
duke@0 2646 StackFrameStream fst(this, UseBiasedLocking);
duke@0 2647 for(; !fst.is_done(); fst.next()) {
duke@0 2648 if (fst.current()->should_be_deoptimized()) {
vlivanov@4027 2649 if (LogCompilation && xtty != NULL) {
vlivanov@4027 2650 nmethod* nm = fst.current()->cb()->as_nmethod_or_null();
vlivanov@4027 2651 xtty->elem("deoptimized thread='" UINTX_FORMAT "' compile_id='%d'",
vlivanov@4027 2652 this->name(), nm != NULL ? nm->compile_id() : -1);
vlivanov@4027 2653 }
vlivanov@4027 2654
duke@0 2655 Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
duke@0 2656 }
duke@0 2657 }
duke@0 2658 }
duke@0 2659
duke@0 2660
duke@0 2661 // GC support
duke@0 2662 static void frame_gc_epilogue(frame* f, const RegisterMap* map) { f->gc_epilogue(); }
duke@0 2663
duke@0 2664 void JavaThread::gc_epilogue() {
duke@0 2665 frames_do(frame_gc_epilogue);
duke@0 2666 }
duke@0 2667
duke@0 2668
duke@0 2669 static void frame_gc_prologue(frame* f, const RegisterMap* map) { f->gc_prologue(); }
duke@0 2670
duke@0 2671 void JavaThread::gc_prologue() {
duke@0 2672 frames_do(frame_gc_prologue);
duke@0 2673 }
duke@0 2674
minqi@1119 2675 // If the caller is a NamedThread, then remember, in the current scope,
minqi@1119 2676 // the given JavaThread in its _processed_thread field.
minqi@1119 2677 class RememberProcessedThread: public StackObj {
minqi@1119 2678 NamedThread* _cur_thr;
minqi@1119 2679 public:
minqi@1119 2680 RememberProcessedThread(JavaThread* jthr) {
minqi@1119 2681 Thread* thread = Thread::current();
minqi@1119 2682 if (thread->is_Named_thread()) {
minqi@1119 2683 _cur_thr = (NamedThread *)thread;
minqi@1119 2684 _cur_thr->set_processed_thread(jthr);
minqi@1119 2685 } else {
minqi@1119 2686 _cur_thr = NULL;
minqi@1119 2687 }
minqi@1119 2688 }
minqi@1119 2689
minqi@1119 2690 ~RememberProcessedThread() {
minqi@1119 2691 if (_cur_thr) {
minqi@1119 2692 _cur_thr->set_processed_thread(NULL);
minqi@1119 2693 }
minqi@1119 2694 }
minqi@1119 2695 };
duke@0 2696
jrose@989 2697 void JavaThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
ysr@1166 2698 // Verify that the deferred card marks have been flushed.
ysr@1166 2699 assert(deferred_card_mark().is_empty(), "Should be empty during GC");
ysr@1027 2700
duke@0 2701 // The ThreadProfiler oops_do is done from FlatProfiler::oops_do
duke@0 2702 // since there may be more than one thread using each ThreadProfiler.
duke@0 2703
duke@0 2704 // Traverse the GCHandles
jrose@989 2705 Thread::oops_do(f, cf);
duke@0 2706
duke@0 2707 assert( (!has_last_Java_frame() && java_call_counter() == 0) ||
duke@0 2708 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
duke@0 2709
duke@0 2710 if (has_last_Java_frame()) {
minqi@1119 2711 // Record JavaThread to GC thread
minqi@1119 2712 RememberProcessedThread rpt(this);
duke@0 2713
duke@0 2714 // Traverse the privileged stack
duke@0 2715 if (_privileged_stack_top != NULL) {
duke@0 2716 _privileged_stack_top->oops_do(f);
duke@0 2717 }
duke@0 2718
duke@0 2719 // traverse the registered growable array
duke@0 2720 if (_array_for_gc != NULL) {
duke@0 2721 for (int index = 0; index < _array_for_gc->length(); index++) {
duke@0 2722 f->do_oop(_array_for_gc->adr_at(index));
duke@0 2723 }
duke@0 2724 }
duke@0 2725
duke@0 2726 // Traverse the monitor chunks
duke@0 2727 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
duke@0 2728 chunk->oops_do(f);
duke@0 2729 }
duke@0 2730
duke@0 2731 // Traverse the execution stack
duke@0 2732 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
jrose@989 2733 fst.current()->oops_do(f, cf, fst.register_map());
duke@0 2734 }
duke@0 2735 }
duke@0 2736
duke@0 2737 // callee_target is never live across a gc point so NULL it here should
duke@0 2738 // it still contain a methdOop.
duke@0 2739
duke@0 2740 set_callee_target(NULL);
duke@0 2741
duke@0 2742 assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
duke@0 2743 // If we have deferred set_locals there might be oops waiting to be
duke@0 2744 // written
duke@0 2745 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals();
duke@0 2746 if (list != NULL) {
duke@0 2747 for (int i = 0; i < list->length(); i++) {
duke@0 2748 list->at(i)->oops_do(f);
duke@0 2749 }
duke@0 2750 }
duke@0 2751
duke@0 2752 // Traverse instance variables at the end since the GC may be moving things
duke@0 2753 // around using this function
duke@0 2754 f->do_oop((oop*) &_threadObj);
duke@0 2755 f->do_oop((oop*) &_vm_result);
duke@0 2756 f->do_oop((oop*) &_vm_result_2);
duke@0 2757 f->do_oop((oop*) &_exception_oop);
duke@0 2758 f->do_oop((oop*) &_pending_async_exception);
duke@0 2759
duke@0 2760 if (jvmti_thread_state() != NULL) {
duke@0 2761 jvmti_thread_state()->oops_do(f);
duke@0 2762 }
duke@0 2763 }
duke@0 2764
jrose@989 2765 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
jrose@989 2766 Thread::nmethods_do(cf); // (super method is a no-op)
duke@0 2767
duke@0 2768 assert( (!has_last_Java_frame() && java_call_counter() == 0) ||
duke@0 2769 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
duke@0 2770
duke@0 2771 if (has_last_Java_frame()) {
duke@0 2772 // Traverse the execution stack
duke@0 2773 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
jrose@989 2774 fst.current()->nmethods_do(cf);
duke@0 2775 }
duke@0 2776 }
duke@0 2777 }
duke@0 2778
duke@0 2779 // Printing
duke@0 2780 const char* _get_thread_state_name(JavaThreadState _thread_state) {
duke@0 2781 switch (_thread_state) {
duke@0 2782 case _thread_uninitialized: return "_thread_uninitialized";
duke@0 2783 case _thread_new: return "_thread_new";
duke@0 2784 case _thread_new_trans: return "_thread_new_trans";
duke@0 2785 case _thread_in_native: return "_thread_in_native";
duke@0 2786 case _thread_in_native_trans: return "_thread_in_native_trans";
duke@0 2787 case _thread_in_vm: return "_thread_in_vm";
duke@0 2788 case _thread_in_vm_trans: return "_thread_in_vm_trans";
duke@0 2789 case _thread_in_Java: return "_thread_in_Java";
duke@0 2790 case _thread_in_Java_trans: return "_thread_in_Java_trans";
duke@0 2791 case _thread_blocked: return "_thread_blocked";
duke@0 2792 case _thread_blocked_trans: return "_thread_blocked_trans";
duke@0 2793 default: return "unknown thread state";
duke@0 2794 }
duke@0 2795 }
duke@0 2796
duke@0 2797 #ifndef PRODUCT
duke@0 2798 void JavaThread::print_thread_state_on(outputStream *st) const {
duke@0 2799 st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state));
duke@0 2800 };
duke@0 2801 void JavaThread::print_thread_state() const {
duke@0 2802 print_thread_state_on(tty);
duke@0 2803 };
duke@0 2804 #endif // PRODUCT
duke@0 2805
duke@0 2806 // Called by Threads::print() for VM_PrintThreads operation
duke@0 2807 void JavaThread::print_on(outputStream *st) const {
duke@0 2808 st->print("\"%s\" ", get_thread_name());
duke@0 2809 oop thread_oop = threadObj();
duke@0 2810 if (thread_oop != NULL && java_lang_Thread::is_daemon(thread_oop)) st->print("daemon ");
duke@0 2811 Thread::print_on(st);
duke@0 2812 // print guess for valid stack memory region (assume 4K pages); helps lock debugging
xlu@702 2813 st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
duke@0 2814 if (thread_oop != NULL && JDK_Version::is_gte_jdk15x_version()) {
duke@0 2815 st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
duke@0 2816 }
duke@0 2817 #ifndef PRODUCT
duke@0 2818 print_thread_state_on(st);
duke@0 2819 _safepoint_state->print_on(st);
duke@0 2820 #endif // PRODUCT
duke@0 2821 }
duke@0 2822
duke@0 2823 // Called by fatal error handler. The difference between this and
duke@0 2824 // JavaThread::print() is that we can't grab lock or allocate memory.
duke@0 2825 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
duke@0 2826 st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
duke@0 2827 oop thread_obj = threadObj();
duke@0 2828 if (thread_obj != NULL) {
duke@0 2829 if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
duke@0 2830 }
duke@0 2831 st->print(" [");
duke@0 2832 st->print("%s", _get_thread_state_name(_thread_state));
duke@0 2833 if (osthread()) {
duke@0 2834 st->print(", id=%d", osthread()->thread_id());
duke@0 2835 }
duke@0 2836 st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
duke@0 2837 _stack_base - _stack_size, _stack_base);
duke@0 2838 st->print("]");
duke@0 2839 return;
duke@0 2840 }
duke@0 2841
duke@0 2842 // Verification
duke@0 2843
duke@0 2844 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
duke@0 2845
duke@0 2846 void JavaThread::verify() {
duke@0 2847 // Verify oops in the thread.
jrose@989 2848 oops_do(&VerifyOopClosure::verify_oop, NULL);
duke@0 2849
duke@0 2850 // Verify the stack frames.
duke@0 2851 frames_do(frame_verify);
duke@0 2852 }
duke@0 2853
duke@0 2854 // CR 6300358 (sub-CR 2137150)
duke@0 2855 // Most callers of this method assume that it can't return NULL but a
duke@0 2856 // thread may not have a name whilst it is in the process of attaching to
duke@0 2857 // the VM - see CR 6412693, and there are places where a JavaThread can be
duke@0 2858 // seen prior to having it's threadObj set (eg JNI attaching threads and
duke@0 2859 // if vm exit occurs during initialization). These cases can all be accounted
duke@0 2860 // for such that this method never returns NULL.
duke@0 2861 const char* JavaThread::get_thread_name() const {
duke@0 2862 #ifdef ASSERT
duke@0 2863 // early safepoints can hit while current thread does not yet have TLS
duke@0 2864 if (!SafepointSynchronize::is_at_safepoint()) {
duke@0 2865 Thread *cur = Thread::current();
duke@0 2866 if (!(cur->is_Java_thread() && cur == this)) {
duke@0 2867 // Current JavaThreads are allowed to get their own name without
duke@0 2868 // the Threads_lock.
duke@0 2869 assert_locked_or_safepoint(Threads_lock);
duke@0 2870 }
duke@0 2871 }
duke@0 2872 #endif // ASSERT
duke@0 2873 return get_thread_name_string();
duke@0 2874 }
duke@0 2875
duke@0 2876 // Returns a non-NULL representation of this thread's name, or a suitable
duke@0 2877 // descriptive string if there is no set name
duke@0 2878 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
duke@0 2879 const char* name_str;
duke@0 2880 oop thread_obj = threadObj();
duke@0 2881 if (thread_obj != NULL) {
duke@0 2882 typeArrayOop name = java_lang_Thread::name(thread_obj);
duke@0 2883 if (name != NULL) {
duke@0 2884 if (buf == NULL) {
duke@0 2885 name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
duke@0 2886 }
duke@0 2887 else {
duke@0 2888 name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length(), buf, buflen);
duke@0 2889 }
duke@0 2890 }
dcubed@2842 2891 else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
duke@0 2892 name_str = "<no-name - thread is attaching>";
duke@0 2893 }
duke@0 2894 else {
duke@0 2895 name_str = Thread::name();
duke@0 2896 }
duke@0 2897 }
duke@0 2898 else {
duke@0 2899 name_str = Thread::name();
duke@0 2900 }
duke@0 2901 assert(name_str != NULL, "unexpected NULL thread name");
duke@0 2902 return name_str;
duke@0 2903 }
duke@0 2904
duke@0 2905
duke@0 2906 const char* JavaThread::get_threadgroup_name() const {
duke@0 2907 debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
duke@0 2908 oop thread_obj = threadObj();
duke@0 2909 if (thread_obj != NULL) {
duke@0 2910 oop thread_group = java_lang_Thread::threadGroup(thread_obj);
duke@0 2911 if (thread_group != NULL) {
duke@0 2912 typeArrayOop name = java_lang_ThreadGroup::name(thread_group);
duke@0 2913 // ThreadGroup.name can be null
duke@0 2914 if (name != NULL) {
duke@0 2915 const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
duke@0 2916 return str;
duke@0 2917 }
duke@0 2918 }
duke@0 2919 }
duke@0 2920 return NULL;
duke@0 2921 }
duke@0 2922
duke@0 2923 const char* JavaThread::get_parent_name() const {
duke@0 2924 debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
duke@0 2925 oop thread_obj = threadObj();
duke@0 2926 if (thread_obj != NULL) {
duke@0 2927 oop thread_group = java_lang_Thread::threadGroup(thread_obj);
duke@0 2928 if (thread_group != NULL) {
duke@0 2929 oop parent = java_lang_ThreadGroup::parent(thread_group);
duke@0 2930 if (parent != NULL) {
duke@0 2931 typeArrayOop name = java_lang_ThreadGroup::name(parent);
duke@0 2932 // ThreadGroup.name can be null
duke@0 2933 if (name != NULL) {
duke@0 2934 const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
duke@0 2935 return str;
duke@0 2936 }
duke@0 2937 }
duke@0 2938 }
duke@0 2939 }
duke@0 2940 return NULL;
duke@0 2941 }
duke@0 2942
duke@0 2943 ThreadPriority JavaThread::java_priority() const {
duke@0 2944 oop thr_oop = threadObj();
duke@0 2945 if (thr_oop == NULL) return NormPriority; // Bootstrapping
duke@0 2946 ThreadPriority priority = java_lang_Thread::priority(thr_oop);
duke@0 2947 assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
duke@0 2948 return priority;
duke@0 2949 }
duke@0 2950
duke@0 2951 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
duke@0 2952
duke@0 2953 assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
duke@0 2954 // Link Java Thread object <-> C++ Thread
duke@0 2955
duke@0 2956 // Get the C++ thread object (an oop) from the JNI handle (a jthread)
duke@0 2957 // and put it into a new Handle. The Handle "thread_oop" can then
duke@0 2958 // be used to pass the C++ thread object to other methods.
duke@0 2959
duke@0 2960 // Set the Java level thread object (jthread) field of the
duke@0 2961 // new thread (a JavaThread *) to C++ thread object using the
duke@0 2962 // "thread_oop" handle.
duke@0 2963
duke@0 2964 // Set the thread field (a JavaThread *) of the
duke@0 2965 // oop representing the java_lang_Thread to the new thread (a JavaThread *).
duke@0 2966
duke@0 2967 Handle thread_oop(Thread::current(),
duke@0 2968 JNIHandles::resolve_non_null(jni_thread));
duke@0 2969 assert(instanceKlass::cast(thread_oop->klass())->is_linked(),
duke@0 2970 "must be initialized");
duke@0 2971 set_threadObj(thread_oop());
duke@0 2972 java_lang_Thread::set_thread(thread_oop(), this);
duke@0 2973
duke@0 2974 if (prio == NoPriority) {
duke@0 2975 prio = java_lang_Thread::priority(thread_oop());
duke@0 2976 assert(prio != NoPriority, "A valid priority should be present");
duke@0 2977 }
duke@0 2978
duke@0 2979 // Push the Java priority down to the native thread; needs Threads_lock
duke@0 2980 Thread::set_priority(this, prio);
duke@0 2981
duke@0 2982 // Add the new thread to the Threads list and set it in motion.
duke@0 2983 // We must have threads lock in order to call Threads::add.
duke@0 2984 // It is crucial that we do not block before the thread is
duke@0 2985 // added to the Threads list for if a GC happens, then the java_thread oop
duke@0 2986 // will not be visited by GC.
duke@0 2987 Threads::add(this);
duke@0 2988 }
duke@0 2989
duke@0 2990 oop JavaThread::current_park_blocker() {
duke@0 2991 // Support for JSR-166 locks
duke@0 2992 oop thread_oop = threadObj();
kamg@242 2993 if (thread_oop != NULL &&
kamg@242 2994 JDK_Version::current().supports_thread_park_blocker()) {
duke@0 2995 return java_lang_Thread::park_blocker(thread_oop);
duke@0 2996 }
duke@0 2997 return NULL;
duke@0 2998 }
duke@0 2999
duke@0 3000
duke@0 3001 void JavaThread::print_stack_on(outputStream* st) {
duke@0 3002 if (!has_last_Java_frame()) return;
duke@0 3003 ResourceMark rm;
duke@0 3004 HandleMark hm;
duke@0 3005
duke@0 3006 RegisterMap reg_map(this);
duke@0 3007 vframe* start_vf = last_java_vframe(&reg_map);
duke@0 3008 int count = 0;
duke@0 3009 for (vframe* f = start_vf; f; f = f->sender() ) {
duke@0 3010 if (f->is_java_frame()) {
duke@0 3011 javaVFrame* jvf = javaVFrame::cast(f);
duke@0 3012 java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
duke@0 3013
duke@0 3014 // Print out lock information
duke@0 3015 if (JavaMonitorsInStackTrace) {
duke@0 3016 jvf->print_lock_info_on(st, count);
duke@0 3017 }
duke@0 3018 } else {
duke@0 3019 // Ignore non-Java frames
duke@0 3020 }
duke@0 3021
duke@0 3022 // Bail-out case for too deep stacks
duke@0 3023 count++;
duke@0 3024 if (MaxJavaStackTraceDepth == count) return;
duke@0 3025 }
duke@0 3026 }
duke@0 3027
duke@0 3028
duke@0 3029 // JVMTI PopFrame support
duke@0 3030 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
duke@0 3031 assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
duke@0 3032 if (in_bytes(size_in_bytes) != 0) {
zgu@3863 3033 _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
duke@0 3034 _popframe_preserved_args_size = in_bytes(size_in_bytes);
kvn@1523 3035 Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
duke@0 3036 }
duke@0 3037 }
duke@0 3038
duke@0 3039 void* JavaThread::popframe_preserved_args() {
duke@0 3040 return _popframe_preserved_args;
duke@0 3041 }
duke@0 3042
duke@0 3043 ByteSize JavaThread::popframe_preserved_args_size() {
duke@0 3044 return in_ByteSize(_popframe_preserved_args_size);
duke@0 3045 }
duke@0 3046
duke@0 3047 WordSize JavaThread::popframe_preserved_args_size_in_words() {
duke@0 3048 int sz = in_bytes(popframe_preserved_args_size());
duke@0 3049 assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
duke@0 3050 return in_WordSize(sz / wordSize);
duke@0 3051 }
duke@0 3052
duke@0 3053 void JavaThread::popframe_free_preserved_args() {
duke@0 3054 assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
zgu@3863 3055 FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args, mtThread);
duke@0 3056 _popframe_preserved_args = NULL;
duke@0 3057 _popframe_preserved_args_size = 0;
duke@0 3058 }
duke@0 3059
duke@0 3060 #ifndef PRODUCT
duke@0 3061
duke@0 3062 void JavaThread::trace_frames() {
duke@0 3063 tty->print_cr("[Describe stack]");
duke@0 3064 int frame_no = 1;
duke@0 3065 for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
duke@0 3066 tty->print(" %d. ", frame_no++);
duke@0 3067 fst.current()->print_value_on(tty,this);
duke@0 3068 tty->cr();
duke@0 3069 }
duke@0 3070 }
duke@0 3071
never@2742 3072 class PrintAndVerifyOopClosure: public OopClosure {
never@2742 3073 protected:
never@2742 3074 template <class T> inline void do_oop_work(T* p) {
never@2742 3075 oop obj = oopDesc::load_decode_heap_oop(p);
never@2742 3076 if (obj == NULL) return;
never@2742 3077 tty->print(INTPTR_FORMAT ": ", p);
never@2742 3078 if (obj->is_oop_or_null()) {
never@2742 3079 if (obj->is_objArray()) {
never@2742 3080 tty->print_cr("valid objArray: " INTPTR_FORMAT, (oopDesc*) obj);
never@2742 3081 } else {
never@2742 3082 obj->print();
never@2742 3083 }
never@2742 3084 } else {
never@2742 3085 tty->print_cr("invalid oop: " INTPTR_FORMAT, (oopDesc*) obj);
never@2742 3086 }
never@2742 3087 tty->cr();
never@2742 3088 }
never@2742 3089 public:
never@2742 3090 virtual void do_oop(oop* p) { do_oop_work(p); }
never@2742 3091 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
never@2742 3092 };
never@2742 3093
never@2742 3094
never@2742 3095 static void oops_print(frame* f, const RegisterMap *map) {
never@2742 3096 PrintAndVerifyOopClosure print;
never@2742 3097 f->print_value();
never@2742 3098 f->oops_do(&print, NULL, (RegisterMap*)map);
never@2742 3099 }
never@2742 3100
never@2742 3101 // Print our all the locations that contain oops and whether they are
never@2742 3102 // valid or not. This useful when trying to find the oldest frame
never@2742 3103 // where an oop has gone bad since the frame walk is from youngest to
never@2742 3104 // oldest.
never@2742 3105 void JavaThread::trace_oops() {
never@2742 3106 tty->print_cr("[Trace oops]");
never@2742 3107 frames_do(oops_print);
never@2742 3108 }
never@2742 3109
duke@0 3110
never@2485 3111 #ifdef ASSERT
never@2433 3112 // Print or validate the layout of stack frames
never@2433 3113 void JavaThread::print_frame_layout(int depth, bool validate_only) {
never@2433 3114 ResourceMark rm;
never@2433 3115 PRESERVE_EXCEPTION_MARK;
never@2433 3116 FrameValues values;
never@2433 3117 int frame_no = 0;
never@2433 3118 for(StackFrameStream fst(this, false); !fst.is_done(); fst.next()) {
never@2433 3119 fst.current()->describe(values, ++frame_no);
never@2433 3120 if (depth == frame_no) break;
never@2433 3121 }
never@2433 3122 if (validate_only) {
never@2433 3123 values.validate();
never@2433 3124 } else {
never@2433 3125 tty->print_cr("[Describe stack layout]");
twisti@2880 3126 values.print(this);
never@2433 3127 }
never@2433 3128 }
never@2485 3129 #endif
never@2433 3130
duke@0 3131 void JavaThread::trace_stack_from(vframe* start_vf) {
duke@0 3132 ResourceMark rm;
duke@0 3133 int vframe_no = 1;
duke@0 3134 for (vframe* f = start_vf; f; f = f->sender() ) {
duke@0 3135 if (f->is_java_frame()) {
duke@0 3136 javaVFrame::cast(f)->print_activation(vframe_no++);
duke@0 3137 } else {
duke@0 3138 f->print();
duke@0 3139 }
duke@0 3140 if (vframe_no > StackPrintLimit) {
duke@0 3141 tty->print_cr("...<more frames>...");
duke@0 3142 return;
duke@0 3143 }
duke@0 3144 }
duke@0 3145 }
duke@0 3146
duke@0 3147
duke@0 3148 void JavaThread::trace_stack() {
duke@0 3149 if (!has_last_Java_frame()) return;
duke@0 3150 ResourceMark rm;
duke@0 3151 HandleMark hm;
duke@0 3152 RegisterMap reg_map(this);
duke@0 3153 trace_stack_from(last_java_vframe(&reg_map));
duke@0 3154 }
duke@0 3155
duke@0 3156
duke@0 3157 #endif // PRODUCT
duke@0 3158
duke@0 3159
duke@0 3160 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
duke@0 3161 assert(reg_map != NULL, "a map must be given");
duke@0 3162 frame f = last_frame();
duke@0 3163 for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender() ) {
duke@0 3164 if (vf->is_java_frame()) return javaVFrame::cast(vf);
duke@0 3165 }
duke@0 3166 return NULL;
duke@0 3167 }
duke@0 3168
duke@0 3169
duke@0 3170 klassOop JavaThread::security_get_caller_class(int depth) {
duke@0 3171 vframeStream vfst(this);
duke@0 3172 vfst.security_get_caller_frame(depth);
duke@0 3173 if (!vfst.at_end()) {
duke@0 3174 return vfst.method()->method_holder();
duke@0 3175 }
duke@0 3176 return NULL;
duke@0 3177 }
duke@0 3178
duke@0 3179 static void compiler_thread_entry(JavaThread* thread, TRAPS) {
duke@0 3180 assert(thread->is_Compiler_thread(), "must be compiler thread");
duke@0 3181 CompileBroker::compiler_thread_loop();
duke@0 3182 }
duke@0 3183
duke@0 3184 // Create a CompilerThread
duke@0 3185 CompilerThread::CompilerThread(CompileQueue* queue, CompilerCounters* counters)
duke@0 3186 : JavaThread(&compiler_thread_entry) {
duke@0 3187 _env = NULL;
duke@0 3188 _log = NULL;
duke@0 3189 _task = NULL;
duke@0 3190 _queue = queue;
duke@0 3191 _counters = counters;
iveresov@1504 3192 _buffer_blob = NULL;
never@2481 3193 _scanned_nmethod = NULL;
duke@0 3194
duke@0 3195 #ifndef PRODUCT
duke@0 3196 _ideal_graph_printer = NULL;
duke@0 3197 #endif
duke@0 3198 }
duke@0 3199
never@2481 3200 void CompilerThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
never@2481 3201 JavaThread::oops_do(f, cf);
never@2481 3202 if (_scanned_nmethod != NULL && cf != NULL) {
never@2481 3203 // Safepoints can occur when the sweeper is scanning an nmethod so
never@2481 3204 // process it here to make sure it isn't unloaded in the middle of
never@2481 3205 // a scan.
never@2481 3206 cf->do_code_blob(_scanned_nmethod);
never@2481 3207 }
never@2481 3208 }
duke@0 3209
duke@0 3210 // ======= Threads ========
duke@0 3211
duke@0 3212 // The Threads class links together all active threads, and provides
duke@0 3213 // operations over all threads. It is protected by its own Mutex
duke@0 3214 // lock, which is also used in other contexts to protect thread
duke@0 3215 // operations from having the thread being operated on from exiting
duke@0 3216 // and going away unexpectedly (e.g., safepoint synchronization)
duke@0 3217
duke@0 3218 JavaThread* Threads::_thread_list = NULL;
duke@0 3219 int Threads::_number_of_threads = 0;
duke@0 3220 int Threads::_number_of_non_daemon_threads = 0;
duke@0 3221 int Threads::_return_code = 0;
duke@0 3222 size_t JavaThread::_stack_size_at_create = 0;
duke@0 3223
duke@0 3224 // All JavaThreads
duke@0 3225 #define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next())
duke@0 3226
duke@0 3227 void os_stream();
duke@0 3228
duke@0 3229 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
duke@0 3230 void Threads::threads_do(ThreadClosure* tc) {
duke@0 3231 assert_locked_or_safepoint(Threads_lock);
duke@0 3232 // ALL_JAVA_THREADS iterates through all JavaThreads
duke@0 3233 ALL_JAVA_THREADS(p) {
duke@0 3234 tc->do_thread(p);
duke@0 3235 }
duke@0 3236 // Someday we could have a table or list of all non-JavaThreads.
duke@0 3237 // For now, just manually iterate through them.
duke@0 3238 tc->do_thread(VMThread::vm_thread());
duke@0 3239 Universe::heap()->gc_threads_do(tc);
xlu@323 3240 WatcherThread *wt = WatcherThread::watcher_thread();
xlu@323 3241 // Strictly speaking, the following NULL check isn't sufficient to make sure
xlu@323 3242 // the data for WatcherThread is still valid upon being examined. However,
xlu@323 3243 // considering that WatchThread terminates when the VM is on the way to
xlu@323 3244 // exit at safepoint, the chance of the above is extremely small. The right
xlu@323 3245 // way to prevent termination of WatcherThread would be to acquire
xlu@323 3246 // Terminator_lock, but we can't do that without violating the lock rank
xlu@323 3247 // checking in some cases.
xlu@323 3248 if (wt != NULL)
xlu@323 3249 tc->do_thread(wt);
xlu@323 3250
duke@0 3251 // If CompilerThreads ever become non-JavaThreads, add them here
duke@0 3252 }
duke@0 3253
duke@0 3254 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
duke@0 3255
kamg@242 3256 extern void JDK_Version_init();
kamg@242 3257
duke@0 3258 // Check version
duke@0 3259 if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
duke@0 3260
duke@0 3261 // Initialize the output stream module
duke@0 3262 ostream_init();
duke@0 3263
duke@0 3264 // Process java launcher properties.
duke@0 3265 Arguments::process_sun_java_launcher_properties(args);
duke@0 3266
duke@0 3267 // Initialize the os module before using TLS
duke@0 3268 os::init();
duke@0 3269
duke@0 3270 // Initialize system properties.
duke@0 3271 Arguments::init_system_properties();
duke@0 3272
kamg@242 3273 // So that JDK version can be used as a discrimintor when parsing arguments
kamg@242 3274 JDK_Version_init();
kamg@242 3275
zgu@1784 3276 // Update/Initialize System properties after JDK version number is known
zgu@1784 3277 Arguments::init_version_specific_system_properties();
zgu@1784 3278
duke@0 3279 // Parse arguments
duke@0 3280 jint parse_result = Arguments::parse(args);
duke@0 3281 if (parse_result != JNI_OK) return parse_result;
duke@0 3282
duke@0 3283 if (PauseAtStartup) {
duke@0 3284 os::pause();
duke@0 3285 }
duke@0 3286
dcubed@2842 3287 #ifndef USDT2
duke@0 3288 HS_DTRACE_PROBE(hotspot, vm__init__begin);
dcubed@2842 3289 #else /* USDT2 */
dcubed@2842 3290 HOTSPOT_VM_INIT_BEGIN();
dcubed@2842 3291 #endif /* USDT2 */
duke@0 3292
duke@0 3293 // Record VM creation timing statistics
duke@0 3294 TraceVmCreationTime create_vm_timer;
duke@0 3295 create_vm_timer.start();
duke@0 3296
duke@0 3297 // Timing (must come after argument parsing)
duke@0 3298 TraceTime timer("Create VM", TraceStartupTime);
duke@0 3299
duke@0 3300 // Initialize the os module after parsing the args
duke@0 3301 jint os_init_2_result = os::init_2();
duke@0 3302 if (os_init_2_result != JNI_OK) return os_init_2_result;
duke@0 3303
zgu@3863 3304 // intialize TLS
zgu@3863 3305 ThreadLocalStorage::init();
zgu@3863 3306
zgu@3863 3307 // Bootstrap native memory tracking, so it can start recording memory
zgu@3863 3308 // activities before worker thread is started. This is the first phase
zgu@3863 3309 // of bootstrapping, VM is currently running in single-thread mode.
zgu@3863 3310 MemTracker::bootstrap_single_thread();
zgu@3863 3311
duke@0 3312 // Initialize output stream logging
duke@0 3313 ostream_init_log();
duke@0 3314
duke@0 3315 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
duke@0 3316 // Must be before create_vm_init_agents()
duke@0 3317 if (Arguments::init_libraries_at_startup()) {
duke@0 3318 convert_vm_init_libraries_to_agents();
duke@0 3319 }
duke@0 3320
duke@0 3321 // Launch -agentlib/-agentpath and converted -Xrun agents
duke@0 3322 if (Arguments::init_agents_at_startup()) {
duke@0 3323 create_vm_init_agents();
duke@0 3324 }
duke@0 3325
duke@0 3326 // Initialize Threads state
duke@0 3327 _thread_list = NULL;
duke@0 3328 _number_of_threads = 0;
duke@0 3329 _number_of_non_daemon_threads = 0;
duke@0 3330
duke@0 3331 // Initialize global data structures and create system classes in heap
duke@0 3332 vm_init_globals();
duke@0 3333
duke@0 3334 // Attach the main thread to this os thread
duke@0 3335 JavaThread* main_thread = new JavaThread();
duke@0 3336 main_thread->set_thread_state(_thread_in_vm);
duke@0 3337 // must do this before set_active_handles and initialize_thread_local_storage
duke@0 3338 // Note: on solaris initialize_thread_local_storage() will (indirectly)
duke@0 3339 // change the stack size recorded here to one based on the java thread
duke@0 3340 // stacksize. This adjusted size is what is used to figure the placement
duke@0 3341 // of the guard pages.
duke@0 3342 main_thread->record_stack_base_and_size();
duke@0 3343 main_thread->initialize_thread_local_storage();
duke@0 3344
duke@0 3345 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
duke@0 3346
duke@0 3347 if (!main_thread->set_as_starting_thread()) {
duke@0 3348 vm_shutdown_during_initialization(
duke@0 3349 "Failed necessary internal allocation. Out of swap space");
duke@0 3350 delete main_thread;
duke@0 3351 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
duke@0 3352 return JNI_ENOMEM;
duke@0 3353 }
duke@0 3354
duke@0 3355 // Enable guard page *after* os::create_main_thread(), otherwise it would
duke@0 3356 // crash Linux VM, see notes in os_linux.cpp.
duke@0 3357 main_thread->create_stack_guard_pages();
duke@0 3358
acorn@1798 3359 // Initialize Java-Level synchronization subsystem
acorn@1798 3360 ObjectMonitor::Initialize() ;
duke@0 3361
zgu@3863 3362 // Second phase of bootstrapping, VM is about entering multi-thread mode
zgu@3863 3363 MemTracker::bootstrap_multi_thread();
zgu@3863 3364
duke@0 3365 // Initialize global modules
duke@0 3366 jint status = init_globals();
duke@0 3367 if (status != JNI_OK) {
duke@0 3368 delete main_thread;
duke@0 3369 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
duke@0 3370 return status;
duke@0 3371 }
duke@0 3372
bobv@1601 3373 // Should be done after the heap is fully created
bobv@1601 3374 main_thread->cache_global_variables();
bobv@1601 3375
duke@0 3376 HandleMark hm;
duke@0 3377
duke@0 3378 { MutexLocker mu(Threads_lock);
duke@0 3379 Threads::add(main_thread);
duke@0 3380 }
duke@0 3381
duke@0 3382 // Any JVMTI raw monitors entered in onload will transition into
duke@0 3383 // real raw monitor. VM is setup enough here for raw monitor enter.
duke@0 3384 JvmtiExport::transition_pending_onload_raw_monitors();
duke@0 3385
zgu@3863 3386 // Fully start NMT
zgu@3863 3387 MemTracker::start();
zgu@3863 3388
duke@0 3389 // Create the VMThread
duke@0 3390 { TraceTime timer("Start VMThread", TraceStartupTime);
duke@0 3391 VMThread::create();
duke@0 3392 Thread* vmthread = VMThread::vm_thread();
duke@0 3393
duke@0 3394 if (!os::create_thread(vmthread, os::vm_thread))
duke@0 3395 vm_exit_during_initialization("Cannot create VM thread. Out of system resources.");
duke@0 3396
duke@0 3397 // Wait for the VM thread to become ready, and VMThread::run to initialize
duke@0 3398 // Monitors can have spurious returns, must always check another state flag
duke@0 3399 {
duke@0 3400 MutexLocker ml(Notify_lock);
duke@0 3401 os::start_thread(vmthread);
duke@0 3402 while (vmthread->active_handles() == NULL) {
duke@0 3403 Notify_lock->wait();
duke@0 3404 }
duke@0 3405 }
duke@0 3406 }
duke@0 3407
duke@0 3408 assert (Universe::is_fully_initialized(), "not initialized");
johnc@4483 3409 if (VerifyBeforeGC && VerifyGCStartAt == 0) {
johnc@4483 3410 Universe::heap()->prepare_for_verify();
johnc@4483 3411 Universe::verify(); // make sure we're starting with a clean slate
johnc@4483 3412 }
johnc@4483 3413
duke@0 3414 EXCEPTION_MARK;
duke@0 3415
duke@0 3416 // At this point, the Universe is initialized, but we have not executed
duke@0 3417 // any byte code. Now is a good time (the only time) to dump out the
duke@0 3418 // internal state of the JVM for sharing.
duke@0 3419
duke@0 3420 if (DumpSharedSpaces) {
duke@0 3421 Universe::heap()->preload_and_dump(CHECK_0);
duke@0 3422 ShouldNotReachHere();
duke@0 3423 }
duke@0 3424
duke@0 3425 // Always call even when there are not JVMTI environments yet, since environments
duke@0 3426 // may be attached late and JVMTI must track phases of VM execution
duke@0 3427 JvmtiExport::enter_start_phase();
duke@0 3428
duke@0 3429 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
duke@0 3430 JvmtiExport::post_vm_start();
duke@0 3431
duke@0 3432 {
duke@0 3433 TraceTime timer("Initialize java.lang classes", TraceStartupTime);
duke@0 3434
duke@0 3435 if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
duke@0 3436 create_vm_init_libraries();
duke@0 3437 }
duke@0 3438
duke@0 3439 if (InitializeJavaLangString) {
coleenp@2062 3440 initialize_class(vmSymbols::java_lang_String(), CHECK_0);
duke@0 3441 } else {
duke@0 3442 warning("java.lang.String not initialized");
duke@0 3443 }
duke@0 3444
phh@18 3445 if (AggressiveOpts) {
kvn@192 3446 {
kvn@192 3447 // Forcibly initialize java/util/HashMap and mutate the private
kvn@192 3448 // static final "frontCacheEnabled" field before we start creating instances
phh@18 3449 #ifdef ASSERT
coleenp@2062 3450 klassOop tmp_k = SystemDictionary::find(vmSymbols::java_util_HashMap(), Handle(), Handle(), CHECK_0);
kvn@192 3451 assert(tmp_k == NULL, "java/util/HashMap should not be loaded yet");
phh@18 3452 #endif
coleenp@2062 3453 klassOop k_o = SystemDictionary::resolve_or_null(vmSymbols::java_util_HashMap(), Handle(), Handle(), CHECK_0);
kvn@192 3454 KlassHandle k = KlassHandle(THREAD, k_o);
kvn@192 3455 guarantee(k.not_null(), "Must find java/util/HashMap");
kvn@192 3456 instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
kvn@192 3457 ik->initialize(CHECK_0);
kvn@192 3458 fieldDescriptor fd;
kvn@192 3459 // Possible we might not find this field; if so, don't break
kvn@192 3460 if (ik->find_local_field(vmSymbols::frontCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
never@2223 3461 k()->java_mirror()->bool_field_put(fd.offset(), true);
kvn@192 3462 }
kvn@192 3463 }
kvn@192 3464
kvn@192 3465 if (UseStringCache) {
phh@669 3466 // Forcibly initialize java/lang/StringValue and mutate the private
kvn@192 3467 // static final "stringCacheEnabled" field before we start creating instances
coleenp@2062 3468 klassOop k_o = SystemDictionary::resolve_or_null(vmSymbols::java_lang_StringValue(), Handle(), Handle(), CHECK_0);
phh@669 3469 // Possible that StringValue isn't present: if so, silently don't break
phh@669 3470 if (k_o != NULL) {
phh@669 3471 KlassHandle k = KlassHandle(THREAD, k_o);
phh@669 3472 instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
phh@669 3473 ik->initialize(CHECK_0);
phh@669 3474 fieldDescriptor fd;
phh@669 3475 // Possible we might not find this field: if so, silently don't break
phh@669 3476 if (ik->find_local_field(vmSymbols::stringCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
never@2223 3477 k()->java_mirror()->bool_field_put(fd.offset(), true);
phh@669 3478 }
kvn@192 3479 }
phh@18 3480 }
phh@18 3481 }
phh@18 3482
duke@0 3483 // Initialize java_lang.System (needed before creating the thread)
duke@0 3484 if (InitializeJavaLangSystem) {
coleenp@2062 3485 initialize_class(vmSymbols::java_lang_System(), CHECK_0);
coleenp@2062 3486 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0);
duke@0 3487 Handle thread_group = create_initial_thread_group(CHECK_0);
duke@0 3488 Universe::set_main_thread_group(thread_group());
coleenp@2062 3489 initialize_class(vmSymbols::java_lang_Thread(), CHECK_0);
duke@0 3490 oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0);
duke@0 3491 main_thread->set_threadObj(thread_object);
duke@0 3492 // Set thread status to running since main thread has
duke@0 3493 // been started and running.
duke@0 3494 java_lang_Thread::set_thread_status(thread_object,
duke@0 3495 java_lang_Thread::RUNNABLE);
duke@0 3496
duke@0 3497 // The VM preresolve methods to these classes. Make sure that get initialized
coleenp@2062 3498 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK_0);
coleenp@2062 3499 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK_0);
duke@0 3500 // The VM creates & returns objects of this class. Make sure it's initialized.
coleenp@2062 3501 initialize_class(vmSymbols::java_lang_Class(), CHECK_0);
duke@0 3502 call_initializeSystemClass(CHECK_0);
twisti@3847 3503
twisti@3847 3504 // get the Java runtime name after java.lang.System is initialized
twisti@3847 3505 JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
sla@4063 3506 JDK_Version::set_runtime_version(get_java_runtime_version(THREAD));
duke@0 3507 } else {
duke@0 3508 warning("java.lang.System not initialized");
duke@0 3509 }
duke@0 3510
duke@0 3511 // an instance of OutOfMemory exception has been allocated earlier
duke@0 3512 if (InitializeJavaLangExceptionsErrors) {
coleenp@2062 3513 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK_0);
coleenp@2062 3514 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK_0);
coleenp@2062 3515 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK_0);
coleenp@2062 3516 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK_0);
coleenp@2062 3517 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK_0);
coleenp@2062 3518 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK_0);
coleenp@2062 3519 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK_0);
fparain@3221 3520 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK_0);
duke@0 3521 } else {
duke@0 3522 warning("java.lang.OutOfMemoryError has not been initialized");
duke@0 3523 warning("java.lang.NullPointerException has not been initialized");
duke@0 3524 warning("java.lang.ClassCastException has not been initialized");
duke@0 3525 warning("java.lang.ArrayStoreException has not been initialized");
duke@0 3526 warning("java.lang.ArithmeticException has not been initialized");
duke@0 3527 warning("java.lang.StackOverflowError has not been initialized");
fparain@3221 3528 warning("java.lang.IllegalArgumentException has not been initialized");
duke@0 3529 }
twisti@2263 3530 }
duke@0 3531
duke@0 3532 // See : bugid 4211085.
duke@0 3533 // Background : the static initializer of java.lang.Compiler tries to read
duke@0 3534 // property"java.compiler" and read & write property "java.vm.info".
duke@0 3535 // When a security manager is installed through the command line
duke@0 3536 // option "-Djava.security.manager", the above properties are not
duke@0 3537 // readable and the static initializer for java.lang.Compiler fails
duke@0 3538 // resulting in a NoClassDefFoundError. This can happen in any
duke@0 3539 // user code which calls methods in java.lang.Compiler.
duke@0 3540 // Hack : the hack is to pre-load and initialize this class, so that only
duke@0 3541 // system domains are on the stack when the properties are read.
duke@0 3542 // Currently even the AWT code has calls to methods in java.lang.Compiler.
duke@0 3543 // On the classic VM, java.lang.Compiler is loaded very early to load the JIT.
duke@0 3544 // Future Fix : the best fix is to grant everyone permissions to read "java.compiler" and
duke@0 3545 // read and write"java.vm.info" in the default policy file. See bugid 4211383
duke@0 3546 // Once that is done, we should remove this hack.
coleenp@2062 3547 initialize_class(vmSymbols::java_lang_Compiler(), CHECK_0);
duke@0 3548
duke@0 3549 // More hackery - the static initializer of java.lang.Compiler adds the string "nojit" to
duke@0 3550 // the java.vm.info property if no jit gets loaded through java.lang.Compiler (the hotspot
duke@0 3551 // compiler does not get loaded through java.lang.Compiler). "java -version" with the
duke@0 3552 // hotspot vm says "nojit" all the time which is confusing. So, we reset it here.
duke@0 3553 // This should also be taken out as soon as 4211383 gets fixed.
duke@0 3554 reset_vm_info_property(CHECK_0);
duke@0 3555
duke@0 3556 quicken_jni_functions();
duke@0 3557
fparain@3221 3558 // Must be run after init_ft which initializes ft_enabled
fparain@3221 3559 if (TRACE_INITIALIZE() != JNI_OK) {
fparain@3221 3560 vm_exit_during_initialization("Failed to initialize tracing backend");
fparain@3221 3561 }
fparain@3221 3562
duke@0 3563 // Set flag that basic initialization has completed. Used by exceptions and various
duke@0 3564 // debug stuff, that does not work until all basic classes have been initialized.
duke@0 3565 set_init_completed();
duke@0 3566
dcubed@2842 3567 #ifndef USDT2
duke@0 3568 HS_DTRACE_PROBE(hotspot, vm__init__end);
dcubed@2842 3569 #else /* USDT2 */
dcubed@2842 3570 HOTSPOT_VM_INIT_END();
dcubed@2842 3571 #endif /* USDT2 */
duke@0 3572
duke@0 3573 // record VM initialization completion time
duke@0 3574 Management::record_vm_init_completed();
duke@0 3575
duke@0 3576 // Compute system loader. Note that this has to occur after set_init_completed, since
duke@0 3577 // valid exceptions may be thrown in the process.
duke@0 3578 // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
duke@0 3579 // set_init_completed has just been called, causing exceptions not to be shortcut
duke@0 3580 // anymore. We call vm_exit_during_initialization directly instead.
duke@0 3581 SystemDictionary::compute_java_system_loader(THREAD);
duke@0 3582 if (HAS_PENDING_EXCEPTION) {
duke@0 3583 vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
duke@0 3584 }
duke@0 3585
duke@0 3586 #ifndef SERIALGC
duke@0 3587 // Support for ConcurrentMarkSweep. This should be cleaned up
ysr@342 3588 // and better encapsulated. The ugly nested if test would go away
ysr@342 3589 // once things are properly refactored. XXX YSR
ysr@342 3590 if (UseConcMarkSweepGC || UseG1GC) {
ysr@342 3591 if (UseConcMarkSweepGC) {
ysr@342 3592 ConcurrentMarkSweepThread::makeSurrogateLockerThread(THREAD);
ysr@342 3593 } else {
ysr@342 3594 ConcurrentMarkThread::makeSurrogateLockerThread(THREAD);
ysr@342 3595 }
duke@0 3596 if (HAS_PENDING_EXCEPTION) {
duke@0 3597 vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
duke@0 3598 }
duke@0 3599 }
duke@0 3600 #endif // SERIALGC
duke@0 3601
duke@0 3602 // Always call even when there are not JVMTI environments yet, since environments
duke@0 3603 // may be attached late and JVMTI must track phases of VM execution
duke@0 3604 JvmtiExport::enter_live_phase();
duke@0 3605
duke@0 3606 // Signal Dispatcher needs to be started before VMInit event is posted
duke@0 3607 os::signal_init();
duke@0 3608
duke@0 3609 // Start Attach Listener if +StartAttachListener or it can't be started lazily
duke@0 3610 if (!DisableAttachMechanism) {
duke@0 3611 if (StartAttachListener || AttachListener::init_at_startup()) {
duke@0 3612 AttachListener::init();
duke@0 3613 }
duke@0 3614 }
duke@0 3615
duke@0 3616 // Launch -Xrun agents
duke@0 3617 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
duke@0 3618 // back-end can launch with -Xdebug -Xrunjdwp.
duke@0 3619 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
duke@0 3620 create