15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "classfile/classLoader.hpp"
27 #include "classfile/javaClasses.hpp"
28 #include "classfile/systemDictionary.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "code/scopeDesc.hpp"
31 #include "compiler/compileBroker.hpp"
32 #include "interpreter/interpreter.hpp"
33 #include "interpreter/linkResolver.hpp"
34 #include "interpreter/oopMapCache.hpp"
35 #include "jvmtifiles/jvmtiEnv.hpp"
36 #include "memory/gcLocker.inline.hpp"
37 #include "memory/metaspaceShared.hpp"
38 #include "memory/oopFactory.hpp"
39 #include "memory/universe.inline.hpp"
40 #include "oops/instanceKlass.hpp"
41 #include "oops/objArrayOop.hpp"
42 #include "oops/oop.inline.hpp"
43 #include "oops/symbol.hpp"
44 #include "prims/jvm_misc.hpp"
45 #include "prims/jvmtiExport.hpp"
46 #include "prims/jvmtiThreadState.hpp"
47 #include "prims/privilegedStack.hpp"
48 #include "runtime/arguments.hpp"
49 #include "runtime/biasedLocking.hpp"
50 #include "runtime/deoptimization.hpp"
51 #include "runtime/fprofiler.hpp"
52 #include "runtime/frame.inline.hpp"
53 #include "runtime/init.hpp"
54 #include "runtime/interfaceSupport.hpp"
60 #include "runtime/objectMonitor.hpp"
61 #include "runtime/orderAccess.inline.hpp"
62 #include "runtime/osThread.hpp"
63 #include "runtime/safepoint.hpp"
64 #include "runtime/sharedRuntime.hpp"
65 #include "runtime/statSampler.hpp"
66 #include "runtime/stubRoutines.hpp"
67 #include "runtime/task.hpp"
68 #include "runtime/thread.inline.hpp"
69 #include "runtime/threadCritical.hpp"
70 #include "runtime/threadLocalStorage.hpp"
71 #include "runtime/vframe.hpp"
72 #include "runtime/vframeArray.hpp"
73 #include "runtime/vframe_hp.hpp"
74 #include "runtime/vmThread.hpp"
75 #include "runtime/vm_operations.hpp"
76 #include "services/attachListener.hpp"
77 #include "services/management.hpp"
78 #include "services/memTracker.hpp"
79 #include "services/threadService.hpp"
80 #include "trace/tracing.hpp"
81 #include "trace/traceMacros.hpp"
82 #include "utilities/defaultStream.hpp"
83 #include "utilities/dtrace.hpp"
84 #include "utilities/events.hpp"
85 #include "utilities/preserveException.hpp"
86 #include "utilities/macros.hpp"
87 #ifdef TARGET_OS_FAMILY_linux
88 # include "os_linux.inline.hpp"
89 #endif
90 #ifdef TARGET_OS_FAMILY_solaris
91 # include "os_solaris.inline.hpp"
92 #endif
93 #ifdef TARGET_OS_FAMILY_windows
94 # include "os_windows.inline.hpp"
95 #endif
96 #ifdef TARGET_OS_FAMILY_bsd
97 # include "os_bsd.inline.hpp"
98 #endif
99 #if INCLUDE_ALL_GCS
100 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
101 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
102 #include "gc_implementation/parallelScavenge/pcTasks.hpp"
103 #endif // INCLUDE_ALL_GCS
104 #ifdef COMPILER1
105 #include "c1/c1_Compiler.hpp"
106 #endif
107 #ifdef COMPILER2
108 #include "opto/c2compiler.hpp"
109 #include "opto/idealGraphPrinter.hpp"
110 #endif
111 #if INCLUDE_RTM_OPT
112 #include "runtime/rtmLocking.hpp"
113 #endif
114
115 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
116
117 #ifdef DTRACE_ENABLED
118
119 // Only bother with this argument setup if dtrace is available
120
121 #ifndef USDT2
122 HS_DTRACE_PROBE_DECL(hotspot, vm__init__begin);
123 HS_DTRACE_PROBE_DECL(hotspot, vm__init__end);
124 HS_DTRACE_PROBE_DECL5(hotspot, thread__start, char*, intptr_t,
125 intptr_t, intptr_t, bool);
126 HS_DTRACE_PROBE_DECL5(hotspot, thread__stop, char*, intptr_t,
127 intptr_t, intptr_t, bool);
128
129 #define DTRACE_THREAD_PROBE(probe, javathread) \
130 { \
131 ResourceMark rm(this); \
132 int len = 0; \
133 const char* name = (javathread)->get_thread_name(); \
325 // CR 7190089: on Solaris, primordial thread's stack is adjusted
326 // in initialize_thread(). Without the adjustment, stack size is
327 // incorrect if stack is set to unlimited (ulimit -s unlimited).
328 // So far, only Solaris has real implementation of initialize_thread().
329 //
330 // set up any platform-specific state.
331 os::initialize_thread(this);
332
333 #if INCLUDE_NMT
334 // record thread's native stack, stack grows downward
335 address stack_low_addr = stack_base() - stack_size();
336 MemTracker::record_thread_stack(stack_low_addr, stack_size());
337 #endif // INCLUDE_NMT
338 }
339
340
341 Thread::~Thread() {
342 // Reclaim the objectmonitors from the omFreeList of the moribund thread.
343 ObjectSynchronizer::omFlush (this) ;
344
345 EVENT_THREAD_DESTRUCT(this);
346
347 // stack_base can be NULL if the thread is never started or exited before
348 // record_stack_base_and_size called. Although, we would like to ensure
349 // that all started threads do call record_stack_base_and_size(), there is
350 // not proper way to enforce that.
351 #if INCLUDE_NMT
352 if (_stack_base != NULL) {
353 address low_stack_addr = stack_base() - stack_size();
354 MemTracker::release_thread_stack(low_stack_addr, stack_size());
355 #ifdef ASSERT
356 set_stack_base(NULL);
357 #endif
358 }
359 #endif // INCLUDE_NMT
360
361 // deallocate data structures
362 delete resource_area();
363 // since the handle marks are using the handle area, we have to deallocated the root
364 // handle mark before deallocating the thread's handle area,
365 assert(last_handle_mark() != NULL, "check we have an element");
1653
1654 // Thread is now sufficient initialized to be handled by the safepoint code as being
1655 // in the VM. Change thread state from _thread_new to _thread_in_vm
1656 ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
1657
1658 assert(JavaThread::current() == this, "sanity check");
1659 assert(!Thread::current()->owns_locks(), "sanity check");
1660
1661 DTRACE_THREAD_PROBE(start, this);
1662
1663 // This operation might block. We call that after all safepoint checks for a new thread has
1664 // been completed.
1665 this->set_active_handles(JNIHandleBlock::allocate_block());
1666
1667 if (JvmtiExport::should_post_thread_life()) {
1668 JvmtiExport::post_thread_start(this);
1669 }
1670
1671 EventThreadStart event;
1672 if (event.should_commit()) {
1673 event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj()));
1674 event.commit();
1675 }
1676
1677 // We call another function to do the rest so we are sure that the stack addresses used
1678 // from there will be lower than the stack base just computed
1679 thread_main_inner();
1680
1681 // Note, thread is no longer valid at this point!
1682 }
1683
1684
1685 void JavaThread::thread_main_inner() {
1686 assert(JavaThread::current() == this, "sanity check");
1687 assert(this->threadObj() != NULL, "just checking");
1688
1689 // Execute thread entry point unless this thread has a pending exception
1690 // or has been stopped before starting.
1691 // Note: Due to JVM_StopThread we can have pending exceptions already!
1692 if (!this->has_pending_exception() &&
1693 !java_lang_Thread::is_stillborn(this->threadObj())) {
1787 threadObj, // Arg 1
1788 uncaught_exception, // Arg 2
1789 THREAD);
1790 }
1791 if (HAS_PENDING_EXCEPTION) {
1792 ResourceMark rm(this);
1793 jio_fprintf(defaultStream::error_stream(),
1794 "\nException: %s thrown from the UncaughtExceptionHandler"
1795 " in thread \"%s\"\n",
1796 pending_exception()->klass()->external_name(),
1797 get_thread_name());
1798 CLEAR_PENDING_EXCEPTION;
1799 }
1800 }
1801 }
1802
1803 // Called before the java thread exit since we want to read info
1804 // from java_lang_Thread object
1805 EventThreadEnd event;
1806 if (event.should_commit()) {
1807 event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj()));
1808 event.commit();
1809 }
1810
1811 // Call after last event on thread
1812 EVENT_THREAD_EXIT(this);
1813
1814 // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
1815 // the execution of the method. If that is not enough, then we don't really care. Thread.stop
1816 // is deprecated anyhow.
1817 if (!is_Compiler_thread()) {
1818 int count = 3;
1819 while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
1820 EXCEPTION_MARK;
1821 JavaValue result(T_VOID);
1822 KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
1823 JavaCalls::call_virtual(&result,
1824 threadObj, thread_klass,
1825 vmSymbols::exit_method_name(),
1826 vmSymbols::void_method_signature(),
1827 THREAD);
1828 CLEAR_PENDING_EXCEPTION;
1829 }
1830 }
1831 // notify JVMTI
1832 if (JvmtiExport::should_post_thread_life()) {
2168 // }
2169 // set_thread_state(_thread_in_vm_trans);
2170 // if (safepoint) block;
2171 // set_thread_state(state);
2172 //
2173 // but that is pretty messy. Instead we just go with the way the
2174 // code has worked before and note that this is the only path to
2175 // java_suspend_self that doesn't put the thread in _thread_blocked
2176 // mode.
2177
2178 frame_anchor()->make_walkable(this);
2179 java_suspend_self();
2180
2181 // We might be here for reasons in addition to the self-suspend request
2182 // so check for other async requests.
2183 }
2184
2185 if (check_asyncs) {
2186 check_and_handle_async_exceptions();
2187 }
2188 }
2189
2190 void JavaThread::send_thread_stop(oop java_throwable) {
2191 assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
2192 assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
2193 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
2194
2195 // Do not throw asynchronous exceptions against the compiler thread
2196 // (the compiler thread should not be a Java thread -- fix in 1.4.2)
2197 if (is_Compiler_thread()) return;
2198
2199 {
2200 // Actually throw the Throwable against the target Thread - however
2201 // only if there is no thread death exception installed already.
2202 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
2203 // If the topmost frame is a runtime stub, then we are calling into
2204 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
2205 // must deoptimize the caller before continuing, as the compiled exception handler table
2206 // may not be valid
2207 if (has_last_Java_frame()) {
2406 if (SafepointSynchronize::do_call_back()) {
2407 // If we are safepointing, then block the caller which may not be
2408 // the same as the target thread (see above).
2409 SafepointSynchronize::block(curJT);
2410 }
2411
2412 if (thread->is_deopt_suspend()) {
2413 thread->clear_deopt_suspend();
2414 RegisterMap map(thread, false);
2415 frame f = thread->last_frame();
2416 while ( f.id() != thread->must_deopt_id() && ! f.is_first_frame()) {
2417 f = f.sender(&map);
2418 }
2419 if (f.id() == thread->must_deopt_id()) {
2420 thread->clear_must_deopt_id();
2421 f.deoptimize(thread);
2422 } else {
2423 fatal("missed deoptimization!");
2424 }
2425 }
2426 }
2427
2428 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2429 // progress or when _suspend_flags is non-zero.
2430 // Current thread needs to self-suspend if there is a suspend request and/or
2431 // block if a safepoint is in progress.
2432 // Also check for pending async exception (not including unsafe access error).
2433 // Note only the native==>VM/Java barriers can call this function and when
2434 // thread state is _thread_in_native_trans.
2435 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
2436 check_safepoint_and_suspend_for_native_trans(thread);
2437
2438 if (thread->has_async_exception()) {
2439 // We are in _thread_in_native_trans state, don't handle unsafe
2440 // access error since that may block.
2441 thread->check_and_handle_async_exceptions(false);
2442 }
2443 }
2444
2445 // This is a variant of the normal
3294 assert_locked_or_safepoint(Threads_lock);
3295 // ALL_JAVA_THREADS iterates through all JavaThreads
3296 ALL_JAVA_THREADS(p) {
3297 tc->do_thread(p);
3298 }
3299 // Someday we could have a table or list of all non-JavaThreads.
3300 // For now, just manually iterate through them.
3301 tc->do_thread(VMThread::vm_thread());
3302 Universe::heap()->gc_threads_do(tc);
3303 WatcherThread *wt = WatcherThread::watcher_thread();
3304 // Strictly speaking, the following NULL check isn't sufficient to make sure
3305 // the data for WatcherThread is still valid upon being examined. However,
3306 // considering that WatchThread terminates when the VM is on the way to
3307 // exit at safepoint, the chance of the above is extremely small. The right
3308 // way to prevent termination of WatcherThread would be to acquire
3309 // Terminator_lock, but we can't do that without violating the lock rank
3310 // checking in some cases.
3311 if (wt != NULL)
3312 tc->do_thread(wt);
3313
3314 // If CompilerThreads ever become non-JavaThreads, add them here
3315 }
3316
3317 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
3318
3319 extern void JDK_Version_init();
3320
3321 // Preinitialize version info.
3322 VM_Version::early_initialize();
3323
3324 // Check version
3325 if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
3326
3327 // Initialize the output stream module
3328 ostream_init();
3329
3330 // Process java launcher properties.
3331 Arguments::process_sun_java_launcher_properties(args);
3332
3333 // Initialize the os module before using TLS
3420 delete main_thread;
3421 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3422 return JNI_ENOMEM;
3423 }
3424
3425 // Enable guard page *after* os::create_main_thread(), otherwise it would
3426 // crash Linux VM, see notes in os_linux.cpp.
3427 main_thread->create_stack_guard_pages();
3428
3429 // Initialize Java-Level synchronization subsystem
3430 ObjectMonitor::Initialize() ;
3431
3432 // Initialize global modules
3433 jint status = init_globals();
3434 if (status != JNI_OK) {
3435 delete main_thread;
3436 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3437 return status;
3438 }
3439
3440 // Should be done after the heap is fully created
3441 main_thread->cache_global_variables();
3442
3443 HandleMark hm;
3444
3445 { MutexLocker mu(Threads_lock);
3446 Threads::add(main_thread);
3447 }
3448
3449 // Any JVMTI raw monitors entered in onload will transition into
3450 // real raw monitor. VM is setup enough here for raw monitor enter.
3451 JvmtiExport::transition_pending_onload_raw_monitors();
3452
3453 // Create the VMThread
3454 { TraceTime timer("Start VMThread", TraceStartupTime);
3455 VMThread::create();
3456 Thread* vmthread = VMThread::vm_thread();
3457
3458 if (!os::create_thread(vmthread, os::vm_thread))
3459 vm_exit_during_initialization("Cannot create VM thread. Out of system resources.");
3547 // resulting in a NoClassDefFoundError. This can happen in any
3548 // user code which calls methods in java.lang.Compiler.
3549 // Hack : the hack is to pre-load and initialize this class, so that only
3550 // system domains are on the stack when the properties are read.
3551 // Currently even the AWT code has calls to methods in java.lang.Compiler.
3552 // On the classic VM, java.lang.Compiler is loaded very early to load the JIT.
3553 // Future Fix : the best fix is to grant everyone permissions to read "java.compiler" and
3554 // read and write"java.vm.info" in the default policy file. See bugid 4211383
3555 // Once that is done, we should remove this hack.
3556 initialize_class(vmSymbols::java_lang_Compiler(), CHECK_0);
3557
3558 // More hackery - the static initializer of java.lang.Compiler adds the string "nojit" to
3559 // the java.vm.info property if no jit gets loaded through java.lang.Compiler (the hotspot
3560 // compiler does not get loaded through java.lang.Compiler). "java -version" with the
3561 // hotspot vm says "nojit" all the time which is confusing. So, we reset it here.
3562 // This should also be taken out as soon as 4211383 gets fixed.
3563 reset_vm_info_property(CHECK_0);
3564
3565 quicken_jni_functions();
3566
3567 // Must be run after init_ft which initializes ft_enabled
3568 if (TRACE_INITIALIZE() != JNI_OK) {
3569 vm_exit_during_initialization("Failed to initialize tracing backend");
3570 }
3571
3572 // Set flag that basic initialization has completed. Used by exceptions and various
3573 // debug stuff, that does not work until all basic classes have been initialized.
3574 set_init_completed();
3575
3576 Metaspace::post_initialize();
3577
3578 #ifndef USDT2
3579 HS_DTRACE_PROBE(hotspot, vm__init__end);
3580 #else /* USDT2 */
3581 HOTSPOT_VM_INIT_END();
3582 #endif /* USDT2 */
3583
3584 // record VM initialization completion time
3585 #if INCLUDE_MANAGEMENT
3586 Management::record_vm_init_completed();
3587 #endif // INCLUDE_MANAGEMENT
3588
3589 // Compute system loader. Note that this has to occur after set_init_completed, since
3590 // valid exceptions may be thrown in the process.
3591 // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
3620 os::signal_init();
3621
3622 // Start Attach Listener if +StartAttachListener or it can't be started lazily
3623 if (!DisableAttachMechanism) {
3624 AttachListener::vm_start();
3625 if (StartAttachListener || AttachListener::init_at_startup()) {
3626 AttachListener::init();
3627 }
3628 }
3629
3630 // Launch -Xrun agents
3631 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3632 // back-end can launch with -Xdebug -Xrunjdwp.
3633 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3634 create_vm_init_libraries();
3635 }
3636
3637 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3638 JvmtiExport::post_vm_initialized();
3639
3640 if (TRACE_START() != JNI_OK) {
3641 vm_exit_during_initialization("Failed to start tracing backend.");
3642 }
3643
3644 if (CleanChunkPoolAsync) {
3645 Chunk::start_chunk_pool_cleaner_task();
3646 }
3647
3648 // initialize compiler(s)
3649 #if defined(COMPILER1) || defined(COMPILER2) || defined(SHARK)
3650 CompileBroker::compilation_init();
3651 #endif
3652
3653 if (EnableInvokeDynamic) {
3654 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
3655 // It is done after compilers are initialized, because otherwise compilations of
3656 // signature polymorphic MH intrinsics can be missed
3657 // (see SystemDictionary::find_method_handle_intrinsic).
3658 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK_0);
3659 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK_0);
3660 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK_0);
3661 }
3662
|
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "classfile/classLoader.hpp"
27 #include "classfile/javaClasses.hpp"
28 #include "classfile/systemDictionary.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "code/scopeDesc.hpp"
31 #include "compiler/compileBroker.hpp"
32 #include "interpreter/interpreter.hpp"
33 #include "interpreter/linkResolver.hpp"
34 #include "interpreter/oopMapCache.hpp"
35 #include "jfr/jfrEvents.hpp"
36 #include "jfr/support/jfrThreadId.hpp"
37 #include "jvmtifiles/jvmtiEnv.hpp"
38 #include "memory/gcLocker.inline.hpp"
39 #include "memory/metaspaceShared.hpp"
40 #include "memory/oopFactory.hpp"
41 #include "memory/universe.inline.hpp"
42 #include "oops/instanceKlass.hpp"
43 #include "oops/objArrayOop.hpp"
44 #include "oops/oop.inline.hpp"
45 #include "oops/symbol.hpp"
46 #include "prims/jvm_misc.hpp"
47 #include "prims/jvmtiExport.hpp"
48 #include "prims/jvmtiThreadState.hpp"
49 #include "prims/privilegedStack.hpp"
50 #include "runtime/arguments.hpp"
51 #include "runtime/biasedLocking.hpp"
52 #include "runtime/deoptimization.hpp"
53 #include "runtime/fprofiler.hpp"
54 #include "runtime/frame.inline.hpp"
55 #include "runtime/init.hpp"
56 #include "runtime/interfaceSupport.hpp"
62 #include "runtime/objectMonitor.hpp"
63 #include "runtime/orderAccess.inline.hpp"
64 #include "runtime/osThread.hpp"
65 #include "runtime/safepoint.hpp"
66 #include "runtime/sharedRuntime.hpp"
67 #include "runtime/statSampler.hpp"
68 #include "runtime/stubRoutines.hpp"
69 #include "runtime/task.hpp"
70 #include "runtime/thread.inline.hpp"
71 #include "runtime/threadCritical.hpp"
72 #include "runtime/threadLocalStorage.hpp"
73 #include "runtime/vframe.hpp"
74 #include "runtime/vframeArray.hpp"
75 #include "runtime/vframe_hp.hpp"
76 #include "runtime/vmThread.hpp"
77 #include "runtime/vm_operations.hpp"
78 #include "services/attachListener.hpp"
79 #include "services/management.hpp"
80 #include "services/memTracker.hpp"
81 #include "services/threadService.hpp"
82 #include "utilities/defaultStream.hpp"
83 #include "utilities/dtrace.hpp"
84 #include "utilities/events.hpp"
85 #include "utilities/preserveException.hpp"
86 #include "utilities/macros.hpp"
87 #ifdef TARGET_OS_FAMILY_linux
88 # include "os_linux.inline.hpp"
89 #endif
90 #ifdef TARGET_OS_FAMILY_solaris
91 # include "os_solaris.inline.hpp"
92 #endif
93 #ifdef TARGET_OS_FAMILY_windows
94 # include "os_windows.inline.hpp"
95 #endif
96 #ifdef TARGET_OS_FAMILY_bsd
97 # include "os_bsd.inline.hpp"
98 #endif
99 #if INCLUDE_ALL_GCS
100 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
101 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
102 #include "gc_implementation/parallelScavenge/pcTasks.hpp"
103 #endif // INCLUDE_ALL_GCS
104 #ifdef COMPILER1
105 #include "c1/c1_Compiler.hpp"
106 #endif
107 #ifdef COMPILER2
108 #include "opto/c2compiler.hpp"
109 #include "opto/idealGraphPrinter.hpp"
110 #endif
111 #if INCLUDE_RTM_OPT
112 #include "runtime/rtmLocking.hpp"
113 #endif
114 #if INCLUDE_JFR
115 #include "jfr/jfr.hpp"
116 #endif
117
118 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
119
120 #ifdef DTRACE_ENABLED
121
122 // Only bother with this argument setup if dtrace is available
123
124 #ifndef USDT2
125 HS_DTRACE_PROBE_DECL(hotspot, vm__init__begin);
126 HS_DTRACE_PROBE_DECL(hotspot, vm__init__end);
127 HS_DTRACE_PROBE_DECL5(hotspot, thread__start, char*, intptr_t,
128 intptr_t, intptr_t, bool);
129 HS_DTRACE_PROBE_DECL5(hotspot, thread__stop, char*, intptr_t,
130 intptr_t, intptr_t, bool);
131
132 #define DTRACE_THREAD_PROBE(probe, javathread) \
133 { \
134 ResourceMark rm(this); \
135 int len = 0; \
136 const char* name = (javathread)->get_thread_name(); \
328 // CR 7190089: on Solaris, primordial thread's stack is adjusted
329 // in initialize_thread(). Without the adjustment, stack size is
330 // incorrect if stack is set to unlimited (ulimit -s unlimited).
331 // So far, only Solaris has real implementation of initialize_thread().
332 //
333 // set up any platform-specific state.
334 os::initialize_thread(this);
335
336 #if INCLUDE_NMT
337 // record thread's native stack, stack grows downward
338 address stack_low_addr = stack_base() - stack_size();
339 MemTracker::record_thread_stack(stack_low_addr, stack_size());
340 #endif // INCLUDE_NMT
341 }
342
343
344 Thread::~Thread() {
345 // Reclaim the objectmonitors from the omFreeList of the moribund thread.
346 ObjectSynchronizer::omFlush (this) ;
347
348 JFR_ONLY(Jfr::on_thread_destruct(this);)
349
350 // stack_base can be NULL if the thread is never started or exited before
351 // record_stack_base_and_size called. Although, we would like to ensure
352 // that all started threads do call record_stack_base_and_size(), there is
353 // not proper way to enforce that.
354 #if INCLUDE_NMT
355 if (_stack_base != NULL) {
356 address low_stack_addr = stack_base() - stack_size();
357 MemTracker::release_thread_stack(low_stack_addr, stack_size());
358 #ifdef ASSERT
359 set_stack_base(NULL);
360 #endif
361 }
362 #endif // INCLUDE_NMT
363
364 // deallocate data structures
365 delete resource_area();
366 // since the handle marks are using the handle area, we have to deallocated the root
367 // handle mark before deallocating the thread's handle area,
368 assert(last_handle_mark() != NULL, "check we have an element");
1656
1657 // Thread is now sufficient initialized to be handled by the safepoint code as being
1658 // in the VM. Change thread state from _thread_new to _thread_in_vm
1659 ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
1660
1661 assert(JavaThread::current() == this, "sanity check");
1662 assert(!Thread::current()->owns_locks(), "sanity check");
1663
1664 DTRACE_THREAD_PROBE(start, this);
1665
1666 // This operation might block. We call that after all safepoint checks for a new thread has
1667 // been completed.
1668 this->set_active_handles(JNIHandleBlock::allocate_block());
1669
1670 if (JvmtiExport::should_post_thread_life()) {
1671 JvmtiExport::post_thread_start(this);
1672 }
1673
1674 EventThreadStart event;
1675 if (event.should_commit()) {
1676 event.set_thread(JFR_THREAD_ID(this));
1677 event.commit();
1678 }
1679
1680 // We call another function to do the rest so we are sure that the stack addresses used
1681 // from there will be lower than the stack base just computed
1682 thread_main_inner();
1683
1684 // Note, thread is no longer valid at this point!
1685 }
1686
1687
1688 void JavaThread::thread_main_inner() {
1689 assert(JavaThread::current() == this, "sanity check");
1690 assert(this->threadObj() != NULL, "just checking");
1691
1692 // Execute thread entry point unless this thread has a pending exception
1693 // or has been stopped before starting.
1694 // Note: Due to JVM_StopThread we can have pending exceptions already!
1695 if (!this->has_pending_exception() &&
1696 !java_lang_Thread::is_stillborn(this->threadObj())) {
1790 threadObj, // Arg 1
1791 uncaught_exception, // Arg 2
1792 THREAD);
1793 }
1794 if (HAS_PENDING_EXCEPTION) {
1795 ResourceMark rm(this);
1796 jio_fprintf(defaultStream::error_stream(),
1797 "\nException: %s thrown from the UncaughtExceptionHandler"
1798 " in thread \"%s\"\n",
1799 pending_exception()->klass()->external_name(),
1800 get_thread_name());
1801 CLEAR_PENDING_EXCEPTION;
1802 }
1803 }
1804 }
1805
1806 // Called before the java thread exit since we want to read info
1807 // from java_lang_Thread object
1808 EventThreadEnd event;
1809 if (event.should_commit()) {
1810 event.set_thread(JFR_THREAD_ID(this));
1811 event.commit();
1812 }
1813
1814 // Call after last event on thread
1815 JFR_ONLY(Jfr::on_thread_exit(this);)
1816
1817 // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
1818 // the execution of the method. If that is not enough, then we don't really care. Thread.stop
1819 // is deprecated anyhow.
1820 if (!is_Compiler_thread()) {
1821 int count = 3;
1822 while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
1823 EXCEPTION_MARK;
1824 JavaValue result(T_VOID);
1825 KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
1826 JavaCalls::call_virtual(&result,
1827 threadObj, thread_klass,
1828 vmSymbols::exit_method_name(),
1829 vmSymbols::void_method_signature(),
1830 THREAD);
1831 CLEAR_PENDING_EXCEPTION;
1832 }
1833 }
1834 // notify JVMTI
1835 if (JvmtiExport::should_post_thread_life()) {
2171 // }
2172 // set_thread_state(_thread_in_vm_trans);
2173 // if (safepoint) block;
2174 // set_thread_state(state);
2175 //
2176 // but that is pretty messy. Instead we just go with the way the
2177 // code has worked before and note that this is the only path to
2178 // java_suspend_self that doesn't put the thread in _thread_blocked
2179 // mode.
2180
2181 frame_anchor()->make_walkable(this);
2182 java_suspend_self();
2183
2184 // We might be here for reasons in addition to the self-suspend request
2185 // so check for other async requests.
2186 }
2187
2188 if (check_asyncs) {
2189 check_and_handle_async_exceptions();
2190 }
2191
2192 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);)
2193 }
2194
2195 void JavaThread::send_thread_stop(oop java_throwable) {
2196 assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
2197 assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
2198 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
2199
2200 // Do not throw asynchronous exceptions against the compiler thread
2201 // (the compiler thread should not be a Java thread -- fix in 1.4.2)
2202 if (is_Compiler_thread()) return;
2203
2204 {
2205 // Actually throw the Throwable against the target Thread - however
2206 // only if there is no thread death exception installed already.
2207 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
2208 // If the topmost frame is a runtime stub, then we are calling into
2209 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
2210 // must deoptimize the caller before continuing, as the compiled exception handler table
2211 // may not be valid
2212 if (has_last_Java_frame()) {
2411 if (SafepointSynchronize::do_call_back()) {
2412 // If we are safepointing, then block the caller which may not be
2413 // the same as the target thread (see above).
2414 SafepointSynchronize::block(curJT);
2415 }
2416
2417 if (thread->is_deopt_suspend()) {
2418 thread->clear_deopt_suspend();
2419 RegisterMap map(thread, false);
2420 frame f = thread->last_frame();
2421 while ( f.id() != thread->must_deopt_id() && ! f.is_first_frame()) {
2422 f = f.sender(&map);
2423 }
2424 if (f.id() == thread->must_deopt_id()) {
2425 thread->clear_must_deopt_id();
2426 f.deoptimize(thread);
2427 } else {
2428 fatal("missed deoptimization!");
2429 }
2430 }
2431
2432 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(thread);)
2433 }
2434
2435 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2436 // progress or when _suspend_flags is non-zero.
2437 // Current thread needs to self-suspend if there is a suspend request and/or
2438 // block if a safepoint is in progress.
2439 // Also check for pending async exception (not including unsafe access error).
2440 // Note only the native==>VM/Java barriers can call this function and when
2441 // thread state is _thread_in_native_trans.
2442 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
2443 check_safepoint_and_suspend_for_native_trans(thread);
2444
2445 if (thread->has_async_exception()) {
2446 // We are in _thread_in_native_trans state, don't handle unsafe
2447 // access error since that may block.
2448 thread->check_and_handle_async_exceptions(false);
2449 }
2450 }
2451
2452 // This is a variant of the normal
3301 assert_locked_or_safepoint(Threads_lock);
3302 // ALL_JAVA_THREADS iterates through all JavaThreads
3303 ALL_JAVA_THREADS(p) {
3304 tc->do_thread(p);
3305 }
3306 // Someday we could have a table or list of all non-JavaThreads.
3307 // For now, just manually iterate through them.
3308 tc->do_thread(VMThread::vm_thread());
3309 Universe::heap()->gc_threads_do(tc);
3310 WatcherThread *wt = WatcherThread::watcher_thread();
3311 // Strictly speaking, the following NULL check isn't sufficient to make sure
3312 // the data for WatcherThread is still valid upon being examined. However,
3313 // considering that WatchThread terminates when the VM is on the way to
3314 // exit at safepoint, the chance of the above is extremely small. The right
3315 // way to prevent termination of WatcherThread would be to acquire
3316 // Terminator_lock, but we can't do that without violating the lock rank
3317 // checking in some cases.
3318 if (wt != NULL)
3319 tc->do_thread(wt);
3320
3321 #if INCLUDE_JFR
3322 Thread* sampler_thread = Jfr::sampler_thread();
3323 if (sampler_thread != NULL) {
3324 tc->do_thread(sampler_thread);
3325 }
3326
3327 #endif
3328
3329 // If CompilerThreads ever become non-JavaThreads, add them here
3330 }
3331
3332 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
3333
3334 extern void JDK_Version_init();
3335
3336 // Preinitialize version info.
3337 VM_Version::early_initialize();
3338
3339 // Check version
3340 if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
3341
3342 // Initialize the output stream module
3343 ostream_init();
3344
3345 // Process java launcher properties.
3346 Arguments::process_sun_java_launcher_properties(args);
3347
3348 // Initialize the os module before using TLS
3435 delete main_thread;
3436 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3437 return JNI_ENOMEM;
3438 }
3439
3440 // Enable guard page *after* os::create_main_thread(), otherwise it would
3441 // crash Linux VM, see notes in os_linux.cpp.
3442 main_thread->create_stack_guard_pages();
3443
3444 // Initialize Java-Level synchronization subsystem
3445 ObjectMonitor::Initialize() ;
3446
3447 // Initialize global modules
3448 jint status = init_globals();
3449 if (status != JNI_OK) {
3450 delete main_thread;
3451 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3452 return status;
3453 }
3454
3455 JFR_ONLY(Jfr::on_vm_init();)
3456
3457 // Should be done after the heap is fully created
3458 main_thread->cache_global_variables();
3459
3460 HandleMark hm;
3461
3462 { MutexLocker mu(Threads_lock);
3463 Threads::add(main_thread);
3464 }
3465
3466 // Any JVMTI raw monitors entered in onload will transition into
3467 // real raw monitor. VM is setup enough here for raw monitor enter.
3468 JvmtiExport::transition_pending_onload_raw_monitors();
3469
3470 // Create the VMThread
3471 { TraceTime timer("Start VMThread", TraceStartupTime);
3472 VMThread::create();
3473 Thread* vmthread = VMThread::vm_thread();
3474
3475 if (!os::create_thread(vmthread, os::vm_thread))
3476 vm_exit_during_initialization("Cannot create VM thread. Out of system resources.");
3564 // resulting in a NoClassDefFoundError. This can happen in any
3565 // user code which calls methods in java.lang.Compiler.
3566 // Hack : the hack is to pre-load and initialize this class, so that only
3567 // system domains are on the stack when the properties are read.
3568 // Currently even the AWT code has calls to methods in java.lang.Compiler.
3569 // On the classic VM, java.lang.Compiler is loaded very early to load the JIT.
3570 // Future Fix : the best fix is to grant everyone permissions to read "java.compiler" and
3571 // read and write"java.vm.info" in the default policy file. See bugid 4211383
3572 // Once that is done, we should remove this hack.
3573 initialize_class(vmSymbols::java_lang_Compiler(), CHECK_0);
3574
3575 // More hackery - the static initializer of java.lang.Compiler adds the string "nojit" to
3576 // the java.vm.info property if no jit gets loaded through java.lang.Compiler (the hotspot
3577 // compiler does not get loaded through java.lang.Compiler). "java -version" with the
3578 // hotspot vm says "nojit" all the time which is confusing. So, we reset it here.
3579 // This should also be taken out as soon as 4211383 gets fixed.
3580 reset_vm_info_property(CHECK_0);
3581
3582 quicken_jni_functions();
3583
3584 // Set flag that basic initialization has completed. Used by exceptions and various
3585 // debug stuff, that does not work until all basic classes have been initialized.
3586 set_init_completed();
3587
3588 Metaspace::post_initialize();
3589
3590 #ifndef USDT2
3591 HS_DTRACE_PROBE(hotspot, vm__init__end);
3592 #else /* USDT2 */
3593 HOTSPOT_VM_INIT_END();
3594 #endif /* USDT2 */
3595
3596 // record VM initialization completion time
3597 #if INCLUDE_MANAGEMENT
3598 Management::record_vm_init_completed();
3599 #endif // INCLUDE_MANAGEMENT
3600
3601 // Compute system loader. Note that this has to occur after set_init_completed, since
3602 // valid exceptions may be thrown in the process.
3603 // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
3632 os::signal_init();
3633
3634 // Start Attach Listener if +StartAttachListener or it can't be started lazily
3635 if (!DisableAttachMechanism) {
3636 AttachListener::vm_start();
3637 if (StartAttachListener || AttachListener::init_at_startup()) {
3638 AttachListener::init();
3639 }
3640 }
3641
3642 // Launch -Xrun agents
3643 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3644 // back-end can launch with -Xdebug -Xrunjdwp.
3645 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3646 create_vm_init_libraries();
3647 }
3648
3649 // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3650 JvmtiExport::post_vm_initialized();
3651
3652 JFR_ONLY(Jfr::on_vm_start();)
3653
3654 if (CleanChunkPoolAsync) {
3655 Chunk::start_chunk_pool_cleaner_task();
3656 }
3657
3658 // initialize compiler(s)
3659 #if defined(COMPILER1) || defined(COMPILER2) || defined(SHARK)
3660 CompileBroker::compilation_init();
3661 #endif
3662
3663 if (EnableInvokeDynamic) {
3664 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
3665 // It is done after compilers are initialized, because otherwise compilations of
3666 // signature polymorphic MH intrinsics can be missed
3667 // (see SystemDictionary::find_method_handle_intrinsic).
3668 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK_0);
3669 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK_0);
3670 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK_0);
3671 }
3672
|