src/share/vm/runtime/thread.cpp

Wed, 27 Apr 2016 01:25:04 +0800

author
aoqi
date
Wed, 27 Apr 2016 01:25:04 +0800
changeset 0
f90c822e73f8
child 1
2d8a650513c2
permissions
-rw-r--r--

Initial load
http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/
changeset: 6782:28b50d07f6f8
tag: jdk8u25-b17

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

mercurial