blob: 7b70be81fa7adaae11094c3494ff9ab34f78cb28 [file] [log] [blame]
Elliott Hughes8d768a92011-09-14 16:35:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapirob5573532011-07-12 18:22:59 -070016
Mathieu Chartier752a0e62013-06-27 11:03:27 -070017#define ATRACE_TAG ATRACE_TAG_DALVIK
18
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070019#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -070020
Mathieu Chartier752a0e62013-06-27 11:03:27 -070021#include <cutils/trace.h>
Ian Rogersb033c752011-07-20 12:22:35 -070022#include <pthread.h>
Elliott Hughes2acf36d2012-04-17 13:30:13 -070023#include <signal.h>
Brian Carlstromdbf05b72011-12-15 00:55:24 -080024#include <sys/resource.h>
25#include <sys/time.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070026
Carl Shapirob5573532011-07-12 18:22:59 -070027#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070028#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070029#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070030#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070031#include <list>
Ian Rogersc7dd2952014-10-21 23:31:19 -070032#include <sstream>
Carl Shapirob5573532011-07-12 18:22:59 -070033
Ian Rogers166db042013-07-26 12:05:57 -070034#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070035#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070036#include "art_method-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010037#include "base/bit_utils.h"
Evgenii Stepanov1e133742015-05-20 12:30:59 -070038#include "base/memory_tool.h"
Elliott Hughes76b61672012-12-12 17:47:30 -080039#include "base/mutex.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080040#include "base/timing_logger.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070041#include "base/to_str.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "class_linker-inl.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070043#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070044#include "dex_file-inl.h"
Ian Rogers7655f292013-07-29 11:07:13 -070045#include "entrypoints/entrypoint_utils.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080046#include "entrypoints/quick/quick_alloc_entrypoints.h"
Ian Rogers0c7abda2012-09-19 13:33:42 -070047#include "gc_map.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070048#include "gc/accounting/card_table-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070049#include "gc/allocator/rosalloc.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070050#include "gc/heap.h"
51#include "gc/space/space.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070052#include "handle_scope-inl.h"
Mathieu Chartierc56057e2014-05-04 13:18:58 -070053#include "indirect_reference_table-inl.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070054#include "jni_internal.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/class_loader.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070056#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/object_array-inl.h"
58#include "mirror/stack_trace_element.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070059#include "monitor.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070060#include "object_lock.h"
Sebastien Hertzfd3077e2014-04-23 10:32:43 +020061#include "quick_exception_handler.h"
Vladimir Marko7624d252014-05-02 14:40:15 +010062#include "quick/quick_method_frame_info.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -050063#include "reflection.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070064#include "runtime.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070065#include "scoped_thread_state_change.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070066#include "ScopedLocalRef.h"
Anwar Ghuloum3c539ff2013-06-20 08:58:23 -070067#include "ScopedUtfChars.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070068#include "stack.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070069#include "thread_list.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070070#include "thread-inl.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070071#include "utils.h"
TDYa127ce4cc0d2012-11-18 16:59:53 -080072#include "verifier/dex_gc_map.h"
Mathieu Chartier12d625f2015-03-13 11:33:37 -070073#include "verifier/method_verifier.h"
Mathieu Chartier4e305412014-02-19 10:54:44 -080074#include "verify_object-inl.h"
Ian Rogers1809a722013-08-09 22:05:32 -070075#include "vmap_table.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070076#include "well_known_classes.h"
Carl Shapirob5573532011-07-12 18:22:59 -070077
78namespace art {
79
Ian Rogers0878d652013-04-18 17:38:35 -070080bool Thread::is_started_ = false;
Carl Shapirob5573532011-07-12 18:22:59 -070081pthread_key_t Thread::pthread_key_self_;
Dave Allison0aded082013-11-07 13:15:11 -080082ConditionVariable* Thread::resume_cond_ = nullptr;
Dave Allison648d7112014-07-25 16:15:27 -070083const size_t Thread::kStackOverflowImplicitCheckSize = GetStackOverflowReservedBytes(kRuntimeISA);
Carl Shapirob5573532011-07-12 18:22:59 -070084
Evgenii Stepanov1e133742015-05-20 12:30:59 -070085// For implicit overflow checks we reserve an extra piece of memory at the bottom
86// of the stack (lowest memory). The higher portion of the memory
87// is protected against reads and the lower is available for use while
88// throwing the StackOverflow exception.
89constexpr size_t kStackOverflowProtectedSize = 4 * kMemoryToolStackGuardSizeScale * KB;
90
Elliott Hughes7dc51662012-05-16 14:48:43 -070091static const char* kThreadNameDuringStartup = "<native thread without managed peer>";
92
Ian Rogers5d76c432011-10-31 21:42:49 -070093void Thread::InitCardTable() {
Ian Rogersdd7624d2014-03-14 17:43:00 -070094 tlsPtr_.card_table = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -070095}
96
Elliott Hughes3ea0f422012-04-16 17:01:43 -070097static void UnimplementedEntryPoint() {
98 UNIMPLEMENTED(FATAL);
99}
100
Ian Rogers848871b2013-08-05 10:56:33 -0700101void InitEntryPoints(InterpreterEntryPoints* ipoints, JniEntryPoints* jpoints,
Elliott Hughes956af0f2014-12-11 14:34:28 -0800102 QuickEntryPoints* qpoints);
Ian Rogers7655f292013-07-29 11:07:13 -0700103
Ian Rogers848871b2013-08-05 10:56:33 -0700104void Thread::InitTlsEntryPoints() {
Elliott Hughes3ea0f422012-04-16 17:01:43 -0700105 // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700106 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&tlsPtr_.interpreter_entrypoints);
Xingxing Panacbb3082014-10-16 13:41:58 +0800107 uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(&tlsPtr_.quick_entrypoints) +
108 sizeof(tlsPtr_.quick_entrypoints));
Ian Rogers7655f292013-07-29 11:07:13 -0700109 for (uintptr_t* it = begin; it != end; ++it) {
110 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
111 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700112 InitEntryPoints(&tlsPtr_.interpreter_entrypoints, &tlsPtr_.jni_entrypoints,
Elliott Hughes956af0f2014-12-11 14:34:28 -0800113 &tlsPtr_.quick_entrypoints);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700114}
115
Jeff Hao848f70a2014-01-15 13:49:50 -0800116void Thread::InitStringEntryPoints() {
117 ScopedObjectAccess soa(this);
118 QuickEntryPoints* qpoints = &tlsPtr_.quick_entrypoints;
119 qpoints->pNewEmptyString = reinterpret_cast<void(*)()>(
120 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newEmptyString));
121 qpoints->pNewStringFromBytes_B = reinterpret_cast<void(*)()>(
122 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_B));
123 qpoints->pNewStringFromBytes_BI = reinterpret_cast<void(*)()>(
124 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BI));
125 qpoints->pNewStringFromBytes_BII = reinterpret_cast<void(*)()>(
126 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BII));
127 qpoints->pNewStringFromBytes_BIII = reinterpret_cast<void(*)()>(
128 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BIII));
129 qpoints->pNewStringFromBytes_BIIString = reinterpret_cast<void(*)()>(
130 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BIIString));
131 qpoints->pNewStringFromBytes_BString = reinterpret_cast<void(*)()>(
132 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BString));
133 qpoints->pNewStringFromBytes_BIICharset = reinterpret_cast<void(*)()>(
134 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BIICharset));
135 qpoints->pNewStringFromBytes_BCharset = reinterpret_cast<void(*)()>(
136 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromBytes_BCharset));
137 qpoints->pNewStringFromChars_C = reinterpret_cast<void(*)()>(
138 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromChars_C));
139 qpoints->pNewStringFromChars_CII = reinterpret_cast<void(*)()>(
140 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromChars_CII));
141 qpoints->pNewStringFromChars_IIC = reinterpret_cast<void(*)()>(
142 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromChars_IIC));
143 qpoints->pNewStringFromCodePoints = reinterpret_cast<void(*)()>(
144 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromCodePoints));
145 qpoints->pNewStringFromString = reinterpret_cast<void(*)()>(
146 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromString));
147 qpoints->pNewStringFromStringBuffer = reinterpret_cast<void(*)()>(
148 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromStringBuffer));
149 qpoints->pNewStringFromStringBuilder = reinterpret_cast<void(*)()>(
150 soa.DecodeMethod(WellKnownClasses::java_lang_StringFactory_newStringFromStringBuilder));
151}
152
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700153void Thread::ResetQuickAllocEntryPointsForThread() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700154 ResetQuickAllocEntryPoints(&tlsPtr_.quick_entrypoints);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700155}
156
Sebastien Hertzf7958692015-06-09 14:09:14 +0200157class DeoptimizationReturnValueRecord {
158 public:
159 DeoptimizationReturnValueRecord(const JValue& ret_val,
160 bool is_reference,
161 DeoptimizationReturnValueRecord* link)
162 : ret_val_(ret_val), is_reference_(is_reference), link_(link) {}
163
164 JValue GetReturnValue() const { return ret_val_; }
165 bool IsReference() const { return is_reference_; }
166 DeoptimizationReturnValueRecord* GetLink() const { return link_; }
167 mirror::Object** GetGCRoot() {
168 DCHECK(is_reference_);
169 return ret_val_.GetGCRoot();
170 }
171
172 private:
173 JValue ret_val_;
174 const bool is_reference_;
175 DeoptimizationReturnValueRecord* const link_;
176
177 DISALLOW_COPY_AND_ASSIGN(DeoptimizationReturnValueRecord);
178};
179
180class StackedShadowFrameRecord {
181 public:
182 StackedShadowFrameRecord(ShadowFrame* shadow_frame,
183 StackedShadowFrameType type,
184 StackedShadowFrameRecord* link)
185 : shadow_frame_(shadow_frame),
186 type_(type),
187 link_(link) {}
188
189 ShadowFrame* GetShadowFrame() const { return shadow_frame_; }
190 StackedShadowFrameType GetType() const { return type_; }
191 StackedShadowFrameRecord* GetLink() const { return link_; }
192
193 private:
194 ShadowFrame* const shadow_frame_;
195 const StackedShadowFrameType type_;
196 StackedShadowFrameRecord* const link_;
197
198 DISALLOW_COPY_AND_ASSIGN(StackedShadowFrameRecord);
199};
200
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700201void Thread::PushAndClearDeoptimizationReturnValue() {
202 DeoptimizationReturnValueRecord* record = new DeoptimizationReturnValueRecord(
203 tls64_.deoptimization_return_value,
204 tls32_.deoptimization_return_value_is_reference,
205 tlsPtr_.deoptimization_return_value_stack);
206 tlsPtr_.deoptimization_return_value_stack = record;
207 ClearDeoptimizationReturnValue();
buzbee3ea4ec52011-08-22 17:37:19 -0700208}
209
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700210JValue Thread::PopDeoptimizationReturnValue() {
211 DeoptimizationReturnValueRecord* record = tlsPtr_.deoptimization_return_value_stack;
212 DCHECK(record != nullptr);
213 tlsPtr_.deoptimization_return_value_stack = record->GetLink();
214 JValue ret_val(record->GetReturnValue());
215 delete record;
216 return ret_val;
Ian Rogers306057f2012-11-26 12:45:53 -0800217}
218
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700219void Thread::PushStackedShadowFrame(ShadowFrame* sf, StackedShadowFrameType type) {
220 StackedShadowFrameRecord* record = new StackedShadowFrameRecord(
221 sf, type, tlsPtr_.stacked_shadow_frame_record);
222 tlsPtr_.stacked_shadow_frame_record = record;
Ian Rogers306057f2012-11-26 12:45:53 -0800223}
224
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700225ShadowFrame* Thread::PopStackedShadowFrame(StackedShadowFrameType type) {
226 StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record;
227 DCHECK(record != nullptr);
Sebastien Hertzf7958692015-06-09 14:09:14 +0200228 DCHECK_EQ(record->GetType(), type);
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700229 tlsPtr_.stacked_shadow_frame_record = record->GetLink();
230 ShadowFrame* shadow_frame = record->GetShadowFrame();
231 delete record;
232 return shadow_frame;
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -0700233}
234
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700235void Thread::InitTid() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700236 tls32_.tid = ::art::GetTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700237}
238
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700239void Thread::InitAfterFork() {
Elliott Hughes8029cbe2012-05-22 09:13:08 -0700240 // One thread (us) survived the fork, but we have a new tid so we need to
241 // update the value stashed in this Thread*.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700242 InitTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700243}
244
Brian Carlstrom78128a62011-09-15 17:21:19 -0700245void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700246 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogers120f1c72012-09-28 17:17:10 -0700247 Runtime* runtime = Runtime::Current();
Dave Allison0aded082013-11-07 13:15:11 -0800248 if (runtime == nullptr) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700249 LOG(ERROR) << "Thread attaching to non-existent runtime: " << *self;
Dave Allison0aded082013-11-07 13:15:11 -0800250 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700251 }
252 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700253 // TODO: pass self to MutexLock - requires self to equal Thread::Current(), which is only true
254 // after self->Init().
Dave Allison0aded082013-11-07 13:15:11 -0800255 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700256 // Check that if we got here we cannot be shutting down (as shutdown should never have started
257 // while threads are being born).
Mathieu Chartier590fee92013-09-13 13:46:47 -0700258 CHECK(!runtime->IsShuttingDownLocked());
Andreas Gampe449357d2015-06-01 22:29:51 -0700259 // Note: given that the JNIEnv is created in the parent thread, the only failure point here is
260 // a mess in InitStackHwm. We do not have a reasonable way to recover from that, so abort
261 // the runtime in such a case. In case this ever changes, we need to make sure here to
262 // delete the tmp_jni_env, as we own it at this point.
263 CHECK(self->Init(runtime->GetThreadList(), runtime->GetJavaVM(), self->tlsPtr_.tmp_jni_env));
264 self->tlsPtr_.tmp_jni_env = nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700265 Runtime::Current()->EndThreadBirth();
266 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700267 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700268 ScopedObjectAccess soa(self);
Jeff Hao848f70a2014-01-15 13:49:50 -0800269 self->InitStringEntryPoints();
Ian Rogerscfaa4552012-11-26 21:00:08 -0800270
271 // Copy peer into self, deleting global reference when done.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700272 CHECK(self->tlsPtr_.jpeer != nullptr);
273 self->tlsPtr_.opeer = soa.Decode<mirror::Object*>(self->tlsPtr_.jpeer);
274 self->GetJniEnv()->DeleteGlobalRef(self->tlsPtr_.jpeer);
275 self->tlsPtr_.jpeer = nullptr;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700276 self->SetThreadName(self->GetThreadName(soa)->ToModifiedUtf8().c_str());
Narayan Kamatha0b34512014-10-07 12:51:26 +0100277
Mathieu Chartierc7853442015-03-27 14:35:38 -0700278 ArtField* priorityField = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority);
Narayan Kamatha0b34512014-10-07 12:51:26 +0100279 self->SetNativePriority(priorityField->GetInt(self->tlsPtr_.opeer));
Ian Rogers365c1022012-06-22 15:05:28 -0700280 Dbg::PostThreadStart(self);
281
282 // Invoke the 'run' method of our java.lang.Thread.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700283 mirror::Object* receiver = self->tlsPtr_.opeer;
Ian Rogers365c1022012-06-22 15:05:28 -0700284 jmethodID mid = WellKnownClasses::java_lang_Thread_run;
Jeff Hao39b6c242015-05-19 20:30:23 -0700285 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
286 InvokeVirtualOrInterfaceWithJValues(soa, ref.get(), mid, nullptr);
Elliott Hughes47179f72011-10-27 16:44:39 -0700287 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700288 // Detach and delete self.
289 Runtime::Current()->GetThreadList()->Unregister(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700290
Dave Allison0aded082013-11-07 13:15:11 -0800291 return nullptr;
Carl Shapirob5573532011-07-12 18:22:59 -0700292}
293
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700294Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800295 mirror::Object* thread_peer) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700296 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800297 Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetLong(thread_peer)));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700298 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_
299 // to stop it from going away.
Ian Rogers81d425b2012-09-27 16:03:43 -0700300 if (kIsDebugBuild) {
301 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -0800302 if (result != nullptr && !result->IsSuspended()) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700303 Locks::thread_list_lock_->AssertHeld(soa.Self());
304 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700305 }
306 return result;
Elliott Hughes761928d2011-11-16 18:33:03 -0800307}
308
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700309Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa,
310 jobject java_thread) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800311 return FromManagedThread(soa, soa.Decode<mirror::Object*>(java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700312}
313
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700314static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700315 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700316 if (stack_size == 0) {
317 stack_size = Runtime::Current()->GetDefaultStackSize();
318 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700319
Brian Carlstrom6414a972012-04-14 14:20:04 -0700320 // Dalvik used the bionic pthread default stack size for native threads,
321 // so include that here to support apps that expect large native stacks.
322 stack_size += 1 * MB;
323
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700324 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
325 if (stack_size < PTHREAD_STACK_MIN) {
326 stack_size = PTHREAD_STACK_MIN;
327 }
328
Dave Allisonf9439142014-03-27 15:10:22 -0700329 if (Runtime::Current()->ExplicitStackOverflowChecks()) {
330 // It's likely that callers are trying to ensure they have at least a certain amount of
331 // stack space, so we should add our reserved space on top of what they requested, rather
332 // than implicitly take it away from them.
Andreas Gampe7ea6f792014-07-14 16:21:44 -0700333 stack_size += GetStackOverflowReservedBytes(kRuntimeISA);
Dave Allisonf9439142014-03-27 15:10:22 -0700334 } else {
335 // If we are going to use implicit stack checks, allocate space for the protected
336 // region at the bottom of the stack.
Dave Allisonb090a182014-08-14 17:02:48 +0000337 stack_size += Thread::kStackOverflowImplicitCheckSize +
338 GetStackOverflowReservedBytes(kRuntimeISA);
Dave Allisonf9439142014-03-27 15:10:22 -0700339 }
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700340
341 // Some systems require the stack size to be a multiple of the system page size, so round up.
342 stack_size = RoundUp(stack_size, kPageSize);
343
344 return stack_size;
345}
346
Dave Allison69dfe512014-07-11 17:11:58 +0000347// Global variable to prevent the compiler optimizing away the page reads for the stack.
Ian Rogers13735952014-10-08 12:43:28 -0700348uint8_t dont_optimize_this;
Dave Allison69dfe512014-07-11 17:11:58 +0000349
Dave Allisonf9439142014-03-27 15:10:22 -0700350// Install a protected region in the stack. This is used to trigger a SIGSEGV if a stack
Dave Allison648d7112014-07-25 16:15:27 -0700351// overflow is detected. It is located right below the stack_begin_.
Dave Allison69dfe512014-07-11 17:11:58 +0000352//
Dave Allison648d7112014-07-25 16:15:27 -0700353// There is a little complexity here that deserves a special mention. On some
354// architectures, the stack created using a VM_GROWSDOWN flag
Dave Allison69dfe512014-07-11 17:11:58 +0000355// to prevent memory being allocated when it's not needed. This flag makes the
356// kernel only allocate memory for the stack by growing down in memory. Because we
357// want to put an mprotected region far away from that at the stack top, we need
358// to make sure the pages for the stack are mapped in before we call mprotect. We do
359// this by reading every page from the stack bottom (highest address) to the stack top.
360// We then madvise this away.
Dave Allison648d7112014-07-25 16:15:27 -0700361void Thread::InstallImplicitProtection() {
Ian Rogers13735952014-10-08 12:43:28 -0700362 uint8_t* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
363 uint8_t* stack_himem = tlsPtr_.stack_end;
364 uint8_t* stack_top = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(&stack_himem) &
Dave Allison69dfe512014-07-11 17:11:58 +0000365 ~(kPageSize - 1)); // Page containing current top of stack.
Dave Allisonf9439142014-03-27 15:10:22 -0700366
Dave Allison648d7112014-07-25 16:15:27 -0700367 // First remove the protection on the protected region as will want to read and
368 // write it. This may fail (on the first attempt when the stack is not mapped)
369 // but we ignore that.
370 UnprotectStack();
Dave Allison69dfe512014-07-11 17:11:58 +0000371
Dave Allison648d7112014-07-25 16:15:27 -0700372 // Map in the stack. This must be done by reading from the
373 // current stack pointer downwards as the stack may be mapped using VM_GROWSDOWN
374 // in the kernel. Any access more than a page below the current SP might cause
375 // a segv.
Dave Allison69dfe512014-07-11 17:11:58 +0000376
Dave Allison648d7112014-07-25 16:15:27 -0700377 // Read every page from the high address to the low.
Ian Rogers13735952014-10-08 12:43:28 -0700378 for (uint8_t* p = stack_top; p >= pregion; p -= kPageSize) {
Dave Allison648d7112014-07-25 16:15:27 -0700379 dont_optimize_this = *p;
Dave Allison69dfe512014-07-11 17:11:58 +0000380 }
381
Dave Allisonf9439142014-03-27 15:10:22 -0700382 VLOG(threads) << "installing stack protected region at " << std::hex <<
383 static_cast<void*>(pregion) << " to " <<
384 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1);
385
Dave Allison648d7112014-07-25 16:15:27 -0700386 // Protect the bottom of the stack to prevent read/write to it.
387 ProtectStack();
Dave Allison5cd33752014-04-15 15:57:58 -0700388
389 // Tell the kernel that we won't be needing these pages any more.
Dave Allison69dfe512014-07-11 17:11:58 +0000390 // NB. madvise will probably write zeroes into the memory (on linux it does).
Dave Allison648d7112014-07-25 16:15:27 -0700391 uint32_t unwanted_size = stack_top - pregion - kPageSize;
392 madvise(pregion, unwanted_size, MADV_DONTNEED);
Dave Allisonf9439142014-03-27 15:10:22 -0700393}
394
Ian Rogers120f1c72012-09-28 17:17:10 -0700395void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
Dave Allison0aded082013-11-07 13:15:11 -0800396 CHECK(java_peer != nullptr);
Ian Rogers120f1c72012-09-28 17:17:10 -0700397 Thread* self = static_cast<JNIEnvExt*>(env)->self;
Andreas Gampe56623832015-07-09 21:53:15 -0700398
399 if (VLOG_IS_ON(threads)) {
400 ScopedObjectAccess soa(env);
401
402 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
403 mirror::String* java_name = reinterpret_cast<mirror::String*>(f->GetObject(
404 soa.Decode<mirror::Object*>(java_peer)));
405 std::string thread_name;
406 if (java_name != nullptr) {
407 thread_name = java_name->ToModifiedUtf8();
408 } else {
409 thread_name = "(Unnamed)";
410 }
411
412 VLOG(threads) << "Creating native thread for " << thread_name;
413 self->Dump(LOG(INFO));
414 }
415
Ian Rogers120f1c72012-09-28 17:17:10 -0700416 Runtime* runtime = Runtime::Current();
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700417
Ian Rogers120f1c72012-09-28 17:17:10 -0700418 // Atomically start the birth of the thread ensuring the runtime isn't shutting down.
419 bool thread_start_during_shutdown = false;
Elliott Hughes47179f72011-10-27 16:44:39 -0700420 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700421 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700422 if (runtime->IsShuttingDownLocked()) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700423 thread_start_during_shutdown = true;
424 } else {
425 runtime->StartThreadBirth();
426 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700427 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700428 if (thread_start_during_shutdown) {
429 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError"));
430 env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown");
431 return;
432 }
433
434 Thread* child_thread = new Thread(is_daemon);
435 // Use global JNI ref to hold peer live while child thread starts.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700436 child_thread->tlsPtr_.jpeer = env->NewGlobalRef(java_peer);
Ian Rogers120f1c72012-09-28 17:17:10 -0700437 stack_size = FixStackSize(stack_size);
438
Anwar Ghuloum3c50a4b2013-06-21 13:05:23 -0700439 // Thread.start is synchronized, so we know that nativePeer is 0, and know that we're not racing to
Ian Rogers120f1c72012-09-28 17:17:10 -0700440 // assign it.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800441 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer,
442 reinterpret_cast<jlong>(child_thread));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700443
Andreas Gampe449357d2015-06-01 22:29:51 -0700444 // Try to allocate a JNIEnvExt for the thread. We do this here as we might be out of memory and
445 // do not have a good way to report this on the child's side.
446 std::unique_ptr<JNIEnvExt> child_jni_env_ext(
447 JNIEnvExt::Create(child_thread, Runtime::Current()->GetJavaVM()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448
Andreas Gampe449357d2015-06-01 22:29:51 -0700449 int pthread_create_result = 0;
450 if (child_jni_env_ext.get() != nullptr) {
451 pthread_t new_pthread;
452 pthread_attr_t attr;
453 child_thread->tlsPtr_.tmp_jni_env = child_jni_env_ext.get();
454 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
455 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
456 "PTHREAD_CREATE_DETACHED");
457 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
458 pthread_create_result = pthread_create(&new_pthread,
459 &attr,
460 Thread::CreateCallback,
461 child_thread);
462 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
463
464 if (pthread_create_result == 0) {
465 // pthread_create started the new thread. The child is now responsible for managing the
466 // JNIEnvExt we created.
467 // Note: we can't check for tmp_jni_env == nullptr, as that would require synchronization
468 // between the threads.
469 child_jni_env_ext.release();
470 return;
Ian Rogers120f1c72012-09-28 17:17:10 -0700471 }
Andreas Gampe449357d2015-06-01 22:29:51 -0700472 }
473
474 // Either JNIEnvExt::Create or pthread_create(3) failed, so clean up.
475 {
476 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
477 runtime->EndThreadBirth();
478 }
479 // Manually delete the global reference since Thread::Init will not have been run.
480 env->DeleteGlobalRef(child_thread->tlsPtr_.jpeer);
481 child_thread->tlsPtr_.jpeer = nullptr;
482 delete child_thread;
483 child_thread = nullptr;
484 // TODO: remove from thread group?
485 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 0);
486 {
487 std::string msg(child_jni_env_ext.get() == nullptr ?
488 "Could not allocate JNI Env" :
489 StringPrintf("pthread_create (%s stack) failed: %s",
490 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
491 ScopedObjectAccess soa(env);
492 soa.Self()->ThrowOutOfMemoryError(msg.c_str());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700493 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700494}
495
Andreas Gampe449357d2015-06-01 22:29:51 -0700496bool Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm, JNIEnvExt* jni_env_ext) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700497 // This function does all the initialization that must be run by the native thread it applies to.
498 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
499 // we can handshake with the corresponding native thread when it's ready.) Check this native
500 // thread hasn't been through here already...
Dave Allison0aded082013-11-07 13:15:11 -0800501 CHECK(Thread::Current() == nullptr);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800502
503 // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this
504 // avoids pthread_self_ ever being invalid when discovered from Thread::Current().
505 tlsPtr_.pthread_self = pthread_self();
506 CHECK(is_started_);
507
Elliott Hughesd8af1592012-04-16 20:40:15 -0700508 SetUpAlternateSignalStack();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800509 if (!InitStackHwm()) {
510 return false;
511 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700512 InitCpu();
Ian Rogers848871b2013-08-05 10:56:33 -0700513 InitTlsEntryPoints();
Dave Allisonb373e092014-02-20 16:06:36 -0800514 RemoveSuspendTrigger();
Ian Rogers5d76c432011-10-31 21:42:49 -0700515 InitCardTable();
Ian Rogers01ae5802012-09-28 16:14:01 -0700516 InitTid();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800517
Ian Rogers120f1c72012-09-28 17:17:10 -0700518 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
519 DCHECK_EQ(Thread::Current(), this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700520
Ian Rogersdd7624d2014-03-14 17:43:00 -0700521 tls32_.thin_lock_thread_id = thread_list->AllocThreadId(this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700522
Andreas Gampe449357d2015-06-01 22:29:51 -0700523 if (jni_env_ext != nullptr) {
524 DCHECK_EQ(jni_env_ext->vm, java_vm);
525 DCHECK_EQ(jni_env_ext->self, this);
526 tlsPtr_.jni_env = jni_env_ext;
527 } else {
528 tlsPtr_.jni_env = JNIEnvExt::Create(this, java_vm);
529 if (tlsPtr_.jni_env == nullptr) {
530 return false;
531 }
Andreas Gampe3f5881f2015-04-08 10:26:16 -0700532 }
533
Ian Rogers120f1c72012-09-28 17:17:10 -0700534 thread_list->Register(this);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800535 return true;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700536}
537
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800538Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group,
539 bool create_peer) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700540 Runtime* runtime = Runtime::Current();
Dave Allison0aded082013-11-07 13:15:11 -0800541 if (runtime == nullptr) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700542 LOG(ERROR) << "Thread attaching to non-existent runtime: " << thread_name;
Dave Allison0aded082013-11-07 13:15:11 -0800543 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700544 }
Ian Rogersf4d4da12014-11-11 16:10:33 -0800545 Thread* self;
Ian Rogers120f1c72012-09-28 17:17:10 -0700546 {
Dave Allison0aded082013-11-07 13:15:11 -0800547 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700548 if (runtime->IsShuttingDownLocked()) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700549 LOG(ERROR) << "Thread attaching while runtime is shutting down: " << thread_name;
Dave Allison0aded082013-11-07 13:15:11 -0800550 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700551 } else {
552 Runtime::Current()->StartThreadBirth();
553 self = new Thread(as_daemon);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800554 bool init_success = self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
Ian Rogers120f1c72012-09-28 17:17:10 -0700555 Runtime::Current()->EndThreadBirth();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800556 if (!init_success) {
557 delete self;
558 return nullptr;
559 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700560 }
561 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700562
Jeff Hao848f70a2014-01-15 13:49:50 -0800563 self->InitStringEntryPoints();
564
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700565 CHECK_NE(self->GetState(), kRunnable);
566 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700567
Elliott Hughescac6cc72011-11-03 20:31:21 -0700568 // If we're the main thread, ClassLinker won't be created until after we're attached,
569 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800570 // In the compiler, all threads need this hack, because no-one's going to be getting
571 // a native peer!
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800572 if (create_peer) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700573 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800574 } else {
575 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Dave Allison0aded082013-11-07 13:15:11 -0800576 if (thread_name != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700577 self->tlsPtr_.name->assign(thread_name);
Elliott Hughes22869a92012-03-27 14:08:24 -0700578 ::art::SetThreadName(thread_name);
Brian Carlstrom3ea69c02014-08-18 15:38:34 -0700579 } else if (self->GetJniEnv()->check_jni) {
580 LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
Elliott Hughes22869a92012-03-27 14:08:24 -0700581 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700582 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700583
Andreas Gampe56623832015-07-09 21:53:15 -0700584 if (VLOG_IS_ON(threads)) {
585 if (thread_name != nullptr) {
586 VLOG(threads) << "Attaching thread " << thread_name;
587 } else {
588 VLOG(threads) << "Attaching unnamed thread.";
589 }
590 ScopedObjectAccess soa(self);
591 self->Dump(LOG(INFO));
592 }
593
Daniel Mihalyidfafeef2014-10-20 11:47:56 +0200594 {
595 ScopedObjectAccess soa(self);
596 Dbg::PostThreadStart(self);
597 }
598
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700599 return self;
600}
601
Ian Rogers365c1022012-06-22 15:05:28 -0700602void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
603 Runtime* runtime = Runtime::Current();
604 CHECK(runtime->IsStarted());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700605 JNIEnv* env = tlsPtr_.jni_env;
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700606
Dave Allison0aded082013-11-07 13:15:11 -0800607 if (thread_group == nullptr) {
Ian Rogers365c1022012-06-22 15:05:28 -0700608 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -0700609 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700610 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Mathieu Chartiere07fd172014-11-10 16:58:19 -0800611 // Add missing null check in case of OOM b/18297817
Vladimir Marko44512052014-11-12 15:41:57 +0000612 if (name != nullptr && thread_name.get() == nullptr) {
Mathieu Chartiere07fd172014-11-10 16:58:19 -0800613 CHECK(IsExceptionPending());
614 return;
615 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700616 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700617 jboolean thread_is_daemon = as_daemon;
618
Elliott Hugheseac76672012-05-24 21:56:51 -0700619 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Dave Allison0aded082013-11-07 13:15:11 -0800620 if (peer.get() == nullptr) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700621 CHECK(IsExceptionPending());
622 return;
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700623 }
Ian Rogerscfaa4552012-11-26 21:00:08 -0800624 {
625 ScopedObjectAccess soa(this);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700626 tlsPtr_.opeer = soa.Decode<mirror::Object*>(peer.get());
Ian Rogerscfaa4552012-11-26 21:00:08 -0800627 }
Elliott Hugheseac76672012-05-24 21:56:51 -0700628 env->CallNonvirtualVoidMethod(peer.get(),
629 WellKnownClasses::java_lang_Thread,
630 WellKnownClasses::java_lang_Thread_init,
Ian Rogers365c1022012-06-22 15:05:28 -0700631 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700632 AssertNoPendingException();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700633
Ian Rogers120f1c72012-09-28 17:17:10 -0700634 Thread* self = this;
635 DCHECK_EQ(self, Thread::Current());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700636 env->SetLongField(peer.get(), WellKnownClasses::java_lang_Thread_nativePeer,
637 reinterpret_cast<jlong>(self));
Ian Rogers120f1c72012-09-28 17:17:10 -0700638
639 ScopedObjectAccess soa(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700640 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -0700641 MutableHandle<mirror::String> peer_thread_name(hs.NewHandle(GetThreadName(soa)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700642 if (peer_thread_name.Get() == nullptr) {
Brian Carlstrom00fae582011-10-28 01:16:28 -0700643 // The Thread constructor should have set the Thread.name to a
644 // non-null value. However, because we can run without code
645 // available (in the compiler, in tests), we manually assign the
646 // fields the constructor should have set.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100647 if (runtime->IsActiveTransaction()) {
648 InitPeer<true>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority);
649 } else {
650 InitPeer<false>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority);
651 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700652 peer_thread_name.Assign(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700653 }
Elliott Hughes225f5a12012-06-11 11:23:48 -0700654 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700655 if (peer_thread_name.Get() != nullptr) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800656 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700657 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700658}
659
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100660template<bool kTransactionActive>
661void Thread::InitPeer(ScopedObjectAccess& soa, jboolean thread_is_daemon, jobject thread_group,
662 jobject thread_name, jint thread_priority) {
663 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700664 SetBoolean<kTransactionActive>(tlsPtr_.opeer, thread_is_daemon);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100665 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700666 SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_group));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100667 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700668 SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_name));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100669 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700670 SetInt<kTransactionActive>(tlsPtr_.opeer, thread_priority);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100671}
672
Elliott Hughes899e7892012-01-24 14:57:32 -0800673void Thread::SetThreadName(const char* name) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700674 tlsPtr_.name->assign(name);
Elliott Hughes899e7892012-01-24 14:57:32 -0800675 ::art::SetThreadName(name);
676 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
677}
678
Ian Rogersf4d4da12014-11-11 16:10:33 -0800679bool Thread::InitStackHwm() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700680 void* read_stack_base;
681 size_t read_stack_size;
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700682 size_t read_guard_size;
683 GetThreadStack(tlsPtr_.pthread_self, &read_stack_base, &read_stack_size, &read_guard_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700684
Ian Rogers13735952014-10-08 12:43:28 -0700685 tlsPtr_.stack_begin = reinterpret_cast<uint8_t*>(read_stack_base);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700686 tlsPtr_.stack_size = read_stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -0700687
Dave Allison648d7112014-07-25 16:15:27 -0700688 // The minimum stack size we can cope with is the overflow reserved bytes (typically
689 // 8K) + the protected region size (4K) + another page (4K). Typically this will
690 // be 8+4+4 = 16K. The thread won't be able to do much with this stack even the GC takes
691 // between 8K and 12K.
692 uint32_t min_stack = GetStackOverflowReservedBytes(kRuntimeISA) + kStackOverflowProtectedSize
693 + 4 * KB;
694 if (read_stack_size <= min_stack) {
Ian Rogersf4d4da12014-11-11 16:10:33 -0800695 // Note, as we know the stack is small, avoid operations that could use a lot of stack.
696 LogMessage::LogLineLowStack(__PRETTY_FUNCTION__, __LINE__, ERROR,
697 "Attempt to attach a thread with a too-small stack");
698 return false;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700699 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700700
Vladimir Markob8f2f632015-01-02 14:23:26 +0000701 // This is included in the SIGQUIT output, but it's useful here for thread debugging.
702 VLOG(threads) << StringPrintf("Native stack is at %p (%s with %s guard)",
703 read_stack_base,
704 PrettySize(read_stack_size).c_str(),
705 PrettySize(read_guard_size).c_str());
706
Ian Rogers932746a2011-09-22 18:57:50 -0700707 // Set stack_end_ to the bottom of the stack saving space of stack overflows
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700708
709 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800710 bool implicit_stack_check = !runtime->ExplicitStackOverflowChecks() && !runtime->IsAotCompiler();
Dave Allisonb090a182014-08-14 17:02:48 +0000711 ResetDefaultStackEnd();
Dave Allisonf9439142014-03-27 15:10:22 -0700712
713 // Install the protected region if we are doing implicit overflow checks.
714 if (implicit_stack_check) {
Dave Allison648d7112014-07-25 16:15:27 -0700715 // The thread might have protected region at the bottom. We need
716 // to install our own region so we need to move the limits
717 // of the stack to make room for it.
Dave Allison216cf232014-08-18 15:49:51 -0700718
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700719 tlsPtr_.stack_begin += read_guard_size + kStackOverflowProtectedSize;
720 tlsPtr_.stack_end += read_guard_size + kStackOverflowProtectedSize;
721 tlsPtr_.stack_size -= read_guard_size;
Dave Allison648d7112014-07-25 16:15:27 -0700722
723 InstallImplicitProtection();
Dave Allisonf9439142014-03-27 15:10:22 -0700724 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700725
726 // Sanity check.
727 int stack_variable;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700728 CHECK_GT(&stack_variable, reinterpret_cast<void*>(tlsPtr_.stack_end));
Ian Rogersf4d4da12014-11-11 16:10:33 -0800729
730 return true;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700731}
732
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700733void Thread::ShortDump(std::ostream& os) const {
734 os << "Thread[";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700735 if (GetThreadId() != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700736 // If we're in kStarting, we won't have a thin lock id or tid yet.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700737 os << GetThreadId()
Mathieu Chartierb28412e2015-04-24 15:28:36 -0700738 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -0700739 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700740 os << GetState()
Mathieu Chartierb28412e2015-04-24 15:28:36 -0700741 << ",Thread*=" << this
742 << ",peer=" << tlsPtr_.opeer
743 << ",\"" << (tlsPtr_.name != nullptr ? *tlsPtr_.name : "null") << "\""
744 << "]";
Elliott Hughesa0957642011-09-02 14:27:33 -0700745}
746
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700747void Thread::Dump(std::ostream& os) const {
748 DumpState(os);
749 DumpStack(os);
750}
751
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700752mirror::String* Thread::GetThreadName(const ScopedObjectAccessAlreadyRunnable& soa) const {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700753 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700754 return (tlsPtr_.opeer != nullptr) ?
755 reinterpret_cast<mirror::String*>(f->GetObject(tlsPtr_.opeer)) : nullptr;
Elliott Hughesfc861622011-10-17 17:57:47 -0700756}
757
Elliott Hughesffb465f2012-03-01 18:46:05 -0800758void Thread::GetThreadName(std::string& name) const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700759 name.assign(*tlsPtr_.name);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800760}
761
Jeff Hao57dac6e2013-08-15 16:36:24 -0700762uint64_t Thread::GetCpuMicroTime() const {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800763#if defined(__linux__)
Jeff Hao57dac6e2013-08-15 16:36:24 -0700764 clockid_t cpu_clock_id;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700765 pthread_getcpuclockid(tlsPtr_.pthread_self, &cpu_clock_id);
Jeff Hao57dac6e2013-08-15 16:36:24 -0700766 timespec now;
767 clock_gettime(cpu_clock_id, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700768 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughes0a18df82015-01-09 15:16:16 -0800769#else // __APPLE__
Jeff Hao57dac6e2013-08-15 16:36:24 -0700770 UNIMPLEMENTED(WARNING);
771 return -1;
772#endif
773}
774
Ian Rogers01ae5802012-09-28 16:14:01 -0700775// Attempt to rectify locks so that we dump thread list with required locks before exiting.
776static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers120f1c72012-09-28 17:17:10 -0700777 LOG(ERROR) << *thread << " suspend count already zero.";
Ian Rogers01ae5802012-09-28 16:14:01 -0700778 Locks::thread_suspend_count_lock_->Unlock(self);
779 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
780 Locks::mutator_lock_->SharedTryLock(self);
781 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
782 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
783 }
784 }
785 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
786 Locks::thread_list_lock_->TryLock(self);
787 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
788 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
789 }
790 }
791 std::ostringstream ss;
Ian Rogers7b078e82014-09-10 14:44:24 -0700792 Runtime::Current()->GetThreadList()->Dump(ss);
Ian Rogers120f1c72012-09-28 17:17:10 -0700793 LOG(FATAL) << ss.str();
Ian Rogers01ae5802012-09-28 16:14:01 -0700794}
795
796void Thread::ModifySuspendCount(Thread* self, int delta, bool for_debugger) {
Ian Rogers2966e132014-04-02 08:34:36 -0700797 if (kIsDebugBuild) {
798 DCHECK(delta == -1 || delta == +1 || delta == -tls32_.debug_suspend_count)
799 << delta << " " << tls32_.debug_suspend_count << " " << this;
800 DCHECK_GE(tls32_.suspend_count, tls32_.debug_suspend_count) << this;
801 Locks::thread_suspend_count_lock_->AssertHeld(self);
802 if (this != self && !IsSuspended()) {
803 Locks::thread_list_lock_->AssertHeld(self);
804 }
Ian Rogerscfaa4552012-11-26 21:00:08 -0800805 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700806 if (UNLIKELY(delta < 0 && tls32_.suspend_count <= 0)) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700807 UnsafeLogFatalForSuspendCount(self, this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700808 return;
809 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700810
Ian Rogersdd7624d2014-03-14 17:43:00 -0700811 tls32_.suspend_count += delta;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700812 if (for_debugger) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700813 tls32_.debug_suspend_count += delta;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700814 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700815
Ian Rogersdd7624d2014-03-14 17:43:00 -0700816 if (tls32_.suspend_count == 0) {
Ian Rogers474b6da2012-09-25 00:20:38 -0700817 AtomicClearFlag(kSuspendRequest);
818 } else {
819 AtomicSetFlag(kSuspendRequest);
Dave Allisonb373e092014-02-20 16:06:36 -0800820 TriggerSuspend();
Ian Rogers474b6da2012-09-25 00:20:38 -0700821 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700822}
823
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700824void Thread::RunCheckpointFunction() {
Dave Allison0aded082013-11-07 13:15:11 -0800825 Closure *checkpoints[kMaxCheckpoints];
826
827 // Grab the suspend_count lock and copy the current set of
828 // checkpoints. Then clear the list and the flag. The RequestCheckpoint
829 // function will also grab this lock so we prevent a race between setting
830 // the kCheckpointRequest flag and clearing it.
831 {
832 MutexLock mu(this, *Locks::thread_suspend_count_lock_);
833 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700834 checkpoints[i] = tlsPtr_.checkpoint_functions[i];
835 tlsPtr_.checkpoint_functions[i] = nullptr;
Dave Allison0aded082013-11-07 13:15:11 -0800836 }
837 AtomicClearFlag(kCheckpointRequest);
838 }
839
840 // Outside the lock, run all the checkpoint functions that
841 // we collected.
842 bool found_checkpoint = false;
843 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
844 if (checkpoints[i] != nullptr) {
845 ATRACE_BEGIN("Checkpoint function");
846 checkpoints[i]->Run(this);
847 ATRACE_END();
848 found_checkpoint = true;
849 }
850 }
851 CHECK(found_checkpoint);
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700852}
853
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700854bool Thread::RequestCheckpoint(Closure* function) {
Chris Dearman59cde532013-12-04 18:53:49 -0800855 union StateAndFlags old_state_and_flags;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700856 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700857 if (old_state_and_flags.as_struct.state != kRunnable) {
858 return false; // Fail, thread is suspended and so can't run a checkpoint.
859 }
Dave Allison0aded082013-11-07 13:15:11 -0800860
861 uint32_t available_checkpoint = kMaxCheckpoints;
862 for (uint32_t i = 0 ; i < kMaxCheckpoints; ++i) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700863 if (tlsPtr_.checkpoint_functions[i] == nullptr) {
Dave Allison0aded082013-11-07 13:15:11 -0800864 available_checkpoint = i;
865 break;
866 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700867 }
Dave Allison0aded082013-11-07 13:15:11 -0800868 if (available_checkpoint == kMaxCheckpoints) {
869 // No checkpoint functions available, we can't run a checkpoint
870 return false;
871 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700872 tlsPtr_.checkpoint_functions[available_checkpoint] = function;
Dave Allison0aded082013-11-07 13:15:11 -0800873
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700874 // Checkpoint function installed now install flag bit.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700875 // We must be runnable to request a checkpoint.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800876 DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable);
Chris Dearman59cde532013-12-04 18:53:49 -0800877 union StateAndFlags new_state_and_flags;
878 new_state_and_flags.as_int = old_state_and_flags.as_int;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700879 new_state_and_flags.as_struct.flags |= kCheckpointRequest;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700880 bool success = tls32_.state_and_flags.as_atomic_int.CompareExchangeStrongSequentiallyConsistent(
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700881 old_state_and_flags.as_int, new_state_and_flags.as_int);
Ian Rogers8c1b5f72014-07-09 22:02:36 -0700882 if (UNLIKELY(!success)) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700883 // The thread changed state before the checkpoint was installed.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700884 CHECK_EQ(tlsPtr_.checkpoint_functions[available_checkpoint], function);
885 tlsPtr_.checkpoint_functions[available_checkpoint] = nullptr;
Dave Allison0aded082013-11-07 13:15:11 -0800886 } else {
887 CHECK_EQ(ReadFlag(kCheckpointRequest), true);
Dave Allisonb373e092014-02-20 16:06:36 -0800888 TriggerSuspend();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700889 }
Ian Rogers8c1b5f72014-07-09 22:02:36 -0700890 return success;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700891}
892
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800893Closure* Thread::GetFlipFunction() {
894 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
895 Closure* func;
896 do {
897 func = atomic_func->LoadRelaxed();
898 if (func == nullptr) {
899 return nullptr;
900 }
901 } while (!atomic_func->CompareExchangeWeakSequentiallyConsistent(func, nullptr));
902 DCHECK(func != nullptr);
903 return func;
904}
905
906void Thread::SetFlipFunction(Closure* function) {
907 CHECK(function != nullptr);
908 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
909 atomic_func->StoreSequentiallyConsistent(function);
910}
911
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700912void Thread::FullSuspendCheck() {
913 VLOG(threads) << this << " self-suspending";
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700914 ATRACE_BEGIN("Full suspend check");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700915 // Make thread appear suspended to other threads, release mutator_lock_.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800916 tls32_.suspended_at_suspend_check = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700917 TransitionFromRunnableToSuspended(kSuspended);
918 // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
919 TransitionFromSuspendedToRunnable();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800920 tls32_.suspended_at_suspend_check = false;
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700921 ATRACE_END();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700922 VLOG(threads) << this << " self-reviving";
923}
924
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700925void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700926 std::string group_name;
927 int priority;
928 bool is_daemon = false;
Ian Rogers81d425b2012-09-27 16:03:43 -0700929 Thread* self = Thread::Current();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700930
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800931 // If flip_function is not null, it means we have run a checkpoint
932 // before the thread wakes up to execute the flip function and the
933 // thread roots haven't been forwarded. So the following access to
934 // the roots (opeer or methods in the frames) would be bad. Run it
935 // here. TODO: clean up.
936 if (thread != nullptr) {
937 ScopedObjectAccessUnchecked soa(self);
938 Thread* this_thread = const_cast<Thread*>(thread);
939 Closure* flip_func = this_thread->GetFlipFunction();
940 if (flip_func != nullptr) {
941 flip_func->Run(this_thread);
942 }
943 }
944
Mathieu Chartierc7a966d2014-04-10 18:06:32 -0700945 // Don't do this if we are aborting since the GC may have all the threads suspended. This will
946 // cause ScopedObjectAccessUnchecked to deadlock.
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000947 if (gAborting == 0 && self != nullptr && thread != nullptr && thread->tlsPtr_.opeer != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800948 ScopedObjectAccessUnchecked soa(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700949 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)
950 ->GetInt(thread->tlsPtr_.opeer);
951 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)
952 ->GetBoolean(thread->tlsPtr_.opeer);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700953
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800954 mirror::Object* thread_group =
Ian Rogersdd7624d2014-03-14 17:43:00 -0700955 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(thread->tlsPtr_.opeer);
Ian Rogers120f1c72012-09-28 17:17:10 -0700956
Dave Allison0aded082013-11-07 13:15:11 -0800957 if (thread_group != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700958 ArtField* group_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800959 soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
960 mirror::String* group_name_string =
961 reinterpret_cast<mirror::String*>(group_name_field->GetObject(thread_group));
Dave Allison0aded082013-11-07 13:15:11 -0800962 group_name = (group_name_string != nullptr) ? group_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughesd369bb72011-09-12 14:41:14 -0700963 }
964 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700965 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700966 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700967
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700968 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700969 if (scheduler_group_name.empty()) {
970 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700971 }
972
Dave Allison0aded082013-11-07 13:15:11 -0800973 if (thread != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700974 os << '"' << *thread->tlsPtr_.name << '"';
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700975 if (is_daemon) {
976 os << " daemon";
977 }
978 os << " prio=" << priority
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700979 << " tid=" << thread->GetThreadId()
Elliott Hughes80537bb2013-01-04 16:37:26 -0800980 << " " << thread->GetState();
981 if (thread->IsStillStarting()) {
982 os << " (still starting up)";
983 }
984 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700985 } else {
Elliott Hughes289be852012-06-12 13:57:20 -0700986 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700987 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700988 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700989 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700990
Dave Allison0aded082013-11-07 13:15:11 -0800991 if (thread != nullptr) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700992 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700993 os << " | group=\"" << group_name << "\""
Ian Rogersdd7624d2014-03-14 17:43:00 -0700994 << " sCount=" << thread->tls32_.suspend_count
995 << " dsCount=" << thread->tls32_.debug_suspend_count
996 << " obj=" << reinterpret_cast<void*>(thread->tlsPtr_.opeer)
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700997 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
998 }
Elliott Hughes0d39c122012-06-06 16:41:17 -0700999
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001000 os << " | sysTid=" << tid
1001 << " nice=" << getpriority(PRIO_PROCESS, tid)
Elliott Hughes0d39c122012-06-06 16:41:17 -07001002 << " cgrp=" << scheduler_group_name;
Dave Allison0aded082013-11-07 13:15:11 -08001003 if (thread != nullptr) {
Elliott Hughes0d39c122012-06-06 16:41:17 -07001004 int policy;
1005 sched_param sp;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001006 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->tlsPtr_.pthread_self, &policy, &sp),
1007 __FUNCTION__);
Elliott Hughes0d39c122012-06-06 16:41:17 -07001008 os << " sched=" << policy << "/" << sp.sched_priority
Ian Rogersdd7624d2014-03-14 17:43:00 -07001009 << " handle=" << reinterpret_cast<void*>(thread->tlsPtr_.pthread_self);
Elliott Hughes0d39c122012-06-06 16:41:17 -07001010 }
1011 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -07001012
1013 // Grab the scheduler stats for this thread.
1014 std::string scheduler_stats;
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001015 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001016 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
Elliott Hughesd92bec42011-09-02 17:04:36 -07001017 } else {
1018 scheduler_stats = "0 0 0";
1019 }
1020
Elliott Hughesba0b9c52012-09-20 11:25:12 -07001021 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -07001022 int utime = 0;
1023 int stime = 0;
1024 int task_cpu = 0;
Brian Carlstrom29212012013-09-12 22:18:30 -07001025 GetTaskStats(tid, &native_thread_state, &utime, &stime, &task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -07001026
Elliott Hughesba0b9c52012-09-20 11:25:12 -07001027 os << " | state=" << native_thread_state
1028 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -07001029 << " utm=" << utime
1030 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001031 << " core=" << task_cpu
1032 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
Dave Allison0aded082013-11-07 13:15:11 -08001033 if (thread != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001034 os << " | stack=" << reinterpret_cast<void*>(thread->tlsPtr_.stack_begin) << "-"
1035 << reinterpret_cast<void*>(thread->tlsPtr_.stack_end) << " stackSize="
1036 << PrettySize(thread->tlsPtr_.stack_size) << "\n";
Mathieu Chartier9db911e2014-06-04 11:23:58 -07001037 // Dump the held mutexes.
1038 os << " | held mutexes=";
1039 for (size_t i = 0; i < kLockLevelCount; ++i) {
1040 if (i != kMonitorLock) {
1041 BaseMutex* mutex = thread->GetHeldMutex(static_cast<LockLevel>(i));
1042 if (mutex != nullptr) {
1043 os << " \"" << mutex->GetName() << "\"";
1044 if (mutex->IsReaderWriterMutex()) {
1045 ReaderWriterMutex* rw_mutex = down_cast<ReaderWriterMutex*>(mutex);
Ian Rogersa9d8c4c2014-07-07 21:38:36 -07001046 if (rw_mutex->GetExclusiveOwnerTid() == static_cast<uint64_t>(tid)) {
Mathieu Chartier9db911e2014-06-04 11:23:58 -07001047 os << "(exclusive held)";
1048 } else {
Mathieu Chartier9db911e2014-06-04 11:23:58 -07001049 os << "(shared held)";
1050 }
1051 }
1052 }
1053 }
1054 }
1055 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001056 }
1057}
1058
1059void Thread::DumpState(std::ostream& os) const {
1060 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -07001061}
1062
Ian Rogers0399dde2012-06-06 17:09:28 -07001063struct StackDumpVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001064 StackDumpVisitor(std::ostream& os_in, Thread* thread_in, Context* context, bool can_allocate_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001065 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001066 : StackVisitor(thread_in, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
1067 os(os_in),
1068 thread(thread_in),
1069 can_allocate(can_allocate_in),
1070 last_method(nullptr),
1071 last_line_number(0),
1072 repetition_count(0),
1073 frame_count(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001074
Ian Rogersbdb03912011-09-14 00:55:44 -07001075 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -07001076 if (frame_count == 0) {
1077 os << " (no managed stack frames)\n";
1078 }
Elliott Hughesd369bb72011-09-12 14:41:14 -07001079 }
1080
Ian Rogersb726dcb2012-09-05 08:57:23 -07001081 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001082 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001083 if (m->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001084 return true;
Ian Rogers90865722011-09-19 11:11:44 -07001085 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07001086 const int kMaxRepetition = 3;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001087 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001088 mirror::DexCache* dex_cache = c->GetDexCache();
Ian Rogersb861dc02011-11-14 17:00:05 -08001089 int line_number = -1;
Dave Allison0aded082013-11-07 13:15:11 -08001090 if (dex_cache != nullptr) { // be tolerant of bad input
Ian Rogers4445a7e2012-10-05 17:19:13 -07001091 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001092 line_number = dex_file.GetLineNumFromPC(m, GetDexPc(false));
Ian Rogersb861dc02011-11-14 17:00:05 -08001093 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07001094 if (line_number == last_line_number && last_method == m) {
Dave Allison0aded082013-11-07 13:15:11 -08001095 ++repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -07001096 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001097 if (repetition_count >= kMaxRepetition) {
1098 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
1099 }
1100 repetition_count = 0;
1101 last_line_number = line_number;
1102 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -07001103 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07001104 if (repetition_count < kMaxRepetition) {
1105 os << " at " << PrettyMethod(m, false);
1106 if (m->IsNative()) {
1107 os << "(Native method)";
1108 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001109 const char* source_file(m->GetDeclaringClassSourceFile());
Dave Allison0aded082013-11-07 13:15:11 -08001110 os << "(" << (source_file != nullptr ? source_file : "unavailable")
Brian Carlstrom2e450bf2013-09-06 15:39:46 -07001111 << ":" << line_number << ")";
Ian Rogers28ad40d2011-10-27 15:19:26 -07001112 }
1113 os << "\n";
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001114 if (frame_count == 0) {
1115 Monitor::DescribeWait(os, thread);
1116 }
1117 if (can_allocate) {
Andreas Gampe956a5222014-08-16 13:41:10 -07001118 // Visit locks, but do not abort on errors. This would trigger a nested abort.
1119 Monitor::VisitLocks(this, DumpLockedObject, &os, false);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001120 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07001121 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001122
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001123 ++frame_count;
Elliott Hughes530fa002012-03-12 11:44:49 -07001124 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -07001125 }
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001126
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001127 static void DumpLockedObject(mirror::Object* o, void* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001128 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1129 std::ostream& os = *reinterpret_cast<std::ostream*>(context);
Ian Rogersd803bc72014-04-01 15:33:03 -07001130 os << " - locked ";
1131 if (o == nullptr) {
1132 os << "an unknown object";
1133 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001134 if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07001135 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1136 // Getting the identity hashcode here would result in lock inflation and suspension of the
1137 // current thread, which isn't safe if this is the only runnable thread.
1138 os << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)", reinterpret_cast<intptr_t>(o),
1139 PrettyTypeOf(o).c_str());
1140 } else {
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001141 // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
1142 // we get the pretty type beofre we call IdentityHashCode.
1143 const std::string pretty_type(PrettyTypeOf(o));
1144 os << StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001145 }
1146 }
1147 os << "\n";
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001148 }
1149
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001150 std::ostream& os;
1151 const Thread* thread;
Ian Rogers0878d652013-04-18 17:38:35 -07001152 const bool can_allocate;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001153 ArtMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -07001154 int last_line_number;
1155 int repetition_count;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001156 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -07001157};
1158
Ian Rogers33e95662013-05-20 20:29:14 -07001159static bool ShouldShowNativeStack(const Thread* thread)
1160 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaef701d2013-04-05 18:15:40 -07001161 ThreadState state = thread->GetState();
1162
1163 // In native code somewhere in the VM (one of the kWaitingFor* states)? That's interesting.
1164 if (state > kWaiting && state < kStarting) {
1165 return true;
1166 }
1167
1168 // In an Object.wait variant or Thread.sleep? That's not interesting.
1169 if (state == kTimedWaiting || state == kSleeping || state == kWaiting) {
1170 return false;
1171 }
1172
Christopher Ferris2366f4e2014-09-19 17:23:59 -07001173 // Threads with no managed stack frames should be shown.
1174 const ManagedStack* managed_stack = thread->GetManagedStack();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001175 if (managed_stack == nullptr || (managed_stack->GetTopQuickFrame() == nullptr &&
1176 managed_stack->GetTopShadowFrame() == nullptr)) {
Christopher Ferris2366f4e2014-09-19 17:23:59 -07001177 return true;
1178 }
1179
Elliott Hughesaef701d2013-04-05 18:15:40 -07001180 // In some other native method? That's interesting.
1181 // We don't just check kNative because native methods will be in state kSuspended if they're
1182 // calling back into the VM, or kBlocked if they're blocked on a monitor, or one of the
1183 // thread-startup states if it's early enough in their life cycle (http://b/7432159).
Mathieu Chartiere401d142015-04-22 13:56:20 -07001184 ArtMethod* current_method = thread->GetCurrentMethod(nullptr);
Dave Allison0aded082013-11-07 13:15:11 -08001185 return current_method != nullptr && current_method->IsNative();
Elliott Hughesaef701d2013-04-05 18:15:40 -07001186}
1187
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001188void Thread::DumpJavaStack(std::ostream& os) const {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001189 // If flip_function is not null, it means we have run a checkpoint
1190 // before the thread wakes up to execute the flip function and the
1191 // thread roots haven't been forwarded. So the following access to
1192 // the roots (locks or methods in the frames) would be bad. Run it
1193 // here. TODO: clean up.
1194 {
1195 Thread* this_thread = const_cast<Thread*>(this);
1196 Closure* flip_func = this_thread->GetFlipFunction();
1197 if (flip_func != nullptr) {
1198 flip_func->Run(this_thread);
1199 }
1200 }
1201
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001202 // Dumping the Java stack involves the verifier for locks. The verifier operates under the
1203 // assumption that there is no exception pending on entry. Thus, stash any pending exception.
Mathieu Chartierbef89c92015-01-09 09:46:49 -08001204 // Thread::Current() instead of this in case a thread is dumping the stack of another suspended
1205 // thread.
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001206 StackHandleScope<1> scope(Thread::Current());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001207 Handle<mirror::Throwable> exc;
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001208 bool have_exception = false;
1209 if (IsExceptionPending()) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001210 exc = scope.NewHandle(GetException());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001211 const_cast<Thread*>(this)->ClearException();
1212 have_exception = true;
1213 }
1214
Ian Rogers700a4022014-05-19 16:49:03 -07001215 std::unique_ptr<Context> context(Context::Create());
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001216 StackDumpVisitor dumper(os, const_cast<Thread*>(this), context.get(),
1217 !tls32_.throwing_OutOfMemoryError);
1218 dumper.WalkStack();
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001219
1220 if (have_exception) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001221 const_cast<Thread*>(this)->SetException(exc.Get());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001222 }
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001223}
1224
Elliott Hughesd92bec42011-09-02 17:04:36 -07001225void Thread::DumpStack(std::ostream& os) const {
Jeff Haoed1790e2013-04-12 09:58:14 -07001226 // TODO: we call this code when dying but may not have suspended the thread ourself. The
1227 // IsSuspended check is therefore racy with the use for dumping (normally we inhibit
1228 // the race with the thread_suspend_count_lock_).
Ian Rogerseef2e542014-06-24 22:48:01 -07001229 bool dump_for_abort = (gAborting > 0);
1230 bool safe_to_dump = (this == Thread::Current() || IsSuspended());
1231 if (!kIsDebugBuild) {
1232 // We always want to dump the stack for an abort, however, there is no point dumping another
1233 // thread's stack in debug builds where we'll hit the not suspended check in the stack walk.
1234 safe_to_dump = (safe_to_dump || dump_for_abort);
1235 }
1236 if (safe_to_dump) {
Ian Rogersf08e4732013-04-09 09:45:49 -07001237 // If we're currently in native code, dump that stack before dumping the managed stack.
Ian Rogersd090cf42013-06-06 15:35:18 -07001238 if (dump_for_abort || ShouldShowNativeStack(this)) {
Ian Rogersf08e4732013-04-09 09:45:49 -07001239 DumpKernelStack(os, GetTid(), " kernel: ", false);
Andreas Gampeb2f5dbb2014-09-16 15:15:13 -07001240 DumpNativeStack(os, GetTid(), " native: ", GetCurrentMethod(nullptr, !dump_for_abort));
Ian Rogersf08e4732013-04-09 09:45:49 -07001241 }
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001242 DumpJavaStack(os);
Ian Rogersf08e4732013-04-09 09:45:49 -07001243 } else {
1244 os << "Not able to dump stack of thread that isn't suspended";
Elliott Hughesffb465f2012-03-01 18:46:05 -08001245 }
Elliott Hughese27955c2011-08-26 15:21:24 -07001246}
1247
Elliott Hughesbe759c62011-09-08 19:38:21 -07001248void Thread::ThreadExitCallback(void* arg) {
1249 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001250 if (self->tls32_.thread_exit_check_count == 0) {
1251 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's "
1252 "going to use a pthread_key_create destructor?): " << *self;
Ian Rogers0878d652013-04-18 17:38:35 -07001253 CHECK(is_started_);
Elliott Hughes6a607ad2012-07-13 20:40:00 -07001254 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
Ian Rogersdd7624d2014-03-14 17:43:00 -07001255 self->tls32_.thread_exit_check_count = 1;
Elliott Hughes6a607ad2012-07-13 20:40:00 -07001256 } else {
1257 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
1258 }
Carl Shapirob5573532011-07-12 18:22:59 -07001259}
1260
Elliott Hughesbe759c62011-09-08 19:38:21 -07001261void Thread::Startup() {
Ian Rogers0878d652013-04-18 17:38:35 -07001262 CHECK(!is_started_);
1263 is_started_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001264 {
Brian Carlstrom6d69f592013-07-16 17:18:16 -07001265 // MutexLock to keep annotalysis happy.
1266 //
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001267 // Note we use null for the thread because Thread::Current can
Brian Carlstrom6d69f592013-07-16 17:18:16 -07001268 // return garbage since (is_started_ == true) and
1269 // Thread::pthread_key_self_ is not yet initialized.
1270 // This was seen on glibc.
Dave Allison0aded082013-11-07 13:15:11 -08001271 MutexLock mu(nullptr, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07001272 resume_cond_ = new ConditionVariable("Thread resumption condition variable",
1273 *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001274 }
1275
Carl Shapirob5573532011-07-12 18:22:59 -07001276 // Allocate a TLS slot.
Ian Rogersf4d4da12014-11-11 16:10:33 -08001277 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback),
1278 "self key");
Carl Shapirob5573532011-07-12 18:22:59 -07001279
1280 // Double-check the TLS slot allocation.
Dave Allison0aded082013-11-07 13:15:11 -08001281 if (pthread_getspecific(pthread_key_self_) != nullptr) {
1282 LOG(FATAL) << "Newly-created pthread TLS slot is not nullptr";
Carl Shapirob5573532011-07-12 18:22:59 -07001283 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001284}
Carl Shapirob5573532011-07-12 18:22:59 -07001285
Elliott Hughes038a8062011-09-18 14:12:41 -07001286void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -07001287 Runtime* runtime = Runtime::Current();
1288 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -07001289
Elliott Hughes01158d72011-09-19 19:47:10 -07001290 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001291 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -07001292 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -05001293
Elliott Hughesaf8d15a2012-05-29 09:12:18 -07001294 Runtime::Current()->GetClassLinker()->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -07001295}
1296
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001297void Thread::Shutdown() {
Ian Rogers0878d652013-04-18 17:38:35 -07001298 CHECK(is_started_);
1299 is_started_ = false;
Elliott Hughes8d768a92011-09-14 16:35:25 -07001300 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Ian Rogers33e95662013-05-20 20:29:14 -07001301 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -08001302 if (resume_cond_ != nullptr) {
Ian Rogers0878d652013-04-18 17:38:35 -07001303 delete resume_cond_;
Dave Allison0aded082013-11-07 13:15:11 -08001304 resume_cond_ = nullptr;
Ian Rogers0878d652013-04-18 17:38:35 -07001305 }
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001306}
1307
Ian Rogersdd7624d2014-03-14 17:43:00 -07001308Thread::Thread(bool daemon) : tls32_(daemon), wait_monitor_(nullptr), interrupted_(false) {
1309 wait_mutex_ = new Mutex("a thread wait mutex");
1310 wait_cond_ = new ConditionVariable("a thread wait condition variable", *wait_mutex_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001311 tlsPtr_.instrumentation_stack = new std::deque<instrumentation::InstrumentationStackFrame>;
1312 tlsPtr_.name = new std::string(kThreadNameDuringStartup);
Dave Allison8ce6b902014-08-26 11:07:58 -07001313 tlsPtr_.nested_signal_state = static_cast<jmp_buf*>(malloc(sizeof(jmp_buf)));
Ian Rogersdd7624d2014-03-14 17:43:00 -07001314
Roland Levillain33d69032015-06-18 18:20:59 +01001315 static_assert((sizeof(Thread) % 4) == 0U,
1316 "art::Thread has a size which is not a multiple of 4.");
Ian Rogersdd7624d2014-03-14 17:43:00 -07001317 tls32_.state_and_flags.as_struct.flags = 0;
1318 tls32_.state_and_flags.as_struct.state = kNative;
1319 memset(&tlsPtr_.held_mutexes[0], 0, sizeof(tlsPtr_.held_mutexes));
Mathieu Chartier0651d412014-04-29 14:37:57 -07001320 std::fill(tlsPtr_.rosalloc_runs,
Ian Rogerse63db272014-07-15 15:36:11 -07001321 tlsPtr_.rosalloc_runs + kNumRosAllocThreadLocalSizeBrackets,
Mathieu Chartier73d1e172014-04-11 17:53:48 -07001322 gc::allocator::RosAlloc::GetDedicatedFullRun());
Dave Allison0aded082013-11-07 13:15:11 -08001323 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001324 tlsPtr_.checkpoint_functions[i] = nullptr;
Dave Allison0aded082013-11-07 13:15:11 -08001325 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001326 tlsPtr_.flip_function = nullptr;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001327 tlsPtr_.thread_local_mark_stack = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001328 tls32_.suspended_at_suspend_check = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001329}
1330
Elliott Hughes7dc51662012-05-16 14:48:43 -07001331bool Thread::IsStillStarting() const {
1332 // You might think you can check whether the state is kStarting, but for much of thread startup,
Elliott Hughes80537bb2013-01-04 16:37:26 -08001333 // the thread is in kNative; it might also be in kVmWait.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001334 // You might think you can check whether the peer is null, but the peer is actually created and
Elliott Hughes7dc51662012-05-16 14:48:43 -07001335 // assigned fairly early on, and needs to be.
1336 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
1337 // this thread _ever_ entered kRunnable".
Ian Rogersdd7624d2014-03-14 17:43:00 -07001338 return (tlsPtr_.jpeer == nullptr && tlsPtr_.opeer == nullptr) ||
1339 (*tlsPtr_.name == kThreadNameDuringStartup);
Elliott Hughes7dc51662012-05-16 14:48:43 -07001340}
1341
Andreas Gamped9efea62014-07-21 22:56:08 -07001342void Thread::AssertPendingException() const {
Mathieu Chartiera61894d2015-04-23 16:32:54 -07001343 CHECK(IsExceptionPending()) << "Pending exception expected.";
1344}
1345
1346void Thread::AssertPendingOOMException() const {
1347 AssertPendingException();
1348 auto* e = GetException();
1349 CHECK_EQ(e->GetClass(), DecodeJObject(WellKnownClasses::java_lang_OutOfMemoryError)->AsClass())
1350 << e->Dump();
Andreas Gamped9efea62014-07-21 22:56:08 -07001351}
1352
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001353void Thread::AssertNoPendingException() const {
1354 if (UNLIKELY(IsExceptionPending())) {
1355 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001356 mirror::Throwable* exception = GetException();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001357 LOG(FATAL) << "No pending exception expected: " << exception->Dump();
1358 }
1359}
1360
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001361void Thread::AssertNoPendingExceptionForNewException(const char* msg) const {
1362 if (UNLIKELY(IsExceptionPending())) {
1363 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001364 mirror::Throwable* exception = GetException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07001365 LOG(FATAL) << "Throwing new exception '" << msg << "' with unexpected pending exception: "
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001366 << exception->Dump();
1367 }
1368}
1369
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001370class MonitorExitVisitor : public SingleRootVisitor {
1371 public:
1372 explicit MonitorExitVisitor(Thread* self) : self_(self) { }
1373
1374 // NO_THREAD_SAFETY_ANALYSIS due to MonitorExit.
1375 void VisitRoot(mirror::Object* entered_monitor, const RootInfo& info ATTRIBUTE_UNUSED)
1376 OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1377 if (self_->HoldsLock(entered_monitor)) {
1378 LOG(WARNING) << "Calling MonitorExit on object "
1379 << entered_monitor << " (" << PrettyTypeOf(entered_monitor) << ")"
1380 << " left locked by native thread "
1381 << *Thread::Current() << " which is detaching";
1382 entered_monitor->MonitorExit(self_);
1383 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001384 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001385
1386 private:
1387 Thread* const self_;
1388};
Elliott Hughes02b48d12011-09-07 17:15:51 -07001389
Elliott Hughesc0f09332012-03-26 13:27:06 -07001390void Thread::Destroy() {
Ian Rogers120f1c72012-09-28 17:17:10 -07001391 Thread* self = this;
1392 DCHECK_EQ(self, Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07001393
Ian Rogers68d8b422014-07-17 11:09:10 -07001394 if (tlsPtr_.jni_env != nullptr) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001395 {
1396 ScopedObjectAccess soa(self);
1397 MonitorExitVisitor visitor(self);
1398 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
1399 tlsPtr_.jni_env->monitors.VisitRoots(&visitor, RootInfo(kRootVMInternal));
1400 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001401 // Release locally held global references which releasing may require the mutator lock.
1402 if (tlsPtr_.jpeer != nullptr) {
1403 // If pthread_create fails we don't have a jni env here.
1404 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.jpeer);
1405 tlsPtr_.jpeer = nullptr;
1406 }
1407 if (tlsPtr_.class_loader_override != nullptr) {
1408 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.class_loader_override);
1409 tlsPtr_.class_loader_override = nullptr;
1410 }
1411 }
1412
Ian Rogersdd7624d2014-03-14 17:43:00 -07001413 if (tlsPtr_.opeer != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001414 ScopedObjectAccess soa(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001415 // We may need to call user-supplied managed code, do this before final clean-up.
Ian Rogerscfaa4552012-11-26 21:00:08 -08001416 HandleUncaughtExceptions(soa);
1417 RemoveFromThreadGroup(soa);
Elliott Hughes534da072012-03-27 15:17:42 -07001418
Anwar Ghuloum3c50a4b2013-06-21 13:05:23 -07001419 // this.nativePeer = 0;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001420 if (Runtime::Current()->IsActiveTransaction()) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001421 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer)
1422 ->SetLong<true>(tlsPtr_.opeer, 0);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001423 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001424 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer)
1425 ->SetLong<false>(tlsPtr_.opeer, 0);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001426 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001427 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001428
Ian Rogerscfaa4552012-11-26 21:00:08 -08001429 // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone
1430 // who is waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001431 mirror::Object* lock =
Ian Rogersdd7624d2014-03-14 17:43:00 -07001432 soa.DecodeField(WellKnownClasses::java_lang_Thread_lock)->GetObject(tlsPtr_.opeer);
Elliott Hughes038a8062011-09-18 14:12:41 -07001433 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001434 if (lock != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001435 StackHandleScope<1> hs(self);
1436 Handle<mirror::Object> h_obj(hs.NewHandle(lock));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001437 ObjectLock<mirror::Object> locker(self, h_obj);
Yevgeny Rouban63e8a682014-04-16 18:26:09 +07001438 locker.NotifyAll();
Elliott Hughes5f791332011-09-15 17:45:30 -07001439 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001440 tlsPtr_.opeer = nullptr;
Elliott Hughes5f791332011-09-15 17:45:30 -07001441 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001442
Hiroshi Yamauchia1b94c62014-12-17 15:49:56 -08001443 {
1444 ScopedObjectAccess soa(self);
1445 Runtime::Current()->GetHeap()->RevokeThreadLocalBuffers(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001446 if (kUseReadBarrier) {
1447 Runtime::Current()->GetHeap()->ConcurrentCopyingCollector()->RevokeThreadLocalMarkStack(this);
1448 }
Hiroshi Yamauchia1b94c62014-12-17 15:49:56 -08001449 }
Elliott Hughesc0f09332012-03-26 13:27:06 -07001450}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001451
Elliott Hughesc0f09332012-03-26 13:27:06 -07001452Thread::~Thread() {
Ian Rogers68d8b422014-07-17 11:09:10 -07001453 CHECK(tlsPtr_.class_loader_override == nullptr);
1454 CHECK(tlsPtr_.jpeer == nullptr);
1455 CHECK(tlsPtr_.opeer == nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001456 bool initialized = (tlsPtr_.jni_env != nullptr); // Did Thread::Init run?
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001457 if (initialized) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001458 delete tlsPtr_.jni_env;
1459 tlsPtr_.jni_env = nullptr;
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001460 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001461 CHECK_NE(GetState(), kRunnable);
Dave Allison0aded082013-11-07 13:15:11 -08001462 CHECK_NE(ReadFlag(kCheckpointRequest), true);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001463 CHECK(tlsPtr_.checkpoint_functions[0] == nullptr);
1464 CHECK(tlsPtr_.checkpoint_functions[1] == nullptr);
1465 CHECK(tlsPtr_.checkpoint_functions[2] == nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001466 CHECK(tlsPtr_.flip_function == nullptr);
1467 CHECK_EQ(tls32_.suspended_at_suspend_check, false);
Dave Allison0aded082013-11-07 13:15:11 -08001468
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001469 // We may be deleting a still born thread.
1470 SetStateUnsafe(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001471
1472 delete wait_cond_;
1473 delete wait_mutex_;
1474
Ian Rogersdd7624d2014-03-14 17:43:00 -07001475 if (tlsPtr_.long_jump_context != nullptr) {
1476 delete tlsPtr_.long_jump_context;
Ian Rogersc928de92013-02-27 14:30:44 -08001477 }
Elliott Hughes475fc232011-10-25 15:00:35 -07001478
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001479 if (initialized) {
1480 CleanupCpu();
1481 }
1482
Sebastien Hertz597c4f02015-01-26 17:37:14 +01001483 if (tlsPtr_.single_step_control != nullptr) {
1484 delete tlsPtr_.single_step_control;
1485 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001486 delete tlsPtr_.instrumentation_stack;
1487 delete tlsPtr_.name;
1488 delete tlsPtr_.stack_trace_sample;
Dave Allison8ce6b902014-08-26 11:07:58 -07001489 free(tlsPtr_.nested_signal_state);
Elliott Hughesd8af1592012-04-16 20:40:15 -07001490
Ian Rogers68d8b422014-07-17 11:09:10 -07001491 Runtime::Current()->GetHeap()->AssertThreadLocalBuffersAreRevoked(this);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001492
Elliott Hughesd8af1592012-04-16 20:40:15 -07001493 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001494}
1495
Ian Rogerscfaa4552012-11-26 21:00:08 -08001496void Thread::HandleUncaughtExceptions(ScopedObjectAccess& soa) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001497 if (!IsExceptionPending()) {
1498 return;
1499 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001500 ScopedLocalRef<jobject> peer(tlsPtr_.jni_env, soa.AddLocalReference<jobject>(tlsPtr_.opeer));
Ian Rogerscfaa4552012-11-26 21:00:08 -08001501 ScopedThreadStateChange tsc(this, kNative);
Ian Rogers120f1c72012-09-28 17:17:10 -07001502
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001503 // Get and clear the exception.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001504 ScopedLocalRef<jthrowable> exception(tlsPtr_.jni_env, tlsPtr_.jni_env->ExceptionOccurred());
1505 tlsPtr_.jni_env->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001506
1507 // If the thread has its own handler, use that.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001508 ScopedLocalRef<jobject> handler(tlsPtr_.jni_env,
1509 tlsPtr_.jni_env->GetObjectField(peer.get(),
1510 WellKnownClasses::java_lang_Thread_uncaughtHandler));
Dave Allison0aded082013-11-07 13:15:11 -08001511 if (handler.get() == nullptr) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001512 // Otherwise use the thread group's default handler.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001513 handler.reset(tlsPtr_.jni_env->GetObjectField(peer.get(),
1514 WellKnownClasses::java_lang_Thread_group));
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001515 }
1516
1517 // Call the handler.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001518 tlsPtr_.jni_env->CallVoidMethod(handler.get(),
Andreas Gampec8ccf682014-09-29 20:07:43 -07001519 WellKnownClasses::java_lang_Thread__UncaughtExceptionHandler_uncaughtException,
Ian Rogersdd7624d2014-03-14 17:43:00 -07001520 peer.get(), exception.get());
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001521
1522 // If the handler threw, clear that exception too.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001523 tlsPtr_.jni_env->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001524}
1525
Ian Rogerscfaa4552012-11-26 21:00:08 -08001526void Thread::RemoveFromThreadGroup(ScopedObjectAccess& soa) {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001527 // this.group.removeThread(this);
1528 // group can be null if we're in the compiler or a test.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001529 mirror::Object* ogroup = soa.DecodeField(WellKnownClasses::java_lang_Thread_group)
1530 ->GetObject(tlsPtr_.opeer);
Dave Allison0aded082013-11-07 13:15:11 -08001531 if (ogroup != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001532 ScopedLocalRef<jobject> group(soa.Env(), soa.AddLocalReference<jobject>(ogroup));
Ian Rogersdd7624d2014-03-14 17:43:00 -07001533 ScopedLocalRef<jobject> peer(soa.Env(), soa.AddLocalReference<jobject>(tlsPtr_.opeer));
Ian Rogerscfaa4552012-11-26 21:00:08 -08001534 ScopedThreadStateChange tsc(soa.Self(), kNative);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001535 tlsPtr_.jni_env->CallVoidMethod(group.get(),
1536 WellKnownClasses::java_lang_ThreadGroup_removeThread,
1537 peer.get());
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001538 }
1539}
1540
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001541size_t Thread::NumHandleReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001542 size_t count = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001543 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur != nullptr; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001544 count += cur->NumberOfReferences();
1545 }
1546 return count;
1547}
1548
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001549bool Thread::HandleScopeContains(jobject obj) const {
1550 StackReference<mirror::Object>* hs_entry =
Ian Rogersef7d42f2014-01-06 12:55:46 -08001551 reinterpret_cast<StackReference<mirror::Object>*>(obj);
Ian Rogersc0542af2014-09-03 16:16:56 -07001552 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur!= nullptr; cur = cur->GetLink()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001553 if (cur->Contains(hs_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001554 return true;
1555 }
1556 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001557 // JNI code invoked from portable code uses shadow frames rather than the handle scope.
1558 return tlsPtr_.managed_stack.ShadowFramesContain(hs_entry);
TDYa12728f1a142012-03-15 21:51:52 -07001559}
1560
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001561void Thread::HandleScopeVisitRoots(RootVisitor* visitor, uint32_t thread_id) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001562 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
1563 visitor, RootInfo(kRootNativeStack, thread_id));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001564 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur; cur = cur->GetLink()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001565 for (size_t j = 0, count = cur->NumberOfReferences(); j < count; ++j) {
Mathieu Chartier9086b652015-04-14 09:35:18 -07001566 // GetReference returns a pointer to the stack reference within the handle scope. If this
1567 // needs to be updated, it will be done by the root visitor.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001568 buffered_visitor.VisitRootIfNonNull(cur->GetHandle(j).GetReference());
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001569 }
1570 }
1571}
1572
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001573mirror::Object* Thread::DecodeJObject(jobject obj) const {
Dave Allison0aded082013-11-07 13:15:11 -08001574 if (obj == nullptr) {
1575 return nullptr;
Ian Rogers408f79a2011-08-23 18:22:33 -07001576 }
1577 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1578 IndirectRefKind kind = GetIndirectRefKind(ref);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001579 mirror::Object* result;
Ian Rogersc0542af2014-09-03 16:16:56 -07001580 bool expect_null = false;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001581 // The "kinds" below are sorted by the frequency we expect to encounter them.
1582 if (kind == kLocal) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001583 IndirectReferenceTable& locals = tlsPtr_.jni_env->locals;
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -07001584 // Local references do not need a read barrier.
1585 result = locals.Get<kWithoutReadBarrier>(ref);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001586 } else if (kind == kHandleScopeOrInvalid) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001587 // TODO: make stack indirect reference table lookup more efficient.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001588 // Check if this is a local reference in the handle scope.
1589 if (LIKELY(HandleScopeContains(obj))) {
1590 // Read from handle scope.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001591 result = reinterpret_cast<StackReference<mirror::Object>*>(obj)->AsMirrorPtr();
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08001592 VerifyObject(result);
Ian Rogers408f79a2011-08-23 18:22:33 -07001593 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -07001594 tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of invalid jobject %p", obj);
1595 expect_null = true;
1596 result = nullptr;
Ian Rogers408f79a2011-08-23 18:22:33 -07001597 }
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001598 } else if (kind == kGlobal) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001599 result = tlsPtr_.jni_env->vm->DecodeGlobal(const_cast<Thread*>(this), ref);
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001600 } else {
1601 DCHECK_EQ(kind, kWeakGlobal);
Ian Rogers68d8b422014-07-17 11:09:10 -07001602 result = tlsPtr_.jni_env->vm->DecodeWeakGlobal(const_cast<Thread*>(this), ref);
Ian Rogersc0542af2014-09-03 16:16:56 -07001603 if (Runtime::Current()->IsClearedJniWeakGlobal(result)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001604 // This is a special case where it's okay to return null.
Ian Rogersc0542af2014-09-03 16:16:56 -07001605 expect_null = true;
1606 result = nullptr;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001607 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001608 }
1609
Ian Rogersc0542af2014-09-03 16:16:56 -07001610 if (UNLIKELY(!expect_null && result == nullptr)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001611 tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of deleted %s %p",
1612 ToStr<IndirectRefKind>(kind).c_str(), obj);
Ian Rogers408f79a2011-08-23 18:22:33 -07001613 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001614 return result;
1615}
1616
Ian Rogers81d425b2012-09-27 16:03:43 -07001617// Implements java.lang.Thread.interrupted.
1618bool Thread::Interrupted() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001619 MutexLock mu(Thread::Current(), *wait_mutex_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001620 bool interrupted = IsInterruptedLocked();
1621 SetInterruptedLocked(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001622 return interrupted;
1623}
1624
1625// Implements java.lang.Thread.isInterrupted.
1626bool Thread::IsInterrupted() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001627 MutexLock mu(Thread::Current(), *wait_mutex_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001628 return IsInterruptedLocked();
Ian Rogers81d425b2012-09-27 16:03:43 -07001629}
1630
Ian Rogersdd7624d2014-03-14 17:43:00 -07001631void Thread::Interrupt(Thread* self) {
Ian Rogersc604d732012-10-14 16:09:54 -07001632 MutexLock mu(self, *wait_mutex_);
Ian Rogers81d425b2012-09-27 16:03:43 -07001633 if (interrupted_) {
1634 return;
1635 }
1636 interrupted_ = true;
Ian Rogersc604d732012-10-14 16:09:54 -07001637 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001638}
1639
1640void Thread::Notify() {
Ian Rogersc604d732012-10-14 16:09:54 -07001641 Thread* self = Thread::Current();
1642 MutexLock mu(self, *wait_mutex_);
1643 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001644}
1645
Ian Rogersc604d732012-10-14 16:09:54 -07001646void Thread::NotifyLocked(Thread* self) {
Dave Allison0aded082013-11-07 13:15:11 -08001647 if (wait_monitor_ != nullptr) {
Ian Rogersc604d732012-10-14 16:09:54 -07001648 wait_cond_->Signal(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001649 }
1650}
1651
Ian Rogers68d8b422014-07-17 11:09:10 -07001652void Thread::SetClassLoaderOverride(jobject class_loader_override) {
1653 if (tlsPtr_.class_loader_override != nullptr) {
1654 GetJniEnv()->DeleteGlobalRef(tlsPtr_.class_loader_override);
1655 }
1656 tlsPtr_.class_loader_override = GetJniEnv()->NewGlobalRef(class_loader_override);
1657}
1658
Ian Rogers0399dde2012-06-06 17:09:28 -07001659class CountStackDepthVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001660 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001661 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001662 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001663 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001664 depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001665
Ian Rogersb726dcb2012-09-05 08:57:23 -07001666 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001667 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001668 // Note we also skip the frame if it doesn't have a method (namely the callee
1669 // save frame)
Mathieu Chartiere401d142015-04-22 13:56:20 -07001670 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001671 if (skipping_ && !m->IsRuntimeMethod() &&
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001672 !mirror::Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001673 skipping_ = false;
1674 }
1675 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001676 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001677 ++depth_;
1678 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001679 } else {
1680 ++skip_depth_;
1681 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001682 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001683 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001684
1685 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001686 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001687 }
1688
Elliott Hughes29f27422011-09-18 16:02:18 -07001689 int GetSkipDepth() const {
1690 return skip_depth_;
1691 }
1692
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001693 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001694 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001695 uint32_t skip_depth_;
1696 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001697};
1698
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001699template<bool kTransactionActive>
Ian Rogers0399dde2012-06-06 17:09:28 -07001700class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001701 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001702 explicit BuildInternalStackTraceVisitor(Thread* self, Thread* thread, int skip_depth)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001703 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
1704 self_(self),
1705 skip_depth_(skip_depth),
1706 count_(0),
Mathieu Chartiere401d142015-04-22 13:56:20 -07001707 trace_(nullptr),
1708 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08001709
Ian Rogers1f539342012-10-03 21:09:42 -07001710 bool Init(int depth)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001711 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz415fd082015-06-01 11:42:27 +02001712 // Allocate method trace with format [method pointers][pcs].
Mathieu Chartiere401d142015-04-22 13:56:20 -07001713 auto* cl = Runtime::Current()->GetClassLinker();
1714 trace_ = cl->AllocPointerArray(self_, depth * 2);
1715 if (trace_ == nullptr) {
1716 self_->AssertPendingOOMException();
Ian Rogers283ed0d2012-02-16 15:25:09 -08001717 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001718 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001719 // If We are called from native, use non-transactional mode.
Ian Rogers52673ff2012-06-27 23:25:34 -07001720 const char* last_no_suspend_cause =
Ian Rogers1f539342012-10-03 21:09:42 -07001721 self_->StartAssertNoThreadSuspension("Building internal stack trace");
Dave Allison0aded082013-11-07 13:15:11 -08001722 CHECK(last_no_suspend_cause == nullptr) << last_no_suspend_cause;
Ian Rogers283ed0d2012-02-16 15:25:09 -08001723 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001724 }
1725
Ian Rogers0399dde2012-06-06 17:09:28 -07001726 virtual ~BuildInternalStackTraceVisitor() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001727 if (trace_ != nullptr) {
Dave Allison0aded082013-11-07 13:15:11 -08001728 self_->EndAssertNoThreadSuspension(nullptr);
Ian Rogers52673ff2012-06-27 23:25:34 -07001729 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001730 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001731
Ian Rogersb726dcb2012-09-05 08:57:23 -07001732 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001733 if (trace_ == nullptr) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001734 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001735 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001736 if (skip_depth_ > 0) {
1737 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001738 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001739 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001740 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001741 if (m->IsRuntimeMethod()) {
1742 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001743 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001744 trace_->SetElementPtrSize<kTransactionActive>(
1745 count_, m, pointer_size_);
1746 trace_->SetElementPtrSize<kTransactionActive>(
1747 trace_->GetLength() / 2 + count_, m->IsProxyMethod() ? DexFile::kDexNoIndex : GetDexPc(),
1748 pointer_size_);
Ian Rogersaaa20802011-09-11 21:47:37 -07001749 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001750 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001751 }
1752
Mathieu Chartiere401d142015-04-22 13:56:20 -07001753 mirror::PointerArray* GetInternalStackTrace() const {
1754 return trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001755 }
1756
1757 private:
Ian Rogers1f539342012-10-03 21:09:42 -07001758 Thread* const self_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001759 // How many more frames to skip.
1760 int32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001761 // Current position down stack trace.
Ian Rogersaaa20802011-09-11 21:47:37 -07001762 uint32_t count_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001763 // An array of the methods on the stack, the last entries are the dex PCs.
1764 mirror::PointerArray* trace_;
1765 // For cross compilation.
1766 size_t pointer_size_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001767};
1768
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001769template<bool kTransactionActive>
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07001770jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001771 // Compute depth of stack
Ian Rogers7a22fa62013-01-23 12:16:16 -08001772 CountStackDepthVisitor count_visitor(const_cast<Thread*>(this));
Ian Rogers0399dde2012-06-06 17:09:28 -07001773 count_visitor.WalkStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001774 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001775 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001776
Ian Rogers1f539342012-10-03 21:09:42 -07001777 // Build internal stack trace.
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001778 BuildInternalStackTraceVisitor<kTransactionActive> build_trace_visitor(soa.Self(),
1779 const_cast<Thread*>(this),
1780 skip_depth);
Ian Rogers1f539342012-10-03 21:09:42 -07001781 if (!build_trace_visitor.Init(depth)) {
Dave Allison0aded082013-11-07 13:15:11 -08001782 return nullptr; // Allocation failed.
Ian Rogers283ed0d2012-02-16 15:25:09 -08001783 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001784 build_trace_visitor.WalkStack();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001785 mirror::PointerArray* trace = build_trace_visitor.GetInternalStackTrace();
Ian Rogers7a22fa62013-01-23 12:16:16 -08001786 if (kIsDebugBuild) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001787 // Second half is dex PCs.
1788 for (uint32_t i = 0; i < static_cast<uint32_t>(trace->GetLength() / 2); ++i) {
1789 auto* method = trace->GetElementPtrSize<ArtMethod*>(
1790 i, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
1791 CHECK(method != nullptr);
Ian Rogers7a22fa62013-01-23 12:16:16 -08001792 }
1793 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001794 return soa.AddLocalReference<jobject>(trace);
Ian Rogersaaa20802011-09-11 21:47:37 -07001795}
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07001796template jobject Thread::CreateInternalStackTrace<false>(
1797 const ScopedObjectAccessAlreadyRunnable& soa) const;
1798template jobject Thread::CreateInternalStackTrace<true>(
1799 const ScopedObjectAccessAlreadyRunnable& soa) const;
Ian Rogersaaa20802011-09-11 21:47:37 -07001800
Nicolas Geoffray7642cfc2015-02-26 10:56:09 +00001801bool Thread::IsExceptionThrownByCurrentMethod(mirror::Throwable* exception) const {
1802 CountStackDepthVisitor count_visitor(const_cast<Thread*>(this));
1803 count_visitor.WalkStack();
1804 return count_visitor.GetDepth() == exception->GetStackDepth();
1805}
1806
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07001807jobjectArray Thread::InternalStackTraceToStackTraceElementArray(
1808 const ScopedObjectAccessAlreadyRunnable& soa, jobject internal, jobjectArray output_array,
1809 int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001810 // Decode the internal stack trace into the depth, method trace and PC trace
Mathieu Chartiere401d142015-04-22 13:56:20 -07001811 int32_t depth = soa.Decode<mirror::PointerArray*>(internal)->GetLength() / 2;
Ian Rogersaaa20802011-09-11 21:47:37 -07001812
Mathieu Chartiere401d142015-04-22 13:56:20 -07001813 auto* cl = Runtime::Current()->GetClassLinker();
Ian Rogersaaa20802011-09-11 21:47:37 -07001814
Elliott Hughes01158d72011-09-19 19:47:10 -07001815 jobjectArray result;
Mathieu Chartier530825b2013-09-25 17:56:49 -07001816
Dave Allison0aded082013-11-07 13:15:11 -08001817 if (output_array != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07001818 // Reuse the array we were given.
1819 result = output_array;
Elliott Hughes01158d72011-09-19 19:47:10 -07001820 // ...adjusting the number of frames we'll write to not exceed the array length.
Mathieu Chartier530825b2013-09-25 17:56:49 -07001821 const int32_t traces_length =
1822 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->GetLength();
1823 depth = std::min(depth, traces_length);
Elliott Hughes01158d72011-09-19 19:47:10 -07001824 } else {
1825 // Create java_trace array and place in local reference table
Mathieu Chartier530825b2013-09-25 17:56:49 -07001826 mirror::ObjectArray<mirror::StackTraceElement>* java_traces =
Mathieu Chartiere401d142015-04-22 13:56:20 -07001827 cl->AllocStackTraceElementArray(soa.Self(), depth);
Dave Allison0aded082013-11-07 13:15:11 -08001828 if (java_traces == nullptr) {
1829 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001830 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001831 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07001832 }
1833
Dave Allison0aded082013-11-07 13:15:11 -08001834 if (stack_depth != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07001835 *stack_depth = depth;
1836 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001837
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001838 for (int32_t i = 0; i < depth; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001839 auto* method_trace = soa.Decode<mirror::PointerArray*>(internal);
Ian Rogersaaa20802011-09-11 21:47:37 -07001840 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Mathieu Chartiere401d142015-04-22 13:56:20 -07001841 ArtMethod* method = method_trace->GetElementPtrSize<ArtMethod*>(i, sizeof(void*));
1842 uint32_t dex_pc = method_trace->GetElementPtrSize<uint32_t>(
1843 i + method_trace->GetLength() / 2, sizeof(void*));
Jeff Hao228d6b82013-12-03 15:00:05 -08001844 int32_t line_number;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001845 StackHandleScope<3> hs(soa.Self());
1846 auto class_name_object(hs.NewHandle<mirror::String>(nullptr));
1847 auto source_name_object(hs.NewHandle<mirror::String>(nullptr));
Jeff Hao228d6b82013-12-03 15:00:05 -08001848 if (method->IsProxyMethod()) {
1849 line_number = -1;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001850 class_name_object.Assign(method->GetDeclaringClass()->GetName());
Jeff Hao228d6b82013-12-03 15:00:05 -08001851 // source_name_object intentionally left null for proxy methods
1852 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001853 line_number = method->GetLineNumFromDexPC(dex_pc);
Jeff Hao228d6b82013-12-03 15:00:05 -08001854 // Allocate element, potentially triggering GC
1855 // TODO: reuse class_name_object via Class::name_?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001856 const char* descriptor = method->GetDeclaringClassDescriptor();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001857 CHECK(descriptor != nullptr);
Jeff Hao228d6b82013-12-03 15:00:05 -08001858 std::string class_name(PrettyDescriptor(descriptor));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001859 class_name_object.Assign(
1860 mirror::String::AllocFromModifiedUtf8(soa.Self(), class_name.c_str()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001861 if (class_name_object.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001862 soa.Self()->AssertPendingOOMException();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001863 return nullptr;
Jeff Hao228d6b82013-12-03 15:00:05 -08001864 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001865 const char* source_file = method->GetDeclaringClassSourceFile();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001866 if (source_file != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001867 source_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), source_file));
1868 if (source_name_object.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001869 soa.Self()->AssertPendingOOMException();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001870 return nullptr;
1871 }
Jeff Hao228d6b82013-12-03 15:00:05 -08001872 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001873 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001874 const char* method_name = method->GetInterfaceMethodIfProxy(sizeof(void*))->GetName();
Dave Allison0aded082013-11-07 13:15:11 -08001875 CHECK(method_name != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001876 Handle<mirror::String> method_name_object(
1877 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), method_name)));
1878 if (method_name_object.Get() == nullptr) {
Dave Allison0aded082013-11-07 13:15:11 -08001879 return nullptr;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001880 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001881 mirror::StackTraceElement* obj = mirror::StackTraceElement::Alloc(
1882 soa.Self(), class_name_object, method_name_object, source_name_object, line_number);
Dave Allison0aded082013-11-07 13:15:11 -08001883 if (obj == nullptr) {
1884 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001885 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001886 // We are called from native: use non-transactional mode.
1887 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->Set<false>(i, obj);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001888 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001889 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001890}
1891
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001892void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001893 va_list args;
1894 va_start(args, fmt);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001895 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001896 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001897}
1898
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001899void Thread::ThrowNewExceptionV(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08001900 const char* fmt, va_list ap) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001901 std::string msg;
1902 StringAppendV(&msg, fmt, ap);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001903 ThrowNewException(exception_class_descriptor, msg.c_str());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001904}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001905
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001906void Thread::ThrowNewException(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08001907 const char* msg) {
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001908 // Callers should either clear or call ThrowNewWrappedException.
1909 AssertNoPendingExceptionForNewException(msg);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001910 ThrowNewWrappedException(exception_class_descriptor, msg);
Elliott Hughesa4f94742012-05-29 16:28:38 -07001911}
1912
Nicolas Geoffrayee077032015-03-09 14:56:37 +00001913static mirror::ClassLoader* GetCurrentClassLoader(Thread* self)
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001914 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001915 ArtMethod* method = self->GetCurrentMethod(nullptr);
Nicolas Geoffrayee077032015-03-09 14:56:37 +00001916 return method != nullptr
1917 ? method->GetDeclaringClass()->GetClassLoader()
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001918 : nullptr;
1919}
1920
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001921void Thread::ThrowNewWrappedException(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08001922 const char* msg) {
1923 DCHECK_EQ(this, Thread::Current());
Ian Rogers53b8b092014-03-13 23:45:53 -07001924 ScopedObjectAccessUnchecked soa(this);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001925 StackHandleScope<3> hs(soa.Self());
Nicolas Geoffrayee077032015-03-09 14:56:37 +00001926 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(GetCurrentClassLoader(soa.Self())));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001927 ScopedLocalRef<jobject> cause(GetJniEnv(), soa.AddLocalReference<jobject>(GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08001928 ClearException();
1929 Runtime* runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001930 auto* cl = runtime->GetClassLinker();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001931 Handle<mirror::Class> exception_class(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001932 hs.NewHandle(cl->FindClass(this, exception_class_descriptor, class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001933 if (UNLIKELY(exception_class.Get() == nullptr)) {
Elliott Hughes30646832011-10-13 16:59:46 -07001934 CHECK(IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08001935 LOG(ERROR) << "No exception class " << PrettyDescriptor(exception_class_descriptor);
Elliott Hughes30646832011-10-13 16:59:46 -07001936 return;
1937 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001938
Ian Rogers7b078e82014-09-10 14:44:24 -07001939 if (UNLIKELY(!runtime->GetClassLinker()->EnsureInitialized(soa.Self(), exception_class, true,
1940 true))) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001941 DCHECK(IsExceptionPending());
1942 return;
1943 }
1944 DCHECK(!runtime->IsStarted() || exception_class->IsThrowableClass());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001945 Handle<mirror::Throwable> exception(
1946 hs.NewHandle(down_cast<mirror::Throwable*>(exception_class->AllocObject(this))));
Ian Rogers62d6c772013-02-27 08:32:07 -08001947
Mathieu Chartier590fee92013-09-13 13:46:47 -07001948 // If we couldn't allocate the exception, throw the pre-allocated out of memory exception.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001949 if (exception.Get() == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001950 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001951 return;
1952 }
1953
Ian Rogers62d6c772013-02-27 08:32:07 -08001954 // Choose an appropriate constructor and set up the arguments.
1955 const char* signature;
Ian Rogers53b8b092014-03-13 23:45:53 -07001956 ScopedLocalRef<jstring> msg_string(GetJniEnv(), nullptr);
Dave Allison0aded082013-11-07 13:15:11 -08001957 if (msg != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001958 // Ensure we remember this and the method over the String allocation.
Ian Rogers53b8b092014-03-13 23:45:53 -07001959 msg_string.reset(
1960 soa.AddLocalReference<jstring>(mirror::String::AllocFromModifiedUtf8(this, msg)));
Dave Allison0aded082013-11-07 13:15:11 -08001961 if (UNLIKELY(msg_string.get() == nullptr)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001962 CHECK(IsExceptionPending()); // OOME.
1963 return;
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001964 }
Dave Allison0aded082013-11-07 13:15:11 -08001965 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001966 signature = "(Ljava/lang/String;)V";
1967 } else {
1968 signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V";
1969 }
1970 } else {
Dave Allison0aded082013-11-07 13:15:11 -08001971 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001972 signature = "()V";
1973 } else {
1974 signature = "(Ljava/lang/Throwable;)V";
1975 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001976 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001977 ArtMethod* exception_init_method =
1978 exception_class->FindDeclaredDirectMethod("<init>", signature, cl->GetImagePointerSize());
Ian Rogers62d6c772013-02-27 08:32:07 -08001979
Dave Allison0aded082013-11-07 13:15:11 -08001980 CHECK(exception_init_method != nullptr) << "No <init>" << signature << " in "
Ian Rogers62d6c772013-02-27 08:32:07 -08001981 << PrettyDescriptor(exception_class_descriptor);
1982
1983 if (UNLIKELY(!runtime->IsStarted())) {
1984 // Something is trying to throw an exception without a started runtime, which is the common
1985 // case in the compiler. We won't be able to invoke the constructor of the exception, so set
1986 // the exception fields directly.
Dave Allison0aded082013-11-07 13:15:11 -08001987 if (msg != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001988 exception->SetDetailMessage(down_cast<mirror::String*>(DecodeJObject(msg_string.get())));
Ian Rogers62d6c772013-02-27 08:32:07 -08001989 }
Dave Allison0aded082013-11-07 13:15:11 -08001990 if (cause.get() != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001991 exception->SetCause(down_cast<mirror::Throwable*>(DecodeJObject(cause.get())));
Ian Rogers62d6c772013-02-27 08:32:07 -08001992 }
Ian Rogersc45b8b52014-05-03 01:39:59 -07001993 ScopedLocalRef<jobject> trace(GetJniEnv(),
1994 Runtime::Current()->IsActiveTransaction()
1995 ? CreateInternalStackTrace<true>(soa)
1996 : CreateInternalStackTrace<false>(soa));
1997 if (trace.get() != nullptr) {
1998 exception->SetStackState(down_cast<mirror::Throwable*>(DecodeJObject(trace.get())));
1999 }
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002000 SetException(exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08002001 } else {
Ian Rogers53b8b092014-03-13 23:45:53 -07002002 jvalue jv_args[2];
2003 size_t i = 0;
2004
Dave Allison0aded082013-11-07 13:15:11 -08002005 if (msg != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07002006 jv_args[i].l = msg_string.get();
2007 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08002008 }
Dave Allison0aded082013-11-07 13:15:11 -08002009 if (cause.get() != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07002010 jv_args[i].l = cause.get();
2011 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08002012 }
Jeff Hao39b6c242015-05-19 20:30:23 -07002013 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(exception.Get()));
2014 InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(exception_init_method), jv_args);
Ian Rogers62d6c772013-02-27 08:32:07 -08002015 if (LIKELY(!IsExceptionPending())) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002016 SetException(exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08002017 }
Elliott Hughes30646832011-10-13 16:59:46 -07002018 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07002019}
2020
Elliott Hughes2ced6a52011-10-16 18:44:48 -07002021void Thread::ThrowOutOfMemoryError(const char* msg) {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002022 LOG(WARNING) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
Ian Rogersdd7624d2014-03-14 17:43:00 -07002023 msg, (tls32_.throwing_OutOfMemoryError ? " (recursive case)" : ""));
Ian Rogersdd7624d2014-03-14 17:43:00 -07002024 if (!tls32_.throwing_OutOfMemoryError) {
2025 tls32_.throwing_OutOfMemoryError = true;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00002026 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002027 tls32_.throwing_OutOfMemoryError = false;
Elliott Hughes418dfe72011-10-06 18:56:27 -07002028 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002029 Dump(LOG(WARNING)); // The pre-allocated OOME has no stack, so help out and log one.
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002030 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Elliott Hughes418dfe72011-10-06 18:56:27 -07002031 }
Elliott Hughes79082e32011-08-25 12:07:32 -07002032}
2033
Elliott Hughes498508c2011-10-17 14:58:22 -07002034Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002035 return Thread::Current();
2036}
2037
2038void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002039 std::ostringstream ss;
2040 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08002041 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002042 // log to stderr for debugging command line processes
2043 std::cerr << str;
2044#ifdef HAVE_ANDROID_OS
2045 // log to logcat for debugging frameworks processes
2046 LOG(INFO) << str;
2047#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002048}
2049
Ian Rogersdd7624d2014-03-14 17:43:00 -07002050// Explicitly instantiate 32 and 64bit thread offset dumping support.
2051template void Thread::DumpThreadOffset<4>(std::ostream& os, uint32_t offset);
2052template void Thread::DumpThreadOffset<8>(std::ostream& os, uint32_t offset);
Elliott Hughes98e20172012-04-24 15:38:13 -07002053
Ian Rogersdd7624d2014-03-14 17:43:00 -07002054template<size_t ptr_size>
2055void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset) {
2056#define DO_THREAD_OFFSET(x, y) \
2057 if (offset == x.Uint32Value()) { \
2058 os << y; \
Brian Carlstromf69863b2013-07-17 21:53:13 -07002059 return; \
2060 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002061 DO_THREAD_OFFSET(ThreadFlagsOffset<ptr_size>(), "state_and_flags")
2062 DO_THREAD_OFFSET(CardTableOffset<ptr_size>(), "card_table")
2063 DO_THREAD_OFFSET(ExceptionOffset<ptr_size>(), "exception")
2064 DO_THREAD_OFFSET(PeerOffset<ptr_size>(), "peer");
2065 DO_THREAD_OFFSET(JniEnvOffset<ptr_size>(), "jni_env")
2066 DO_THREAD_OFFSET(SelfOffset<ptr_size>(), "self")
2067 DO_THREAD_OFFSET(StackEndOffset<ptr_size>(), "stack_end")
2068 DO_THREAD_OFFSET(ThinLockIdOffset<ptr_size>(), "thin_lock_thread_id")
2069 DO_THREAD_OFFSET(TopOfManagedStackOffset<ptr_size>(), "top_quick_frame_method")
Ian Rogersdd7624d2014-03-14 17:43:00 -07002070 DO_THREAD_OFFSET(TopShadowFrameOffset<ptr_size>(), "top_shadow_frame")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002071 DO_THREAD_OFFSET(TopHandleScopeOffset<ptr_size>(), "top_handle_scope")
Ian Rogersdd7624d2014-03-14 17:43:00 -07002072 DO_THREAD_OFFSET(ThreadSuspendTriggerOffset<ptr_size>(), "suspend_trigger")
Elliott Hughes28fa76d2012-04-09 17:31:46 -07002073#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07002074
Ian Rogersdd7624d2014-03-14 17:43:00 -07002075#define INTERPRETER_ENTRY_POINT_INFO(x) \
2076 if (INTERPRETER_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
2077 os << #x; \
2078 return; \
Elliott Hughes98e20172012-04-24 15:38:13 -07002079 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002080 INTERPRETER_ENTRY_POINT_INFO(pInterpreterToInterpreterBridge)
2081 INTERPRETER_ENTRY_POINT_INFO(pInterpreterToCompiledCodeBridge)
2082#undef INTERPRETER_ENTRY_POINT_INFO
2083
2084#define JNI_ENTRY_POINT_INFO(x) \
2085 if (JNI_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
2086 os << #x; \
2087 return; \
2088 }
2089 JNI_ENTRY_POINT_INFO(pDlsymLookup)
2090#undef JNI_ENTRY_POINT_INFO
2091
Ian Rogersdd7624d2014-03-14 17:43:00 -07002092#define QUICK_ENTRY_POINT_INFO(x) \
2093 if (QUICK_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
2094 os << #x; \
2095 return; \
2096 }
2097 QUICK_ENTRY_POINT_INFO(pAllocArray)
2098 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved)
2099 QUICK_ENTRY_POINT_INFO(pAllocArrayWithAccessCheck)
2100 QUICK_ENTRY_POINT_INFO(pAllocObject)
2101 QUICK_ENTRY_POINT_INFO(pAllocObjectResolved)
2102 QUICK_ENTRY_POINT_INFO(pAllocObjectInitialized)
2103 QUICK_ENTRY_POINT_INFO(pAllocObjectWithAccessCheck)
2104 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArray)
2105 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArrayWithAccessCheck)
Jeff Hao848f70a2014-01-15 13:49:50 -08002106 QUICK_ENTRY_POINT_INFO(pAllocStringFromBytes)
2107 QUICK_ENTRY_POINT_INFO(pAllocStringFromChars)
2108 QUICK_ENTRY_POINT_INFO(pAllocStringFromString)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002109 QUICK_ENTRY_POINT_INFO(pInstanceofNonTrivial)
2110 QUICK_ENTRY_POINT_INFO(pCheckCast)
2111 QUICK_ENTRY_POINT_INFO(pInitializeStaticStorage)
2112 QUICK_ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccess)
2113 QUICK_ENTRY_POINT_INFO(pInitializeType)
2114 QUICK_ENTRY_POINT_INFO(pResolveString)
Fred Shih37f05ef2014-07-16 18:38:08 -07002115 QUICK_ENTRY_POINT_INFO(pSet8Instance)
2116 QUICK_ENTRY_POINT_INFO(pSet8Static)
2117 QUICK_ENTRY_POINT_INFO(pSet16Instance)
2118 QUICK_ENTRY_POINT_INFO(pSet16Static)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002119 QUICK_ENTRY_POINT_INFO(pSet32Instance)
2120 QUICK_ENTRY_POINT_INFO(pSet32Static)
2121 QUICK_ENTRY_POINT_INFO(pSet64Instance)
2122 QUICK_ENTRY_POINT_INFO(pSet64Static)
2123 QUICK_ENTRY_POINT_INFO(pSetObjInstance)
2124 QUICK_ENTRY_POINT_INFO(pSetObjStatic)
Fred Shih37f05ef2014-07-16 18:38:08 -07002125 QUICK_ENTRY_POINT_INFO(pGetByteInstance)
2126 QUICK_ENTRY_POINT_INFO(pGetBooleanInstance)
2127 QUICK_ENTRY_POINT_INFO(pGetByteStatic)
2128 QUICK_ENTRY_POINT_INFO(pGetBooleanStatic)
2129 QUICK_ENTRY_POINT_INFO(pGetShortInstance)
2130 QUICK_ENTRY_POINT_INFO(pGetCharInstance)
2131 QUICK_ENTRY_POINT_INFO(pGetShortStatic)
2132 QUICK_ENTRY_POINT_INFO(pGetCharStatic)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002133 QUICK_ENTRY_POINT_INFO(pGet32Instance)
2134 QUICK_ENTRY_POINT_INFO(pGet32Static)
2135 QUICK_ENTRY_POINT_INFO(pGet64Instance)
2136 QUICK_ENTRY_POINT_INFO(pGet64Static)
2137 QUICK_ENTRY_POINT_INFO(pGetObjInstance)
2138 QUICK_ENTRY_POINT_INFO(pGetObjStatic)
2139 QUICK_ENTRY_POINT_INFO(pAputObjectWithNullAndBoundCheck)
2140 QUICK_ENTRY_POINT_INFO(pAputObjectWithBoundCheck)
2141 QUICK_ENTRY_POINT_INFO(pAputObject)
2142 QUICK_ENTRY_POINT_INFO(pHandleFillArrayData)
2143 QUICK_ENTRY_POINT_INFO(pJniMethodStart)
2144 QUICK_ENTRY_POINT_INFO(pJniMethodStartSynchronized)
2145 QUICK_ENTRY_POINT_INFO(pJniMethodEnd)
2146 QUICK_ENTRY_POINT_INFO(pJniMethodEndSynchronized)
2147 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReference)
2148 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized)
2149 QUICK_ENTRY_POINT_INFO(pQuickGenericJniTrampoline)
2150 QUICK_ENTRY_POINT_INFO(pLockObject)
2151 QUICK_ENTRY_POINT_INFO(pUnlockObject)
2152 QUICK_ENTRY_POINT_INFO(pCmpgDouble)
2153 QUICK_ENTRY_POINT_INFO(pCmpgFloat)
2154 QUICK_ENTRY_POINT_INFO(pCmplDouble)
2155 QUICK_ENTRY_POINT_INFO(pCmplFloat)
2156 QUICK_ENTRY_POINT_INFO(pFmod)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002157 QUICK_ENTRY_POINT_INFO(pL2d)
2158 QUICK_ENTRY_POINT_INFO(pFmodf)
2159 QUICK_ENTRY_POINT_INFO(pL2f)
2160 QUICK_ENTRY_POINT_INFO(pD2iz)
2161 QUICK_ENTRY_POINT_INFO(pF2iz)
2162 QUICK_ENTRY_POINT_INFO(pIdivmod)
2163 QUICK_ENTRY_POINT_INFO(pD2l)
2164 QUICK_ENTRY_POINT_INFO(pF2l)
2165 QUICK_ENTRY_POINT_INFO(pLdiv)
2166 QUICK_ENTRY_POINT_INFO(pLmod)
2167 QUICK_ENTRY_POINT_INFO(pLmul)
2168 QUICK_ENTRY_POINT_INFO(pShlLong)
2169 QUICK_ENTRY_POINT_INFO(pShrLong)
2170 QUICK_ENTRY_POINT_INFO(pUshrLong)
2171 QUICK_ENTRY_POINT_INFO(pIndexOf)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002172 QUICK_ENTRY_POINT_INFO(pStringCompareTo)
2173 QUICK_ENTRY_POINT_INFO(pMemcpy)
2174 QUICK_ENTRY_POINT_INFO(pQuickImtConflictTrampoline)
2175 QUICK_ENTRY_POINT_INFO(pQuickResolutionTrampoline)
2176 QUICK_ENTRY_POINT_INFO(pQuickToInterpreterBridge)
2177 QUICK_ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck)
2178 QUICK_ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck)
2179 QUICK_ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck)
2180 QUICK_ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck)
2181 QUICK_ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002182 QUICK_ENTRY_POINT_INFO(pTestSuspend)
2183 QUICK_ENTRY_POINT_INFO(pDeliverException)
2184 QUICK_ENTRY_POINT_INFO(pThrowArrayBounds)
2185 QUICK_ENTRY_POINT_INFO(pThrowDivZero)
2186 QUICK_ENTRY_POINT_INFO(pThrowNoSuchMethod)
2187 QUICK_ENTRY_POINT_INFO(pThrowNullPointer)
2188 QUICK_ENTRY_POINT_INFO(pThrowStackOverflow)
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07002189 QUICK_ENTRY_POINT_INFO(pDeoptimize)
Douglas Leungd9cb8ae2014-07-09 14:28:35 -07002190 QUICK_ENTRY_POINT_INFO(pA64Load)
2191 QUICK_ENTRY_POINT_INFO(pA64Store)
Jeff Hao848f70a2014-01-15 13:49:50 -08002192 QUICK_ENTRY_POINT_INFO(pNewEmptyString)
2193 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_B)
2194 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BI)
2195 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BII)
2196 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIII)
2197 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIIString)
2198 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BString)
2199 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIICharset)
2200 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BCharset)
2201 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_C)
2202 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_CII)
2203 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_IIC)
2204 QUICK_ENTRY_POINT_INFO(pNewStringFromCodePoints)
2205 QUICK_ENTRY_POINT_INFO(pNewStringFromString)
2206 QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuffer)
2207 QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuilder)
Hiroshi Yamauchi1cc71eb2015-05-07 10:47:27 -07002208 QUICK_ENTRY_POINT_INFO(pReadBarrierJni)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002209#undef QUICK_ENTRY_POINT_INFO
2210
Elliott Hughes98e20172012-04-24 15:38:13 -07002211 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07002212}
2213
jeffhao94d6df42012-11-26 16:02:12 -08002214void Thread::QuickDeliverException() {
Ian Rogers62d6c772013-02-27 08:32:07 -08002215 // Get exception from thread.
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002216 mirror::Throwable* exception = GetException();
Dave Allison0aded082013-11-07 13:15:11 -08002217 CHECK(exception != nullptr);
Ian Rogers28ad40d2011-10-27 15:19:26 -07002218 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08002219 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07002220 ClearException();
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002221 bool is_deoptimization = (exception == GetDeoptimizationException());
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002222 QuickExceptionHandler exception_handler(this, is_deoptimization);
2223 if (is_deoptimization) {
2224 exception_handler.DeoptimizeStack();
2225 } else {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002226 exception_handler.FindCatch(exception);
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002227 }
2228 exception_handler.UpdateInstrumentationStack();
2229 exception_handler.DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07002230}
2231
Ian Rogersbdb03912011-09-14 00:55:44 -07002232Context* Thread::GetLongJumpContext() {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002233 Context* result = tlsPtr_.long_jump_context;
Dave Allison0aded082013-11-07 13:15:11 -08002234 if (result == nullptr) {
Ian Rogersbdb03912011-09-14 00:55:44 -07002235 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07002236 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002237 tlsPtr_.long_jump_context = nullptr; // Avoid context being shared.
Mathieu Chartier67022432012-11-29 18:04:50 -08002238 result->Reset();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07002239 }
Ian Rogersbdb03912011-09-14 00:55:44 -07002240 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07002241}
2242
Andreas Gampe4a8c3fa2014-07-16 22:20:31 -07002243// Note: this visitor may return with a method set, but dex_pc_ being DexFile:kDexNoIndex. This is
2244// so we don't abort in a special situation (thinlocked monitor) when dumping the Java stack.
Ian Rogerse0dcd462014-03-08 15:21:04 -08002245struct CurrentMethodVisitor FINAL : public StackVisitor {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002246 CurrentMethodVisitor(Thread* thread, Context* context, bool abort_on_error)
Ian Rogers62d6c772013-02-27 08:32:07 -08002247 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002248 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2249 this_object_(nullptr),
2250 method_(nullptr),
2251 dex_pc_(0),
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002252 abort_on_error_(abort_on_error) {}
Ian Rogerse0dcd462014-03-08 15:21:04 -08002253 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002254 ArtMethod* m = GetMethod();
Ian Rogers62d6c772013-02-27 08:32:07 -08002255 if (m->IsRuntimeMethod()) {
2256 // Continue if this is a runtime method.
2257 return true;
Ian Rogers0399dde2012-06-06 17:09:28 -07002258 }
Dave Allison0aded082013-11-07 13:15:11 -08002259 if (context_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002260 this_object_ = GetThisObject();
2261 }
2262 method_ = m;
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002263 dex_pc_ = GetDexPc(abort_on_error_);
Ian Rogers62d6c772013-02-27 08:32:07 -08002264 return false;
2265 }
2266 mirror::Object* this_object_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002267 ArtMethod* method_;
Ian Rogers62d6c772013-02-27 08:32:07 -08002268 uint32_t dex_pc_;
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002269 const bool abort_on_error_;
Ian Rogers62d6c772013-02-27 08:32:07 -08002270};
Ian Rogers0399dde2012-06-06 17:09:28 -07002271
Mathieu Chartiere401d142015-04-22 13:56:20 -07002272ArtMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, bool abort_on_error) const {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002273 CurrentMethodVisitor visitor(const_cast<Thread*>(this), nullptr, abort_on_error);
Ian Rogers0399dde2012-06-06 17:09:28 -07002274 visitor.WalkStack(false);
Dave Allison0aded082013-11-07 13:15:11 -08002275 if (dex_pc != nullptr) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002276 *dex_pc = visitor.dex_pc_;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07002277 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002278 return visitor.method_;
jeffhao33dc7712011-11-09 17:54:24 -08002279}
2280
Ian Rogersdd7624d2014-03-14 17:43:00 -07002281bool Thread::HoldsLock(mirror::Object* object) const {
Dave Allison0aded082013-11-07 13:15:11 -08002282 if (object == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -07002283 return false;
2284 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002285 return object->GetLockOwnerThreadId() == GetThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07002286}
2287
Ian Rogers40e3bac2012-11-20 00:09:14 -08002288// RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor).
2289template <typename RootVisitor>
Ian Rogers0399dde2012-06-06 17:09:28 -07002290class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07002291 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002292 ReferenceMapVisitor(Thread* thread, Context* context, RootVisitor& visitor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002293 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002294 // We are visiting the references in compiled frames, so we do not need
2295 // to know the inlined frames.
2296 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kSkipInlinedFrames),
2297 visitor_(visitor) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07002298
Ian Rogersb726dcb2012-09-05 08:57:23 -07002299 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07002300 if (false) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002301 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
Sebastien Hertz714f1752014-04-28 15:03:08 +02002302 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07002303 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002304 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
Dave Allison0aded082013-11-07 13:15:11 -08002305 if (shadow_frame != nullptr) {
Sebastien Hertz714f1752014-04-28 15:03:08 +02002306 VisitShadowFrame(shadow_frame);
2307 } else {
2308 VisitQuickFrame();
2309 }
2310 return true;
2311 }
2312
2313 void VisitShadowFrame(ShadowFrame* shadow_frame) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002314 ArtMethod* m = shadow_frame->GetMethod();
Hiroshi Yamauchi92d1a662014-05-15 21:43:59 -07002315 DCHECK(m != nullptr);
Sebastien Hertz714f1752014-04-28 15:03:08 +02002316 size_t num_regs = shadow_frame->NumberOfVRegs();
2317 if (m->IsNative() || shadow_frame->HasReferenceArray()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002318 // handle scope for JNI or References for interpreter.
Sebastien Hertz714f1752014-04-28 15:03:08 +02002319 for (size_t reg = 0; reg < num_regs; ++reg) {
2320 mirror::Object* ref = shadow_frame->GetVRegReference(reg);
2321 if (ref != nullptr) {
2322 mirror::Object* new_ref = ref;
2323 visitor_(&new_ref, reg, this);
2324 if (new_ref != ref) {
2325 shadow_frame->SetVRegReference(reg, new_ref);
2326 }
2327 }
2328 }
2329 } else {
2330 // Java method.
2331 // Portable path use DexGcMap and store in Method.native_gc_map_.
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002332 const uint8_t* gc_map = m->GetNativeGcMap(sizeof(void*));
Sebastien Hertz714f1752014-04-28 15:03:08 +02002333 CHECK(gc_map != nullptr) << PrettyMethod(m);
2334 verifier::DexPcToReferenceMap dex_gc_map(gc_map);
2335 uint32_t dex_pc = shadow_frame->GetDexPC();
2336 const uint8_t* reg_bitmap = dex_gc_map.FindBitMap(dex_pc);
2337 DCHECK(reg_bitmap != nullptr);
2338 num_regs = std::min(dex_gc_map.RegWidth() * 8, num_regs);
2339 for (size_t reg = 0; reg < num_regs; ++reg) {
2340 if (TestBitmap(reg, reg_bitmap)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002341 mirror::Object* ref = shadow_frame->GetVRegReference(reg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002342 if (ref != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08002343 mirror::Object* new_ref = ref;
2344 visitor_(&new_ref, reg, this);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002345 if (new_ref != ref) {
Sebastien Hertz714f1752014-04-28 15:03:08 +02002346 shadow_frame->SetVRegReference(reg, new_ref);
TDYa127ce4cc0d2012-11-18 16:59:53 -08002347 }
2348 }
2349 }
2350 }
Sebastien Hertz714f1752014-04-28 15:03:08 +02002351 }
2352 }
2353
2354 private:
2355 void VisitQuickFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002356 auto* cur_quick_frame = GetCurrentQuickFrame();
2357 DCHECK(cur_quick_frame != nullptr);
2358 auto* m = *cur_quick_frame;
Andreas Gampecf4035a2014-05-28 22:43:01 -07002359
Sebastien Hertz714f1752014-04-28 15:03:08 +02002360 // Process register map (which native and runtime methods don't have)
2361 if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002362 if (m->IsOptimized(sizeof(void*))) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002363 auto* vreg_base = reinterpret_cast<StackReference<mirror::Object>*>(
2364 reinterpret_cast<uintptr_t>(cur_quick_frame));
Vladimir Marko4c1c5102014-05-14 16:51:16 +01002365 Runtime* runtime = Runtime::Current();
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002366 const void* entry_point = runtime->GetInstrumentation()->GetQuickCodeFor(m, sizeof(void*));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002367 uintptr_t native_pc_offset = m->NativeQuickPcOffset(GetCurrentQuickFramePc(), entry_point);
Nicolas Geoffray004c2302015-03-20 10:06:38 +00002368 CodeInfo code_info = m->GetOptimizedCodeInfo();
David Brazdilf677ebf2015-05-29 16:29:43 +01002369 StackMapEncoding encoding = code_info.ExtractEncoding();
2370 StackMap map = code_info.GetStackMapForNativePcOffset(native_pc_offset, encoding);
Nicolas Geoffraye12997f2015-05-22 14:01:33 +01002371 DCHECK(map.IsValid());
David Brazdilf677ebf2015-05-29 16:29:43 +01002372 MemoryRegion mask = map.GetStackMask(encoding);
Nicolas Geoffray98893962015-01-21 12:32:32 +00002373 // Visit stack entries that hold pointers.
Nicolas Geoffray39468442014-09-02 15:17:15 +01002374 for (size_t i = 0; i < mask.size_in_bits(); ++i) {
2375 if (mask.LoadBit(i)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002376 auto* ref_addr = vreg_base + i;
Nicolas Geoffray39468442014-09-02 15:17:15 +01002377 mirror::Object* ref = ref_addr->AsMirrorPtr();
2378 if (ref != nullptr) {
2379 mirror::Object* new_ref = ref;
2380 visitor_(&new_ref, -1, this);
2381 if (ref != new_ref) {
2382 ref_addr->Assign(new_ref);
Sebastien Hertz714f1752014-04-28 15:03:08 +02002383 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01002384 }
2385 }
2386 }
Nicolas Geoffray98893962015-01-21 12:32:32 +00002387 // Visit callee-save registers that hold pointers.
David Brazdilf677ebf2015-05-29 16:29:43 +01002388 uint32_t register_mask = map.GetRegisterMask(encoding);
Nicolas Geoffray98893962015-01-21 12:32:32 +00002389 for (size_t i = 0; i < BitSizeOf<uint32_t>(); ++i) {
2390 if (register_mask & (1 << i)) {
2391 mirror::Object** ref_addr = reinterpret_cast<mirror::Object**>(GetGPRAddress(i));
2392 if (*ref_addr != nullptr) {
2393 visitor_(ref_addr, -1, this);
2394 }
2395 }
2396 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01002397 } else {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002398 const uint8_t* native_gc_map = m->GetNativeGcMap(sizeof(void*));
Nicolas Geoffray39468442014-09-02 15:17:15 +01002399 CHECK(native_gc_map != nullptr) << PrettyMethod(m);
2400 const DexFile::CodeItem* code_item = m->GetCodeItem();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002401 // Can't be null or how would we compile its instructions?
Nicolas Geoffray39468442014-09-02 15:17:15 +01002402 DCHECK(code_item != nullptr) << PrettyMethod(m);
2403 NativePcOffsetToReferenceMap map(native_gc_map);
Pavel Vyssotski41f9cc22015-06-16 17:57:37 +06002404 size_t num_regs = map.RegWidth() * 8;
Nicolas Geoffray39468442014-09-02 15:17:15 +01002405 if (num_regs > 0) {
2406 Runtime* runtime = Runtime::Current();
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002407 const void* entry_point = runtime->GetInstrumentation()->GetQuickCodeFor(m, sizeof(void*));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002408 uintptr_t native_pc_offset = m->NativeQuickPcOffset(GetCurrentQuickFramePc(), entry_point);
Nicolas Geoffray39468442014-09-02 15:17:15 +01002409 const uint8_t* reg_bitmap = map.FindBitMap(native_pc_offset);
2410 DCHECK(reg_bitmap != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002411 const void* code_pointer = ArtMethod::EntryPointToCodePointer(entry_point);
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002412 const VmapTable vmap_table(m->GetVmapTable(code_pointer, sizeof(void*)));
Nicolas Geoffray39468442014-09-02 15:17:15 +01002413 QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
2414 // For all dex registers in the bitmap
Nicolas Geoffray39468442014-09-02 15:17:15 +01002415 DCHECK(cur_quick_frame != nullptr);
2416 for (size_t reg = 0; reg < num_regs; ++reg) {
2417 // Does this register hold a reference?
2418 if (TestBitmap(reg, reg_bitmap)) {
2419 uint32_t vmap_offset;
2420 if (vmap_table.IsInContext(reg, kReferenceVReg, &vmap_offset)) {
2421 int vmap_reg = vmap_table.ComputeRegister(frame_info.CoreSpillMask(), vmap_offset,
2422 kReferenceVReg);
2423 // This is sound as spilled GPRs will be word sized (ie 32 or 64bit).
2424 mirror::Object** ref_addr =
2425 reinterpret_cast<mirror::Object**>(GetGPRAddress(vmap_reg));
2426 if (*ref_addr != nullptr) {
2427 visitor_(ref_addr, reg, this);
2428 }
2429 } else {
2430 StackReference<mirror::Object>* ref_addr =
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00002431 reinterpret_cast<StackReference<mirror::Object>*>(GetVRegAddrFromQuickCode(
2432 cur_quick_frame, code_item, frame_info.CoreSpillMask(),
2433 frame_info.FpSpillMask(), frame_info.FrameSizeInBytes(), reg));
Nicolas Geoffray39468442014-09-02 15:17:15 +01002434 mirror::Object* ref = ref_addr->AsMirrorPtr();
2435 if (ref != nullptr) {
2436 mirror::Object* new_ref = ref;
2437 visitor_(&new_ref, reg, this);
2438 if (ref != new_ref) {
2439 ref_addr->Assign(new_ref);
2440 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002441 }
Ian Rogers0c7abda2012-09-19 13:33:42 -07002442 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002443 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07002444 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002445 }
2446 }
2447 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002448 }
2449
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002450 // Visitor for when we visit a root.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002451 RootVisitor& visitor_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07002452};
2453
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002454class RootCallbackVisitor {
2455 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002456 RootCallbackVisitor(RootVisitor* visitor, uint32_t tid) : visitor_(visitor), tid_(tid) {}
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002457
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002458 void operator()(mirror::Object** obj, size_t vreg, const StackVisitor* stack_visitor) const
2459 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2460 visitor_->VisitRoot(obj, JavaFrameRootInfo(tid_, stack_visitor, vreg));
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002461 }
2462
2463 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002464 RootVisitor* const visitor_;
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002465 const uint32_t tid_;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002466};
2467
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002468void Thread::VisitRoots(RootVisitor* visitor) {
2469 const uint32_t thread_id = GetThreadId();
2470 visitor->VisitRootIfNonNull(&tlsPtr_.opeer, RootInfo(kRootThreadObject, thread_id));
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002471 if (tlsPtr_.exception != nullptr && tlsPtr_.exception != GetDeoptimizationException()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002472 visitor->VisitRoot(reinterpret_cast<mirror::Object**>(&tlsPtr_.exception),
2473 RootInfo(kRootNativeStack, thread_id));
Elliott Hughesd369bb72011-09-12 14:41:14 -07002474 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002475 visitor->VisitRootIfNonNull(&tlsPtr_.monitor_enter_object, RootInfo(kRootNativeStack, thread_id));
2476 tlsPtr_.jni_env->locals.VisitRoots(visitor, RootInfo(kRootJNILocal, thread_id));
2477 tlsPtr_.jni_env->monitors.VisitRoots(visitor, RootInfo(kRootJNIMonitor, thread_id));
2478 HandleScopeVisitRoots(visitor, thread_id);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002479 if (tlsPtr_.debug_invoke_req != nullptr) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002480 tlsPtr_.debug_invoke_req->VisitRoots(visitor, RootInfo(kRootDebugger, thread_id));
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07002481 }
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -07002482 if (tlsPtr_.stacked_shadow_frame_record != nullptr) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002483 RootCallbackVisitor visitor_to_callback(visitor, thread_id);
2484 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, nullptr, visitor_to_callback);
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -07002485 for (StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record;
2486 record != nullptr;
2487 record = record->GetLink()) {
2488 for (ShadowFrame* shadow_frame = record->GetShadowFrame();
2489 shadow_frame != nullptr;
2490 shadow_frame = shadow_frame->GetLink()) {
2491 mapper.VisitShadowFrame(shadow_frame);
2492 }
Sebastien Hertz714f1752014-04-28 15:03:08 +02002493 }
2494 }
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -07002495 if (tlsPtr_.deoptimization_return_value_stack != nullptr) {
2496 for (DeoptimizationReturnValueRecord* record = tlsPtr_.deoptimization_return_value_stack;
2497 record != nullptr;
2498 record = record->GetLink()) {
2499 if (record->IsReference()) {
2500 visitor->VisitRootIfNonNull(record->GetGCRoot(),
2501 RootInfo(kRootThreadObject, thread_id));
2502 }
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -07002503 }
2504 }
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07002505 for (auto* verifier = tlsPtr_.method_verifier; verifier != nullptr; verifier = verifier->link_) {
2506 verifier->VisitRoots(visitor, RootInfo(kRootNativeStack, thread_id));
Mathieu Chartier12d625f2015-03-13 11:33:37 -07002507 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002508 // Visit roots on this thread's stack
Ian Rogers0399dde2012-06-06 17:09:28 -07002509 Context* context = GetLongJumpContext();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002510 RootCallbackVisitor visitor_to_callback(visitor, thread_id);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002511 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context, visitor_to_callback);
Ian Rogers0399dde2012-06-06 17:09:28 -07002512 mapper.WalkStack();
2513 ReleaseLongJumpContext(context);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002514 for (instrumentation::InstrumentationStackFrame& frame : *GetInstrumentationStack()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002515 visitor->VisitRootIfNonNull(&frame.this_object_, RootInfo(kRootVMInternal, thread_id));
Ian Rogers62d6c772013-02-27 08:32:07 -08002516 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07002517}
2518
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002519class VerifyRootVisitor : public SingleRootVisitor {
2520 public:
2521 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
2522 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2523 VerifyObject(root);
2524 }
2525};
jeffhao25045522012-03-13 19:34:37 -07002526
Ian Rogers04d7aa92013-03-16 14:29:17 -07002527void Thread::VerifyStackImpl() {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002528 VerifyRootVisitor visitor;
Ian Rogers700a4022014-05-19 16:49:03 -07002529 std::unique_ptr<Context> context(Context::Create());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002530 RootCallbackVisitor visitor_to_callback(&visitor, GetThreadId());
2531 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context.get(), visitor_to_callback);
Ian Rogers0399dde2012-06-06 17:09:28 -07002532 mapper.WalkStack();
jeffhao25045522012-03-13 19:34:37 -07002533}
jeffhao25045522012-03-13 19:34:37 -07002534
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002535// Set the stack end to that to be used during a stack overflow
2536void Thread::SetStackEndForStackOverflow() {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002537 // During stack overflow we allow use of the full stack.
Ian Rogersdd7624d2014-03-14 17:43:00 -07002538 if (tlsPtr_.stack_end == tlsPtr_.stack_begin) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002539 // However, we seem to have already extended to use the full stack.
2540 LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently "
Andreas Gampe7ea6f792014-07-14 16:21:44 -07002541 << GetStackOverflowReservedBytes(kRuntimeISA) << ")?";
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002542 DumpStack(LOG(ERROR));
2543 LOG(FATAL) << "Recursive stack overflow.";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002544 }
2545
Ian Rogersdd7624d2014-03-14 17:43:00 -07002546 tlsPtr_.stack_end = tlsPtr_.stack_begin;
Dave Allison648d7112014-07-25 16:15:27 -07002547
2548 // Remove the stack overflow protection if is it set up.
2549 bool implicit_stack_check = !Runtime::Current()->ExplicitStackOverflowChecks();
2550 if (implicit_stack_check) {
2551 if (!UnprotectStack()) {
2552 LOG(ERROR) << "Unable to remove stack protection for stack overflow";
2553 }
2554 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002555}
2556
Ian Rogers13735952014-10-08 12:43:28 -07002557void Thread::SetTlab(uint8_t* start, uint8_t* end) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002558 DCHECK_LE(start, end);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002559 tlsPtr_.thread_local_start = start;
2560 tlsPtr_.thread_local_pos = tlsPtr_.thread_local_start;
2561 tlsPtr_.thread_local_end = end;
2562 tlsPtr_.thread_local_objects = 0;
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002563}
2564
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002565bool Thread::HasTlab() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002566 bool has_tlab = tlsPtr_.thread_local_pos != nullptr;
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002567 if (has_tlab) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002568 DCHECK(tlsPtr_.thread_local_start != nullptr && tlsPtr_.thread_local_end != nullptr);
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002569 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002570 DCHECK(tlsPtr_.thread_local_start == nullptr && tlsPtr_.thread_local_end == nullptr);
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002571 }
2572 return has_tlab;
2573}
2574
Elliott Hughes330304d2011-08-12 14:28:05 -07002575std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002576 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07002577 return os;
2578}
2579
Dave Allison648d7112014-07-25 16:15:27 -07002580void Thread::ProtectStack() {
2581 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
2582 VLOG(threads) << "Protecting stack at " << pregion;
2583 if (mprotect(pregion, kStackOverflowProtectedSize, PROT_NONE) == -1) {
2584 LOG(FATAL) << "Unable to create protected region in stack for implicit overflow check. "
2585 "Reason: "
2586 << strerror(errno) << " size: " << kStackOverflowProtectedSize;
2587 }
2588}
2589
2590bool Thread::UnprotectStack() {
2591 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
2592 VLOG(threads) << "Unprotecting stack at " << pregion;
2593 return mprotect(pregion, kStackOverflowProtectedSize, PROT_READ|PROT_WRITE) == 0;
2594}
2595
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002596void Thread::ActivateSingleStepControl(SingleStepControl* ssc) {
2597 CHECK(Dbg::IsDebuggerActive());
2598 CHECK(GetSingleStepControl() == nullptr) << "Single step already active in thread " << *this;
2599 CHECK(ssc != nullptr);
2600 tlsPtr_.single_step_control = ssc;
2601}
2602
2603void Thread::DeactivateSingleStepControl() {
2604 CHECK(Dbg::IsDebuggerActive());
2605 CHECK(GetSingleStepControl() != nullptr) << "Single step not active in thread " << *this;
2606 SingleStepControl* ssc = GetSingleStepControl();
2607 tlsPtr_.single_step_control = nullptr;
2608 delete ssc;
2609}
Dave Allison648d7112014-07-25 16:15:27 -07002610
Sebastien Hertz1558b572015-02-25 15:05:59 +01002611void Thread::SetDebugInvokeReq(DebugInvokeReq* req) {
2612 CHECK(Dbg::IsDebuggerActive());
2613 CHECK(GetInvokeReq() == nullptr) << "Debug invoke req already active in thread " << *this;
2614 CHECK(Thread::Current() != this) << "Debug invoke can't be dispatched by the thread itself";
2615 CHECK(req != nullptr);
2616 tlsPtr_.debug_invoke_req = req;
2617}
2618
2619void Thread::ClearDebugInvokeReq() {
Sebastien Hertz1558b572015-02-25 15:05:59 +01002620 CHECK(GetInvokeReq() != nullptr) << "Debug invoke req not active in thread " << *this;
2621 CHECK(Thread::Current() == this) << "Debug invoke must be finished by the thread itself";
Sebastien Hertzcbc50642015-06-01 17:33:12 +02002622 DebugInvokeReq* req = tlsPtr_.debug_invoke_req;
Sebastien Hertz1558b572015-02-25 15:05:59 +01002623 tlsPtr_.debug_invoke_req = nullptr;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02002624 delete req;
Sebastien Hertz1558b572015-02-25 15:05:59 +01002625}
2626
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07002627void Thread::PushVerifier(verifier::MethodVerifier* verifier) {
2628 verifier->link_ = tlsPtr_.method_verifier;
Mathieu Chartier12d625f2015-03-13 11:33:37 -07002629 tlsPtr_.method_verifier = verifier;
2630}
2631
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07002632void Thread::PopVerifier(verifier::MethodVerifier* verifier) {
Mathieu Chartier12d625f2015-03-13 11:33:37 -07002633 CHECK_EQ(tlsPtr_.method_verifier, verifier);
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07002634 tlsPtr_.method_verifier = verifier->link_;
Mathieu Chartier12d625f2015-03-13 11:33:37 -07002635}
2636
Elliott Hughes8daa0922011-09-11 13:46:25 -07002637} // namespace art