This repository has been archived by the owner on Aug 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
thread.cpp
4255 lines (3618 loc) · 152 KB
/
thread.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "jvm.h"
#include "aot/aotLoader.hpp"
#include "classfile/classLoader.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/javaThreadStatus.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmClasses.hpp"
#include "classfile/vmSymbols.hpp"
#include "code/codeCache.hpp"
#include "code/scopeDesc.hpp"
#include "compiler/compileBroker.hpp"
#include "compiler/compileTask.hpp"
#include "compiler/compilerThread.hpp"
#include "gc/shared/barrierSet.hpp"
#include "gc/shared/collectedHeap.hpp"
#include "gc/shared/gcId.hpp"
#include "gc/shared/gcLocker.inline.hpp"
#include "gc/shared/gcVMOperations.hpp"
#include "gc/shared/oopStorage.hpp"
#include "gc/shared/oopStorageSet.hpp"
#include "gc/shared/tlab_globals.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/linkResolver.hpp"
#include "interpreter/oopMapCache.hpp"
#include "jfr/jfrEvents.hpp"
#include "jvmtifiles/jvmtiEnv.hpp"
#include "logging/log.hpp"
#include "logging/logConfiguration.hpp"
#include "logging/logStream.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/iterator.hpp"
#include "memory/metaspaceShared.hpp"
#include "memory/oopFactory.hpp"
#include "memory/resourceArea.hpp"
#include "memory/universe.hpp"
#include "oops/access.inline.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/klass.inline.hpp"
#include "oops/objArrayOop.hpp"
#include "oops/oop.inline.hpp"
#include "oops/oopHandle.inline.hpp"
#include "oops/symbol.hpp"
#include "oops/typeArrayOop.inline.hpp"
#include "oops/verifyOopClosure.hpp"
#include "prims/jvm_misc.hpp"
#include "prims/jvmtiDeferredUpdates.hpp"
#include "prims/jvmtiExport.hpp"
#include "prims/jvmtiThreadState.hpp"
#include "runtime/arguments.hpp"
#include "runtime/atomic.hpp"
#include "runtime/biasedLocking.hpp"
#include "runtime/fieldDescriptor.inline.hpp"
#include "runtime/flags/jvmFlagLimit.hpp"
#include "runtime/deoptimization.hpp"
#include "runtime/frame.inline.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/handshake.hpp"
#include "runtime/init.hpp"
#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/jniHandles.inline.hpp"
#include "runtime/jniPeriodicChecker.hpp"
#include "runtime/memprofiler.hpp"
#include "runtime/monitorDeflationThread.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/nonJavaThread.hpp"
#include "runtime/objectMonitor.hpp"
#include "runtime/orderAccess.hpp"
#include "runtime/osThread.hpp"
#include "runtime/prefetch.inline.hpp"
#include "runtime/safepoint.hpp"
#include "runtime/safepointMechanism.inline.hpp"
#include "runtime/safepointVerifiers.hpp"
#include "runtime/serviceThread.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/stackWatermarkSet.hpp"
#include "runtime/statSampler.hpp"
#include "runtime/task.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/threadCritical.hpp"
#include "runtime/threadSMR.inline.hpp"
#include "runtime/threadStatisticalInfo.hpp"
#include "runtime/timer.hpp"
#include "runtime/timerTrace.hpp"
#include "runtime/vframe.inline.hpp"
#include "runtime/vframeArray.hpp"
#include "runtime/vframe_hp.hpp"
#include "runtime/vmThread.hpp"
#include "runtime/vmOperations.hpp"
#include "runtime/vm_version.hpp"
#include "services/attachListener.hpp"
#include "services/management.hpp"
#include "services/memTracker.hpp"
#include "services/threadService.hpp"
#include "utilities/align.hpp"
#include "utilities/copy.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/dtrace.hpp"
#include "utilities/events.hpp"
#include "utilities/macros.hpp"
#include "utilities/preserveException.hpp"
#include "utilities/spinYield.hpp"
#include "utilities/vmError.hpp"
#if INCLUDE_JVMCI
#include "jvmci/jvmci.hpp"
#include "jvmci/jvmciEnv.hpp"
#endif
#ifdef COMPILER1
#include "c1/c1_Compiler.hpp"
#endif
#ifdef COMPILER2
#include "opto/c2compiler.hpp"
#include "opto/idealGraphPrinter.hpp"
#endif
#if INCLUDE_RTM_OPT
#include "runtime/rtmLocking.hpp"
#endif
#if INCLUDE_JFR
#include "jfr/jfr.hpp"
#endif
// Initialization after module runtime initialization
void universe_post_module_init(); // must happen after call_initPhase2
#ifdef DTRACE_ENABLED
// Only bother with this argument setup if dtrace is available
#define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
#define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
#define DTRACE_THREAD_PROBE(probe, javathread) \
{ \
ResourceMark rm(this); \
int len = 0; \
const char* name = (javathread)->get_thread_name(); \
len = strlen(name); \
HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */ \
(char *) name, len, \
java_lang_Thread::thread_id((javathread)->threadObj()), \
(uintptr_t) (javathread)->osthread()->thread_id(), \
java_lang_Thread::is_daemon((javathread)->threadObj())); \
}
#else // ndef DTRACE_ENABLED
#define DTRACE_THREAD_PROBE(probe, javathread)
#endif // ndef DTRACE_ENABLED
#ifndef USE_LIBRARY_BASED_TLS_ONLY
// Current thread is maintained as a thread-local variable
THREAD_LOCAL Thread* Thread::_thr_current = NULL;
#endif
// ======= Thread ========
// Support for forcing alignment of thread objects for biased locking
void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
if (UseBiasedLocking) {
const size_t alignment = markWord::biased_lock_alignment;
size_t aligned_size = size + (alignment - sizeof(intptr_t));
void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC)
: AllocateHeap(aligned_size, flags, CURRENT_PC,
AllocFailStrategy::RETURN_NULL);
void* aligned_addr = align_up(real_malloc_addr, alignment);
assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
"JavaThread alignment code overflowed allocated storage");
if (aligned_addr != real_malloc_addr) {
log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
p2i(real_malloc_addr),
p2i(aligned_addr));
}
((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
return aligned_addr;
} else {
return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
: AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
}
}
void Thread::operator delete(void* p) {
if (UseBiasedLocking) {
FreeHeap(((Thread*) p)->_real_malloc_address);
} else {
FreeHeap(p);
}
}
void JavaThread::smr_delete() {
if (_on_thread_list) {
ThreadsSMRSupport::smr_delete(this);
} else {
delete this;
}
}
// Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
// JavaThread
DEBUG_ONLY(Thread* Thread::_starting_thread = NULL;)
Thread::Thread() {
DEBUG_ONLY(_run_state = PRE_CALL_RUN;)
// stack and get_thread
set_stack_base(NULL);
set_stack_size(0);
set_lgrp_id(-1);
DEBUG_ONLY(clear_suspendible_thread();)
// allocated data structures
set_osthread(NULL);
set_resource_area(new (mtThread)ResourceArea());
DEBUG_ONLY(_current_resource_mark = NULL;)
set_handle_area(new (mtThread) HandleArea(NULL));
set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, mtClass));
set_active_handles(NULL);
set_free_handle_block(NULL);
set_last_handle_mark(NULL);
DEBUG_ONLY(_missed_ic_stub_refill_verifier = NULL);
// Initial value of zero ==> never claimed.
_threads_do_token = 0;
_threads_hazard_ptr = NULL;
_threads_list_ptr = NULL;
_nested_threads_hazard_ptr_cnt = 0;
_rcu_counter = 0;
// the handle mark links itself to last_handle_mark
new HandleMark(this);
// plain initialization
debug_only(_owned_locks = NULL;)
NOT_PRODUCT(_no_safepoint_count = 0;)
NOT_PRODUCT(_skip_gcalot = false;)
_jvmti_env_iteration_count = 0;
set_allocated_bytes(0);
_current_pending_monitor = NULL;
_current_pending_monitor_is_from_java = true;
_current_waiting_monitor = NULL;
_current_pending_raw_monitor = NULL;
#ifdef ASSERT
_visited_for_critical_count = false;
#endif
_SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true,
Monitor::_safepoint_check_sometimes);
_suspend_flags = 0;
// thread-specific hashCode stream generator state - Marsaglia shift-xor form
_hashStateX = os::random();
_hashStateY = 842502087;
_hashStateZ = 0x8767; // (int)(3579807591LL & 0xffff) ;
_hashStateW = 273326509;
_OnTrap = 0;
_Stalled = 0;
_TypeTag = 0x2BAD;
// Many of the following fields are effectively final - immutable
// Note that nascent threads can't use the Native Monitor-Mutex
// construct until the _MutexEvent is initialized ...
// CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
// we might instead use a stack of ParkEvents that we could provision on-demand.
// The stack would act as a cache to avoid calls to ParkEvent::Allocate()
// and ::Release()
_ParkEvent = ParkEvent::Allocate(this);
#ifdef CHECK_UNHANDLED_OOPS
if (CheckUnhandledOops) {
_unhandled_oops = new UnhandledOops(this);
}
#endif // CHECK_UNHANDLED_OOPS
#ifdef ASSERT
if (UseBiasedLocking) {
assert(is_aligned(this, markWord::biased_lock_alignment), "forced alignment of thread object failed");
assert(this == _real_malloc_address ||
this == align_up(_real_malloc_address, markWord::biased_lock_alignment),
"bug in forced alignment of thread objects");
}
#endif // ASSERT
// Notify the barrier set that a thread is being created. The initial
// thread is created before the barrier set is available. The call to
// BarrierSet::on_thread_create() for this thread is therefore deferred
// to BarrierSet::set_barrier_set().
BarrierSet* const barrier_set = BarrierSet::barrier_set();
if (barrier_set != NULL) {
barrier_set->on_thread_create(this);
} else {
// Only the main thread should be created before the barrier set
// and that happens just before Thread::current is set. No other thread
// can attach as the VM is not created yet, so they can't execute this code.
// If the main thread creates other threads before the barrier set that is an error.
assert(Thread::current_or_null() == NULL, "creating thread before barrier set");
}
}
void Thread::initialize_tlab() {
if (UseTLAB) {
tlab().initialize();
}
}
void Thread::initialize_thread_current() {
#ifndef USE_LIBRARY_BASED_TLS_ONLY
assert(_thr_current == NULL, "Thread::current already initialized");
_thr_current = this;
#endif
assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized");
ThreadLocalStorage::set_thread(this);
assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
}
void Thread::clear_thread_current() {
assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
#ifndef USE_LIBRARY_BASED_TLS_ONLY
_thr_current = NULL;
#endif
ThreadLocalStorage::set_thread(NULL);
}
void Thread::record_stack_base_and_size() {
// Note: at this point, Thread object is not yet initialized. Do not rely on
// any members being initialized. Do not rely on Thread::current() being set.
// If possible, refrain from doing anything which may crash or assert since
// quite probably those crash dumps will be useless.
set_stack_base(os::current_stack_base());
set_stack_size(os::current_stack_size());
// Set stack limits after thread is initialized.
if (is_Java_thread()) {
as_Java_thread()->stack_overflow_state()->initialize(stack_base(), stack_end());
}
}
#if INCLUDE_NMT
void Thread::register_thread_stack_with_NMT() {
MemTracker::record_thread_stack(stack_end(), stack_size());
}
void Thread::unregister_thread_stack_with_NMT() {
MemTracker::release_thread_stack(stack_end(), stack_size());
}
#endif // INCLUDE_NMT
void Thread::call_run() {
DEBUG_ONLY(_run_state = CALL_RUN;)
// At this point, Thread object should be fully initialized and
// Thread::current() should be set.
assert(Thread::current_or_null() != NULL, "current thread is unset");
assert(Thread::current_or_null() == this, "current thread is wrong");
// Perform common initialization actions
register_thread_stack_with_NMT();
JFR_ONLY(Jfr::on_thread_start(this);)
log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: "
PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).",
os::current_thread_id(), p2i(stack_end()),
p2i(stack_base()), stack_size()/1024);
// Perform <ChildClass> initialization actions
DEBUG_ONLY(_run_state = PRE_RUN;)
this->pre_run();
// Invoke <ChildClass>::run()
DEBUG_ONLY(_run_state = RUN;)
this->run();
// Returned from <ChildClass>::run(). Thread finished.
// Perform common tear-down actions
assert(Thread::current_or_null() != NULL, "current thread is unset");
assert(Thread::current_or_null() == this, "current thread is wrong");
// Perform <ChildClass> tear-down actions
DEBUG_ONLY(_run_state = POST_RUN;)
this->post_run();
// Note: at this point the thread object may already have deleted itself,
// so from here on do not dereference *this*. Not all thread types currently
// delete themselves when they terminate. But no thread should ever be deleted
// asynchronously with respect to its termination - that is what _run_state can
// be used to check.
assert(Thread::current_or_null() == NULL, "current thread still present");
}
Thread::~Thread() {
// Attached threads will remain in PRE_CALL_RUN, as will threads that don't actually
// get started due to errors etc. Any active thread should at least reach post_run
// before it is deleted (usually in post_run()).
assert(_run_state == PRE_CALL_RUN ||
_run_state == POST_RUN, "Active Thread deleted before post_run(): "
"_run_state=%d", (int)_run_state);
// Notify the barrier set that a thread is being destroyed. Note that a barrier
// set might not be available if we encountered errors during bootstrapping.
BarrierSet* const barrier_set = BarrierSet::barrier_set();
if (barrier_set != NULL) {
barrier_set->on_thread_destroy(this);
}
// deallocate data structures
delete resource_area();
// since the handle marks are using the handle area, we have to deallocated the root
// handle mark before deallocating the thread's handle area,
assert(last_handle_mark() != NULL, "check we have an element");
delete last_handle_mark();
assert(last_handle_mark() == NULL, "check we have reached the end");
// It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
// We NULL out the fields for good hygiene.
ParkEvent::Release(_ParkEvent); _ParkEvent = NULL;
delete handle_area();
delete metadata_handles();
// SR_handler uses this as a termination indicator -
// needs to happen before os::free_thread()
delete _SR_lock;
_SR_lock = NULL;
// osthread() can be NULL, if creation of thread failed.
if (osthread() != NULL) os::free_thread(osthread());
// Clear Thread::current if thread is deleting itself and it has not
// already been done. This must be done before the memory is deallocated.
// Needed to ensure JNI correctly detects non-attached threads.
if (this == Thread::current_or_null()) {
Thread::clear_thread_current();
}
CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
}
#ifdef ASSERT
// A JavaThread is considered dangling if it not handshake-safe with respect to
// the current thread, it is not on a ThreadsList, or not at safepoint.
void Thread::check_for_dangling_thread_pointer(Thread *thread) {
assert(!thread->is_Java_thread() ||
thread->as_Java_thread()->is_handshake_safe_for(Thread::current()) ||
!thread->as_Java_thread()->on_thread_list() ||
SafepointSynchronize::is_at_safepoint() ||
ThreadsSMRSupport::is_a_protected_JavaThread_with_lock(thread->as_Java_thread()),
"possibility of dangling Thread pointer");
}
#endif
// Is the target JavaThread protected by the calling Thread
// or by some other mechanism:
bool Thread::is_JavaThread_protected(const JavaThread* p) {
// Do the simplest check first:
if (SafepointSynchronize::is_at_safepoint()) {
// The target is protected since JavaThreads cannot exit
// while we're at a safepoint.
return true;
}
// Now make the simple checks based on who the caller is:
Thread* current_thread = Thread::current();
if (current_thread == p || Threads_lock->owner() == current_thread) {
// Target JavaThread is self or calling thread owns the Threads_lock.
// Second check is the same as Threads_lock->owner_is_self(),
// but we already have the current thread so check directly.
return true;
}
// Check the ThreadsLists associated with the calling thread (if any)
// to see if one of them protects the target JavaThread:
for (SafeThreadsListPtr* stlp = current_thread->_threads_list_ptr;
stlp != NULL; stlp = stlp->previous()) {
if (stlp->list()->includes(p)) {
// The target JavaThread is protected by this ThreadsList:
return true;
}
}
// Use this debug code with -XX:+UseNewCode to diagnose locations that
// are missing a ThreadsListHandle or other protection mechanism:
// guarantee(!UseNewCode, "current_thread=" INTPTR_FORMAT " is not protecting p="
// INTPTR_FORMAT, p2i(current_thread), p2i(p));
// Note: Since 'p' isn't protected by a TLH, the call to
// p->is_handshake_safe_for() may crash, but we have debug bits so
// we'll be able to figure out what protection mechanism is missing.
assert(p->is_handshake_safe_for(current_thread), "JavaThread=" INTPTR_FORMAT
" is not protected and not handshake safe.", p2i(p));
// The target JavaThread is not protected so it is not safe to query:
return false;
}
ThreadPriority Thread::get_priority(const Thread* const thread) {
ThreadPriority priority;
// Can return an error!
(void)os::get_priority(thread, priority);
assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
return priority;
}
void Thread::set_priority(Thread* thread, ThreadPriority priority) {
debug_only(check_for_dangling_thread_pointer(thread);)
// Can return an error!
(void)os::set_priority(thread, priority);
}
void Thread::start(Thread* thread) {
// Start is different from resume in that its safety is guaranteed by context or
// being called from a Java method synchronized on the Thread object.
if (thread->is_Java_thread()) {
// Initialize the thread state to RUNNABLE before starting this thread.
// Can not set it after the thread started because we do not know the
// exact thread state at that time. It could be in MONITOR_WAIT or
// in SLEEPING or some other state.
java_lang_Thread::set_thread_status(thread->as_Java_thread()->threadObj(),
JavaThreadStatus::RUNNABLE);
}
os::start_thread(thread);
}
class InstallAsyncExceptionClosure : public HandshakeClosure {
Handle _throwable; // The Throwable thrown at the target Thread
public:
InstallAsyncExceptionClosure(Handle throwable) : HandshakeClosure("InstallAsyncException"), _throwable(throwable) {}
void do_thread(Thread* thr) {
JavaThread* target = thr->as_Java_thread();
// Note that this now allows multiple ThreadDeath exceptions to be
// thrown at a thread.
// The target thread has run and has not exited yet.
target->send_thread_stop(_throwable());
}
};
void Thread::send_async_exception(oop java_thread, oop java_throwable) {
Handle throwable(Thread::current(), java_throwable);
JavaThread* target = java_lang_Thread::thread(java_thread);
InstallAsyncExceptionClosure vm_stop(throwable);
Handshake::execute(&vm_stop, target);
}
// Check if an external suspend request has completed (or has been
// cancelled). Returns true if the thread is externally suspended and
// false otherwise.
bool JavaThread::is_ext_suspend_completed() {
bool did_trans_retry = false; // only do thread_in_native_trans retry once
bool do_trans_retry; // flag to force the retry
do {
do_trans_retry = false;
if (is_exiting()) {
// Thread is in the process of exiting. This is always checked
// first to reduce the risk of dereferencing a freed JavaThread.
return false;
}
if (!is_external_suspend()) {
// Suspend request is cancelled. This is always checked before
// is_ext_suspended() to reduce the risk of a rogue resume
// confusing the thread that made the suspend request.
return false;
}
if (is_ext_suspended()) {
// thread is suspended
return true;
}
// Now that we no longer do hard suspends of threads running
// native code, the target thread can be changing thread state
// while we are in this routine:
//
// _thread_in_native -> _thread_in_native_trans -> _thread_blocked
//
// We save a copy of the thread state as observed at this moment
// and make our decision about suspend completeness based on the
// copy. This closes the race where the thread state is seen as
// _thread_in_native_trans in the if-thread_blocked check, but is
// seen as _thread_blocked in if-thread_in_native_trans check.
JavaThreadState save_state = thread_state();
if (save_state == _thread_blocked && is_suspend_equivalent()) {
// If the thread's state is _thread_blocked and this blocking
// condition is known to be equivalent to a suspend, then we can
// consider the thread to be externally suspended. This means that
// the code that sets _thread_blocked has been modified to do
// self-suspension if the blocking condition releases. We also
// used to check for CONDVAR_WAIT here, but that is now covered by
// the _thread_blocked with self-suspension check.
//
// Return true since we wouldn't be here unless there was still an
// external suspend request.
return true;
} else if (save_state == _thread_in_native && frame_anchor()->walkable()) {
// Threads running native code will self-suspend on native==>VM/Java
// transitions. If its stack is walkable (should always be the case
// unless this function is called before the actual java_suspend()
// call), then the wait is done.
return true;
} else if (!did_trans_retry &&
save_state == _thread_in_native_trans &&
frame_anchor()->walkable()) {
// The thread is transitioning from thread_in_native to another
// thread state. check_safepoint_and_suspend_for_native_trans()
// will force the thread to self-suspend. If it hasn't gotten
// there yet we may have caught the thread in-between the native
// code check above and the self-suspend.
//
// Since we use the saved thread state in the if-statement above,
// there is a chance that the thread has already transitioned to
// _thread_blocked by the time we get here. In that case, we will
// make a single unnecessary pass through the logic below. This
// doesn't hurt anything since we still do the trans retry.
// Once the thread leaves thread_in_native_trans for another
// thread state, we break out of this retry loop. We shouldn't
// need this flag to prevent us from getting back here, but
// sometimes paranoia is good.
did_trans_retry = true;
// We wait for the thread to transition to a more usable state.
for (int i = 1; i <= SuspendRetryCount; i++) {
// We used to do an "os::yield_all(i)" call here with the intention
// that yielding would increase on each retry. However, the parameter
// is ignored on Linux which means the yield didn't scale up. Waiting
// on the SR_lock below provides a much more predictable scale up for
// the delay. It also provides a simple/direct point to check for any
// safepoint requests from the VMThread
// temporarily drops SR_lock while doing wait with safepoint check
// (if we're a JavaThread - the WatcherThread can also call this)
// and increase delay with each retry
if (Thread::current()->is_Java_thread()) {
SR_lock()->wait(i * SuspendRetryDelay);
} else {
SR_lock()->wait_without_safepoint_check(i * SuspendRetryDelay);
}
// check the actual thread state instead of what we saved above
if (thread_state() != _thread_in_native_trans) {
// the thread has transitioned to another thread state so
// try all the checks (except this one) one more time.
do_trans_retry = true;
break;
}
} // end retry loop
}
} while (do_trans_retry);
return false;
}
// GC Support
bool Thread::claim_par_threads_do(uintx claim_token) {
uintx token = _threads_do_token;
if (token != claim_token) {
uintx res = Atomic::cmpxchg(&_threads_do_token, token, claim_token);
if (res == token) {
return true;
}
guarantee(res == claim_token, "invariant");
}
return false;
}
void Thread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) {
if (active_handles() != NULL) {
active_handles()->oops_do(f);
}
// Do oop for ThreadShadow
f->do_oop((oop*)&_pending_exception);
handle_area()->oops_do(f);
}
// If the caller is a NamedThread, then remember, in the current scope,
// the given JavaThread in its _processed_thread field.
class RememberProcessedThread: public StackObj {
NamedThread* _cur_thr;
public:
RememberProcessedThread(Thread* thread) {
Thread* self = Thread::current();
if (self->is_Named_thread()) {
_cur_thr = (NamedThread *)self;
assert(_cur_thr->processed_thread() == NULL, "nesting not supported");
_cur_thr->set_processed_thread(thread);
} else {
_cur_thr = NULL;
}
}
~RememberProcessedThread() {
if (_cur_thr) {
assert(_cur_thr->processed_thread() != NULL, "nesting not supported");
_cur_thr->set_processed_thread(NULL);
}
}
};
void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
// Record JavaThread to GC thread
RememberProcessedThread rpt(this);
oops_do_no_frames(f, cf);
oops_do_frames(f, cf);
}
void Thread::metadata_handles_do(void f(Metadata*)) {
// Only walk the Handles in Thread.
if (metadata_handles() != NULL) {
for (int i = 0; i< metadata_handles()->length(); i++) {
f(metadata_handles()->at(i));
}
}
}
void Thread::print_on(outputStream* st, bool print_extended_info) const {
// get_priority assumes osthread initialized
if (osthread() != NULL) {
int os_prio;
if (os::get_native_priority(this, &os_prio) == OS_OK) {
st->print("os_prio=%d ", os_prio);
}
st->print("cpu=%.2fms ",
os::thread_cpu_time(const_cast<Thread*>(this), true) / 1000000.0
);
st->print("elapsed=%.2fs ",
_statistical_info.getElapsedTime() / 1000.0
);
if (is_Java_thread() && (PrintExtendedThreadInfo || print_extended_info)) {
size_t allocated_bytes = (size_t) const_cast<Thread*>(this)->cooked_allocated_bytes();
st->print("allocated=" SIZE_FORMAT "%s ",
byte_size_in_proper_unit(allocated_bytes),
proper_unit_for_byte_size(allocated_bytes)
);
st->print("defined_classes=" INT64_FORMAT " ", _statistical_info.getDefineClassCount());
}
st->print("tid=" INTPTR_FORMAT " ", p2i(this));
osthread()->print_on(st);
}
ThreadsSMRSupport::print_info_on(this, st);
st->print(" ");
debug_only(if (WizardMode) print_owned_locks_on(st);)
}
void Thread::print() const { print_on(tty); }
// Thread::print_on_error() is called by fatal error handler. Don't use
// any lock or allocate memory.
void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates");
if (is_VM_thread()) { st->print("VMThread"); }
else if (is_GC_task_thread()) { st->print("GCTaskThread"); }
else if (is_Watcher_thread()) { st->print("WatcherThread"); }
else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); }
else { st->print("Thread"); }
if (is_Named_thread()) {
st->print(" \"%s\"", name());
}
OSThread* os_thr = osthread();
if (os_thr != NULL) {
if (os_thr->get_state() != ZOMBIE) {
st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
p2i(stack_end()), p2i(stack_base()));
st->print(" [id=%d]", osthread()->thread_id());
} else {
st->print(" terminated");
}
} else {
st->print(" unknown state (no osThread)");
}
ThreadsSMRSupport::print_info_on(this, st);
}
void Thread::print_value_on(outputStream* st) const {
if (is_Named_thread()) {
st->print(" \"%s\" ", name());
}
st->print(INTPTR_FORMAT, p2i(this)); // print address
}
#ifdef ASSERT
void Thread::print_owned_locks_on(outputStream* st) const {
Mutex* cur = _owned_locks;
if (cur == NULL) {
st->print(" (no locks) ");
} else {
st->print_cr(" Locks owned:");
while (cur) {
cur->print_on(st);
cur = cur->next();
}
}
}
// Checks safepoint allowed and clears unhandled oops at potential safepoints.
void Thread::check_possible_safepoint() {
if (!is_Java_thread()) return;
if (_no_safepoint_count > 0) {
print_owned_locks();
assert(false, "Possible safepoint reached by thread that does not allow it");
}
#ifdef CHECK_UNHANDLED_OOPS
// Clear unhandled oops in JavaThreads so we get a crash right away.
clear_unhandled_oops();
#endif // CHECK_UNHANDLED_OOPS
}
void Thread::check_for_valid_safepoint_state() {
if (!is_Java_thread()) return;
// Check NoSafepointVerifier, which is implied by locks taken that can be
// shared with the VM thread. This makes sure that no locks with allow_vm_block
// are held.
check_possible_safepoint();
if (this->as_Java_thread()->thread_state() != _thread_in_vm) {
fatal("LEAF method calling lock?");
}
if (GCALotAtAllSafepoints) {
// We could enter a safepoint here and thus have a gc
InterfaceSupport::check_gc_alot();
}
}
#endif // ASSERT
// We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
// However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
// used for compilation in the future. If that change is made, the need for these methods
// should be revisited, and they should be removed if possible.
bool Thread::is_lock_owned(address adr) const {
return is_in_full_stack(adr);
}
bool Thread::set_as_starting_thread() {
assert(_starting_thread == NULL, "already initialized: "
"_starting_thread=" INTPTR_FORMAT, p2i(_starting_thread));
// NOTE: this must be called inside the main thread.
DEBUG_ONLY(_starting_thread = this;)
return os::create_main_thread(this->as_Java_thread());
}
static void initialize_class(Symbol* class_name, TRAPS) {
Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
InstanceKlass::cast(klass)->initialize(CHECK);
}
// Creates the initial ThreadGroup
static Handle create_initial_thread_group(TRAPS) {
Handle system_instance = JavaCalls::construct_new_instance(
vmClasses::ThreadGroup_klass(),
vmSymbols::void_method_signature(),
CHECK_NH);
Universe::set_system_thread_group(system_instance());
Handle string = java_lang_String::create_from_str("main", CHECK_NH);
Handle main_instance = JavaCalls::construct_new_instance(
vmClasses::ThreadGroup_klass(),
vmSymbols::threadgroup_string_void_signature(),
system_instance,
string,
CHECK_NH);
return main_instance;
}
// Creates the initial Thread, and sets it to running.
static void create_initial_thread(Handle thread_group, JavaThread* thread,
TRAPS) {
InstanceKlass* ik = vmClasses::Thread_klass();
assert(ik->is_initialized(), "must be");
instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
// Cannot use JavaCalls::construct_new_instance because the java.lang.Thread
// constructor calls Thread.current(), which must be set here for the
// initial thread.
java_lang_Thread::set_thread(thread_oop(), thread);
java_lang_Thread::set_priority(thread_oop(), NormPriority);
thread->set_threadObj(thread_oop());
Handle string = java_lang_String::create_from_str("main", CHECK);
JavaValue result(T_VOID);
JavaCalls::call_special(&result, thread_oop,
ik,
vmSymbols::object_initializer_name(),
vmSymbols::threadgroup_string_void_signature(),
thread_group,
string,
CHECK);
// Set thread status to running since main thread has
// been started and running.
java_lang_Thread::set_thread_status(thread_oop(),
JavaThreadStatus::RUNNABLE);
}
static char java_version[64] = "";
static char java_runtime_name[128] = "";
static char java_runtime_version[128] = "";
static char java_runtime_vendor_version[128] = "";
static char java_runtime_vendor_vm_bug_url[128] = "";
// Extract version and vendor specific information.
static const char* get_java_version_info(InstanceKlass* ik,
Symbol* field_name,
char* buffer,
int buffer_size) {
fieldDescriptor fd;
bool found = ik != NULL &&
ik->find_local_field(field_name,
vmSymbols::string_signature(), &fd);
if (found) {
oop name_oop = ik->java_mirror()->obj_field(fd.offset());
if (name_oop == NULL) {
return NULL;
}
const char* name = java_lang_String::as_utf8_string(name_oop,
buffer,
buffer_size);
return name;
} else {
return NULL;
}
}
// General purpose hook into Java code, run once when the VM is initialized.
// The Java library method itself may be changed independently from the VM.
static void call_postVMInitHook(TRAPS) {
Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD);
if (klass != NULL) {
JavaValue result(T_VOID);
JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
vmSymbols::void_method_signature(),
CHECK);
}
}
// Initialized by VMThread at vm_global_init
static OopStorage* _thread_oop_storage = NULL;
oop JavaThread::threadObj() const {
return _threadObj.resolve();
}
void JavaThread::set_threadObj(oop p) {
assert(_thread_oop_storage != NULL, "not yet initialized");
_threadObj = OopHandle(_thread_oop_storage, p);
}
OopStorage* JavaThread::thread_oop_storage() {
assert(_thread_oop_storage != NULL, "not yet initialized");
return _thread_oop_storage;
}