annotate src/share/vm/runtime/thread.cpp @ 2139:db2b0f8c1cef

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