blob: 8de16afe4d97325b40294de277b586a4f05e6a00 [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.
Evgenii Stepanov4abf4512015-07-13 10:41:57 -0700361
362// AddressSanitizer does not like the part of this functions that reads every stack page.
363// Looks a lot like an out-of-bounds access.
364ATTRIBUTE_NO_SANITIZE_ADDRESS
Dave Allison648d7112014-07-25 16:15:27 -0700365void Thread::InstallImplicitProtection() {
Ian Rogers13735952014-10-08 12:43:28 -0700366 uint8_t* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
367 uint8_t* stack_himem = tlsPtr_.stack_end;
368 uint8_t* stack_top = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(&stack_himem) &
Dave Allison69dfe512014-07-11 17:11:58 +0000369 ~(kPageSize - 1)); // Page containing current top of stack.
Dave Allisonf9439142014-03-27 15:10:22 -0700370
Dave Allison648d7112014-07-25 16:15:27 -0700371 // First remove the protection on the protected region as will want to read and
372 // write it. This may fail (on the first attempt when the stack is not mapped)
373 // but we ignore that.
374 UnprotectStack();
Dave Allison69dfe512014-07-11 17:11:58 +0000375
Dave Allison648d7112014-07-25 16:15:27 -0700376 // Map in the stack. This must be done by reading from the
377 // current stack pointer downwards as the stack may be mapped using VM_GROWSDOWN
378 // in the kernel. Any access more than a page below the current SP might cause
379 // a segv.
Dave Allison69dfe512014-07-11 17:11:58 +0000380
Dave Allison648d7112014-07-25 16:15:27 -0700381 // Read every page from the high address to the low.
Ian Rogers13735952014-10-08 12:43:28 -0700382 for (uint8_t* p = stack_top; p >= pregion; p -= kPageSize) {
Dave Allison648d7112014-07-25 16:15:27 -0700383 dont_optimize_this = *p;
Dave Allison69dfe512014-07-11 17:11:58 +0000384 }
385
Dave Allisonf9439142014-03-27 15:10:22 -0700386 VLOG(threads) << "installing stack protected region at " << std::hex <<
387 static_cast<void*>(pregion) << " to " <<
388 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1);
389
Dave Allison648d7112014-07-25 16:15:27 -0700390 // Protect the bottom of the stack to prevent read/write to it.
391 ProtectStack();
Dave Allison5cd33752014-04-15 15:57:58 -0700392
393 // Tell the kernel that we won't be needing these pages any more.
Dave Allison69dfe512014-07-11 17:11:58 +0000394 // NB. madvise will probably write zeroes into the memory (on linux it does).
Dave Allison648d7112014-07-25 16:15:27 -0700395 uint32_t unwanted_size = stack_top - pregion - kPageSize;
396 madvise(pregion, unwanted_size, MADV_DONTNEED);
Dave Allisonf9439142014-03-27 15:10:22 -0700397}
398
Ian Rogers120f1c72012-09-28 17:17:10 -0700399void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
Dave Allison0aded082013-11-07 13:15:11 -0800400 CHECK(java_peer != nullptr);
Ian Rogers120f1c72012-09-28 17:17:10 -0700401 Thread* self = static_cast<JNIEnvExt*>(env)->self;
Andreas Gampe56623832015-07-09 21:53:15 -0700402
403 if (VLOG_IS_ON(threads)) {
404 ScopedObjectAccess soa(env);
405
406 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
407 mirror::String* java_name = reinterpret_cast<mirror::String*>(f->GetObject(
408 soa.Decode<mirror::Object*>(java_peer)));
409 std::string thread_name;
410 if (java_name != nullptr) {
411 thread_name = java_name->ToModifiedUtf8();
412 } else {
413 thread_name = "(Unnamed)";
414 }
415
416 VLOG(threads) << "Creating native thread for " << thread_name;
417 self->Dump(LOG(INFO));
418 }
419
Ian Rogers120f1c72012-09-28 17:17:10 -0700420 Runtime* runtime = Runtime::Current();
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700421
Ian Rogers120f1c72012-09-28 17:17:10 -0700422 // Atomically start the birth of the thread ensuring the runtime isn't shutting down.
423 bool thread_start_during_shutdown = false;
Elliott Hughes47179f72011-10-27 16:44:39 -0700424 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700425 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700426 if (runtime->IsShuttingDownLocked()) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700427 thread_start_during_shutdown = true;
428 } else {
429 runtime->StartThreadBirth();
430 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700431 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700432 if (thread_start_during_shutdown) {
433 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError"));
434 env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown");
435 return;
436 }
437
438 Thread* child_thread = new Thread(is_daemon);
439 // Use global JNI ref to hold peer live while child thread starts.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700440 child_thread->tlsPtr_.jpeer = env->NewGlobalRef(java_peer);
Ian Rogers120f1c72012-09-28 17:17:10 -0700441 stack_size = FixStackSize(stack_size);
442
Anwar Ghuloum3c50a4b2013-06-21 13:05:23 -0700443 // 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 -0700444 // assign it.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800445 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer,
446 reinterpret_cast<jlong>(child_thread));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700447
Andreas Gampe449357d2015-06-01 22:29:51 -0700448 // Try to allocate a JNIEnvExt for the thread. We do this here as we might be out of memory and
449 // do not have a good way to report this on the child's side.
450 std::unique_ptr<JNIEnvExt> child_jni_env_ext(
451 JNIEnvExt::Create(child_thread, Runtime::Current()->GetJavaVM()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700452
Andreas Gampe449357d2015-06-01 22:29:51 -0700453 int pthread_create_result = 0;
454 if (child_jni_env_ext.get() != nullptr) {
455 pthread_t new_pthread;
456 pthread_attr_t attr;
457 child_thread->tlsPtr_.tmp_jni_env = child_jni_env_ext.get();
458 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
459 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
460 "PTHREAD_CREATE_DETACHED");
461 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
462 pthread_create_result = pthread_create(&new_pthread,
463 &attr,
464 Thread::CreateCallback,
465 child_thread);
466 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
467
468 if (pthread_create_result == 0) {
469 // pthread_create started the new thread. The child is now responsible for managing the
470 // JNIEnvExt we created.
471 // Note: we can't check for tmp_jni_env == nullptr, as that would require synchronization
472 // between the threads.
473 child_jni_env_ext.release();
474 return;
Ian Rogers120f1c72012-09-28 17:17:10 -0700475 }
Andreas Gampe449357d2015-06-01 22:29:51 -0700476 }
477
478 // Either JNIEnvExt::Create or pthread_create(3) failed, so clean up.
479 {
480 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
481 runtime->EndThreadBirth();
482 }
483 // Manually delete the global reference since Thread::Init will not have been run.
484 env->DeleteGlobalRef(child_thread->tlsPtr_.jpeer);
485 child_thread->tlsPtr_.jpeer = nullptr;
486 delete child_thread;
487 child_thread = nullptr;
488 // TODO: remove from thread group?
489 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 0);
490 {
491 std::string msg(child_jni_env_ext.get() == nullptr ?
492 "Could not allocate JNI Env" :
493 StringPrintf("pthread_create (%s stack) failed: %s",
494 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
495 ScopedObjectAccess soa(env);
496 soa.Self()->ThrowOutOfMemoryError(msg.c_str());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700497 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700498}
499
Andreas Gampe449357d2015-06-01 22:29:51 -0700500bool Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm, JNIEnvExt* jni_env_ext) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700501 // This function does all the initialization that must be run by the native thread it applies to.
502 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
503 // we can handshake with the corresponding native thread when it's ready.) Check this native
504 // thread hasn't been through here already...
Dave Allison0aded082013-11-07 13:15:11 -0800505 CHECK(Thread::Current() == nullptr);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800506
507 // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this
508 // avoids pthread_self_ ever being invalid when discovered from Thread::Current().
509 tlsPtr_.pthread_self = pthread_self();
510 CHECK(is_started_);
511
Elliott Hughesd8af1592012-04-16 20:40:15 -0700512 SetUpAlternateSignalStack();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800513 if (!InitStackHwm()) {
514 return false;
515 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700516 InitCpu();
Ian Rogers848871b2013-08-05 10:56:33 -0700517 InitTlsEntryPoints();
Dave Allisonb373e092014-02-20 16:06:36 -0800518 RemoveSuspendTrigger();
Ian Rogers5d76c432011-10-31 21:42:49 -0700519 InitCardTable();
Ian Rogers01ae5802012-09-28 16:14:01 -0700520 InitTid();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800521
Ian Rogers120f1c72012-09-28 17:17:10 -0700522 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
523 DCHECK_EQ(Thread::Current(), this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700524
Ian Rogersdd7624d2014-03-14 17:43:00 -0700525 tls32_.thin_lock_thread_id = thread_list->AllocThreadId(this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700526
Andreas Gampe449357d2015-06-01 22:29:51 -0700527 if (jni_env_ext != nullptr) {
528 DCHECK_EQ(jni_env_ext->vm, java_vm);
529 DCHECK_EQ(jni_env_ext->self, this);
530 tlsPtr_.jni_env = jni_env_ext;
531 } else {
532 tlsPtr_.jni_env = JNIEnvExt::Create(this, java_vm);
533 if (tlsPtr_.jni_env == nullptr) {
534 return false;
535 }
Andreas Gampe3f5881f2015-04-08 10:26:16 -0700536 }
537
Ian Rogers120f1c72012-09-28 17:17:10 -0700538 thread_list->Register(this);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800539 return true;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700540}
541
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800542Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group,
543 bool create_peer) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700544 Runtime* runtime = Runtime::Current();
Dave Allison0aded082013-11-07 13:15:11 -0800545 if (runtime == nullptr) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700546 LOG(ERROR) << "Thread attaching to non-existent runtime: " << thread_name;
Dave Allison0aded082013-11-07 13:15:11 -0800547 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700548 }
Ian Rogersf4d4da12014-11-11 16:10:33 -0800549 Thread* self;
Ian Rogers120f1c72012-09-28 17:17:10 -0700550 {
Dave Allison0aded082013-11-07 13:15:11 -0800551 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700552 if (runtime->IsShuttingDownLocked()) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700553 LOG(ERROR) << "Thread attaching while runtime is shutting down: " << thread_name;
Dave Allison0aded082013-11-07 13:15:11 -0800554 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700555 } else {
556 Runtime::Current()->StartThreadBirth();
557 self = new Thread(as_daemon);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800558 bool init_success = self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
Ian Rogers120f1c72012-09-28 17:17:10 -0700559 Runtime::Current()->EndThreadBirth();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800560 if (!init_success) {
561 delete self;
562 return nullptr;
563 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700564 }
565 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700566
Jeff Hao848f70a2014-01-15 13:49:50 -0800567 self->InitStringEntryPoints();
568
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700569 CHECK_NE(self->GetState(), kRunnable);
570 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700571
Elliott Hughescac6cc72011-11-03 20:31:21 -0700572 // If we're the main thread, ClassLinker won't be created until after we're attached,
573 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800574 // In the compiler, all threads need this hack, because no-one's going to be getting
575 // a native peer!
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800576 if (create_peer) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700577 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800578 } else {
579 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Dave Allison0aded082013-11-07 13:15:11 -0800580 if (thread_name != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700581 self->tlsPtr_.name->assign(thread_name);
Elliott Hughes22869a92012-03-27 14:08:24 -0700582 ::art::SetThreadName(thread_name);
Brian Carlstrom3ea69c02014-08-18 15:38:34 -0700583 } else if (self->GetJniEnv()->check_jni) {
584 LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
Elliott Hughes22869a92012-03-27 14:08:24 -0700585 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700586 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700587
Andreas Gampe56623832015-07-09 21:53:15 -0700588 if (VLOG_IS_ON(threads)) {
589 if (thread_name != nullptr) {
590 VLOG(threads) << "Attaching thread " << thread_name;
591 } else {
592 VLOG(threads) << "Attaching unnamed thread.";
593 }
594 ScopedObjectAccess soa(self);
595 self->Dump(LOG(INFO));
596 }
597
Daniel Mihalyidfafeef2014-10-20 11:47:56 +0200598 {
599 ScopedObjectAccess soa(self);
600 Dbg::PostThreadStart(self);
601 }
602
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700603 return self;
604}
605
Ian Rogers365c1022012-06-22 15:05:28 -0700606void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
607 Runtime* runtime = Runtime::Current();
608 CHECK(runtime->IsStarted());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700609 JNIEnv* env = tlsPtr_.jni_env;
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700610
Dave Allison0aded082013-11-07 13:15:11 -0800611 if (thread_group == nullptr) {
Ian Rogers365c1022012-06-22 15:05:28 -0700612 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -0700613 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700614 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Mathieu Chartiere07fd172014-11-10 16:58:19 -0800615 // Add missing null check in case of OOM b/18297817
Vladimir Marko44512052014-11-12 15:41:57 +0000616 if (name != nullptr && thread_name.get() == nullptr) {
Mathieu Chartiere07fd172014-11-10 16:58:19 -0800617 CHECK(IsExceptionPending());
618 return;
619 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700620 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700621 jboolean thread_is_daemon = as_daemon;
622
Elliott Hugheseac76672012-05-24 21:56:51 -0700623 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Dave Allison0aded082013-11-07 13:15:11 -0800624 if (peer.get() == nullptr) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700625 CHECK(IsExceptionPending());
626 return;
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700627 }
Ian Rogerscfaa4552012-11-26 21:00:08 -0800628 {
629 ScopedObjectAccess soa(this);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700630 tlsPtr_.opeer = soa.Decode<mirror::Object*>(peer.get());
Ian Rogerscfaa4552012-11-26 21:00:08 -0800631 }
Elliott Hugheseac76672012-05-24 21:56:51 -0700632 env->CallNonvirtualVoidMethod(peer.get(),
633 WellKnownClasses::java_lang_Thread,
634 WellKnownClasses::java_lang_Thread_init,
Ian Rogers365c1022012-06-22 15:05:28 -0700635 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700636 AssertNoPendingException();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700637
Ian Rogers120f1c72012-09-28 17:17:10 -0700638 Thread* self = this;
639 DCHECK_EQ(self, Thread::Current());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700640 env->SetLongField(peer.get(), WellKnownClasses::java_lang_Thread_nativePeer,
641 reinterpret_cast<jlong>(self));
Ian Rogers120f1c72012-09-28 17:17:10 -0700642
643 ScopedObjectAccess soa(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700644 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -0700645 MutableHandle<mirror::String> peer_thread_name(hs.NewHandle(GetThreadName(soa)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700646 if (peer_thread_name.Get() == nullptr) {
Brian Carlstrom00fae582011-10-28 01:16:28 -0700647 // The Thread constructor should have set the Thread.name to a
648 // non-null value. However, because we can run without code
649 // available (in the compiler, in tests), we manually assign the
650 // fields the constructor should have set.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100651 if (runtime->IsActiveTransaction()) {
652 InitPeer<true>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority);
653 } else {
654 InitPeer<false>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority);
655 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700656 peer_thread_name.Assign(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700657 }
Elliott Hughes225f5a12012-06-11 11:23:48 -0700658 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700659 if (peer_thread_name.Get() != nullptr) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800660 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700661 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700662}
663
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100664template<bool kTransactionActive>
665void Thread::InitPeer(ScopedObjectAccess& soa, jboolean thread_is_daemon, jobject thread_group,
666 jobject thread_name, jint thread_priority) {
667 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700668 SetBoolean<kTransactionActive>(tlsPtr_.opeer, thread_is_daemon);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100669 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700670 SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_group));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100671 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700672 SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_name));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100673 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700674 SetInt<kTransactionActive>(tlsPtr_.opeer, thread_priority);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100675}
676
Elliott Hughes899e7892012-01-24 14:57:32 -0800677void Thread::SetThreadName(const char* name) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700678 tlsPtr_.name->assign(name);
Elliott Hughes899e7892012-01-24 14:57:32 -0800679 ::art::SetThreadName(name);
680 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
681}
682
Ian Rogersf4d4da12014-11-11 16:10:33 -0800683bool Thread::InitStackHwm() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700684 void* read_stack_base;
685 size_t read_stack_size;
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700686 size_t read_guard_size;
687 GetThreadStack(tlsPtr_.pthread_self, &read_stack_base, &read_stack_size, &read_guard_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700688
Ian Rogers13735952014-10-08 12:43:28 -0700689 tlsPtr_.stack_begin = reinterpret_cast<uint8_t*>(read_stack_base);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700690 tlsPtr_.stack_size = read_stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -0700691
Dave Allison648d7112014-07-25 16:15:27 -0700692 // The minimum stack size we can cope with is the overflow reserved bytes (typically
693 // 8K) + the protected region size (4K) + another page (4K). Typically this will
694 // be 8+4+4 = 16K. The thread won't be able to do much with this stack even the GC takes
695 // between 8K and 12K.
696 uint32_t min_stack = GetStackOverflowReservedBytes(kRuntimeISA) + kStackOverflowProtectedSize
697 + 4 * KB;
698 if (read_stack_size <= min_stack) {
Ian Rogersf4d4da12014-11-11 16:10:33 -0800699 // Note, as we know the stack is small, avoid operations that could use a lot of stack.
700 LogMessage::LogLineLowStack(__PRETTY_FUNCTION__, __LINE__, ERROR,
701 "Attempt to attach a thread with a too-small stack");
702 return false;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700703 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700704
Vladimir Markob8f2f632015-01-02 14:23:26 +0000705 // This is included in the SIGQUIT output, but it's useful here for thread debugging.
706 VLOG(threads) << StringPrintf("Native stack is at %p (%s with %s guard)",
707 read_stack_base,
708 PrettySize(read_stack_size).c_str(),
709 PrettySize(read_guard_size).c_str());
710
Ian Rogers932746a2011-09-22 18:57:50 -0700711 // Set stack_end_ to the bottom of the stack saving space of stack overflows
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700712
713 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800714 bool implicit_stack_check = !runtime->ExplicitStackOverflowChecks() && !runtime->IsAotCompiler();
Dave Allisonb090a182014-08-14 17:02:48 +0000715 ResetDefaultStackEnd();
Dave Allisonf9439142014-03-27 15:10:22 -0700716
717 // Install the protected region if we are doing implicit overflow checks.
718 if (implicit_stack_check) {
Dave Allison648d7112014-07-25 16:15:27 -0700719 // The thread might have protected region at the bottom. We need
720 // to install our own region so we need to move the limits
721 // of the stack to make room for it.
Dave Allison216cf232014-08-18 15:49:51 -0700722
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700723 tlsPtr_.stack_begin += read_guard_size + kStackOverflowProtectedSize;
724 tlsPtr_.stack_end += read_guard_size + kStackOverflowProtectedSize;
725 tlsPtr_.stack_size -= read_guard_size;
Dave Allison648d7112014-07-25 16:15:27 -0700726
727 InstallImplicitProtection();
Dave Allisonf9439142014-03-27 15:10:22 -0700728 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700729
730 // Sanity check.
731 int stack_variable;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700732 CHECK_GT(&stack_variable, reinterpret_cast<void*>(tlsPtr_.stack_end));
Ian Rogersf4d4da12014-11-11 16:10:33 -0800733
734 return true;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700735}
736
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700737void Thread::ShortDump(std::ostream& os) const {
738 os << "Thread[";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700739 if (GetThreadId() != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700740 // If we're in kStarting, we won't have a thin lock id or tid yet.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700741 os << GetThreadId()
Mathieu Chartierb28412e2015-04-24 15:28:36 -0700742 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -0700743 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700744 os << GetState()
Mathieu Chartierb28412e2015-04-24 15:28:36 -0700745 << ",Thread*=" << this
746 << ",peer=" << tlsPtr_.opeer
747 << ",\"" << (tlsPtr_.name != nullptr ? *tlsPtr_.name : "null") << "\""
748 << "]";
Elliott Hughesa0957642011-09-02 14:27:33 -0700749}
750
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700751void Thread::Dump(std::ostream& os) const {
752 DumpState(os);
753 DumpStack(os);
754}
755
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700756mirror::String* Thread::GetThreadName(const ScopedObjectAccessAlreadyRunnable& soa) const {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700757 ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700758 return (tlsPtr_.opeer != nullptr) ?
759 reinterpret_cast<mirror::String*>(f->GetObject(tlsPtr_.opeer)) : nullptr;
Elliott Hughesfc861622011-10-17 17:57:47 -0700760}
761
Elliott Hughesffb465f2012-03-01 18:46:05 -0800762void Thread::GetThreadName(std::string& name) const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700763 name.assign(*tlsPtr_.name);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800764}
765
Jeff Hao57dac6e2013-08-15 16:36:24 -0700766uint64_t Thread::GetCpuMicroTime() const {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800767#if defined(__linux__)
Jeff Hao57dac6e2013-08-15 16:36:24 -0700768 clockid_t cpu_clock_id;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700769 pthread_getcpuclockid(tlsPtr_.pthread_self, &cpu_clock_id);
Jeff Hao57dac6e2013-08-15 16:36:24 -0700770 timespec now;
771 clock_gettime(cpu_clock_id, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700772 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughes0a18df82015-01-09 15:16:16 -0800773#else // __APPLE__
Jeff Hao57dac6e2013-08-15 16:36:24 -0700774 UNIMPLEMENTED(WARNING);
775 return -1;
776#endif
777}
778
Ian Rogers01ae5802012-09-28 16:14:01 -0700779// Attempt to rectify locks so that we dump thread list with required locks before exiting.
780static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers120f1c72012-09-28 17:17:10 -0700781 LOG(ERROR) << *thread << " suspend count already zero.";
Ian Rogers01ae5802012-09-28 16:14:01 -0700782 Locks::thread_suspend_count_lock_->Unlock(self);
783 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
784 Locks::mutator_lock_->SharedTryLock(self);
785 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
786 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
787 }
788 }
789 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
790 Locks::thread_list_lock_->TryLock(self);
791 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
792 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
793 }
794 }
795 std::ostringstream ss;
Ian Rogers7b078e82014-09-10 14:44:24 -0700796 Runtime::Current()->GetThreadList()->Dump(ss);
Ian Rogers120f1c72012-09-28 17:17:10 -0700797 LOG(FATAL) << ss.str();
Ian Rogers01ae5802012-09-28 16:14:01 -0700798}
799
800void Thread::ModifySuspendCount(Thread* self, int delta, bool for_debugger) {
Ian Rogers2966e132014-04-02 08:34:36 -0700801 if (kIsDebugBuild) {
802 DCHECK(delta == -1 || delta == +1 || delta == -tls32_.debug_suspend_count)
803 << delta << " " << tls32_.debug_suspend_count << " " << this;
804 DCHECK_GE(tls32_.suspend_count, tls32_.debug_suspend_count) << this;
805 Locks::thread_suspend_count_lock_->AssertHeld(self);
806 if (this != self && !IsSuspended()) {
807 Locks::thread_list_lock_->AssertHeld(self);
808 }
Ian Rogerscfaa4552012-11-26 21:00:08 -0800809 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700810 if (UNLIKELY(delta < 0 && tls32_.suspend_count <= 0)) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700811 UnsafeLogFatalForSuspendCount(self, this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700812 return;
813 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700814
Ian Rogersdd7624d2014-03-14 17:43:00 -0700815 tls32_.suspend_count += delta;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700816 if (for_debugger) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700817 tls32_.debug_suspend_count += delta;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700818 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700819
Ian Rogersdd7624d2014-03-14 17:43:00 -0700820 if (tls32_.suspend_count == 0) {
Ian Rogers474b6da2012-09-25 00:20:38 -0700821 AtomicClearFlag(kSuspendRequest);
822 } else {
823 AtomicSetFlag(kSuspendRequest);
Dave Allisonb373e092014-02-20 16:06:36 -0800824 TriggerSuspend();
Ian Rogers474b6da2012-09-25 00:20:38 -0700825 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700826}
827
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700828void Thread::RunCheckpointFunction() {
Dave Allison0aded082013-11-07 13:15:11 -0800829 Closure *checkpoints[kMaxCheckpoints];
830
831 // Grab the suspend_count lock and copy the current set of
832 // checkpoints. Then clear the list and the flag. The RequestCheckpoint
833 // function will also grab this lock so we prevent a race between setting
834 // the kCheckpointRequest flag and clearing it.
835 {
836 MutexLock mu(this, *Locks::thread_suspend_count_lock_);
837 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700838 checkpoints[i] = tlsPtr_.checkpoint_functions[i];
839 tlsPtr_.checkpoint_functions[i] = nullptr;
Dave Allison0aded082013-11-07 13:15:11 -0800840 }
841 AtomicClearFlag(kCheckpointRequest);
842 }
843
844 // Outside the lock, run all the checkpoint functions that
845 // we collected.
846 bool found_checkpoint = false;
847 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
848 if (checkpoints[i] != nullptr) {
849 ATRACE_BEGIN("Checkpoint function");
850 checkpoints[i]->Run(this);
851 ATRACE_END();
852 found_checkpoint = true;
853 }
854 }
855 CHECK(found_checkpoint);
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700856}
857
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700858bool Thread::RequestCheckpoint(Closure* function) {
Chris Dearman59cde532013-12-04 18:53:49 -0800859 union StateAndFlags old_state_and_flags;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700860 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700861 if (old_state_and_flags.as_struct.state != kRunnable) {
862 return false; // Fail, thread is suspended and so can't run a checkpoint.
863 }
Dave Allison0aded082013-11-07 13:15:11 -0800864
865 uint32_t available_checkpoint = kMaxCheckpoints;
866 for (uint32_t i = 0 ; i < kMaxCheckpoints; ++i) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700867 if (tlsPtr_.checkpoint_functions[i] == nullptr) {
Dave Allison0aded082013-11-07 13:15:11 -0800868 available_checkpoint = i;
869 break;
870 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700871 }
Dave Allison0aded082013-11-07 13:15:11 -0800872 if (available_checkpoint == kMaxCheckpoints) {
873 // No checkpoint functions available, we can't run a checkpoint
874 return false;
875 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700876 tlsPtr_.checkpoint_functions[available_checkpoint] = function;
Dave Allison0aded082013-11-07 13:15:11 -0800877
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700878 // Checkpoint function installed now install flag bit.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700879 // We must be runnable to request a checkpoint.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800880 DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable);
Chris Dearman59cde532013-12-04 18:53:49 -0800881 union StateAndFlags new_state_and_flags;
882 new_state_and_flags.as_int = old_state_and_flags.as_int;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700883 new_state_and_flags.as_struct.flags |= kCheckpointRequest;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700884 bool success = tls32_.state_and_flags.as_atomic_int.CompareExchangeStrongSequentiallyConsistent(
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700885 old_state_and_flags.as_int, new_state_and_flags.as_int);
Ian Rogers8c1b5f72014-07-09 22:02:36 -0700886 if (UNLIKELY(!success)) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700887 // The thread changed state before the checkpoint was installed.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700888 CHECK_EQ(tlsPtr_.checkpoint_functions[available_checkpoint], function);
889 tlsPtr_.checkpoint_functions[available_checkpoint] = nullptr;
Dave Allison0aded082013-11-07 13:15:11 -0800890 } else {
891 CHECK_EQ(ReadFlag(kCheckpointRequest), true);
Dave Allisonb373e092014-02-20 16:06:36 -0800892 TriggerSuspend();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700893 }
Ian Rogers8c1b5f72014-07-09 22:02:36 -0700894 return success;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700895}
896
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800897Closure* Thread::GetFlipFunction() {
898 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
899 Closure* func;
900 do {
901 func = atomic_func->LoadRelaxed();
902 if (func == nullptr) {
903 return nullptr;
904 }
905 } while (!atomic_func->CompareExchangeWeakSequentiallyConsistent(func, nullptr));
906 DCHECK(func != nullptr);
907 return func;
908}
909
910void Thread::SetFlipFunction(Closure* function) {
911 CHECK(function != nullptr);
912 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
913 atomic_func->StoreSequentiallyConsistent(function);
914}
915
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700916void Thread::FullSuspendCheck() {
917 VLOG(threads) << this << " self-suspending";
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700918 ATRACE_BEGIN("Full suspend check");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700919 // Make thread appear suspended to other threads, release mutator_lock_.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800920 tls32_.suspended_at_suspend_check = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700921 TransitionFromRunnableToSuspended(kSuspended);
922 // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
923 TransitionFromSuspendedToRunnable();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800924 tls32_.suspended_at_suspend_check = false;
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700925 ATRACE_END();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700926 VLOG(threads) << this << " self-reviving";
927}
928
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700929void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700930 std::string group_name;
931 int priority;
932 bool is_daemon = false;
Ian Rogers81d425b2012-09-27 16:03:43 -0700933 Thread* self = Thread::Current();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700934
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800935 // If flip_function is not null, it means we have run a checkpoint
936 // before the thread wakes up to execute the flip function and the
937 // thread roots haven't been forwarded. So the following access to
938 // the roots (opeer or methods in the frames) would be bad. Run it
939 // here. TODO: clean up.
940 if (thread != nullptr) {
941 ScopedObjectAccessUnchecked soa(self);
942 Thread* this_thread = const_cast<Thread*>(thread);
943 Closure* flip_func = this_thread->GetFlipFunction();
944 if (flip_func != nullptr) {
945 flip_func->Run(this_thread);
946 }
947 }
948
Mathieu Chartierc7a966d2014-04-10 18:06:32 -0700949 // Don't do this if we are aborting since the GC may have all the threads suspended. This will
950 // cause ScopedObjectAccessUnchecked to deadlock.
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000951 if (gAborting == 0 && self != nullptr && thread != nullptr && thread->tlsPtr_.opeer != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800952 ScopedObjectAccessUnchecked soa(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700953 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)
954 ->GetInt(thread->tlsPtr_.opeer);
955 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)
956 ->GetBoolean(thread->tlsPtr_.opeer);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700957
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800958 mirror::Object* thread_group =
Ian Rogersdd7624d2014-03-14 17:43:00 -0700959 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(thread->tlsPtr_.opeer);
Ian Rogers120f1c72012-09-28 17:17:10 -0700960
Dave Allison0aded082013-11-07 13:15:11 -0800961 if (thread_group != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700962 ArtField* group_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800963 soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
964 mirror::String* group_name_string =
965 reinterpret_cast<mirror::String*>(group_name_field->GetObject(thread_group));
Dave Allison0aded082013-11-07 13:15:11 -0800966 group_name = (group_name_string != nullptr) ? group_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughesd369bb72011-09-12 14:41:14 -0700967 }
968 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700969 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700970 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700971
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700972 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700973 if (scheduler_group_name.empty()) {
974 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700975 }
976
Dave Allison0aded082013-11-07 13:15:11 -0800977 if (thread != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700978 os << '"' << *thread->tlsPtr_.name << '"';
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700979 if (is_daemon) {
980 os << " daemon";
981 }
982 os << " prio=" << priority
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700983 << " tid=" << thread->GetThreadId()
Elliott Hughes80537bb2013-01-04 16:37:26 -0800984 << " " << thread->GetState();
985 if (thread->IsStillStarting()) {
986 os << " (still starting up)";
987 }
988 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700989 } else {
Elliott Hughes289be852012-06-12 13:57:20 -0700990 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700991 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700992 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700993 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700994
Dave Allison0aded082013-11-07 13:15:11 -0800995 if (thread != nullptr) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700996 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700997 os << " | group=\"" << group_name << "\""
Ian Rogersdd7624d2014-03-14 17:43:00 -0700998 << " sCount=" << thread->tls32_.suspend_count
999 << " dsCount=" << thread->tls32_.debug_suspend_count
1000 << " obj=" << reinterpret_cast<void*>(thread->tlsPtr_.opeer)
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001001 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
1002 }
Elliott Hughes0d39c122012-06-06 16:41:17 -07001003
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001004 os << " | sysTid=" << tid
1005 << " nice=" << getpriority(PRIO_PROCESS, tid)
Elliott Hughes0d39c122012-06-06 16:41:17 -07001006 << " cgrp=" << scheduler_group_name;
Dave Allison0aded082013-11-07 13:15:11 -08001007 if (thread != nullptr) {
Elliott Hughes0d39c122012-06-06 16:41:17 -07001008 int policy;
1009 sched_param sp;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001010 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->tlsPtr_.pthread_self, &policy, &sp),
1011 __FUNCTION__);
Elliott Hughes0d39c122012-06-06 16:41:17 -07001012 os << " sched=" << policy << "/" << sp.sched_priority
Ian Rogersdd7624d2014-03-14 17:43:00 -07001013 << " handle=" << reinterpret_cast<void*>(thread->tlsPtr_.pthread_self);
Elliott Hughes0d39c122012-06-06 16:41:17 -07001014 }
1015 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -07001016
1017 // Grab the scheduler stats for this thread.
1018 std::string scheduler_stats;
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001019 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001020 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
Elliott Hughesd92bec42011-09-02 17:04:36 -07001021 } else {
1022 scheduler_stats = "0 0 0";
1023 }
1024
Elliott Hughesba0b9c52012-09-20 11:25:12 -07001025 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -07001026 int utime = 0;
1027 int stime = 0;
1028 int task_cpu = 0;
Brian Carlstrom29212012013-09-12 22:18:30 -07001029 GetTaskStats(tid, &native_thread_state, &utime, &stime, &task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -07001030
Elliott Hughesba0b9c52012-09-20 11:25:12 -07001031 os << " | state=" << native_thread_state
1032 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -07001033 << " utm=" << utime
1034 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001035 << " core=" << task_cpu
1036 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
Dave Allison0aded082013-11-07 13:15:11 -08001037 if (thread != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001038 os << " | stack=" << reinterpret_cast<void*>(thread->tlsPtr_.stack_begin) << "-"
1039 << reinterpret_cast<void*>(thread->tlsPtr_.stack_end) << " stackSize="
1040 << PrettySize(thread->tlsPtr_.stack_size) << "\n";
Mathieu Chartier9db911e2014-06-04 11:23:58 -07001041 // Dump the held mutexes.
1042 os << " | held mutexes=";
1043 for (size_t i = 0; i < kLockLevelCount; ++i) {
1044 if (i != kMonitorLock) {
1045 BaseMutex* mutex = thread->GetHeldMutex(static_cast<LockLevel>(i));
1046 if (mutex != nullptr) {
1047 os << " \"" << mutex->GetName() << "\"";
1048 if (mutex->IsReaderWriterMutex()) {
1049 ReaderWriterMutex* rw_mutex = down_cast<ReaderWriterMutex*>(mutex);
Ian Rogersa9d8c4c2014-07-07 21:38:36 -07001050 if (rw_mutex->GetExclusiveOwnerTid() == static_cast<uint64_t>(tid)) {
Mathieu Chartier9db911e2014-06-04 11:23:58 -07001051 os << "(exclusive held)";
1052 } else {
Mathieu Chartier9db911e2014-06-04 11:23:58 -07001053 os << "(shared held)";
1054 }
1055 }
1056 }
1057 }
1058 }
1059 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001060 }
1061}
1062
1063void Thread::DumpState(std::ostream& os) const {
1064 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -07001065}
1066
Ian Rogers0399dde2012-06-06 17:09:28 -07001067struct StackDumpVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001068 StackDumpVisitor(std::ostream& os_in, Thread* thread_in, Context* context, bool can_allocate_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001069 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001070 : StackVisitor(thread_in, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
1071 os(os_in),
1072 thread(thread_in),
1073 can_allocate(can_allocate_in),
1074 last_method(nullptr),
1075 last_line_number(0),
1076 repetition_count(0),
1077 frame_count(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001078
Ian Rogersbdb03912011-09-14 00:55:44 -07001079 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -07001080 if (frame_count == 0) {
1081 os << " (no managed stack frames)\n";
1082 }
Elliott Hughesd369bb72011-09-12 14:41:14 -07001083 }
1084
Ian Rogersb726dcb2012-09-05 08:57:23 -07001085 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001086 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001087 if (m->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001088 return true;
Ian Rogers90865722011-09-19 11:11:44 -07001089 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07001090 const int kMaxRepetition = 3;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001091 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001092 mirror::DexCache* dex_cache = c->GetDexCache();
Ian Rogersb861dc02011-11-14 17:00:05 -08001093 int line_number = -1;
Dave Allison0aded082013-11-07 13:15:11 -08001094 if (dex_cache != nullptr) { // be tolerant of bad input
Ian Rogers4445a7e2012-10-05 17:19:13 -07001095 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001096 line_number = dex_file.GetLineNumFromPC(m, GetDexPc(false));
Ian Rogersb861dc02011-11-14 17:00:05 -08001097 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07001098 if (line_number == last_line_number && last_method == m) {
Dave Allison0aded082013-11-07 13:15:11 -08001099 ++repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -07001100 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001101 if (repetition_count >= kMaxRepetition) {
1102 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
1103 }
1104 repetition_count = 0;
1105 last_line_number = line_number;
1106 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -07001107 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07001108 if (repetition_count < kMaxRepetition) {
1109 os << " at " << PrettyMethod(m, false);
1110 if (m->IsNative()) {
1111 os << "(Native method)";
1112 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001113 const char* source_file(m->GetDeclaringClassSourceFile());
Dave Allison0aded082013-11-07 13:15:11 -08001114 os << "(" << (source_file != nullptr ? source_file : "unavailable")
Brian Carlstrom2e450bf2013-09-06 15:39:46 -07001115 << ":" << line_number << ")";
Ian Rogers28ad40d2011-10-27 15:19:26 -07001116 }
1117 os << "\n";
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001118 if (frame_count == 0) {
1119 Monitor::DescribeWait(os, thread);
1120 }
1121 if (can_allocate) {
Andreas Gampe956a5222014-08-16 13:41:10 -07001122 // Visit locks, but do not abort on errors. This would trigger a nested abort.
1123 Monitor::VisitLocks(this, DumpLockedObject, &os, false);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001124 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07001125 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001126
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001127 ++frame_count;
Elliott Hughes530fa002012-03-12 11:44:49 -07001128 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -07001129 }
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001130
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001131 static void DumpLockedObject(mirror::Object* o, void* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001132 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1133 std::ostream& os = *reinterpret_cast<std::ostream*>(context);
Ian Rogersd803bc72014-04-01 15:33:03 -07001134 os << " - locked ";
1135 if (o == nullptr) {
1136 os << "an unknown object";
1137 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001138 if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07001139 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1140 // Getting the identity hashcode here would result in lock inflation and suspension of the
1141 // current thread, which isn't safe if this is the only runnable thread.
1142 os << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)", reinterpret_cast<intptr_t>(o),
1143 PrettyTypeOf(o).c_str());
1144 } else {
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001145 // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
1146 // we get the pretty type beofre we call IdentityHashCode.
1147 const std::string pretty_type(PrettyTypeOf(o));
1148 os << StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001149 }
1150 }
1151 os << "\n";
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001152 }
1153
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001154 std::ostream& os;
1155 const Thread* thread;
Ian Rogers0878d652013-04-18 17:38:35 -07001156 const bool can_allocate;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001157 ArtMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -07001158 int last_line_number;
1159 int repetition_count;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001160 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -07001161};
1162
Ian Rogers33e95662013-05-20 20:29:14 -07001163static bool ShouldShowNativeStack(const Thread* thread)
1164 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaef701d2013-04-05 18:15:40 -07001165 ThreadState state = thread->GetState();
1166
1167 // In native code somewhere in the VM (one of the kWaitingFor* states)? That's interesting.
1168 if (state > kWaiting && state < kStarting) {
1169 return true;
1170 }
1171
1172 // In an Object.wait variant or Thread.sleep? That's not interesting.
1173 if (state == kTimedWaiting || state == kSleeping || state == kWaiting) {
1174 return false;
1175 }
1176
Christopher Ferris2366f4e2014-09-19 17:23:59 -07001177 // Threads with no managed stack frames should be shown.
1178 const ManagedStack* managed_stack = thread->GetManagedStack();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001179 if (managed_stack == nullptr || (managed_stack->GetTopQuickFrame() == nullptr &&
1180 managed_stack->GetTopShadowFrame() == nullptr)) {
Christopher Ferris2366f4e2014-09-19 17:23:59 -07001181 return true;
1182 }
1183
Elliott Hughesaef701d2013-04-05 18:15:40 -07001184 // In some other native method? That's interesting.
1185 // We don't just check kNative because native methods will be in state kSuspended if they're
1186 // calling back into the VM, or kBlocked if they're blocked on a monitor, or one of the
1187 // thread-startup states if it's early enough in their life cycle (http://b/7432159).
Mathieu Chartiere401d142015-04-22 13:56:20 -07001188 ArtMethod* current_method = thread->GetCurrentMethod(nullptr);
Dave Allison0aded082013-11-07 13:15:11 -08001189 return current_method != nullptr && current_method->IsNative();
Elliott Hughesaef701d2013-04-05 18:15:40 -07001190}
1191
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001192void Thread::DumpJavaStack(std::ostream& os) const {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001193 // If flip_function is not null, it means we have run a checkpoint
1194 // before the thread wakes up to execute the flip function and the
1195 // thread roots haven't been forwarded. So the following access to
1196 // the roots (locks or methods in the frames) would be bad. Run it
1197 // here. TODO: clean up.
1198 {
1199 Thread* this_thread = const_cast<Thread*>(this);
1200 Closure* flip_func = this_thread->GetFlipFunction();
1201 if (flip_func != nullptr) {
1202 flip_func->Run(this_thread);
1203 }
1204 }
1205
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001206 // Dumping the Java stack involves the verifier for locks. The verifier operates under the
1207 // assumption that there is no exception pending on entry. Thus, stash any pending exception.
Mathieu Chartierbef89c92015-01-09 09:46:49 -08001208 // Thread::Current() instead of this in case a thread is dumping the stack of another suspended
1209 // thread.
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001210 StackHandleScope<1> scope(Thread::Current());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001211 Handle<mirror::Throwable> exc;
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001212 bool have_exception = false;
1213 if (IsExceptionPending()) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001214 exc = scope.NewHandle(GetException());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001215 const_cast<Thread*>(this)->ClearException();
1216 have_exception = true;
1217 }
1218
Ian Rogers700a4022014-05-19 16:49:03 -07001219 std::unique_ptr<Context> context(Context::Create());
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001220 StackDumpVisitor dumper(os, const_cast<Thread*>(this), context.get(),
1221 !tls32_.throwing_OutOfMemoryError);
1222 dumper.WalkStack();
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001223
1224 if (have_exception) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001225 const_cast<Thread*>(this)->SetException(exc.Get());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001226 }
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001227}
1228
Elliott Hughesd92bec42011-09-02 17:04:36 -07001229void Thread::DumpStack(std::ostream& os) const {
Jeff Haoed1790e2013-04-12 09:58:14 -07001230 // TODO: we call this code when dying but may not have suspended the thread ourself. The
1231 // IsSuspended check is therefore racy with the use for dumping (normally we inhibit
1232 // the race with the thread_suspend_count_lock_).
Ian Rogerseef2e542014-06-24 22:48:01 -07001233 bool dump_for_abort = (gAborting > 0);
1234 bool safe_to_dump = (this == Thread::Current() || IsSuspended());
1235 if (!kIsDebugBuild) {
1236 // We always want to dump the stack for an abort, however, there is no point dumping another
1237 // thread's stack in debug builds where we'll hit the not suspended check in the stack walk.
1238 safe_to_dump = (safe_to_dump || dump_for_abort);
1239 }
1240 if (safe_to_dump) {
Ian Rogersf08e4732013-04-09 09:45:49 -07001241 // If we're currently in native code, dump that stack before dumping the managed stack.
Ian Rogersd090cf42013-06-06 15:35:18 -07001242 if (dump_for_abort || ShouldShowNativeStack(this)) {
Ian Rogersf08e4732013-04-09 09:45:49 -07001243 DumpKernelStack(os, GetTid(), " kernel: ", false);
Andreas Gampeb2f5dbb2014-09-16 15:15:13 -07001244 DumpNativeStack(os, GetTid(), " native: ", GetCurrentMethod(nullptr, !dump_for_abort));
Ian Rogersf08e4732013-04-09 09:45:49 -07001245 }
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001246 DumpJavaStack(os);
Ian Rogersf08e4732013-04-09 09:45:49 -07001247 } else {
1248 os << "Not able to dump stack of thread that isn't suspended";
Elliott Hughesffb465f2012-03-01 18:46:05 -08001249 }
Elliott Hughese27955c2011-08-26 15:21:24 -07001250}
1251
Elliott Hughesbe759c62011-09-08 19:38:21 -07001252void Thread::ThreadExitCallback(void* arg) {
1253 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001254 if (self->tls32_.thread_exit_check_count == 0) {
1255 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's "
1256 "going to use a pthread_key_create destructor?): " << *self;
Ian Rogers0878d652013-04-18 17:38:35 -07001257 CHECK(is_started_);
Elliott Hughes6a607ad2012-07-13 20:40:00 -07001258 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
Ian Rogersdd7624d2014-03-14 17:43:00 -07001259 self->tls32_.thread_exit_check_count = 1;
Elliott Hughes6a607ad2012-07-13 20:40:00 -07001260 } else {
1261 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
1262 }
Carl Shapirob5573532011-07-12 18:22:59 -07001263}
1264
Elliott Hughesbe759c62011-09-08 19:38:21 -07001265void Thread::Startup() {
Ian Rogers0878d652013-04-18 17:38:35 -07001266 CHECK(!is_started_);
1267 is_started_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001268 {
Brian Carlstrom6d69f592013-07-16 17:18:16 -07001269 // MutexLock to keep annotalysis happy.
1270 //
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001271 // Note we use null for the thread because Thread::Current can
Brian Carlstrom6d69f592013-07-16 17:18:16 -07001272 // return garbage since (is_started_ == true) and
1273 // Thread::pthread_key_self_ is not yet initialized.
1274 // This was seen on glibc.
Dave Allison0aded082013-11-07 13:15:11 -08001275 MutexLock mu(nullptr, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07001276 resume_cond_ = new ConditionVariable("Thread resumption condition variable",
1277 *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001278 }
1279
Carl Shapirob5573532011-07-12 18:22:59 -07001280 // Allocate a TLS slot.
Ian Rogersf4d4da12014-11-11 16:10:33 -08001281 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback),
1282 "self key");
Carl Shapirob5573532011-07-12 18:22:59 -07001283
1284 // Double-check the TLS slot allocation.
Dave Allison0aded082013-11-07 13:15:11 -08001285 if (pthread_getspecific(pthread_key_self_) != nullptr) {
1286 LOG(FATAL) << "Newly-created pthread TLS slot is not nullptr";
Carl Shapirob5573532011-07-12 18:22:59 -07001287 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001288}
Carl Shapirob5573532011-07-12 18:22:59 -07001289
Elliott Hughes038a8062011-09-18 14:12:41 -07001290void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -07001291 Runtime* runtime = Runtime::Current();
1292 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -07001293
Elliott Hughes01158d72011-09-19 19:47:10 -07001294 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001295 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -07001296 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -05001297
Elliott Hughesaf8d15a2012-05-29 09:12:18 -07001298 Runtime::Current()->GetClassLinker()->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -07001299}
1300
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001301void Thread::Shutdown() {
Ian Rogers0878d652013-04-18 17:38:35 -07001302 CHECK(is_started_);
1303 is_started_ = false;
Elliott Hughes8d768a92011-09-14 16:35:25 -07001304 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Ian Rogers33e95662013-05-20 20:29:14 -07001305 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -08001306 if (resume_cond_ != nullptr) {
Ian Rogers0878d652013-04-18 17:38:35 -07001307 delete resume_cond_;
Dave Allison0aded082013-11-07 13:15:11 -08001308 resume_cond_ = nullptr;
Ian Rogers0878d652013-04-18 17:38:35 -07001309 }
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001310}
1311
Ian Rogersdd7624d2014-03-14 17:43:00 -07001312Thread::Thread(bool daemon) : tls32_(daemon), wait_monitor_(nullptr), interrupted_(false) {
1313 wait_mutex_ = new Mutex("a thread wait mutex");
1314 wait_cond_ = new ConditionVariable("a thread wait condition variable", *wait_mutex_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001315 tlsPtr_.instrumentation_stack = new std::deque<instrumentation::InstrumentationStackFrame>;
1316 tlsPtr_.name = new std::string(kThreadNameDuringStartup);
Dave Allison8ce6b902014-08-26 11:07:58 -07001317 tlsPtr_.nested_signal_state = static_cast<jmp_buf*>(malloc(sizeof(jmp_buf)));
Ian Rogersdd7624d2014-03-14 17:43:00 -07001318
Roland Levillain33d69032015-06-18 18:20:59 +01001319 static_assert((sizeof(Thread) % 4) == 0U,
1320 "art::Thread has a size which is not a multiple of 4.");
Ian Rogersdd7624d2014-03-14 17:43:00 -07001321 tls32_.state_and_flags.as_struct.flags = 0;
1322 tls32_.state_and_flags.as_struct.state = kNative;
1323 memset(&tlsPtr_.held_mutexes[0], 0, sizeof(tlsPtr_.held_mutexes));
Mathieu Chartier0651d412014-04-29 14:37:57 -07001324 std::fill(tlsPtr_.rosalloc_runs,
Ian Rogerse63db272014-07-15 15:36:11 -07001325 tlsPtr_.rosalloc_runs + kNumRosAllocThreadLocalSizeBrackets,
Mathieu Chartier73d1e172014-04-11 17:53:48 -07001326 gc::allocator::RosAlloc::GetDedicatedFullRun());
Dave Allison0aded082013-11-07 13:15:11 -08001327 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001328 tlsPtr_.checkpoint_functions[i] = nullptr;
Dave Allison0aded082013-11-07 13:15:11 -08001329 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001330 tlsPtr_.flip_function = nullptr;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001331 tlsPtr_.thread_local_mark_stack = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001332 tls32_.suspended_at_suspend_check = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001333}
1334
Elliott Hughes7dc51662012-05-16 14:48:43 -07001335bool Thread::IsStillStarting() const {
1336 // You might think you can check whether the state is kStarting, but for much of thread startup,
Elliott Hughes80537bb2013-01-04 16:37:26 -08001337 // the thread is in kNative; it might also be in kVmWait.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001338 // 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 -07001339 // assigned fairly early on, and needs to be.
1340 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
1341 // this thread _ever_ entered kRunnable".
Ian Rogersdd7624d2014-03-14 17:43:00 -07001342 return (tlsPtr_.jpeer == nullptr && tlsPtr_.opeer == nullptr) ||
1343 (*tlsPtr_.name == kThreadNameDuringStartup);
Elliott Hughes7dc51662012-05-16 14:48:43 -07001344}
1345
Andreas Gamped9efea62014-07-21 22:56:08 -07001346void Thread::AssertPendingException() const {
Mathieu Chartiera61894d2015-04-23 16:32:54 -07001347 CHECK(IsExceptionPending()) << "Pending exception expected.";
1348}
1349
1350void Thread::AssertPendingOOMException() const {
1351 AssertPendingException();
1352 auto* e = GetException();
1353 CHECK_EQ(e->GetClass(), DecodeJObject(WellKnownClasses::java_lang_OutOfMemoryError)->AsClass())
1354 << e->Dump();
Andreas Gamped9efea62014-07-21 22:56:08 -07001355}
1356
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001357void Thread::AssertNoPendingException() const {
1358 if (UNLIKELY(IsExceptionPending())) {
1359 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001360 mirror::Throwable* exception = GetException();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001361 LOG(FATAL) << "No pending exception expected: " << exception->Dump();
1362 }
1363}
1364
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001365void Thread::AssertNoPendingExceptionForNewException(const char* msg) const {
1366 if (UNLIKELY(IsExceptionPending())) {
1367 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001368 mirror::Throwable* exception = GetException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07001369 LOG(FATAL) << "Throwing new exception '" << msg << "' with unexpected pending exception: "
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001370 << exception->Dump();
1371 }
1372}
1373
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001374class MonitorExitVisitor : public SingleRootVisitor {
1375 public:
1376 explicit MonitorExitVisitor(Thread* self) : self_(self) { }
1377
1378 // NO_THREAD_SAFETY_ANALYSIS due to MonitorExit.
1379 void VisitRoot(mirror::Object* entered_monitor, const RootInfo& info ATTRIBUTE_UNUSED)
1380 OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1381 if (self_->HoldsLock(entered_monitor)) {
1382 LOG(WARNING) << "Calling MonitorExit on object "
1383 << entered_monitor << " (" << PrettyTypeOf(entered_monitor) << ")"
1384 << " left locked by native thread "
1385 << *Thread::Current() << " which is detaching";
1386 entered_monitor->MonitorExit(self_);
1387 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001388 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001389
1390 private:
1391 Thread* const self_;
1392};
Elliott Hughes02b48d12011-09-07 17:15:51 -07001393
Elliott Hughesc0f09332012-03-26 13:27:06 -07001394void Thread::Destroy() {
Ian Rogers120f1c72012-09-28 17:17:10 -07001395 Thread* self = this;
1396 DCHECK_EQ(self, Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07001397
Ian Rogers68d8b422014-07-17 11:09:10 -07001398 if (tlsPtr_.jni_env != nullptr) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001399 {
1400 ScopedObjectAccess soa(self);
1401 MonitorExitVisitor visitor(self);
1402 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
1403 tlsPtr_.jni_env->monitors.VisitRoots(&visitor, RootInfo(kRootVMInternal));
1404 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001405 // Release locally held global references which releasing may require the mutator lock.
1406 if (tlsPtr_.jpeer != nullptr) {
1407 // If pthread_create fails we don't have a jni env here.
1408 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.jpeer);
1409 tlsPtr_.jpeer = nullptr;
1410 }
1411 if (tlsPtr_.class_loader_override != nullptr) {
1412 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.class_loader_override);
1413 tlsPtr_.class_loader_override = nullptr;
1414 }
1415 }
1416
Ian Rogersdd7624d2014-03-14 17:43:00 -07001417 if (tlsPtr_.opeer != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001418 ScopedObjectAccess soa(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001419 // We may need to call user-supplied managed code, do this before final clean-up.
Ian Rogerscfaa4552012-11-26 21:00:08 -08001420 HandleUncaughtExceptions(soa);
1421 RemoveFromThreadGroup(soa);
Elliott Hughes534da072012-03-27 15:17:42 -07001422
Anwar Ghuloum3c50a4b2013-06-21 13:05:23 -07001423 // this.nativePeer = 0;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001424 if (Runtime::Current()->IsActiveTransaction()) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001425 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer)
1426 ->SetLong<true>(tlsPtr_.opeer, 0);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001427 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001428 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer)
1429 ->SetLong<false>(tlsPtr_.opeer, 0);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001430 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001431 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001432
Ian Rogerscfaa4552012-11-26 21:00:08 -08001433 // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone
1434 // who is waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001435 mirror::Object* lock =
Ian Rogersdd7624d2014-03-14 17:43:00 -07001436 soa.DecodeField(WellKnownClasses::java_lang_Thread_lock)->GetObject(tlsPtr_.opeer);
Elliott Hughes038a8062011-09-18 14:12:41 -07001437 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001438 if (lock != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001439 StackHandleScope<1> hs(self);
1440 Handle<mirror::Object> h_obj(hs.NewHandle(lock));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001441 ObjectLock<mirror::Object> locker(self, h_obj);
Yevgeny Rouban63e8a682014-04-16 18:26:09 +07001442 locker.NotifyAll();
Elliott Hughes5f791332011-09-15 17:45:30 -07001443 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001444 tlsPtr_.opeer = nullptr;
Elliott Hughes5f791332011-09-15 17:45:30 -07001445 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001446
Hiroshi Yamauchia1b94c62014-12-17 15:49:56 -08001447 {
1448 ScopedObjectAccess soa(self);
1449 Runtime::Current()->GetHeap()->RevokeThreadLocalBuffers(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001450 if (kUseReadBarrier) {
1451 Runtime::Current()->GetHeap()->ConcurrentCopyingCollector()->RevokeThreadLocalMarkStack(this);
1452 }
Hiroshi Yamauchia1b94c62014-12-17 15:49:56 -08001453 }
Elliott Hughesc0f09332012-03-26 13:27:06 -07001454}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001455
Elliott Hughesc0f09332012-03-26 13:27:06 -07001456Thread::~Thread() {
Ian Rogers68d8b422014-07-17 11:09:10 -07001457 CHECK(tlsPtr_.class_loader_override == nullptr);
1458 CHECK(tlsPtr_.jpeer == nullptr);
1459 CHECK(tlsPtr_.opeer == nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001460 bool initialized = (tlsPtr_.jni_env != nullptr); // Did Thread::Init run?
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001461 if (initialized) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001462 delete tlsPtr_.jni_env;
1463 tlsPtr_.jni_env = nullptr;
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001464 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001465 CHECK_NE(GetState(), kRunnable);
Dave Allison0aded082013-11-07 13:15:11 -08001466 CHECK_NE(ReadFlag(kCheckpointRequest), true);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001467 CHECK(tlsPtr_.checkpoint_functions[0] == nullptr);
1468 CHECK(tlsPtr_.checkpoint_functions[1] == nullptr);
1469 CHECK(tlsPtr_.checkpoint_functions[2] == nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001470 CHECK(tlsPtr_.flip_function == nullptr);
1471 CHECK_EQ(tls32_.suspended_at_suspend_check, false);
Dave Allison0aded082013-11-07 13:15:11 -08001472
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001473 // We may be deleting a still born thread.
1474 SetStateUnsafe(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001475
1476 delete wait_cond_;
1477 delete wait_mutex_;
1478
Ian Rogersdd7624d2014-03-14 17:43:00 -07001479 if (tlsPtr_.long_jump_context != nullptr) {
1480 delete tlsPtr_.long_jump_context;
Ian Rogersc928de92013-02-27 14:30:44 -08001481 }
Elliott Hughes475fc232011-10-25 15:00:35 -07001482
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001483 if (initialized) {
1484 CleanupCpu();
1485 }
1486
Sebastien Hertz597c4f02015-01-26 17:37:14 +01001487 if (tlsPtr_.single_step_control != nullptr) {
1488 delete tlsPtr_.single_step_control;
1489 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001490 delete tlsPtr_.instrumentation_stack;
1491 delete tlsPtr_.name;
1492 delete tlsPtr_.stack_trace_sample;
Dave Allison8ce6b902014-08-26 11:07:58 -07001493 free(tlsPtr_.nested_signal_state);
Elliott Hughesd8af1592012-04-16 20:40:15 -07001494
Ian Rogers68d8b422014-07-17 11:09:10 -07001495 Runtime::Current()->GetHeap()->AssertThreadLocalBuffersAreRevoked(this);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001496
Elliott Hughesd8af1592012-04-16 20:40:15 -07001497 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001498}
1499
Ian Rogerscfaa4552012-11-26 21:00:08 -08001500void Thread::HandleUncaughtExceptions(ScopedObjectAccess& soa) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001501 if (!IsExceptionPending()) {
1502 return;
1503 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001504 ScopedLocalRef<jobject> peer(tlsPtr_.jni_env, soa.AddLocalReference<jobject>(tlsPtr_.opeer));
Ian Rogerscfaa4552012-11-26 21:00:08 -08001505 ScopedThreadStateChange tsc(this, kNative);
Ian Rogers120f1c72012-09-28 17:17:10 -07001506
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001507 // Get and clear the exception.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001508 ScopedLocalRef<jthrowable> exception(tlsPtr_.jni_env, tlsPtr_.jni_env->ExceptionOccurred());
1509 tlsPtr_.jni_env->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001510
1511 // If the thread has its own handler, use that.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001512 ScopedLocalRef<jobject> handler(tlsPtr_.jni_env,
1513 tlsPtr_.jni_env->GetObjectField(peer.get(),
1514 WellKnownClasses::java_lang_Thread_uncaughtHandler));
Dave Allison0aded082013-11-07 13:15:11 -08001515 if (handler.get() == nullptr) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001516 // Otherwise use the thread group's default handler.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001517 handler.reset(tlsPtr_.jni_env->GetObjectField(peer.get(),
1518 WellKnownClasses::java_lang_Thread_group));
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001519 }
1520
1521 // Call the handler.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001522 tlsPtr_.jni_env->CallVoidMethod(handler.get(),
Andreas Gampec8ccf682014-09-29 20:07:43 -07001523 WellKnownClasses::java_lang_Thread__UncaughtExceptionHandler_uncaughtException,
Ian Rogersdd7624d2014-03-14 17:43:00 -07001524 peer.get(), exception.get());
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001525
1526 // If the handler threw, clear that exception too.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001527 tlsPtr_.jni_env->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001528}
1529
Ian Rogerscfaa4552012-11-26 21:00:08 -08001530void Thread::RemoveFromThreadGroup(ScopedObjectAccess& soa) {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001531 // this.group.removeThread(this);
1532 // group can be null if we're in the compiler or a test.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001533 mirror::Object* ogroup = soa.DecodeField(WellKnownClasses::java_lang_Thread_group)
1534 ->GetObject(tlsPtr_.opeer);
Dave Allison0aded082013-11-07 13:15:11 -08001535 if (ogroup != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001536 ScopedLocalRef<jobject> group(soa.Env(), soa.AddLocalReference<jobject>(ogroup));
Ian Rogersdd7624d2014-03-14 17:43:00 -07001537 ScopedLocalRef<jobject> peer(soa.Env(), soa.AddLocalReference<jobject>(tlsPtr_.opeer));
Ian Rogerscfaa4552012-11-26 21:00:08 -08001538 ScopedThreadStateChange tsc(soa.Self(), kNative);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001539 tlsPtr_.jni_env->CallVoidMethod(group.get(),
1540 WellKnownClasses::java_lang_ThreadGroup_removeThread,
1541 peer.get());
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001542 }
1543}
1544
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001545size_t Thread::NumHandleReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001546 size_t count = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001547 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur != nullptr; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001548 count += cur->NumberOfReferences();
1549 }
1550 return count;
1551}
1552
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001553bool Thread::HandleScopeContains(jobject obj) const {
1554 StackReference<mirror::Object>* hs_entry =
Ian Rogersef7d42f2014-01-06 12:55:46 -08001555 reinterpret_cast<StackReference<mirror::Object>*>(obj);
Ian Rogersc0542af2014-09-03 16:16:56 -07001556 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur!= nullptr; cur = cur->GetLink()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001557 if (cur->Contains(hs_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001558 return true;
1559 }
1560 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001561 // JNI code invoked from portable code uses shadow frames rather than the handle scope.
1562 return tlsPtr_.managed_stack.ShadowFramesContain(hs_entry);
TDYa12728f1a142012-03-15 21:51:52 -07001563}
1564
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001565void Thread::HandleScopeVisitRoots(RootVisitor* visitor, uint32_t thread_id) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001566 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
1567 visitor, RootInfo(kRootNativeStack, thread_id));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001568 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur; cur = cur->GetLink()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001569 for (size_t j = 0, count = cur->NumberOfReferences(); j < count; ++j) {
Mathieu Chartier9086b652015-04-14 09:35:18 -07001570 // GetReference returns a pointer to the stack reference within the handle scope. If this
1571 // needs to be updated, it will be done by the root visitor.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001572 buffered_visitor.VisitRootIfNonNull(cur->GetHandle(j).GetReference());
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001573 }
1574 }
1575}
1576
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001577mirror::Object* Thread::DecodeJObject(jobject obj) const {
Dave Allison0aded082013-11-07 13:15:11 -08001578 if (obj == nullptr) {
1579 return nullptr;
Ian Rogers408f79a2011-08-23 18:22:33 -07001580 }
1581 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1582 IndirectRefKind kind = GetIndirectRefKind(ref);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001583 mirror::Object* result;
Ian Rogersc0542af2014-09-03 16:16:56 -07001584 bool expect_null = false;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001585 // The "kinds" below are sorted by the frequency we expect to encounter them.
1586 if (kind == kLocal) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001587 IndirectReferenceTable& locals = tlsPtr_.jni_env->locals;
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -07001588 // Local references do not need a read barrier.
1589 result = locals.Get<kWithoutReadBarrier>(ref);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001590 } else if (kind == kHandleScopeOrInvalid) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001591 // TODO: make stack indirect reference table lookup more efficient.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001592 // Check if this is a local reference in the handle scope.
1593 if (LIKELY(HandleScopeContains(obj))) {
1594 // Read from handle scope.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001595 result = reinterpret_cast<StackReference<mirror::Object>*>(obj)->AsMirrorPtr();
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08001596 VerifyObject(result);
Ian Rogers408f79a2011-08-23 18:22:33 -07001597 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -07001598 tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of invalid jobject %p", obj);
1599 expect_null = true;
1600 result = nullptr;
Ian Rogers408f79a2011-08-23 18:22:33 -07001601 }
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001602 } else if (kind == kGlobal) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001603 result = tlsPtr_.jni_env->vm->DecodeGlobal(const_cast<Thread*>(this), ref);
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001604 } else {
1605 DCHECK_EQ(kind, kWeakGlobal);
Ian Rogers68d8b422014-07-17 11:09:10 -07001606 result = tlsPtr_.jni_env->vm->DecodeWeakGlobal(const_cast<Thread*>(this), ref);
Ian Rogersc0542af2014-09-03 16:16:56 -07001607 if (Runtime::Current()->IsClearedJniWeakGlobal(result)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001608 // This is a special case where it's okay to return null.
Ian Rogersc0542af2014-09-03 16:16:56 -07001609 expect_null = true;
1610 result = nullptr;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001611 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001612 }
1613
Ian Rogersc0542af2014-09-03 16:16:56 -07001614 if (UNLIKELY(!expect_null && result == nullptr)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001615 tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of deleted %s %p",
1616 ToStr<IndirectRefKind>(kind).c_str(), obj);
Ian Rogers408f79a2011-08-23 18:22:33 -07001617 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001618 return result;
1619}
1620
Ian Rogers81d425b2012-09-27 16:03:43 -07001621// Implements java.lang.Thread.interrupted.
1622bool Thread::Interrupted() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001623 MutexLock mu(Thread::Current(), *wait_mutex_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001624 bool interrupted = IsInterruptedLocked();
1625 SetInterruptedLocked(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001626 return interrupted;
1627}
1628
1629// Implements java.lang.Thread.isInterrupted.
1630bool Thread::IsInterrupted() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001631 MutexLock mu(Thread::Current(), *wait_mutex_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001632 return IsInterruptedLocked();
Ian Rogers81d425b2012-09-27 16:03:43 -07001633}
1634
Ian Rogersdd7624d2014-03-14 17:43:00 -07001635void Thread::Interrupt(Thread* self) {
Ian Rogersc604d732012-10-14 16:09:54 -07001636 MutexLock mu(self, *wait_mutex_);
Ian Rogers81d425b2012-09-27 16:03:43 -07001637 if (interrupted_) {
1638 return;
1639 }
1640 interrupted_ = true;
Ian Rogersc604d732012-10-14 16:09:54 -07001641 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001642}
1643
1644void Thread::Notify() {
Ian Rogersc604d732012-10-14 16:09:54 -07001645 Thread* self = Thread::Current();
1646 MutexLock mu(self, *wait_mutex_);
1647 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001648}
1649
Ian Rogersc604d732012-10-14 16:09:54 -07001650void Thread::NotifyLocked(Thread* self) {
Dave Allison0aded082013-11-07 13:15:11 -08001651 if (wait_monitor_ != nullptr) {
Ian Rogersc604d732012-10-14 16:09:54 -07001652 wait_cond_->Signal(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001653 }
1654}
1655
Ian Rogers68d8b422014-07-17 11:09:10 -07001656void Thread::SetClassLoaderOverride(jobject class_loader_override) {
1657 if (tlsPtr_.class_loader_override != nullptr) {
1658 GetJniEnv()->DeleteGlobalRef(tlsPtr_.class_loader_override);
1659 }
1660 tlsPtr_.class_loader_override = GetJniEnv()->NewGlobalRef(class_loader_override);
1661}
1662
Ian Rogers0399dde2012-06-06 17:09:28 -07001663class CountStackDepthVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001664 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001665 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001666 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001667 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001668 depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001669
Ian Rogersb726dcb2012-09-05 08:57:23 -07001670 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001671 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001672 // Note we also skip the frame if it doesn't have a method (namely the callee
1673 // save frame)
Mathieu Chartiere401d142015-04-22 13:56:20 -07001674 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001675 if (skipping_ && !m->IsRuntimeMethod() &&
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001676 !mirror::Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001677 skipping_ = false;
1678 }
1679 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001680 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001681 ++depth_;
1682 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001683 } else {
1684 ++skip_depth_;
1685 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001686 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001687 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001688
1689 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001690 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001691 }
1692
Elliott Hughes29f27422011-09-18 16:02:18 -07001693 int GetSkipDepth() const {
1694 return skip_depth_;
1695 }
1696
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001697 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001698 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001699 uint32_t skip_depth_;
1700 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001701};
1702
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001703template<bool kTransactionActive>
Ian Rogers0399dde2012-06-06 17:09:28 -07001704class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001705 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001706 explicit BuildInternalStackTraceVisitor(Thread* self, Thread* thread, int skip_depth)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01001707 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
1708 self_(self),
1709 skip_depth_(skip_depth),
1710 count_(0),
Mathieu Chartiere401d142015-04-22 13:56:20 -07001711 trace_(nullptr),
1712 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08001713
Ian Rogers1f539342012-10-03 21:09:42 -07001714 bool Init(int depth)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001715 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Sebastien Hertz415fd082015-06-01 11:42:27 +02001716 // Allocate method trace with format [method pointers][pcs].
Mathieu Chartiere401d142015-04-22 13:56:20 -07001717 auto* cl = Runtime::Current()->GetClassLinker();
1718 trace_ = cl->AllocPointerArray(self_, depth * 2);
1719 if (trace_ == nullptr) {
1720 self_->AssertPendingOOMException();
Ian Rogers283ed0d2012-02-16 15:25:09 -08001721 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001722 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001723 // If We are called from native, use non-transactional mode.
Ian Rogers52673ff2012-06-27 23:25:34 -07001724 const char* last_no_suspend_cause =
Ian Rogers1f539342012-10-03 21:09:42 -07001725 self_->StartAssertNoThreadSuspension("Building internal stack trace");
Dave Allison0aded082013-11-07 13:15:11 -08001726 CHECK(last_no_suspend_cause == nullptr) << last_no_suspend_cause;
Ian Rogers283ed0d2012-02-16 15:25:09 -08001727 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001728 }
1729
Ian Rogers0399dde2012-06-06 17:09:28 -07001730 virtual ~BuildInternalStackTraceVisitor() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001731 if (trace_ != nullptr) {
Dave Allison0aded082013-11-07 13:15:11 -08001732 self_->EndAssertNoThreadSuspension(nullptr);
Ian Rogers52673ff2012-06-27 23:25:34 -07001733 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001734 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001735
Ian Rogersb726dcb2012-09-05 08:57:23 -07001736 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001737 if (trace_ == nullptr) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001738 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001739 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001740 if (skip_depth_ > 0) {
1741 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001742 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001743 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001744 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001745 if (m->IsRuntimeMethod()) {
1746 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001747 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001748 trace_->SetElementPtrSize<kTransactionActive>(
1749 count_, m, pointer_size_);
1750 trace_->SetElementPtrSize<kTransactionActive>(
1751 trace_->GetLength() / 2 + count_, m->IsProxyMethod() ? DexFile::kDexNoIndex : GetDexPc(),
1752 pointer_size_);
Ian Rogersaaa20802011-09-11 21:47:37 -07001753 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001754 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001755 }
1756
Mathieu Chartiere401d142015-04-22 13:56:20 -07001757 mirror::PointerArray* GetInternalStackTrace() const {
1758 return trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001759 }
1760
1761 private:
Ian Rogers1f539342012-10-03 21:09:42 -07001762 Thread* const self_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001763 // How many more frames to skip.
1764 int32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001765 // Current position down stack trace.
Ian Rogersaaa20802011-09-11 21:47:37 -07001766 uint32_t count_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001767 // An array of the methods on the stack, the last entries are the dex PCs.
1768 mirror::PointerArray* trace_;
1769 // For cross compilation.
1770 size_t pointer_size_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001771};
1772
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001773template<bool kTransactionActive>
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07001774jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001775 // Compute depth of stack
Ian Rogers7a22fa62013-01-23 12:16:16 -08001776 CountStackDepthVisitor count_visitor(const_cast<Thread*>(this));
Ian Rogers0399dde2012-06-06 17:09:28 -07001777 count_visitor.WalkStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001778 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001779 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001780
Ian Rogers1f539342012-10-03 21:09:42 -07001781 // Build internal stack trace.
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001782 BuildInternalStackTraceVisitor<kTransactionActive> build_trace_visitor(soa.Self(),
1783 const_cast<Thread*>(this),
1784 skip_depth);
Ian Rogers1f539342012-10-03 21:09:42 -07001785 if (!build_trace_visitor.Init(depth)) {
Dave Allison0aded082013-11-07 13:15:11 -08001786 return nullptr; // Allocation failed.
Ian Rogers283ed0d2012-02-16 15:25:09 -08001787 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001788 build_trace_visitor.WalkStack();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001789 mirror::PointerArray* trace = build_trace_visitor.GetInternalStackTrace();
Ian Rogers7a22fa62013-01-23 12:16:16 -08001790 if (kIsDebugBuild) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001791 // Second half is dex PCs.
1792 for (uint32_t i = 0; i < static_cast<uint32_t>(trace->GetLength() / 2); ++i) {
1793 auto* method = trace->GetElementPtrSize<ArtMethod*>(
1794 i, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
1795 CHECK(method != nullptr);
Ian Rogers7a22fa62013-01-23 12:16:16 -08001796 }
1797 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001798 return soa.AddLocalReference<jobject>(trace);
Ian Rogersaaa20802011-09-11 21:47:37 -07001799}
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07001800template jobject Thread::CreateInternalStackTrace<false>(
1801 const ScopedObjectAccessAlreadyRunnable& soa) const;
1802template jobject Thread::CreateInternalStackTrace<true>(
1803 const ScopedObjectAccessAlreadyRunnable& soa) const;
Ian Rogersaaa20802011-09-11 21:47:37 -07001804
Nicolas Geoffray7642cfc2015-02-26 10:56:09 +00001805bool Thread::IsExceptionThrownByCurrentMethod(mirror::Throwable* exception) const {
1806 CountStackDepthVisitor count_visitor(const_cast<Thread*>(this));
1807 count_visitor.WalkStack();
1808 return count_visitor.GetDepth() == exception->GetStackDepth();
1809}
1810
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07001811jobjectArray Thread::InternalStackTraceToStackTraceElementArray(
1812 const ScopedObjectAccessAlreadyRunnable& soa, jobject internal, jobjectArray output_array,
1813 int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001814 // Decode the internal stack trace into the depth, method trace and PC trace
Mathieu Chartiere401d142015-04-22 13:56:20 -07001815 int32_t depth = soa.Decode<mirror::PointerArray*>(internal)->GetLength() / 2;
Ian Rogersaaa20802011-09-11 21:47:37 -07001816
Mathieu Chartiere401d142015-04-22 13:56:20 -07001817 auto* cl = Runtime::Current()->GetClassLinker();
Ian Rogersaaa20802011-09-11 21:47:37 -07001818
Elliott Hughes01158d72011-09-19 19:47:10 -07001819 jobjectArray result;
Mathieu Chartier530825b2013-09-25 17:56:49 -07001820
Dave Allison0aded082013-11-07 13:15:11 -08001821 if (output_array != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07001822 // Reuse the array we were given.
1823 result = output_array;
Elliott Hughes01158d72011-09-19 19:47:10 -07001824 // ...adjusting the number of frames we'll write to not exceed the array length.
Mathieu Chartier530825b2013-09-25 17:56:49 -07001825 const int32_t traces_length =
1826 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->GetLength();
1827 depth = std::min(depth, traces_length);
Elliott Hughes01158d72011-09-19 19:47:10 -07001828 } else {
1829 // Create java_trace array and place in local reference table
Mathieu Chartier530825b2013-09-25 17:56:49 -07001830 mirror::ObjectArray<mirror::StackTraceElement>* java_traces =
Mathieu Chartiere401d142015-04-22 13:56:20 -07001831 cl->AllocStackTraceElementArray(soa.Self(), depth);
Dave Allison0aded082013-11-07 13:15:11 -08001832 if (java_traces == nullptr) {
1833 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001834 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001835 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07001836 }
1837
Dave Allison0aded082013-11-07 13:15:11 -08001838 if (stack_depth != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07001839 *stack_depth = depth;
1840 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001841
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001842 for (int32_t i = 0; i < depth; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001843 auto* method_trace = soa.Decode<mirror::PointerArray*>(internal);
Ian Rogersaaa20802011-09-11 21:47:37 -07001844 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Mathieu Chartiere401d142015-04-22 13:56:20 -07001845 ArtMethod* method = method_trace->GetElementPtrSize<ArtMethod*>(i, sizeof(void*));
1846 uint32_t dex_pc = method_trace->GetElementPtrSize<uint32_t>(
1847 i + method_trace->GetLength() / 2, sizeof(void*));
Jeff Hao228d6b82013-12-03 15:00:05 -08001848 int32_t line_number;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001849 StackHandleScope<3> hs(soa.Self());
1850 auto class_name_object(hs.NewHandle<mirror::String>(nullptr));
1851 auto source_name_object(hs.NewHandle<mirror::String>(nullptr));
Jeff Hao228d6b82013-12-03 15:00:05 -08001852 if (method->IsProxyMethod()) {
1853 line_number = -1;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001854 class_name_object.Assign(method->GetDeclaringClass()->GetName());
Jeff Hao228d6b82013-12-03 15:00:05 -08001855 // source_name_object intentionally left null for proxy methods
1856 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001857 line_number = method->GetLineNumFromDexPC(dex_pc);
Jeff Hao228d6b82013-12-03 15:00:05 -08001858 // Allocate element, potentially triggering GC
1859 // TODO: reuse class_name_object via Class::name_?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001860 const char* descriptor = method->GetDeclaringClassDescriptor();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001861 CHECK(descriptor != nullptr);
Jeff Hao228d6b82013-12-03 15:00:05 -08001862 std::string class_name(PrettyDescriptor(descriptor));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001863 class_name_object.Assign(
1864 mirror::String::AllocFromModifiedUtf8(soa.Self(), class_name.c_str()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001865 if (class_name_object.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001866 soa.Self()->AssertPendingOOMException();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001867 return nullptr;
Jeff Hao228d6b82013-12-03 15:00:05 -08001868 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001869 const char* source_file = method->GetDeclaringClassSourceFile();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001870 if (source_file != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001871 source_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), source_file));
1872 if (source_name_object.Get() == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001873 soa.Self()->AssertPendingOOMException();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001874 return nullptr;
1875 }
Jeff Hao228d6b82013-12-03 15:00:05 -08001876 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001877 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001878 const char* method_name = method->GetInterfaceMethodIfProxy(sizeof(void*))->GetName();
Dave Allison0aded082013-11-07 13:15:11 -08001879 CHECK(method_name != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001880 Handle<mirror::String> method_name_object(
1881 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), method_name)));
1882 if (method_name_object.Get() == nullptr) {
Dave Allison0aded082013-11-07 13:15:11 -08001883 return nullptr;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001884 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001885 mirror::StackTraceElement* obj = mirror::StackTraceElement::Alloc(
1886 soa.Self(), class_name_object, method_name_object, source_name_object, line_number);
Dave Allison0aded082013-11-07 13:15:11 -08001887 if (obj == nullptr) {
1888 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001889 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001890 // We are called from native: use non-transactional mode.
1891 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->Set<false>(i, obj);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001892 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001893 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001894}
1895
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001896void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001897 va_list args;
1898 va_start(args, fmt);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001899 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001900 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001901}
1902
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001903void Thread::ThrowNewExceptionV(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08001904 const char* fmt, va_list ap) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001905 std::string msg;
1906 StringAppendV(&msg, fmt, ap);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001907 ThrowNewException(exception_class_descriptor, msg.c_str());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001908}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001909
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001910void Thread::ThrowNewException(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08001911 const char* msg) {
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001912 // Callers should either clear or call ThrowNewWrappedException.
1913 AssertNoPendingExceptionForNewException(msg);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001914 ThrowNewWrappedException(exception_class_descriptor, msg);
Elliott Hughesa4f94742012-05-29 16:28:38 -07001915}
1916
Nicolas Geoffrayee077032015-03-09 14:56:37 +00001917static mirror::ClassLoader* GetCurrentClassLoader(Thread* self)
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001918 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001919 ArtMethod* method = self->GetCurrentMethod(nullptr);
Nicolas Geoffrayee077032015-03-09 14:56:37 +00001920 return method != nullptr
1921 ? method->GetDeclaringClass()->GetClassLoader()
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001922 : nullptr;
1923}
1924
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001925void Thread::ThrowNewWrappedException(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08001926 const char* msg) {
1927 DCHECK_EQ(this, Thread::Current());
Ian Rogers53b8b092014-03-13 23:45:53 -07001928 ScopedObjectAccessUnchecked soa(this);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001929 StackHandleScope<3> hs(soa.Self());
Nicolas Geoffrayee077032015-03-09 14:56:37 +00001930 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(GetCurrentClassLoader(soa.Self())));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001931 ScopedLocalRef<jobject> cause(GetJniEnv(), soa.AddLocalReference<jobject>(GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08001932 ClearException();
1933 Runtime* runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001934 auto* cl = runtime->GetClassLinker();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001935 Handle<mirror::Class> exception_class(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001936 hs.NewHandle(cl->FindClass(this, exception_class_descriptor, class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001937 if (UNLIKELY(exception_class.Get() == nullptr)) {
Elliott Hughes30646832011-10-13 16:59:46 -07001938 CHECK(IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08001939 LOG(ERROR) << "No exception class " << PrettyDescriptor(exception_class_descriptor);
Elliott Hughes30646832011-10-13 16:59:46 -07001940 return;
1941 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001942
Ian Rogers7b078e82014-09-10 14:44:24 -07001943 if (UNLIKELY(!runtime->GetClassLinker()->EnsureInitialized(soa.Self(), exception_class, true,
1944 true))) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001945 DCHECK(IsExceptionPending());
1946 return;
1947 }
1948 DCHECK(!runtime->IsStarted() || exception_class->IsThrowableClass());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001949 Handle<mirror::Throwable> exception(
1950 hs.NewHandle(down_cast<mirror::Throwable*>(exception_class->AllocObject(this))));
Ian Rogers62d6c772013-02-27 08:32:07 -08001951
Mathieu Chartier590fee92013-09-13 13:46:47 -07001952 // If we couldn't allocate the exception, throw the pre-allocated out of memory exception.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001953 if (exception.Get() == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001954 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001955 return;
1956 }
1957
Ian Rogers62d6c772013-02-27 08:32:07 -08001958 // Choose an appropriate constructor and set up the arguments.
1959 const char* signature;
Ian Rogers53b8b092014-03-13 23:45:53 -07001960 ScopedLocalRef<jstring> msg_string(GetJniEnv(), nullptr);
Dave Allison0aded082013-11-07 13:15:11 -08001961 if (msg != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001962 // Ensure we remember this and the method over the String allocation.
Ian Rogers53b8b092014-03-13 23:45:53 -07001963 msg_string.reset(
1964 soa.AddLocalReference<jstring>(mirror::String::AllocFromModifiedUtf8(this, msg)));
Dave Allison0aded082013-11-07 13:15:11 -08001965 if (UNLIKELY(msg_string.get() == nullptr)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001966 CHECK(IsExceptionPending()); // OOME.
1967 return;
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001968 }
Dave Allison0aded082013-11-07 13:15:11 -08001969 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001970 signature = "(Ljava/lang/String;)V";
1971 } else {
1972 signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V";
1973 }
1974 } else {
Dave Allison0aded082013-11-07 13:15:11 -08001975 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001976 signature = "()V";
1977 } else {
1978 signature = "(Ljava/lang/Throwable;)V";
1979 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001980 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001981 ArtMethod* exception_init_method =
1982 exception_class->FindDeclaredDirectMethod("<init>", signature, cl->GetImagePointerSize());
Ian Rogers62d6c772013-02-27 08:32:07 -08001983
Dave Allison0aded082013-11-07 13:15:11 -08001984 CHECK(exception_init_method != nullptr) << "No <init>" << signature << " in "
Ian Rogers62d6c772013-02-27 08:32:07 -08001985 << PrettyDescriptor(exception_class_descriptor);
1986
1987 if (UNLIKELY(!runtime->IsStarted())) {
1988 // Something is trying to throw an exception without a started runtime, which is the common
1989 // case in the compiler. We won't be able to invoke the constructor of the exception, so set
1990 // the exception fields directly.
Dave Allison0aded082013-11-07 13:15:11 -08001991 if (msg != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001992 exception->SetDetailMessage(down_cast<mirror::String*>(DecodeJObject(msg_string.get())));
Ian Rogers62d6c772013-02-27 08:32:07 -08001993 }
Dave Allison0aded082013-11-07 13:15:11 -08001994 if (cause.get() != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001995 exception->SetCause(down_cast<mirror::Throwable*>(DecodeJObject(cause.get())));
Ian Rogers62d6c772013-02-27 08:32:07 -08001996 }
Ian Rogersc45b8b52014-05-03 01:39:59 -07001997 ScopedLocalRef<jobject> trace(GetJniEnv(),
1998 Runtime::Current()->IsActiveTransaction()
1999 ? CreateInternalStackTrace<true>(soa)
2000 : CreateInternalStackTrace<false>(soa));
2001 if (trace.get() != nullptr) {
2002 exception->SetStackState(down_cast<mirror::Throwable*>(DecodeJObject(trace.get())));
2003 }
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002004 SetException(exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08002005 } else {
Ian Rogers53b8b092014-03-13 23:45:53 -07002006 jvalue jv_args[2];
2007 size_t i = 0;
2008
Dave Allison0aded082013-11-07 13:15:11 -08002009 if (msg != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07002010 jv_args[i].l = msg_string.get();
2011 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08002012 }
Dave Allison0aded082013-11-07 13:15:11 -08002013 if (cause.get() != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07002014 jv_args[i].l = cause.get();
2015 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08002016 }
Jeff Hao39b6c242015-05-19 20:30:23 -07002017 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(exception.Get()));
2018 InvokeWithJValues(soa, ref.get(), soa.EncodeMethod(exception_init_method), jv_args);
Ian Rogers62d6c772013-02-27 08:32:07 -08002019 if (LIKELY(!IsExceptionPending())) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002020 SetException(exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08002021 }
Elliott Hughes30646832011-10-13 16:59:46 -07002022 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07002023}
2024
Elliott Hughes2ced6a52011-10-16 18:44:48 -07002025void Thread::ThrowOutOfMemoryError(const char* msg) {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002026 LOG(WARNING) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
Ian Rogersdd7624d2014-03-14 17:43:00 -07002027 msg, (tls32_.throwing_OutOfMemoryError ? " (recursive case)" : ""));
Ian Rogersdd7624d2014-03-14 17:43:00 -07002028 if (!tls32_.throwing_OutOfMemoryError) {
2029 tls32_.throwing_OutOfMemoryError = true;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00002030 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002031 tls32_.throwing_OutOfMemoryError = false;
Elliott Hughes418dfe72011-10-06 18:56:27 -07002032 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002033 Dump(LOG(WARNING)); // The pre-allocated OOME has no stack, so help out and log one.
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002034 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Elliott Hughes418dfe72011-10-06 18:56:27 -07002035 }
Elliott Hughes79082e32011-08-25 12:07:32 -07002036}
2037
Elliott Hughes498508c2011-10-17 14:58:22 -07002038Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002039 return Thread::Current();
2040}
2041
2042void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002043 std::ostringstream ss;
2044 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08002045 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002046 // log to stderr for debugging command line processes
2047 std::cerr << str;
2048#ifdef HAVE_ANDROID_OS
2049 // log to logcat for debugging frameworks processes
2050 LOG(INFO) << str;
2051#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002052}
2053
Ian Rogersdd7624d2014-03-14 17:43:00 -07002054// Explicitly instantiate 32 and 64bit thread offset dumping support.
2055template void Thread::DumpThreadOffset<4>(std::ostream& os, uint32_t offset);
2056template void Thread::DumpThreadOffset<8>(std::ostream& os, uint32_t offset);
Elliott Hughes98e20172012-04-24 15:38:13 -07002057
Ian Rogersdd7624d2014-03-14 17:43:00 -07002058template<size_t ptr_size>
2059void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset) {
2060#define DO_THREAD_OFFSET(x, y) \
2061 if (offset == x.Uint32Value()) { \
2062 os << y; \
Brian Carlstromf69863b2013-07-17 21:53:13 -07002063 return; \
2064 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002065 DO_THREAD_OFFSET(ThreadFlagsOffset<ptr_size>(), "state_and_flags")
2066 DO_THREAD_OFFSET(CardTableOffset<ptr_size>(), "card_table")
2067 DO_THREAD_OFFSET(ExceptionOffset<ptr_size>(), "exception")
2068 DO_THREAD_OFFSET(PeerOffset<ptr_size>(), "peer");
2069 DO_THREAD_OFFSET(JniEnvOffset<ptr_size>(), "jni_env")
2070 DO_THREAD_OFFSET(SelfOffset<ptr_size>(), "self")
2071 DO_THREAD_OFFSET(StackEndOffset<ptr_size>(), "stack_end")
2072 DO_THREAD_OFFSET(ThinLockIdOffset<ptr_size>(), "thin_lock_thread_id")
2073 DO_THREAD_OFFSET(TopOfManagedStackOffset<ptr_size>(), "top_quick_frame_method")
Ian Rogersdd7624d2014-03-14 17:43:00 -07002074 DO_THREAD_OFFSET(TopShadowFrameOffset<ptr_size>(), "top_shadow_frame")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002075 DO_THREAD_OFFSET(TopHandleScopeOffset<ptr_size>(), "top_handle_scope")
Ian Rogersdd7624d2014-03-14 17:43:00 -07002076 DO_THREAD_OFFSET(ThreadSuspendTriggerOffset<ptr_size>(), "suspend_trigger")
Elliott Hughes28fa76d2012-04-09 17:31:46 -07002077#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07002078
Ian Rogersdd7624d2014-03-14 17:43:00 -07002079#define INTERPRETER_ENTRY_POINT_INFO(x) \
2080 if (INTERPRETER_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
2081 os << #x; \
2082 return; \
Elliott Hughes98e20172012-04-24 15:38:13 -07002083 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002084 INTERPRETER_ENTRY_POINT_INFO(pInterpreterToInterpreterBridge)
2085 INTERPRETER_ENTRY_POINT_INFO(pInterpreterToCompiledCodeBridge)
2086#undef INTERPRETER_ENTRY_POINT_INFO
2087
2088#define JNI_ENTRY_POINT_INFO(x) \
2089 if (JNI_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
2090 os << #x; \
2091 return; \
2092 }
2093 JNI_ENTRY_POINT_INFO(pDlsymLookup)
2094#undef JNI_ENTRY_POINT_INFO
2095
Ian Rogersdd7624d2014-03-14 17:43:00 -07002096#define QUICK_ENTRY_POINT_INFO(x) \
2097 if (QUICK_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
2098 os << #x; \
2099 return; \
2100 }
2101 QUICK_ENTRY_POINT_INFO(pAllocArray)
2102 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved)
2103 QUICK_ENTRY_POINT_INFO(pAllocArrayWithAccessCheck)
2104 QUICK_ENTRY_POINT_INFO(pAllocObject)
2105 QUICK_ENTRY_POINT_INFO(pAllocObjectResolved)
2106 QUICK_ENTRY_POINT_INFO(pAllocObjectInitialized)
2107 QUICK_ENTRY_POINT_INFO(pAllocObjectWithAccessCheck)
2108 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArray)
2109 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArrayWithAccessCheck)
Jeff Hao848f70a2014-01-15 13:49:50 -08002110 QUICK_ENTRY_POINT_INFO(pAllocStringFromBytes)
2111 QUICK_ENTRY_POINT_INFO(pAllocStringFromChars)
2112 QUICK_ENTRY_POINT_INFO(pAllocStringFromString)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002113 QUICK_ENTRY_POINT_INFO(pInstanceofNonTrivial)
2114 QUICK_ENTRY_POINT_INFO(pCheckCast)
2115 QUICK_ENTRY_POINT_INFO(pInitializeStaticStorage)
2116 QUICK_ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccess)
2117 QUICK_ENTRY_POINT_INFO(pInitializeType)
2118 QUICK_ENTRY_POINT_INFO(pResolveString)
Fred Shih37f05ef2014-07-16 18:38:08 -07002119 QUICK_ENTRY_POINT_INFO(pSet8Instance)
2120 QUICK_ENTRY_POINT_INFO(pSet8Static)
2121 QUICK_ENTRY_POINT_INFO(pSet16Instance)
2122 QUICK_ENTRY_POINT_INFO(pSet16Static)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002123 QUICK_ENTRY_POINT_INFO(pSet32Instance)
2124 QUICK_ENTRY_POINT_INFO(pSet32Static)
2125 QUICK_ENTRY_POINT_INFO(pSet64Instance)
2126 QUICK_ENTRY_POINT_INFO(pSet64Static)
2127 QUICK_ENTRY_POINT_INFO(pSetObjInstance)
2128 QUICK_ENTRY_POINT_INFO(pSetObjStatic)
Fred Shih37f05ef2014-07-16 18:38:08 -07002129 QUICK_ENTRY_POINT_INFO(pGetByteInstance)
2130 QUICK_ENTRY_POINT_INFO(pGetBooleanInstance)
2131 QUICK_ENTRY_POINT_INFO(pGetByteStatic)
2132 QUICK_ENTRY_POINT_INFO(pGetBooleanStatic)
2133 QUICK_ENTRY_POINT_INFO(pGetShortInstance)
2134 QUICK_ENTRY_POINT_INFO(pGetCharInstance)
2135 QUICK_ENTRY_POINT_INFO(pGetShortStatic)
2136 QUICK_ENTRY_POINT_INFO(pGetCharStatic)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002137 QUICK_ENTRY_POINT_INFO(pGet32Instance)
2138 QUICK_ENTRY_POINT_INFO(pGet32Static)
2139 QUICK_ENTRY_POINT_INFO(pGet64Instance)
2140 QUICK_ENTRY_POINT_INFO(pGet64Static)
2141 QUICK_ENTRY_POINT_INFO(pGetObjInstance)
2142 QUICK_ENTRY_POINT_INFO(pGetObjStatic)
2143 QUICK_ENTRY_POINT_INFO(pAputObjectWithNullAndBoundCheck)
2144 QUICK_ENTRY_POINT_INFO(pAputObjectWithBoundCheck)
2145 QUICK_ENTRY_POINT_INFO(pAputObject)
2146 QUICK_ENTRY_POINT_INFO(pHandleFillArrayData)
2147 QUICK_ENTRY_POINT_INFO(pJniMethodStart)
2148 QUICK_ENTRY_POINT_INFO(pJniMethodStartSynchronized)
2149 QUICK_ENTRY_POINT_INFO(pJniMethodEnd)
2150 QUICK_ENTRY_POINT_INFO(pJniMethodEndSynchronized)
2151 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReference)
2152 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized)
2153 QUICK_ENTRY_POINT_INFO(pQuickGenericJniTrampoline)
2154 QUICK_ENTRY_POINT_INFO(pLockObject)
2155 QUICK_ENTRY_POINT_INFO(pUnlockObject)
2156 QUICK_ENTRY_POINT_INFO(pCmpgDouble)
2157 QUICK_ENTRY_POINT_INFO(pCmpgFloat)
2158 QUICK_ENTRY_POINT_INFO(pCmplDouble)
2159 QUICK_ENTRY_POINT_INFO(pCmplFloat)
2160 QUICK_ENTRY_POINT_INFO(pFmod)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002161 QUICK_ENTRY_POINT_INFO(pL2d)
2162 QUICK_ENTRY_POINT_INFO(pFmodf)
2163 QUICK_ENTRY_POINT_INFO(pL2f)
2164 QUICK_ENTRY_POINT_INFO(pD2iz)
2165 QUICK_ENTRY_POINT_INFO(pF2iz)
2166 QUICK_ENTRY_POINT_INFO(pIdivmod)
2167 QUICK_ENTRY_POINT_INFO(pD2l)
2168 QUICK_ENTRY_POINT_INFO(pF2l)
2169 QUICK_ENTRY_POINT_INFO(pLdiv)
2170 QUICK_ENTRY_POINT_INFO(pLmod)
2171 QUICK_ENTRY_POINT_INFO(pLmul)
2172 QUICK_ENTRY_POINT_INFO(pShlLong)
2173 QUICK_ENTRY_POINT_INFO(pShrLong)
2174 QUICK_ENTRY_POINT_INFO(pUshrLong)
2175 QUICK_ENTRY_POINT_INFO(pIndexOf)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002176 QUICK_ENTRY_POINT_INFO(pStringCompareTo)
2177 QUICK_ENTRY_POINT_INFO(pMemcpy)
2178 QUICK_ENTRY_POINT_INFO(pQuickImtConflictTrampoline)
2179 QUICK_ENTRY_POINT_INFO(pQuickResolutionTrampoline)
2180 QUICK_ENTRY_POINT_INFO(pQuickToInterpreterBridge)
2181 QUICK_ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck)
2182 QUICK_ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck)
2183 QUICK_ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck)
2184 QUICK_ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck)
2185 QUICK_ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002186 QUICK_ENTRY_POINT_INFO(pTestSuspend)
2187 QUICK_ENTRY_POINT_INFO(pDeliverException)
2188 QUICK_ENTRY_POINT_INFO(pThrowArrayBounds)
2189 QUICK_ENTRY_POINT_INFO(pThrowDivZero)
2190 QUICK_ENTRY_POINT_INFO(pThrowNoSuchMethod)
2191 QUICK_ENTRY_POINT_INFO(pThrowNullPointer)
2192 QUICK_ENTRY_POINT_INFO(pThrowStackOverflow)
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07002193 QUICK_ENTRY_POINT_INFO(pDeoptimize)
Douglas Leungd9cb8ae2014-07-09 14:28:35 -07002194 QUICK_ENTRY_POINT_INFO(pA64Load)
2195 QUICK_ENTRY_POINT_INFO(pA64Store)
Jeff Hao848f70a2014-01-15 13:49:50 -08002196 QUICK_ENTRY_POINT_INFO(pNewEmptyString)
2197 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_B)
2198 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BI)
2199 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BII)
2200 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIII)
2201 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIIString)
2202 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BString)
2203 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIICharset)
2204 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BCharset)
2205 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_C)
2206 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_CII)
2207 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_IIC)
2208 QUICK_ENTRY_POINT_INFO(pNewStringFromCodePoints)
2209 QUICK_ENTRY_POINT_INFO(pNewStringFromString)
2210 QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuffer)
2211 QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuilder)
Hiroshi Yamauchi1cc71eb2015-05-07 10:47:27 -07002212 QUICK_ENTRY_POINT_INFO(pReadBarrierJni)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002213#undef QUICK_ENTRY_POINT_INFO
2214
Elliott Hughes98e20172012-04-24 15:38:13 -07002215 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07002216}
2217
jeffhao94d6df42012-11-26 16:02:12 -08002218void Thread::QuickDeliverException() {
Ian Rogers62d6c772013-02-27 08:32:07 -08002219 // Get exception from thread.
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002220 mirror::Throwable* exception = GetException();
Dave Allison0aded082013-11-07 13:15:11 -08002221 CHECK(exception != nullptr);
Ian Rogers28ad40d2011-10-27 15:19:26 -07002222 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08002223 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07002224 ClearException();
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002225 bool is_deoptimization = (exception == GetDeoptimizationException());
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002226 QuickExceptionHandler exception_handler(this, is_deoptimization);
2227 if (is_deoptimization) {
2228 exception_handler.DeoptimizeStack();
2229 } else {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002230 exception_handler.FindCatch(exception);
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002231 }
2232 exception_handler.UpdateInstrumentationStack();
2233 exception_handler.DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07002234}
2235
Ian Rogersbdb03912011-09-14 00:55:44 -07002236Context* Thread::GetLongJumpContext() {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002237 Context* result = tlsPtr_.long_jump_context;
Dave Allison0aded082013-11-07 13:15:11 -08002238 if (result == nullptr) {
Ian Rogersbdb03912011-09-14 00:55:44 -07002239 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07002240 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002241 tlsPtr_.long_jump_context = nullptr; // Avoid context being shared.
Mathieu Chartier67022432012-11-29 18:04:50 -08002242 result->Reset();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07002243 }
Ian Rogersbdb03912011-09-14 00:55:44 -07002244 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07002245}
2246
Andreas Gampe4a8c3fa2014-07-16 22:20:31 -07002247// Note: this visitor may return with a method set, but dex_pc_ being DexFile:kDexNoIndex. This is
2248// so we don't abort in a special situation (thinlocked monitor) when dumping the Java stack.
Ian Rogerse0dcd462014-03-08 15:21:04 -08002249struct CurrentMethodVisitor FINAL : public StackVisitor {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002250 CurrentMethodVisitor(Thread* thread, Context* context, bool abort_on_error)
Ian Rogers62d6c772013-02-27 08:32:07 -08002251 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002252 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2253 this_object_(nullptr),
2254 method_(nullptr),
2255 dex_pc_(0),
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002256 abort_on_error_(abort_on_error) {}
Ian Rogerse0dcd462014-03-08 15:21:04 -08002257 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002258 ArtMethod* m = GetMethod();
Ian Rogers62d6c772013-02-27 08:32:07 -08002259 if (m->IsRuntimeMethod()) {
2260 // Continue if this is a runtime method.
2261 return true;
Ian Rogers0399dde2012-06-06 17:09:28 -07002262 }
Dave Allison0aded082013-11-07 13:15:11 -08002263 if (context_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002264 this_object_ = GetThisObject();
2265 }
2266 method_ = m;
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002267 dex_pc_ = GetDexPc(abort_on_error_);
Ian Rogers62d6c772013-02-27 08:32:07 -08002268 return false;
2269 }
2270 mirror::Object* this_object_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002271 ArtMethod* method_;
Ian Rogers62d6c772013-02-27 08:32:07 -08002272 uint32_t dex_pc_;
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002273 const bool abort_on_error_;
Ian Rogers62d6c772013-02-27 08:32:07 -08002274};
Ian Rogers0399dde2012-06-06 17:09:28 -07002275
Mathieu Chartiere401d142015-04-22 13:56:20 -07002276ArtMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, bool abort_on_error) const {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002277 CurrentMethodVisitor visitor(const_cast<Thread*>(this), nullptr, abort_on_error);
Ian Rogers0399dde2012-06-06 17:09:28 -07002278 visitor.WalkStack(false);
Dave Allison0aded082013-11-07 13:15:11 -08002279 if (dex_pc != nullptr) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002280 *dex_pc = visitor.dex_pc_;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07002281 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002282 return visitor.method_;
jeffhao33dc7712011-11-09 17:54:24 -08002283}
2284
Ian Rogersdd7624d2014-03-14 17:43:00 -07002285bool Thread::HoldsLock(mirror::Object* object) const {
Dave Allison0aded082013-11-07 13:15:11 -08002286 if (object == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -07002287 return false;
2288 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002289 return object->GetLockOwnerThreadId() == GetThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07002290}
2291
Ian Rogers40e3bac2012-11-20 00:09:14 -08002292// RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor).
2293template <typename RootVisitor>
Ian Rogers0399dde2012-06-06 17:09:28 -07002294class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07002295 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002296 ReferenceMapVisitor(Thread* thread, Context* context, RootVisitor& visitor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002297 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002298 // We are visiting the references in compiled frames, so we do not need
2299 // to know the inlined frames.
2300 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kSkipInlinedFrames),
2301 visitor_(visitor) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07002302
Ian Rogersb726dcb2012-09-05 08:57:23 -07002303 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07002304 if (false) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002305 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
Sebastien Hertz714f1752014-04-28 15:03:08 +02002306 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07002307 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002308 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
Dave Allison0aded082013-11-07 13:15:11 -08002309 if (shadow_frame != nullptr) {
Sebastien Hertz714f1752014-04-28 15:03:08 +02002310 VisitShadowFrame(shadow_frame);
2311 } else {
2312 VisitQuickFrame();
2313 }
2314 return true;
2315 }
2316
2317 void VisitShadowFrame(ShadowFrame* shadow_frame) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002318 ArtMethod* m = shadow_frame->GetMethod();
Hiroshi Yamauchi92d1a662014-05-15 21:43:59 -07002319 DCHECK(m != nullptr);
Sebastien Hertz714f1752014-04-28 15:03:08 +02002320 size_t num_regs = shadow_frame->NumberOfVRegs();
2321 if (m->IsNative() || shadow_frame->HasReferenceArray()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002322 // handle scope for JNI or References for interpreter.
Sebastien Hertz714f1752014-04-28 15:03:08 +02002323 for (size_t reg = 0; reg < num_regs; ++reg) {
2324 mirror::Object* ref = shadow_frame->GetVRegReference(reg);
2325 if (ref != nullptr) {
2326 mirror::Object* new_ref = ref;
2327 visitor_(&new_ref, reg, this);
2328 if (new_ref != ref) {
2329 shadow_frame->SetVRegReference(reg, new_ref);
2330 }
2331 }
2332 }
2333 } else {
2334 // Java method.
2335 // Portable path use DexGcMap and store in Method.native_gc_map_.
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002336 const uint8_t* gc_map = m->GetNativeGcMap(sizeof(void*));
Sebastien Hertz714f1752014-04-28 15:03:08 +02002337 CHECK(gc_map != nullptr) << PrettyMethod(m);
2338 verifier::DexPcToReferenceMap dex_gc_map(gc_map);
2339 uint32_t dex_pc = shadow_frame->GetDexPC();
2340 const uint8_t* reg_bitmap = dex_gc_map.FindBitMap(dex_pc);
2341 DCHECK(reg_bitmap != nullptr);
2342 num_regs = std::min(dex_gc_map.RegWidth() * 8, num_regs);
2343 for (size_t reg = 0; reg < num_regs; ++reg) {
2344 if (TestBitmap(reg, reg_bitmap)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002345 mirror::Object* ref = shadow_frame->GetVRegReference(reg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002346 if (ref != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08002347 mirror::Object* new_ref = ref;
2348 visitor_(&new_ref, reg, this);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002349 if (new_ref != ref) {
Sebastien Hertz714f1752014-04-28 15:03:08 +02002350 shadow_frame->SetVRegReference(reg, new_ref);
TDYa127ce4cc0d2012-11-18 16:59:53 -08002351 }
2352 }
2353 }
2354 }
Sebastien Hertz714f1752014-04-28 15:03:08 +02002355 }
2356 }
2357
2358 private:
2359 void VisitQuickFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002360 auto* cur_quick_frame = GetCurrentQuickFrame();
2361 DCHECK(cur_quick_frame != nullptr);
2362 auto* m = *cur_quick_frame;
Andreas Gampecf4035a2014-05-28 22:43:01 -07002363
Sebastien Hertz714f1752014-04-28 15:03:08 +02002364 // Process register map (which native and runtime methods don't have)
2365 if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002366 if (m->IsOptimized(sizeof(void*))) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002367 auto* vreg_base = reinterpret_cast<StackReference<mirror::Object>*>(
2368 reinterpret_cast<uintptr_t>(cur_quick_frame));
Vladimir Marko4c1c5102014-05-14 16:51:16 +01002369 Runtime* runtime = Runtime::Current();
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002370 const void* entry_point = runtime->GetInstrumentation()->GetQuickCodeFor(m, sizeof(void*));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002371 uintptr_t native_pc_offset = m->NativeQuickPcOffset(GetCurrentQuickFramePc(), entry_point);
Nicolas Geoffray004c2302015-03-20 10:06:38 +00002372 CodeInfo code_info = m->GetOptimizedCodeInfo();
David Brazdilf677ebf2015-05-29 16:29:43 +01002373 StackMapEncoding encoding = code_info.ExtractEncoding();
2374 StackMap map = code_info.GetStackMapForNativePcOffset(native_pc_offset, encoding);
Nicolas Geoffraye12997f2015-05-22 14:01:33 +01002375 DCHECK(map.IsValid());
David Brazdilf677ebf2015-05-29 16:29:43 +01002376 MemoryRegion mask = map.GetStackMask(encoding);
Nicolas Geoffray98893962015-01-21 12:32:32 +00002377 // Visit stack entries that hold pointers.
Nicolas Geoffray39468442014-09-02 15:17:15 +01002378 for (size_t i = 0; i < mask.size_in_bits(); ++i) {
2379 if (mask.LoadBit(i)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002380 auto* ref_addr = vreg_base + i;
Nicolas Geoffray39468442014-09-02 15:17:15 +01002381 mirror::Object* ref = ref_addr->AsMirrorPtr();
2382 if (ref != nullptr) {
2383 mirror::Object* new_ref = ref;
2384 visitor_(&new_ref, -1, this);
2385 if (ref != new_ref) {
2386 ref_addr->Assign(new_ref);
Sebastien Hertz714f1752014-04-28 15:03:08 +02002387 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01002388 }
2389 }
2390 }
Nicolas Geoffray98893962015-01-21 12:32:32 +00002391 // Visit callee-save registers that hold pointers.
David Brazdilf677ebf2015-05-29 16:29:43 +01002392 uint32_t register_mask = map.GetRegisterMask(encoding);
Nicolas Geoffray98893962015-01-21 12:32:32 +00002393 for (size_t i = 0; i < BitSizeOf<uint32_t>(); ++i) {
2394 if (register_mask & (1 << i)) {
2395 mirror::Object** ref_addr = reinterpret_cast<mirror::Object**>(GetGPRAddress(i));
2396 if (*ref_addr != nullptr) {
2397 visitor_(ref_addr, -1, this);
2398 }
2399 }
2400 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01002401 } else {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002402 const uint8_t* native_gc_map = m->GetNativeGcMap(sizeof(void*));
Nicolas Geoffray39468442014-09-02 15:17:15 +01002403 CHECK(native_gc_map != nullptr) << PrettyMethod(m);
2404 const DexFile::CodeItem* code_item = m->GetCodeItem();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002405 // Can't be null or how would we compile its instructions?
Nicolas Geoffray39468442014-09-02 15:17:15 +01002406 DCHECK(code_item != nullptr) << PrettyMethod(m);
2407 NativePcOffsetToReferenceMap map(native_gc_map);
Pavel Vyssotski41f9cc22015-06-16 17:57:37 +06002408 size_t num_regs = map.RegWidth() * 8;
Nicolas Geoffray39468442014-09-02 15:17:15 +01002409 if (num_regs > 0) {
2410 Runtime* runtime = Runtime::Current();
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002411 const void* entry_point = runtime->GetInstrumentation()->GetQuickCodeFor(m, sizeof(void*));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002412 uintptr_t native_pc_offset = m->NativeQuickPcOffset(GetCurrentQuickFramePc(), entry_point);
Nicolas Geoffray39468442014-09-02 15:17:15 +01002413 const uint8_t* reg_bitmap = map.FindBitMap(native_pc_offset);
2414 DCHECK(reg_bitmap != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002415 const void* code_pointer = ArtMethod::EntryPointToCodePointer(entry_point);
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002416 const VmapTable vmap_table(m->GetVmapTable(code_pointer, sizeof(void*)));
Nicolas Geoffray39468442014-09-02 15:17:15 +01002417 QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
2418 // For all dex registers in the bitmap
Nicolas Geoffray39468442014-09-02 15:17:15 +01002419 DCHECK(cur_quick_frame != nullptr);
2420 for (size_t reg = 0; reg < num_regs; ++reg) {
2421 // Does this register hold a reference?
2422 if (TestBitmap(reg, reg_bitmap)) {
2423 uint32_t vmap_offset;
2424 if (vmap_table.IsInContext(reg, kReferenceVReg, &vmap_offset)) {
2425 int vmap_reg = vmap_table.ComputeRegister(frame_info.CoreSpillMask(), vmap_offset,
2426 kReferenceVReg);
2427 // This is sound as spilled GPRs will be word sized (ie 32 or 64bit).
2428 mirror::Object** ref_addr =
2429 reinterpret_cast<mirror::Object**>(GetGPRAddress(vmap_reg));
2430 if (*ref_addr != nullptr) {
2431 visitor_(ref_addr, reg, this);
2432 }
2433 } else {
2434 StackReference<mirror::Object>* ref_addr =
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00002435 reinterpret_cast<StackReference<mirror::Object>*>(GetVRegAddrFromQuickCode(
2436 cur_quick_frame, code_item, frame_info.CoreSpillMask(),
2437 frame_info.FpSpillMask(), frame_info.FrameSizeInBytes(), reg));
Nicolas Geoffray39468442014-09-02 15:17:15 +01002438 mirror::Object* ref = ref_addr->AsMirrorPtr();
2439 if (ref != nullptr) {
2440 mirror::Object* new_ref = ref;
2441 visitor_(&new_ref, reg, this);
2442 if (ref != new_ref) {
2443 ref_addr->Assign(new_ref);
2444 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002445 }
Ian Rogers0c7abda2012-09-19 13:33:42 -07002446 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002447 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07002448 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002449 }
2450 }
2451 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002452 }
2453
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002454 // Visitor for when we visit a root.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002455 RootVisitor& visitor_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07002456};
2457
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002458class RootCallbackVisitor {
2459 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002460 RootCallbackVisitor(RootVisitor* visitor, uint32_t tid) : visitor_(visitor), tid_(tid) {}
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002461
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002462 void operator()(mirror::Object** obj, size_t vreg, const StackVisitor* stack_visitor) const
2463 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2464 visitor_->VisitRoot(obj, JavaFrameRootInfo(tid_, stack_visitor, vreg));
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002465 }
2466
2467 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002468 RootVisitor* const visitor_;
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002469 const uint32_t tid_;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002470};
2471
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002472void Thread::VisitRoots(RootVisitor* visitor) {
2473 const uint32_t thread_id = GetThreadId();
2474 visitor->VisitRootIfNonNull(&tlsPtr_.opeer, RootInfo(kRootThreadObject, thread_id));
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002475 if (tlsPtr_.exception != nullptr && tlsPtr_.exception != GetDeoptimizationException()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002476 visitor->VisitRoot(reinterpret_cast<mirror::Object**>(&tlsPtr_.exception),
2477 RootInfo(kRootNativeStack, thread_id));
Elliott Hughesd369bb72011-09-12 14:41:14 -07002478 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002479 visitor->VisitRootIfNonNull(&tlsPtr_.monitor_enter_object, RootInfo(kRootNativeStack, thread_id));
2480 tlsPtr_.jni_env->locals.VisitRoots(visitor, RootInfo(kRootJNILocal, thread_id));
2481 tlsPtr_.jni_env->monitors.VisitRoots(visitor, RootInfo(kRootJNIMonitor, thread_id));
2482 HandleScopeVisitRoots(visitor, thread_id);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002483 if (tlsPtr_.debug_invoke_req != nullptr) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002484 tlsPtr_.debug_invoke_req->VisitRoots(visitor, RootInfo(kRootDebugger, thread_id));
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07002485 }
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -07002486 if (tlsPtr_.stacked_shadow_frame_record != nullptr) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002487 RootCallbackVisitor visitor_to_callback(visitor, thread_id);
2488 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, nullptr, visitor_to_callback);
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -07002489 for (StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record;
2490 record != nullptr;
2491 record = record->GetLink()) {
2492 for (ShadowFrame* shadow_frame = record->GetShadowFrame();
2493 shadow_frame != nullptr;
2494 shadow_frame = shadow_frame->GetLink()) {
2495 mapper.VisitShadowFrame(shadow_frame);
2496 }
Sebastien Hertz714f1752014-04-28 15:03:08 +02002497 }
2498 }
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -07002499 if (tlsPtr_.deoptimization_return_value_stack != nullptr) {
2500 for (DeoptimizationReturnValueRecord* record = tlsPtr_.deoptimization_return_value_stack;
2501 record != nullptr;
2502 record = record->GetLink()) {
2503 if (record->IsReference()) {
2504 visitor->VisitRootIfNonNull(record->GetGCRoot(),
2505 RootInfo(kRootThreadObject, thread_id));
2506 }
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -07002507 }
2508 }
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07002509 for (auto* verifier = tlsPtr_.method_verifier; verifier != nullptr; verifier = verifier->link_) {
2510 verifier->VisitRoots(visitor, RootInfo(kRootNativeStack, thread_id));
Mathieu Chartier12d625f2015-03-13 11:33:37 -07002511 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002512 // Visit roots on this thread's stack
Ian Rogers0399dde2012-06-06 17:09:28 -07002513 Context* context = GetLongJumpContext();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002514 RootCallbackVisitor visitor_to_callback(visitor, thread_id);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002515 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context, visitor_to_callback);
Ian Rogers0399dde2012-06-06 17:09:28 -07002516 mapper.WalkStack();
2517 ReleaseLongJumpContext(context);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002518 for (instrumentation::InstrumentationStackFrame& frame : *GetInstrumentationStack()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002519 visitor->VisitRootIfNonNull(&frame.this_object_, RootInfo(kRootVMInternal, thread_id));
Ian Rogers62d6c772013-02-27 08:32:07 -08002520 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07002521}
2522
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002523class VerifyRootVisitor : public SingleRootVisitor {
2524 public:
2525 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
2526 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2527 VerifyObject(root);
2528 }
2529};
jeffhao25045522012-03-13 19:34:37 -07002530
Ian Rogers04d7aa92013-03-16 14:29:17 -07002531void Thread::VerifyStackImpl() {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002532 VerifyRootVisitor visitor;
Ian Rogers700a4022014-05-19 16:49:03 -07002533 std::unique_ptr<Context> context(Context::Create());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002534 RootCallbackVisitor visitor_to_callback(&visitor, GetThreadId());
2535 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context.get(), visitor_to_callback);
Ian Rogers0399dde2012-06-06 17:09:28 -07002536 mapper.WalkStack();
jeffhao25045522012-03-13 19:34:37 -07002537}
jeffhao25045522012-03-13 19:34:37 -07002538
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002539// Set the stack end to that to be used during a stack overflow
2540void Thread::SetStackEndForStackOverflow() {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002541 // During stack overflow we allow use of the full stack.
Ian Rogersdd7624d2014-03-14 17:43:00 -07002542 if (tlsPtr_.stack_end == tlsPtr_.stack_begin) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002543 // However, we seem to have already extended to use the full stack.
2544 LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently "
Andreas Gampe7ea6f792014-07-14 16:21:44 -07002545 << GetStackOverflowReservedBytes(kRuntimeISA) << ")?";
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002546 DumpStack(LOG(ERROR));
2547 LOG(FATAL) << "Recursive stack overflow.";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002548 }
2549
Ian Rogersdd7624d2014-03-14 17:43:00 -07002550 tlsPtr_.stack_end = tlsPtr_.stack_begin;
Dave Allison648d7112014-07-25 16:15:27 -07002551
2552 // Remove the stack overflow protection if is it set up.
2553 bool implicit_stack_check = !Runtime::Current()->ExplicitStackOverflowChecks();
2554 if (implicit_stack_check) {
2555 if (!UnprotectStack()) {
2556 LOG(ERROR) << "Unable to remove stack protection for stack overflow";
2557 }
2558 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002559}
2560
Ian Rogers13735952014-10-08 12:43:28 -07002561void Thread::SetTlab(uint8_t* start, uint8_t* end) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002562 DCHECK_LE(start, end);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002563 tlsPtr_.thread_local_start = start;
2564 tlsPtr_.thread_local_pos = tlsPtr_.thread_local_start;
2565 tlsPtr_.thread_local_end = end;
2566 tlsPtr_.thread_local_objects = 0;
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002567}
2568
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002569bool Thread::HasTlab() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002570 bool has_tlab = tlsPtr_.thread_local_pos != nullptr;
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002571 if (has_tlab) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002572 DCHECK(tlsPtr_.thread_local_start != nullptr && tlsPtr_.thread_local_end != nullptr);
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002573 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002574 DCHECK(tlsPtr_.thread_local_start == nullptr && tlsPtr_.thread_local_end == nullptr);
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002575 }
2576 return has_tlab;
2577}
2578
Elliott Hughes330304d2011-08-12 14:28:05 -07002579std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002580 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07002581 return os;
2582}
2583
Dave Allison648d7112014-07-25 16:15:27 -07002584void Thread::ProtectStack() {
2585 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
2586 VLOG(threads) << "Protecting stack at " << pregion;
2587 if (mprotect(pregion, kStackOverflowProtectedSize, PROT_NONE) == -1) {
2588 LOG(FATAL) << "Unable to create protected region in stack for implicit overflow check. "
2589 "Reason: "
2590 << strerror(errno) << " size: " << kStackOverflowProtectedSize;
2591 }
2592}
2593
2594bool Thread::UnprotectStack() {
2595 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
2596 VLOG(threads) << "Unprotecting stack at " << pregion;
2597 return mprotect(pregion, kStackOverflowProtectedSize, PROT_READ|PROT_WRITE) == 0;
2598}
2599
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002600void Thread::ActivateSingleStepControl(SingleStepControl* ssc) {
2601 CHECK(Dbg::IsDebuggerActive());
2602 CHECK(GetSingleStepControl() == nullptr) << "Single step already active in thread " << *this;
2603 CHECK(ssc != nullptr);
2604 tlsPtr_.single_step_control = ssc;
2605}
2606
2607void Thread::DeactivateSingleStepControl() {
2608 CHECK(Dbg::IsDebuggerActive());
2609 CHECK(GetSingleStepControl() != nullptr) << "Single step not active in thread " << *this;
2610 SingleStepControl* ssc = GetSingleStepControl();
2611 tlsPtr_.single_step_control = nullptr;
2612 delete ssc;
2613}
Dave Allison648d7112014-07-25 16:15:27 -07002614
Sebastien Hertz1558b572015-02-25 15:05:59 +01002615void Thread::SetDebugInvokeReq(DebugInvokeReq* req) {
2616 CHECK(Dbg::IsDebuggerActive());
2617 CHECK(GetInvokeReq() == nullptr) << "Debug invoke req already active in thread " << *this;
2618 CHECK(Thread::Current() != this) << "Debug invoke can't be dispatched by the thread itself";
2619 CHECK(req != nullptr);
2620 tlsPtr_.debug_invoke_req = req;
2621}
2622
2623void Thread::ClearDebugInvokeReq() {
Sebastien Hertz1558b572015-02-25 15:05:59 +01002624 CHECK(GetInvokeReq() != nullptr) << "Debug invoke req not active in thread " << *this;
2625 CHECK(Thread::Current() == this) << "Debug invoke must be finished by the thread itself";
Sebastien Hertzcbc50642015-06-01 17:33:12 +02002626 DebugInvokeReq* req = tlsPtr_.debug_invoke_req;
Sebastien Hertz1558b572015-02-25 15:05:59 +01002627 tlsPtr_.debug_invoke_req = nullptr;
Sebastien Hertzcbc50642015-06-01 17:33:12 +02002628 delete req;
Sebastien Hertz1558b572015-02-25 15:05:59 +01002629}
2630
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07002631void Thread::PushVerifier(verifier::MethodVerifier* verifier) {
2632 verifier->link_ = tlsPtr_.method_verifier;
Mathieu Chartier12d625f2015-03-13 11:33:37 -07002633 tlsPtr_.method_verifier = verifier;
2634}
2635
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07002636void Thread::PopVerifier(verifier::MethodVerifier* verifier) {
Mathieu Chartier12d625f2015-03-13 11:33:37 -07002637 CHECK_EQ(tlsPtr_.method_verifier, verifier);
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07002638 tlsPtr_.method_verifier = verifier->link_;
Mathieu Chartier12d625f2015-03-13 11:33:37 -07002639}
2640
Elliott Hughes8daa0922011-09-11 13:46:25 -07002641} // namespace art