82 #include "runtime/vframe_hp.hpp"
83 #include "runtime/vmThread.hpp"
84 #include "runtime/vm_operations.hpp"
85 #include "runtime/vm_version.hpp"
86 #include "services/attachListener.hpp"
87 #include "services/management.hpp"
88 #include "services/memTracker.hpp"
89 #include "services/threadService.hpp"
90 #include "trace/traceMacros.hpp"
91 #include "trace/tracing.hpp"
92 #include "utilities/defaultStream.hpp"
93 #include "utilities/dtrace.hpp"
94 #include "utilities/events.hpp"
95 #include "utilities/macros.hpp"
96 #include "utilities/preserveException.hpp"
97 #if INCLUDE_ALL_GCS
98 #include "gc/cms/concurrentMarkSweepThread.hpp"
99 #include "gc/g1/concurrentMarkThread.inline.hpp"
100 #include "gc/parallel/pcTasks.hpp"
101 #endif // INCLUDE_ALL_GCS
102 #ifdef COMPILER1
103 #include "c1/c1_Compiler.hpp"
104 #endif
105 #ifdef COMPILER2
106 #include "opto/c2compiler.hpp"
107 #include "opto/idealGraphPrinter.hpp"
108 #endif
109 #if INCLUDE_RTM_OPT
110 #include "runtime/rtmLocking.hpp"
111 #endif
112
113 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
114
115 #ifdef DTRACE_ENABLED
116
117 // Only bother with this argument setup if dtrace is available
118
119 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
120 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
121
1369 // suspend-equivalent condition solves that timeout problem.
1370 //
1371 Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
1372 Mutex::_as_suspend_equivalent_flag);
1373 }
1374 }
1375
1376 void WatcherThread::unpark() {
1377 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1378 PeriodicTask_lock->notify();
1379 }
1380
1381 void WatcherThread::print_on(outputStream* st) const {
1382 st->print("\"%s\" ", name());
1383 Thread::print_on(st);
1384 st->cr();
1385 }
1386
1387 // ======= JavaThread ========
1388
1389 // A JavaThread is a normal Java thread
1390
1391 void JavaThread::initialize() {
1392 // Initialize fields
1393
1394 // Set the claimed par_id to UINT_MAX (ie not claiming any par_ids)
1395 set_claimed_par_id(UINT_MAX);
1396
1397 set_saved_exception_pc(NULL);
1398 set_threadObj(NULL);
1399 _anchor.clear();
1400 set_entry_point(NULL);
1401 set_jni_functions(jni_functions());
1402 set_callee_target(NULL);
1403 set_vm_result(NULL);
1404 set_vm_result_2(NULL);
1405 set_vframe_array_head(NULL);
1406 set_vframe_array_last(NULL);
1407 set_deferred_locals(NULL);
1408 set_deopt_mark(NULL);
1409 set_deopt_nmethod(NULL);
1410 clear_must_deopt_id();
1411 set_monitor_chunks(NULL);
1412 set_next(NULL);
1413 set_thread_state(_thread_new);
1414 _terminated = _not_terminated;
1415 _privileged_stack_top = NULL;
1416 _array_for_gc = NULL;
1417 _suspend_equivalent = false;
1418 _in_deopt_handler = 0;
1419 _doing_unsafe_access = false;
1420 _stack_guard_state = stack_guard_unused;
1421 (void)const_cast<oop&>(_exception_oop = oop(NULL));
1422 _exception_pc = 0;
1423 _exception_handler_pc = 0;
1424 _is_method_handle_return = 0;
1425 _jvmti_thread_state= NULL;
1426 _should_post_on_exceptions_flag = JNI_FALSE;
1427 _jvmti_get_loaded_classes_closure = NULL;
1428 _interp_only_mode = 0;
1429 _special_runtime_exit_condition = _no_async_condition;
1430 _pending_async_exception = NULL;
1431 _thread_stat = NULL;
1432 _thread_stat = new ThreadStatistics();
1433 _blocked_on_compilation = false;
1434 _jni_active_critical = 0;
1435 _pending_jni_exception_check_fn = NULL;
1436 _do_not_unlock_if_synchronized = false;
1437 _cached_monitor_info = NULL;
1438 _parker = Parker::Allocate(this);
1439
1440 #ifndef PRODUCT
1575 delete old_array;
1576 }
1577
1578 GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals();
1579 if (deferred != NULL) {
1580 // This can only happen if thread is destroyed before deoptimization occurs.
1581 assert(deferred->length() != 0, "empty array!");
1582 do {
1583 jvmtiDeferredLocalVariableSet* dlv = deferred->at(0);
1584 deferred->remove_at(0);
1585 // individual jvmtiDeferredLocalVariableSet are CHeapObj's
1586 delete dlv;
1587 } while (deferred->length() != 0);
1588 delete deferred;
1589 }
1590
1591 // All Java related clean up happens in exit
1592 ThreadSafepointState::destroy(this);
1593 if (_thread_profiler != NULL) delete _thread_profiler;
1594 if (_thread_stat != NULL) delete _thread_stat;
1595 }
1596
1597
1598 // The first routine called by a new Java thread
1599 void JavaThread::run() {
1600 // initialize thread-local alloc buffer related fields
1601 this->initialize_tlab();
1602
1603 // used to test validity of stack trace backs
1604 this->record_base_of_stack_pointer();
1605
1606 // Record real stack base and size.
1607 this->record_stack_base_and_size();
1608
1609 // Initialize thread local storage; set before calling MutexLocker
1610 this->initialize_thread_local_storage();
1611
1612 this->create_stack_guard_pages();
1613
1614 this->cache_global_variables();
2118
2119 frame_anchor()->make_walkable(this);
2120 java_suspend_self();
2121
2122 // We might be here for reasons in addition to the self-suspend request
2123 // so check for other async requests.
2124 }
2125
2126 if (check_asyncs) {
2127 check_and_handle_async_exceptions();
2128 }
2129 }
2130
2131 void JavaThread::send_thread_stop(oop java_throwable) {
2132 assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
2133 assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
2134 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
2135
2136 // Do not throw asynchronous exceptions against the compiler thread
2137 // (the compiler thread should not be a Java thread -- fix in 1.4.2)
2138 if (is_Compiler_thread()) return;
2139
2140 {
2141 // Actually throw the Throwable against the target Thread - however
2142 // only if there is no thread death exception installed already.
2143 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
2144 // If the topmost frame is a runtime stub, then we are calling into
2145 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
2146 // must deoptimize the caller before continuing, as the compiled exception handler table
2147 // may not be valid
2148 if (has_last_Java_frame()) {
2149 frame f = last_frame();
2150 if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
2151 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2152 RegisterMap reg_map(this, UseBiasedLocking);
2153 frame compiled_frame = f.sender(®_map);
2154 if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
2155 Deoptimization::deoptimize(this, compiled_frame, ®_map);
2156 }
2157 }
2158 }
2597
2598 // Make zombies
2599 void JavaThread::make_zombies() {
2600 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2601 if (fst.current()->can_be_deoptimized()) {
2602 // it is a Java nmethod
2603 nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
2604 nm->make_not_entrant();
2605 }
2606 }
2607 }
2608 #endif // PRODUCT
2609
2610
2611 void JavaThread::deoptimized_wrt_marked_nmethods() {
2612 if (!has_last_Java_frame()) return;
2613 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2614 StackFrameStream fst(this, UseBiasedLocking);
2615 for (; !fst.is_done(); fst.next()) {
2616 if (fst.current()->should_be_deoptimized()) {
2617 if (LogCompilation && xtty != NULL) {
2618 nmethod* nm = fst.current()->cb()->as_nmethod_or_null();
2619 xtty->elem("deoptimized thread='" UINTX_FORMAT "' compile_id='%d'",
2620 this->name(), nm != NULL ? nm->compile_id() : -1);
2621 }
2622
2623 Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2624 }
2625 }
2626 }
2627
2628
2629 // If the caller is a NamedThread, then remember, in the current scope,
2630 // the given JavaThread in its _processed_thread field.
2631 class RememberProcessedThread: public StackObj {
2632 NamedThread* _cur_thr;
2633 public:
2634 RememberProcessedThread(JavaThread* jthr) {
2635 Thread* thread = Thread::current();
2636 if (thread->is_Named_thread()) {
2637 _cur_thr = (NamedThread *)thread;
2638 _cur_thr->set_processed_thread(jthr);
2639 } else {
2640 _cur_thr = NULL;
2641 }
2642 }
2643
2644 ~RememberProcessedThread() {
2645 if (_cur_thr) {
2646 _cur_thr->set_processed_thread(NULL);
2647 }
2648 }
2649 };
2650
2651 void JavaThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
2652 // Verify that the deferred card marks have been flushed.
2653 assert(deferred_card_mark().is_empty(), "Should be empty during GC");
2654
2655 // The ThreadProfiler oops_do is done from FlatProfiler::oops_do
2656 // since there may be more than one thread using each ThreadProfiler.
2657
2658 // Traverse the GCHandles
2659 Thread::oops_do(f, cld_f, cf);
2660
2661 assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2662 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2663
2664 if (has_last_Java_frame()) {
2665 // Record JavaThread to GC thread
2666 RememberProcessedThread rpt(this);
2667
2668 // Traverse the privileged stack
2669 if (_privileged_stack_top != NULL) {
2670 _privileged_stack_top->oops_do(f);
2671 }
2672
2673 // traverse the registered growable array
2674 if (_array_for_gc != NULL) {
2675 for (int index = 0; index < _array_for_gc->length(); index++) {
2676 f->do_oop(_array_for_gc->adr_at(index));
2677 }
2678 }
2679
2680 // Traverse the monitor chunks
3158 NMethodSweeper::sweeper_loop();
3159 }
3160
3161 // Create a CompilerThread
3162 CompilerThread::CompilerThread(CompileQueue* queue,
3163 CompilerCounters* counters)
3164 : JavaThread(&compiler_thread_entry) {
3165 _env = NULL;
3166 _log = NULL;
3167 _task = NULL;
3168 _queue = queue;
3169 _counters = counters;
3170 _buffer_blob = NULL;
3171 _compiler = NULL;
3172
3173 #ifndef PRODUCT
3174 _ideal_graph_printer = NULL;
3175 #endif
3176 }
3177
3178 // Create sweeper thread
3179 CodeCacheSweeperThread::CodeCacheSweeperThread()
3180 : JavaThread(&sweeper_thread_entry) {
3181 _scanned_nmethod = NULL;
3182 }
3183 void CodeCacheSweeperThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
3184 JavaThread::oops_do(f, cld_f, cf);
3185 if (_scanned_nmethod != NULL && cf != NULL) {
3186 // Safepoints can occur when the sweeper is scanning an nmethod so
3187 // process it here to make sure it isn't unloaded in the middle of
3188 // a scan.
3189 cf->do_code_blob(_scanned_nmethod);
3190 }
3191 }
3192
3193
3194 // ======= Threads ========
3195
3196 // The Threads class links together all active threads, and provides
3197 // operations over all threads. It is protected by its own Mutex
3363
3364 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
3365 // Must be before create_vm_init_agents()
3366 if (Arguments::init_libraries_at_startup()) {
3367 convert_vm_init_libraries_to_agents();
3368 }
3369
3370 // Launch -agentlib/-agentpath and converted -Xrun agents
3371 if (Arguments::init_agents_at_startup()) {
3372 create_vm_init_agents();
3373 }
3374
3375 // Initialize Threads state
3376 _thread_list = NULL;
3377 _number_of_threads = 0;
3378 _number_of_non_daemon_threads = 0;
3379
3380 // Initialize global data structures and create system classes in heap
3381 vm_init_globals();
3382
3383 // Attach the main thread to this os thread
3384 JavaThread* main_thread = new JavaThread();
3385 main_thread->set_thread_state(_thread_in_vm);
3386 // must do this before set_active_handles and initialize_thread_local_storage
3387 // Note: on solaris initialize_thread_local_storage() will (indirectly)
3388 // change the stack size recorded here to one based on the java thread
3389 // stacksize. This adjusted size is what is used to figure the placement
3390 // of the guard pages.
3391 main_thread->record_stack_base_and_size();
3392 main_thread->initialize_thread_local_storage();
3393
3394 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
3395
3396 if (!main_thread->set_as_starting_thread()) {
3397 vm_shutdown_during_initialization(
3398 "Failed necessary internal allocation. Out of swap space");
3399 delete main_thread;
3400 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3401 return JNI_ENOMEM;
3402 }
3489 }
3490
3491 // Set flag that basic initialization has completed. Used by exceptions and various
3492 // debug stuff, that does not work until all basic classes have been initialized.
3493 set_init_completed();
3494
3495 Metaspace::post_initialize();
3496
3497 HOTSPOT_VM_INIT_END();
3498
3499 // record VM initialization completion time
3500 #if INCLUDE_MANAGEMENT
3501 Management::record_vm_init_completed();
3502 #endif // INCLUDE_MANAGEMENT
3503
3504 // Compute system loader. Note that this has to occur after set_init_completed, since
3505 // valid exceptions may be thrown in the process.
3506 // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
3507 // set_init_completed has just been called, causing exceptions not to be shortcut
3508 // anymore. We call vm_exit_during_initialization directly instead.
3509 SystemDictionary::compute_java_system_loader(CHECK_JNI_ERR);
3510
3511 #if INCLUDE_ALL_GCS
3512 // Support for ConcurrentMarkSweep. This should be cleaned up
3513 // and better encapsulated. The ugly nested if test would go away
3514 // once things are properly refactored. XXX YSR
3515 if (UseConcMarkSweepGC || UseG1GC) {
3516 if (UseConcMarkSweepGC) {
3517 ConcurrentMarkSweepThread::makeSurrogateLockerThread(CHECK_JNI_ERR);
3518 } else {
3519 ConcurrentMarkThread::makeSurrogateLockerThread(CHECK_JNI_ERR);
3520 }
3521 }
3522 #endif // INCLUDE_ALL_GCS
3523
3524 // Always call even when there are not JVMTI environments yet, since environments
3525 // may be attached late and JVMTI must track phases of VM execution
3526 JvmtiExport::enter_live_phase();
3527
3528 // Signal Dispatcher needs to be started before VMInit event is posted
3529 os::signal_init();
3537 }
3538
3539 // Launch -Xrun agents
3540 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3541 // back-end can launch with -Xdebug -Xrunjdwp.
3542 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3543 create_vm_init_libraries();
3544 }
3545
3546 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3547 JvmtiExport::post_vm_initialized();
3548
3549 if (TRACE_START() != JNI_OK) {
3550 vm_exit_during_initialization("Failed to start tracing backend.");
3551 }
3552
3553 if (CleanChunkPoolAsync) {
3554 Chunk::start_chunk_pool_cleaner_task();
3555 }
3556
3557 // initialize compiler(s)
3558 #if defined(COMPILER1) || defined(COMPILER2) || defined(SHARK)
3559 CompileBroker::compilation_init();
3560 #endif
3561
3562 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
3563 // It is done after compilers are initialized, because otherwise compilations of
3564 // signature polymorphic MH intrinsics can be missed
3565 // (see SystemDictionary::find_method_handle_intrinsic).
3566 initialize_jsr292_core_classes(CHECK_JNI_ERR);
3567
3568 #if INCLUDE_MANAGEMENT
3569 Management::initialize(THREAD);
3570
3571 if (HAS_PENDING_EXCEPTION) {
3572 // management agent fails to start possibly due to
3573 // configuration problem and is responsible for printing
3574 // stack trace if appropriate. Simply exit VM.
3575 vm_exit(1);
3576 }
3577 #endif // INCLUDE_MANAGEMENT
3578
3946
3947 // Now, all Java threads are gone except daemon threads. Daemon threads
3948 // running Java code or in VM are stopped by the Safepoint. However,
3949 // daemon threads executing native code are still running. But they
3950 // will be stopped at native=>Java/VM barriers. Note that we can't
3951 // simply kill or suspend them, as it is inherently deadlock-prone.
3952
3953 #ifndef PRODUCT
3954 // disable function tracing at JNI/JVM barriers
3955 TraceJNICalls = false;
3956 TraceJVMCalls = false;
3957 TraceRuntimeCalls = false;
3958 #endif
3959
3960 VM_Exit::set_vm_exited();
3961
3962 notify_vm_shutdown();
3963
3964 delete thread;
3965
3966 // exit_globals() will delete tty
3967 exit_globals();
3968
3969 return true;
3970 }
3971
3972
3973 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
3974 if (version == JNI_VERSION_1_1) return JNI_TRUE;
3975 return is_supported_jni_version(version);
3976 }
3977
3978
3979 jboolean Threads::is_supported_jni_version(jint version) {
3980 if (version == JNI_VERSION_1_2) return JNI_TRUE;
3981 if (version == JNI_VERSION_1_4) return JNI_TRUE;
3982 if (version == JNI_VERSION_1_6) return JNI_TRUE;
3983 if (version == JNI_VERSION_1_8) return JNI_TRUE;
3984 return JNI_FALSE;
3985 }
4162
4163 void Threads::deoptimized_wrt_marked_nmethods() {
4164 ALL_JAVA_THREADS(p) {
4165 p->deoptimized_wrt_marked_nmethods();
4166 }
4167 }
4168
4169
4170 // Get count Java threads that are waiting to enter the specified monitor.
4171 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
4172 address monitor,
4173 bool doLock) {
4174 assert(doLock || SafepointSynchronize::is_at_safepoint(),
4175 "must grab Threads_lock or be at safepoint");
4176 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
4177
4178 int i = 0;
4179 {
4180 MutexLockerEx ml(doLock ? Threads_lock : NULL);
4181 ALL_JAVA_THREADS(p) {
4182 if (p->is_Compiler_thread()) continue;
4183
4184 address pending = (address)p->current_pending_monitor();
4185 if (pending == monitor) { // found a match
4186 if (i < count) result->append(p); // save the first count matches
4187 i++;
4188 }
4189 }
4190 }
4191 return result;
4192 }
4193
4194
4195 JavaThread *Threads::owning_thread_from_monitor_owner(address owner,
4196 bool doLock) {
4197 assert(doLock ||
4198 Threads_lock->owned_by_self() ||
4199 SafepointSynchronize::is_at_safepoint(),
4200 "must grab Threads_lock or be at safepoint");
4201
4202 // NULL owner means not locked so we can skip the search
4219 // Lock Word in the owning Java thread's stack.
4220 //
4221 JavaThread* the_owner = NULL;
4222 {
4223 MutexLockerEx ml(doLock ? Threads_lock : NULL);
4224 ALL_JAVA_THREADS(q) {
4225 if (q->is_lock_owned(owner)) {
4226 the_owner = q;
4227 break;
4228 }
4229 }
4230 }
4231 // cannot assert on lack of success here; see above comment
4232 return the_owner;
4233 }
4234
4235 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
4236 void Threads::print_on(outputStream* st, bool print_stacks,
4237 bool internal_format, bool print_concurrent_locks) {
4238 char buf[32];
4239 st->print_cr("%s", os::local_time_string(buf, sizeof(buf)));
4240
4241 st->print_cr("Full thread dump %s (%s %s):",
4242 Abstract_VM_Version::vm_name(),
4243 Abstract_VM_Version::vm_release(),
4244 Abstract_VM_Version::vm_info_string());
4245 st->cr();
4246
4247 #if INCLUDE_SERVICES
4248 // Dump concurrent locks
4249 ConcurrentLocksDump concurrent_locks;
4250 if (print_concurrent_locks) {
4251 concurrent_locks.dump_at_safepoint();
4252 }
4253 #endif // INCLUDE_SERVICES
4254
4255 ALL_JAVA_THREADS(p) {
4256 ResourceMark rm;
4257 p->print_on(st);
4258 if (print_stacks) {
4259 if (internal_format) {
|
82 #include "runtime/vframe_hp.hpp"
83 #include "runtime/vmThread.hpp"
84 #include "runtime/vm_operations.hpp"
85 #include "runtime/vm_version.hpp"
86 #include "services/attachListener.hpp"
87 #include "services/management.hpp"
88 #include "services/memTracker.hpp"
89 #include "services/threadService.hpp"
90 #include "trace/traceMacros.hpp"
91 #include "trace/tracing.hpp"
92 #include "utilities/defaultStream.hpp"
93 #include "utilities/dtrace.hpp"
94 #include "utilities/events.hpp"
95 #include "utilities/macros.hpp"
96 #include "utilities/preserveException.hpp"
97 #if INCLUDE_ALL_GCS
98 #include "gc/cms/concurrentMarkSweepThread.hpp"
99 #include "gc/g1/concurrentMarkThread.inline.hpp"
100 #include "gc/parallel/pcTasks.hpp"
101 #endif // INCLUDE_ALL_GCS
102 #if INCLUDE_JVMCI
103 #include "jvmci/jvmciCompiler.hpp"
104 #include "jvmci/jvmciRuntime.hpp"
105 #endif
106 #ifdef COMPILER1
107 #include "c1/c1_Compiler.hpp"
108 #endif
109 #ifdef COMPILER2
110 #include "opto/c2compiler.hpp"
111 #include "opto/idealGraphPrinter.hpp"
112 #endif
113 #if INCLUDE_RTM_OPT
114 #include "runtime/rtmLocking.hpp"
115 #endif
116
117 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
118
119 #ifdef DTRACE_ENABLED
120
121 // Only bother with this argument setup if dtrace is available
122
123 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
124 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
125
1373 // suspend-equivalent condition solves that timeout problem.
1374 //
1375 Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
1376 Mutex::_as_suspend_equivalent_flag);
1377 }
1378 }
1379
1380 void WatcherThread::unpark() {
1381 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1382 PeriodicTask_lock->notify();
1383 }
1384
1385 void WatcherThread::print_on(outputStream* st) const {
1386 st->print("\"%s\" ", name());
1387 Thread::print_on(st);
1388 st->cr();
1389 }
1390
1391 // ======= JavaThread ========
1392
1393 #if INCLUDE_JVMCI
1394
1395 jlong* JavaThread::_jvmci_old_thread_counters;
1396
1397 bool jvmci_counters_include(JavaThread* thread) {
1398 oop threadObj = thread->threadObj();
1399 return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
1400 }
1401
1402 void JavaThread::collect_counters(typeArrayOop array) {
1403 if (JVMCICounterSize > 0) {
1404 MutexLocker tl(Threads_lock);
1405 for (int i = 0; i < array->length(); i++) {
1406 array->long_at_put(i, _jvmci_old_thread_counters[i]);
1407 }
1408 for (JavaThread* tp = Threads::first(); tp != NULL; tp = tp->next()) {
1409 if (jvmci_counters_include(tp)) {
1410 for (int i = 0; i < array->length(); i++) {
1411 array->long_at_put(i, array->long_at(i) + tp->_jvmci_counters[i]);
1412 }
1413 }
1414 }
1415 }
1416 }
1417
1418 #endif
1419
1420 // A JavaThread is a normal Java thread
1421
1422 void JavaThread::initialize() {
1423 // Initialize fields
1424
1425 // Set the claimed par_id to UINT_MAX (ie not claiming any par_ids)
1426 set_claimed_par_id(UINT_MAX);
1427
1428 set_saved_exception_pc(NULL);
1429 set_threadObj(NULL);
1430 _anchor.clear();
1431 set_entry_point(NULL);
1432 set_jni_functions(jni_functions());
1433 set_callee_target(NULL);
1434 set_vm_result(NULL);
1435 set_vm_result_2(NULL);
1436 set_vframe_array_head(NULL);
1437 set_vframe_array_last(NULL);
1438 set_deferred_locals(NULL);
1439 set_deopt_mark(NULL);
1440 set_deopt_nmethod(NULL);
1441 clear_must_deopt_id();
1442 set_monitor_chunks(NULL);
1443 set_next(NULL);
1444 set_thread_state(_thread_new);
1445 _terminated = _not_terminated;
1446 _privileged_stack_top = NULL;
1447 _array_for_gc = NULL;
1448 _suspend_equivalent = false;
1449 _in_deopt_handler = 0;
1450 _doing_unsafe_access = false;
1451 _stack_guard_state = stack_guard_unused;
1452 #if INCLUDE_JVMCI
1453 _pending_monitorenter = false;
1454 _pending_deoptimization = -1;
1455 _pending_failed_speculation = NULL;
1456 _pending_transfer_to_interpreter = false;
1457 _jvmci._alternate_call_target = NULL;
1458 assert(_jvmci._implicit_exception_pc == NULL, "must be");
1459 if (JVMCICounterSize > 0) {
1460 _jvmci_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal);
1461 memset(_jvmci_counters, 0, sizeof(jlong) * JVMCICounterSize);
1462 } else {
1463 _jvmci_counters = NULL;
1464 }
1465 #endif
1466 (void)const_cast<oop&>(_exception_oop = oop(NULL));
1467 _exception_pc = 0;
1468 _exception_handler_pc = 0;
1469 _is_method_handle_return = 0;
1470 _jvmti_thread_state= NULL;
1471 _should_post_on_exceptions_flag = JNI_FALSE;
1472 _jvmti_get_loaded_classes_closure = NULL;
1473 _interp_only_mode = 0;
1474 _special_runtime_exit_condition = _no_async_condition;
1475 _pending_async_exception = NULL;
1476 _thread_stat = NULL;
1477 _thread_stat = new ThreadStatistics();
1478 _blocked_on_compilation = false;
1479 _jni_active_critical = 0;
1480 _pending_jni_exception_check_fn = NULL;
1481 _do_not_unlock_if_synchronized = false;
1482 _cached_monitor_info = NULL;
1483 _parker = Parker::Allocate(this);
1484
1485 #ifndef PRODUCT
1620 delete old_array;
1621 }
1622
1623 GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals();
1624 if (deferred != NULL) {
1625 // This can only happen if thread is destroyed before deoptimization occurs.
1626 assert(deferred->length() != 0, "empty array!");
1627 do {
1628 jvmtiDeferredLocalVariableSet* dlv = deferred->at(0);
1629 deferred->remove_at(0);
1630 // individual jvmtiDeferredLocalVariableSet are CHeapObj's
1631 delete dlv;
1632 } while (deferred->length() != 0);
1633 delete deferred;
1634 }
1635
1636 // All Java related clean up happens in exit
1637 ThreadSafepointState::destroy(this);
1638 if (_thread_profiler != NULL) delete _thread_profiler;
1639 if (_thread_stat != NULL) delete _thread_stat;
1640
1641 #if INCLUDE_JVMCI
1642 if (JVMCICounterSize > 0) {
1643 if (jvmci_counters_include(this)) {
1644 for (int i = 0; i < JVMCICounterSize; i++) {
1645 _jvmci_old_thread_counters[i] += _jvmci_counters[i];
1646 }
1647 }
1648 FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
1649 }
1650 #endif
1651 }
1652
1653
1654 // The first routine called by a new Java thread
1655 void JavaThread::run() {
1656 // initialize thread-local alloc buffer related fields
1657 this->initialize_tlab();
1658
1659 // used to test validity of stack trace backs
1660 this->record_base_of_stack_pointer();
1661
1662 // Record real stack base and size.
1663 this->record_stack_base_and_size();
1664
1665 // Initialize thread local storage; set before calling MutexLocker
1666 this->initialize_thread_local_storage();
1667
1668 this->create_stack_guard_pages();
1669
1670 this->cache_global_variables();
2174
2175 frame_anchor()->make_walkable(this);
2176 java_suspend_self();
2177
2178 // We might be here for reasons in addition to the self-suspend request
2179 // so check for other async requests.
2180 }
2181
2182 if (check_asyncs) {
2183 check_and_handle_async_exceptions();
2184 }
2185 }
2186
2187 void JavaThread::send_thread_stop(oop java_throwable) {
2188 assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
2189 assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
2190 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
2191
2192 // Do not throw asynchronous exceptions against the compiler thread
2193 // (the compiler thread should not be a Java thread -- fix in 1.4.2)
2194 if (!can_call_java()) return;
2195
2196 {
2197 // Actually throw the Throwable against the target Thread - however
2198 // only if there is no thread death exception installed already.
2199 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
2200 // If the topmost frame is a runtime stub, then we are calling into
2201 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
2202 // must deoptimize the caller before continuing, as the compiled exception handler table
2203 // may not be valid
2204 if (has_last_Java_frame()) {
2205 frame f = last_frame();
2206 if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
2207 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2208 RegisterMap reg_map(this, UseBiasedLocking);
2209 frame compiled_frame = f.sender(®_map);
2210 if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
2211 Deoptimization::deoptimize(this, compiled_frame, ®_map);
2212 }
2213 }
2214 }
2653
2654 // Make zombies
2655 void JavaThread::make_zombies() {
2656 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2657 if (fst.current()->can_be_deoptimized()) {
2658 // it is a Java nmethod
2659 nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
2660 nm->make_not_entrant();
2661 }
2662 }
2663 }
2664 #endif // PRODUCT
2665
2666
2667 void JavaThread::deoptimized_wrt_marked_nmethods() {
2668 if (!has_last_Java_frame()) return;
2669 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2670 StackFrameStream fst(this, UseBiasedLocking);
2671 for (; !fst.is_done(); fst.next()) {
2672 if (fst.current()->should_be_deoptimized()) {
2673 Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2674 }
2675 }
2676 }
2677
2678
2679 // If the caller is a NamedThread, then remember, in the current scope,
2680 // the given JavaThread in its _processed_thread field.
2681 class RememberProcessedThread: public StackObj {
2682 NamedThread* _cur_thr;
2683 public:
2684 RememberProcessedThread(JavaThread* jthr) {
2685 Thread* thread = Thread::current();
2686 if (thread->is_Named_thread()) {
2687 _cur_thr = (NamedThread *)thread;
2688 _cur_thr->set_processed_thread(jthr);
2689 } else {
2690 _cur_thr = NULL;
2691 }
2692 }
2693
2694 ~RememberProcessedThread() {
2695 if (_cur_thr) {
2696 _cur_thr->set_processed_thread(NULL);
2697 }
2698 }
2699 };
2700
2701 void JavaThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
2702 // Verify that the deferred card marks have been flushed.
2703 assert(deferred_card_mark().is_empty(), "Should be empty during GC");
2704
2705 // The ThreadProfiler oops_do is done from FlatProfiler::oops_do
2706 // since there may be more than one thread using each ThreadProfiler.
2707
2708 // Traverse the GCHandles
2709 Thread::oops_do(f, cld_f, cf);
2710
2711 JVMCI_ONLY(f->do_oop((oop*)&_pending_failed_speculation);)
2712
2713 assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2714 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2715
2716 if (has_last_Java_frame()) {
2717 // Record JavaThread to GC thread
2718 RememberProcessedThread rpt(this);
2719
2720 // Traverse the privileged stack
2721 if (_privileged_stack_top != NULL) {
2722 _privileged_stack_top->oops_do(f);
2723 }
2724
2725 // traverse the registered growable array
2726 if (_array_for_gc != NULL) {
2727 for (int index = 0; index < _array_for_gc->length(); index++) {
2728 f->do_oop(_array_for_gc->adr_at(index));
2729 }
2730 }
2731
2732 // Traverse the monitor chunks
3210 NMethodSweeper::sweeper_loop();
3211 }
3212
3213 // Create a CompilerThread
3214 CompilerThread::CompilerThread(CompileQueue* queue,
3215 CompilerCounters* counters)
3216 : JavaThread(&compiler_thread_entry) {
3217 _env = NULL;
3218 _log = NULL;
3219 _task = NULL;
3220 _queue = queue;
3221 _counters = counters;
3222 _buffer_blob = NULL;
3223 _compiler = NULL;
3224
3225 #ifndef PRODUCT
3226 _ideal_graph_printer = NULL;
3227 #endif
3228 }
3229
3230 bool CompilerThread::can_call_java() const {
3231 return _compiler != NULL && _compiler->is_jvmci();
3232 }
3233
3234 // Create sweeper thread
3235 CodeCacheSweeperThread::CodeCacheSweeperThread()
3236 : JavaThread(&sweeper_thread_entry) {
3237 _scanned_nmethod = NULL;
3238 }
3239 void CodeCacheSweeperThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
3240 JavaThread::oops_do(f, cld_f, cf);
3241 if (_scanned_nmethod != NULL && cf != NULL) {
3242 // Safepoints can occur when the sweeper is scanning an nmethod so
3243 // process it here to make sure it isn't unloaded in the middle of
3244 // a scan.
3245 cf->do_code_blob(_scanned_nmethod);
3246 }
3247 }
3248
3249
3250 // ======= Threads ========
3251
3252 // The Threads class links together all active threads, and provides
3253 // operations over all threads. It is protected by its own Mutex
3419
3420 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
3421 // Must be before create_vm_init_agents()
3422 if (Arguments::init_libraries_at_startup()) {
3423 convert_vm_init_libraries_to_agents();
3424 }
3425
3426 // Launch -agentlib/-agentpath and converted -Xrun agents
3427 if (Arguments::init_agents_at_startup()) {
3428 create_vm_init_agents();
3429 }
3430
3431 // Initialize Threads state
3432 _thread_list = NULL;
3433 _number_of_threads = 0;
3434 _number_of_non_daemon_threads = 0;
3435
3436 // Initialize global data structures and create system classes in heap
3437 vm_init_globals();
3438
3439 #if INCLUDE_JVMCI
3440 if (JVMCICounterSize > 0) {
3441 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal);
3442 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
3443 } else {
3444 JavaThread::_jvmci_old_thread_counters = NULL;
3445 }
3446 #endif
3447
3448 // Attach the main thread to this os thread
3449 JavaThread* main_thread = new JavaThread();
3450 main_thread->set_thread_state(_thread_in_vm);
3451 // must do this before set_active_handles and initialize_thread_local_storage
3452 // Note: on solaris initialize_thread_local_storage() will (indirectly)
3453 // change the stack size recorded here to one based on the java thread
3454 // stacksize. This adjusted size is what is used to figure the placement
3455 // of the guard pages.
3456 main_thread->record_stack_base_and_size();
3457 main_thread->initialize_thread_local_storage();
3458
3459 main_thread->set_active_handles(JNIHandleBlock::allocate_block());
3460
3461 if (!main_thread->set_as_starting_thread()) {
3462 vm_shutdown_during_initialization(
3463 "Failed necessary internal allocation. Out of swap space");
3464 delete main_thread;
3465 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3466 return JNI_ENOMEM;
3467 }
3554 }
3555
3556 // Set flag that basic initialization has completed. Used by exceptions and various
3557 // debug stuff, that does not work until all basic classes have been initialized.
3558 set_init_completed();
3559
3560 Metaspace::post_initialize();
3561
3562 HOTSPOT_VM_INIT_END();
3563
3564 // record VM initialization completion time
3565 #if INCLUDE_MANAGEMENT
3566 Management::record_vm_init_completed();
3567 #endif // INCLUDE_MANAGEMENT
3568
3569 // Compute system loader. Note that this has to occur after set_init_completed, since
3570 // valid exceptions may be thrown in the process.
3571 // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
3572 // set_init_completed has just been called, causing exceptions not to be shortcut
3573 // anymore. We call vm_exit_during_initialization directly instead.
3574 SystemDictionary::compute_java_system_loader(CHECK_(JNI_ERR));
3575
3576 #if INCLUDE_ALL_GCS
3577 // Support for ConcurrentMarkSweep. This should be cleaned up
3578 // and better encapsulated. The ugly nested if test would go away
3579 // once things are properly refactored. XXX YSR
3580 if (UseConcMarkSweepGC || UseG1GC) {
3581 if (UseConcMarkSweepGC) {
3582 ConcurrentMarkSweepThread::makeSurrogateLockerThread(CHECK_JNI_ERR);
3583 } else {
3584 ConcurrentMarkThread::makeSurrogateLockerThread(CHECK_JNI_ERR);
3585 }
3586 }
3587 #endif // INCLUDE_ALL_GCS
3588
3589 // Always call even when there are not JVMTI environments yet, since environments
3590 // may be attached late and JVMTI must track phases of VM execution
3591 JvmtiExport::enter_live_phase();
3592
3593 // Signal Dispatcher needs to be started before VMInit event is posted
3594 os::signal_init();
3602 }
3603
3604 // Launch -Xrun agents
3605 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3606 // back-end can launch with -Xdebug -Xrunjdwp.
3607 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3608 create_vm_init_libraries();
3609 }
3610
3611 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3612 JvmtiExport::post_vm_initialized();
3613
3614 if (TRACE_START() != JNI_OK) {
3615 vm_exit_during_initialization("Failed to start tracing backend.");
3616 }
3617
3618 if (CleanChunkPoolAsync) {
3619 Chunk::start_chunk_pool_cleaner_task();
3620 }
3621
3622 #if INCLUDE_JVMCI
3623 if (EnableJVMCI) {
3624 const char* jvmciCompiler = Arguments::PropertyList_get_value(Arguments::system_properties(), "jvmci.compiler");
3625 if (jvmciCompiler != NULL) {
3626 JVMCIRuntime::save_compiler(jvmciCompiler);
3627 }
3628 const char* jvmciOptions = Arguments::PropertyList_get_value(Arguments::system_properties(), "jvmci.options");
3629 if (jvmciOptions != NULL) {
3630 JVMCIRuntime::save_options(jvmciOptions);
3631 }
3632 }
3633 #endif
3634
3635 // initialize compiler(s)
3636 #if defined(COMPILER1) || defined(COMPILER2) || defined(SHARK) || INCLUDE_JVMCI
3637 CompileBroker::compilation_init();
3638 #endif
3639
3640 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
3641 // It is done after compilers are initialized, because otherwise compilations of
3642 // signature polymorphic MH intrinsics can be missed
3643 // (see SystemDictionary::find_method_handle_intrinsic).
3644 initialize_jsr292_core_classes(CHECK_JNI_ERR);
3645
3646 #if INCLUDE_MANAGEMENT
3647 Management::initialize(THREAD);
3648
3649 if (HAS_PENDING_EXCEPTION) {
3650 // management agent fails to start possibly due to
3651 // configuration problem and is responsible for printing
3652 // stack trace if appropriate. Simply exit VM.
3653 vm_exit(1);
3654 }
3655 #endif // INCLUDE_MANAGEMENT
3656
4024
4025 // Now, all Java threads are gone except daemon threads. Daemon threads
4026 // running Java code or in VM are stopped by the Safepoint. However,
4027 // daemon threads executing native code are still running. But they
4028 // will be stopped at native=>Java/VM barriers. Note that we can't
4029 // simply kill or suspend them, as it is inherently deadlock-prone.
4030
4031 #ifndef PRODUCT
4032 // disable function tracing at JNI/JVM barriers
4033 TraceJNICalls = false;
4034 TraceJVMCalls = false;
4035 TraceRuntimeCalls = false;
4036 #endif
4037
4038 VM_Exit::set_vm_exited();
4039
4040 notify_vm_shutdown();
4041
4042 delete thread;
4043
4044 #if INCLUDE_JVMCI
4045 if (JVMCICounterSize > 0) {
4046 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
4047 }
4048 #endif
4049
4050 // exit_globals() will delete tty
4051 exit_globals();
4052
4053 return true;
4054 }
4055
4056
4057 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
4058 if (version == JNI_VERSION_1_1) return JNI_TRUE;
4059 return is_supported_jni_version(version);
4060 }
4061
4062
4063 jboolean Threads::is_supported_jni_version(jint version) {
4064 if (version == JNI_VERSION_1_2) return JNI_TRUE;
4065 if (version == JNI_VERSION_1_4) return JNI_TRUE;
4066 if (version == JNI_VERSION_1_6) return JNI_TRUE;
4067 if (version == JNI_VERSION_1_8) return JNI_TRUE;
4068 return JNI_FALSE;
4069 }
4246
4247 void Threads::deoptimized_wrt_marked_nmethods() {
4248 ALL_JAVA_THREADS(p) {
4249 p->deoptimized_wrt_marked_nmethods();
4250 }
4251 }
4252
4253
4254 // Get count Java threads that are waiting to enter the specified monitor.
4255 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
4256 address monitor,
4257 bool doLock) {
4258 assert(doLock || SafepointSynchronize::is_at_safepoint(),
4259 "must grab Threads_lock or be at safepoint");
4260 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
4261
4262 int i = 0;
4263 {
4264 MutexLockerEx ml(doLock ? Threads_lock : NULL);
4265 ALL_JAVA_THREADS(p) {
4266 if (!p->can_call_java()) continue;
4267
4268 address pending = (address)p->current_pending_monitor();
4269 if (pending == monitor) { // found a match
4270 if (i < count) result->append(p); // save the first count matches
4271 i++;
4272 }
4273 }
4274 }
4275 return result;
4276 }
4277
4278
4279 JavaThread *Threads::owning_thread_from_monitor_owner(address owner,
4280 bool doLock) {
4281 assert(doLock ||
4282 Threads_lock->owned_by_self() ||
4283 SafepointSynchronize::is_at_safepoint(),
4284 "must grab Threads_lock or be at safepoint");
4285
4286 // NULL owner means not locked so we can skip the search
4303 // Lock Word in the owning Java thread's stack.
4304 //
4305 JavaThread* the_owner = NULL;
4306 {
4307 MutexLockerEx ml(doLock ? Threads_lock : NULL);
4308 ALL_JAVA_THREADS(q) {
4309 if (q->is_lock_owned(owner)) {
4310 the_owner = q;
4311 break;
4312 }
4313 }
4314 }
4315 // cannot assert on lack of success here; see above comment
4316 return the_owner;
4317 }
4318
4319 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
4320 void Threads::print_on(outputStream* st, bool print_stacks,
4321 bool internal_format, bool print_concurrent_locks) {
4322 char buf[32];
4323 st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
4324
4325 st->print_cr("Full thread dump %s (%s %s):",
4326 Abstract_VM_Version::vm_name(),
4327 Abstract_VM_Version::vm_release(),
4328 Abstract_VM_Version::vm_info_string());
4329 st->cr();
4330
4331 #if INCLUDE_SERVICES
4332 // Dump concurrent locks
4333 ConcurrentLocksDump concurrent_locks;
4334 if (print_concurrent_locks) {
4335 concurrent_locks.dump_at_safepoint();
4336 }
4337 #endif // INCLUDE_SERVICES
4338
4339 ALL_JAVA_THREADS(p) {
4340 ResourceMark rm;
4341 p->print_on(st);
4342 if (print_stacks) {
4343 if (internal_format) {
|