blob: 8e98d530a9244570c5d80cb4b750ed1e8ffcbe56 [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"
Elliott Hughes76b61672012-12-12 17:47:30 -080035#include "base/mutex.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080036#include "base/timing_logger.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070037#include "base/to_str.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "class_linker-inl.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070039#include "class_linker.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070040#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070041#include "dex_file-inl.h"
Ian Rogers7655f292013-07-29 11:07:13 -070042#include "entrypoints/entrypoint_utils.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080043#include "entrypoints/quick/quick_alloc_entrypoints.h"
Ian Rogers0c7abda2012-09-19 13:33:42 -070044#include "gc_map.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070045#include "gc/accounting/card_table-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070046#include "gc/allocator/rosalloc.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070047#include "gc/heap.h"
48#include "gc/space/space.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070049#include "handle_scope-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070050#include "handle_scope.h"
Mathieu Chartierc56057e2014-05-04 13:18:58 -070051#include "indirect_reference_table-inl.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070052#include "jni_internal.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070053#include "mirror/art_field-inl.h"
54#include "mirror/art_method-inl.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 Chartier4e305412014-02-19 10:54:44 -080073#include "verify_object-inl.h"
Ian Rogers1809a722013-08-09 22:05:32 -070074#include "vmap_table.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070075#include "well_known_classes.h"
Carl Shapirob5573532011-07-12 18:22:59 -070076
77namespace art {
78
Ian Rogers0878d652013-04-18 17:38:35 -070079bool Thread::is_started_ = false;
Carl Shapirob5573532011-07-12 18:22:59 -070080pthread_key_t Thread::pthread_key_self_;
Dave Allison0aded082013-11-07 13:15:11 -080081ConditionVariable* Thread::resume_cond_ = nullptr;
Dave Allison648d7112014-07-25 16:15:27 -070082const size_t Thread::kStackOverflowImplicitCheckSize = GetStackOverflowReservedBytes(kRuntimeISA);
Carl Shapirob5573532011-07-12 18:22:59 -070083
Elliott Hughes7dc51662012-05-16 14:48:43 -070084static const char* kThreadNameDuringStartup = "<native thread without managed peer>";
85
Ian Rogers5d76c432011-10-31 21:42:49 -070086void Thread::InitCardTable() {
Ian Rogersdd7624d2014-03-14 17:43:00 -070087 tlsPtr_.card_table = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -070088}
89
Elliott Hughes3ea0f422012-04-16 17:01:43 -070090static void UnimplementedEntryPoint() {
91 UNIMPLEMENTED(FATAL);
92}
93
Ian Rogers848871b2013-08-05 10:56:33 -070094void InitEntryPoints(InterpreterEntryPoints* ipoints, JniEntryPoints* jpoints,
Elliott Hughes956af0f2014-12-11 14:34:28 -080095 QuickEntryPoints* qpoints);
Ian Rogers7655f292013-07-29 11:07:13 -070096
Ian Rogers848871b2013-08-05 10:56:33 -070097void Thread::InitTlsEntryPoints() {
Elliott Hughes3ea0f422012-04-16 17:01:43 -070098 // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
Ian Rogersdd7624d2014-03-14 17:43:00 -070099 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&tlsPtr_.interpreter_entrypoints);
Xingxing Panacbb3082014-10-16 13:41:58 +0800100 uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(&tlsPtr_.quick_entrypoints) +
101 sizeof(tlsPtr_.quick_entrypoints));
Ian Rogers7655f292013-07-29 11:07:13 -0700102 for (uintptr_t* it = begin; it != end; ++it) {
103 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
104 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700105 InitEntryPoints(&tlsPtr_.interpreter_entrypoints, &tlsPtr_.jni_entrypoints,
Elliott Hughes956af0f2014-12-11 14:34:28 -0800106 &tlsPtr_.quick_entrypoints);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700107}
108
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700109void Thread::ResetQuickAllocEntryPointsForThread() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700110 ResetQuickAllocEntryPoints(&tlsPtr_.quick_entrypoints);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700111}
112
Ian Rogers62d6c772013-02-27 08:32:07 -0800113void Thread::SetDeoptimizationShadowFrame(ShadowFrame* sf) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700114 tlsPtr_.deoptimization_shadow_frame = sf;
buzbee3ea4ec52011-08-22 17:37:19 -0700115}
116
Ian Rogers62d6c772013-02-27 08:32:07 -0800117void Thread::SetDeoptimizationReturnValue(const JValue& ret_val) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700118 tls64_.deoptimization_return_value.SetJ(ret_val.GetJ());
Ian Rogers306057f2012-11-26 12:45:53 -0800119}
120
121ShadowFrame* Thread::GetAndClearDeoptimizationShadowFrame(JValue* ret_val) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700122 ShadowFrame* sf = tlsPtr_.deoptimization_shadow_frame;
123 tlsPtr_.deoptimization_shadow_frame = nullptr;
124 ret_val->SetJ(tls64_.deoptimization_return_value.GetJ());
Ian Rogers306057f2012-11-26 12:45:53 -0800125 return sf;
126}
127
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -0700128void Thread::SetShadowFrameUnderConstruction(ShadowFrame* sf) {
129 sf->SetLink(tlsPtr_.shadow_frame_under_construction);
130 tlsPtr_.shadow_frame_under_construction = sf;
131}
132
133void Thread::ClearShadowFrameUnderConstruction() {
134 CHECK_NE(static_cast<ShadowFrame*>(nullptr), tlsPtr_.shadow_frame_under_construction);
135 tlsPtr_.shadow_frame_under_construction = tlsPtr_.shadow_frame_under_construction->GetLink();
136}
137
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700138void Thread::InitTid() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700139 tls32_.tid = ::art::GetTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700140}
141
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700142void Thread::InitAfterFork() {
Elliott Hughes8029cbe2012-05-22 09:13:08 -0700143 // One thread (us) survived the fork, but we have a new tid so we need to
144 // update the value stashed in this Thread*.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700145 InitTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700146}
147
Brian Carlstrom78128a62011-09-15 17:21:19 -0700148void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700149 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogers120f1c72012-09-28 17:17:10 -0700150 Runtime* runtime = Runtime::Current();
Dave Allison0aded082013-11-07 13:15:11 -0800151 if (runtime == nullptr) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700152 LOG(ERROR) << "Thread attaching to non-existent runtime: " << *self;
Dave Allison0aded082013-11-07 13:15:11 -0800153 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700154 }
155 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700156 // TODO: pass self to MutexLock - requires self to equal Thread::Current(), which is only true
157 // after self->Init().
Dave Allison0aded082013-11-07 13:15:11 -0800158 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700159 // Check that if we got here we cannot be shutting down (as shutdown should never have started
160 // while threads are being born).
Mathieu Chartier590fee92013-09-13 13:46:47 -0700161 CHECK(!runtime->IsShuttingDownLocked());
Ian Rogersf4d4da12014-11-11 16:10:33 -0800162 CHECK(self->Init(runtime->GetThreadList(), runtime->GetJavaVM()));
Ian Rogers120f1c72012-09-28 17:17:10 -0700163 Runtime::Current()->EndThreadBirth();
164 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700165 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700166 ScopedObjectAccess soa(self);
Ian Rogerscfaa4552012-11-26 21:00:08 -0800167
168 // Copy peer into self, deleting global reference when done.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700169 CHECK(self->tlsPtr_.jpeer != nullptr);
170 self->tlsPtr_.opeer = soa.Decode<mirror::Object*>(self->tlsPtr_.jpeer);
171 self->GetJniEnv()->DeleteGlobalRef(self->tlsPtr_.jpeer);
172 self->tlsPtr_.jpeer = nullptr;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700173 self->SetThreadName(self->GetThreadName(soa)->ToModifiedUtf8().c_str());
Narayan Kamatha0b34512014-10-07 12:51:26 +0100174
175 mirror::ArtField* priorityField = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority);
176 self->SetNativePriority(priorityField->GetInt(self->tlsPtr_.opeer));
Ian Rogers365c1022012-06-22 15:05:28 -0700177 Dbg::PostThreadStart(self);
178
179 // Invoke the 'run' method of our java.lang.Thread.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700180 mirror::Object* receiver = self->tlsPtr_.opeer;
Ian Rogers365c1022012-06-22 15:05:28 -0700181 jmethodID mid = WellKnownClasses::java_lang_Thread_run;
Ian Rogers53b8b092014-03-13 23:45:53 -0700182 InvokeVirtualOrInterfaceWithJValues(soa, receiver, mid, nullptr);
Elliott Hughes47179f72011-10-27 16:44:39 -0700183 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700184 // Detach and delete self.
185 Runtime::Current()->GetThreadList()->Unregister(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700186
Dave Allison0aded082013-11-07 13:15:11 -0800187 return nullptr;
Carl Shapirob5573532011-07-12 18:22:59 -0700188}
189
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700190Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800191 mirror::Object* thread_peer) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700192 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800193 Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetLong(thread_peer)));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700194 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_
195 // to stop it from going away.
Ian Rogers81d425b2012-09-27 16:03:43 -0700196 if (kIsDebugBuild) {
197 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -0800198 if (result != nullptr && !result->IsSuspended()) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700199 Locks::thread_list_lock_->AssertHeld(soa.Self());
200 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700201 }
202 return result;
Elliott Hughes761928d2011-11-16 18:33:03 -0800203}
204
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700205Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa,
206 jobject java_thread) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800207 return FromManagedThread(soa, soa.Decode<mirror::Object*>(java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700208}
209
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700210static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700211 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700212 if (stack_size == 0) {
213 stack_size = Runtime::Current()->GetDefaultStackSize();
214 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700215
Brian Carlstrom6414a972012-04-14 14:20:04 -0700216 // Dalvik used the bionic pthread default stack size for native threads,
217 // so include that here to support apps that expect large native stacks.
218 stack_size += 1 * MB;
219
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700220 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
221 if (stack_size < PTHREAD_STACK_MIN) {
222 stack_size = PTHREAD_STACK_MIN;
223 }
224
Dave Allisonf9439142014-03-27 15:10:22 -0700225 if (Runtime::Current()->ExplicitStackOverflowChecks()) {
226 // It's likely that callers are trying to ensure they have at least a certain amount of
227 // stack space, so we should add our reserved space on top of what they requested, rather
228 // than implicitly take it away from them.
Andreas Gampe7ea6f792014-07-14 16:21:44 -0700229 stack_size += GetStackOverflowReservedBytes(kRuntimeISA);
Dave Allisonf9439142014-03-27 15:10:22 -0700230 } else {
231 // If we are going to use implicit stack checks, allocate space for the protected
232 // region at the bottom of the stack.
Dave Allisonb090a182014-08-14 17:02:48 +0000233 stack_size += Thread::kStackOverflowImplicitCheckSize +
234 GetStackOverflowReservedBytes(kRuntimeISA);
Dave Allisonf9439142014-03-27 15:10:22 -0700235 }
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700236
237 // Some systems require the stack size to be a multiple of the system page size, so round up.
238 stack_size = RoundUp(stack_size, kPageSize);
239
240 return stack_size;
241}
242
Dave Allison69dfe512014-07-11 17:11:58 +0000243// Global variable to prevent the compiler optimizing away the page reads for the stack.
Ian Rogers13735952014-10-08 12:43:28 -0700244uint8_t dont_optimize_this;
Dave Allison69dfe512014-07-11 17:11:58 +0000245
Dave Allisonf9439142014-03-27 15:10:22 -0700246// Install a protected region in the stack. This is used to trigger a SIGSEGV if a stack
Dave Allison648d7112014-07-25 16:15:27 -0700247// overflow is detected. It is located right below the stack_begin_.
Dave Allison69dfe512014-07-11 17:11:58 +0000248//
Dave Allison648d7112014-07-25 16:15:27 -0700249// There is a little complexity here that deserves a special mention. On some
250// architectures, the stack created using a VM_GROWSDOWN flag
Dave Allison69dfe512014-07-11 17:11:58 +0000251// to prevent memory being allocated when it's not needed. This flag makes the
252// kernel only allocate memory for the stack by growing down in memory. Because we
253// want to put an mprotected region far away from that at the stack top, we need
254// to make sure the pages for the stack are mapped in before we call mprotect. We do
255// this by reading every page from the stack bottom (highest address) to the stack top.
256// We then madvise this away.
Dave Allison648d7112014-07-25 16:15:27 -0700257void Thread::InstallImplicitProtection() {
Ian Rogers13735952014-10-08 12:43:28 -0700258 uint8_t* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
259 uint8_t* stack_himem = tlsPtr_.stack_end;
260 uint8_t* stack_top = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(&stack_himem) &
Dave Allison69dfe512014-07-11 17:11:58 +0000261 ~(kPageSize - 1)); // Page containing current top of stack.
Dave Allisonf9439142014-03-27 15:10:22 -0700262
Dave Allison648d7112014-07-25 16:15:27 -0700263 // First remove the protection on the protected region as will want to read and
264 // write it. This may fail (on the first attempt when the stack is not mapped)
265 // but we ignore that.
266 UnprotectStack();
Dave Allison69dfe512014-07-11 17:11:58 +0000267
Dave Allison648d7112014-07-25 16:15:27 -0700268 // Map in the stack. This must be done by reading from the
269 // current stack pointer downwards as the stack may be mapped using VM_GROWSDOWN
270 // in the kernel. Any access more than a page below the current SP might cause
271 // a segv.
Dave Allison69dfe512014-07-11 17:11:58 +0000272
Dave Allison648d7112014-07-25 16:15:27 -0700273 // Read every page from the high address to the low.
Ian Rogers13735952014-10-08 12:43:28 -0700274 for (uint8_t* p = stack_top; p >= pregion; p -= kPageSize) {
Dave Allison648d7112014-07-25 16:15:27 -0700275 dont_optimize_this = *p;
Dave Allison69dfe512014-07-11 17:11:58 +0000276 }
277
Dave Allisonf9439142014-03-27 15:10:22 -0700278 VLOG(threads) << "installing stack protected region at " << std::hex <<
279 static_cast<void*>(pregion) << " to " <<
280 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1);
281
Dave Allison648d7112014-07-25 16:15:27 -0700282 // Protect the bottom of the stack to prevent read/write to it.
283 ProtectStack();
Dave Allison5cd33752014-04-15 15:57:58 -0700284
285 // Tell the kernel that we won't be needing these pages any more.
Dave Allison69dfe512014-07-11 17:11:58 +0000286 // NB. madvise will probably write zeroes into the memory (on linux it does).
Dave Allison648d7112014-07-25 16:15:27 -0700287 uint32_t unwanted_size = stack_top - pregion - kPageSize;
288 madvise(pregion, unwanted_size, MADV_DONTNEED);
Dave Allisonf9439142014-03-27 15:10:22 -0700289}
290
Ian Rogers120f1c72012-09-28 17:17:10 -0700291void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
Dave Allison0aded082013-11-07 13:15:11 -0800292 CHECK(java_peer != nullptr);
Ian Rogers120f1c72012-09-28 17:17:10 -0700293 Thread* self = static_cast<JNIEnvExt*>(env)->self;
294 Runtime* runtime = Runtime::Current();
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700295
Ian Rogers120f1c72012-09-28 17:17:10 -0700296 // Atomically start the birth of the thread ensuring the runtime isn't shutting down.
297 bool thread_start_during_shutdown = false;
Elliott Hughes47179f72011-10-27 16:44:39 -0700298 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700299 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700300 if (runtime->IsShuttingDownLocked()) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700301 thread_start_during_shutdown = true;
302 } else {
303 runtime->StartThreadBirth();
304 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700305 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700306 if (thread_start_during_shutdown) {
307 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError"));
308 env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown");
309 return;
310 }
311
312 Thread* child_thread = new Thread(is_daemon);
313 // Use global JNI ref to hold peer live while child thread starts.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700314 child_thread->tlsPtr_.jpeer = env->NewGlobalRef(java_peer);
Ian Rogers120f1c72012-09-28 17:17:10 -0700315 stack_size = FixStackSize(stack_size);
316
Anwar Ghuloum3c50a4b2013-06-21 13:05:23 -0700317 // 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 -0700318 // assign it.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800319 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer,
320 reinterpret_cast<jlong>(child_thread));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700321
322 pthread_t new_pthread;
323 pthread_attr_t attr;
324 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
325 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
326 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
Ian Rogers120f1c72012-09-28 17:17:10 -0700327 int pthread_create_result = pthread_create(&new_pthread, &attr, Thread::CreateCallback, child_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700328 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
329
Ian Rogers120f1c72012-09-28 17:17:10 -0700330 if (pthread_create_result != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700331 // pthread_create(3) failed, so clean up.
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700332 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700333 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
334 runtime->EndThreadBirth();
335 }
336 // Manually delete the global reference since Thread::Init will not have been run.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700337 env->DeleteGlobalRef(child_thread->tlsPtr_.jpeer);
338 child_thread->tlsPtr_.jpeer = nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700339 delete child_thread;
Dave Allison0aded082013-11-07 13:15:11 -0800340 child_thread = nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700341 // TODO: remove from thread group?
Ian Rogersef7d42f2014-01-06 12:55:46 -0800342 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 0);
Ian Rogers120f1c72012-09-28 17:17:10 -0700343 {
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700344 std::string msg(StringPrintf("pthread_create (%s stack) failed: %s",
345 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
Ian Rogers120f1c72012-09-28 17:17:10 -0700346 ScopedObjectAccess soa(env);
347 soa.Self()->ThrowOutOfMemoryError(msg.c_str());
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700348 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700349 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700350}
351
Ian Rogersf4d4da12014-11-11 16:10:33 -0800352bool Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700353 // This function does all the initialization that must be run by the native thread it applies to.
354 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
355 // we can handshake with the corresponding native thread when it's ready.) Check this native
356 // thread hasn't been through here already...
Dave Allison0aded082013-11-07 13:15:11 -0800357 CHECK(Thread::Current() == nullptr);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800358
359 // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this
360 // avoids pthread_self_ ever being invalid when discovered from Thread::Current().
361 tlsPtr_.pthread_self = pthread_self();
362 CHECK(is_started_);
363
Elliott Hughesd8af1592012-04-16 20:40:15 -0700364 SetUpAlternateSignalStack();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800365 if (!InitStackHwm()) {
366 return false;
367 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700368 InitCpu();
Ian Rogers848871b2013-08-05 10:56:33 -0700369 InitTlsEntryPoints();
Dave Allisonb373e092014-02-20 16:06:36 -0800370 RemoveSuspendTrigger();
Ian Rogers5d76c432011-10-31 21:42:49 -0700371 InitCardTable();
Ian Rogers01ae5802012-09-28 16:14:01 -0700372 InitTid();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800373
Ian Rogers120f1c72012-09-28 17:17:10 -0700374 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
375 DCHECK_EQ(Thread::Current(), this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700376
Ian Rogersdd7624d2014-03-14 17:43:00 -0700377 tls32_.thin_lock_thread_id = thread_list->AllocThreadId(this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700378
Ian Rogersdd7624d2014-03-14 17:43:00 -0700379 tlsPtr_.jni_env = new JNIEnvExt(this, java_vm);
Ian Rogers120f1c72012-09-28 17:17:10 -0700380 thread_list->Register(this);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800381 return true;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700382}
383
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800384Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group,
385 bool create_peer) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700386 Runtime* runtime = Runtime::Current();
Dave Allison0aded082013-11-07 13:15:11 -0800387 if (runtime == nullptr) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700388 LOG(ERROR) << "Thread attaching to non-existent runtime: " << thread_name;
Dave Allison0aded082013-11-07 13:15:11 -0800389 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700390 }
Ian Rogersf4d4da12014-11-11 16:10:33 -0800391 Thread* self;
Ian Rogers120f1c72012-09-28 17:17:10 -0700392 {
Dave Allison0aded082013-11-07 13:15:11 -0800393 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700394 if (runtime->IsShuttingDownLocked()) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700395 LOG(ERROR) << "Thread attaching while runtime is shutting down: " << thread_name;
Dave Allison0aded082013-11-07 13:15:11 -0800396 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700397 } else {
398 Runtime::Current()->StartThreadBirth();
399 self = new Thread(as_daemon);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800400 bool init_success = self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
Ian Rogers120f1c72012-09-28 17:17:10 -0700401 Runtime::Current()->EndThreadBirth();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800402 if (!init_success) {
403 delete self;
404 return nullptr;
405 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700406 }
407 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700408
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700409 CHECK_NE(self->GetState(), kRunnable);
410 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700411
Elliott Hughescac6cc72011-11-03 20:31:21 -0700412 // If we're the main thread, ClassLinker won't be created until after we're attached,
413 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800414 // In the compiler, all threads need this hack, because no-one's going to be getting
415 // a native peer!
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800416 if (create_peer) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700417 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800418 } else {
419 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Dave Allison0aded082013-11-07 13:15:11 -0800420 if (thread_name != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700421 self->tlsPtr_.name->assign(thread_name);
Elliott Hughes22869a92012-03-27 14:08:24 -0700422 ::art::SetThreadName(thread_name);
Brian Carlstrom3ea69c02014-08-18 15:38:34 -0700423 } else if (self->GetJniEnv()->check_jni) {
424 LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
Elliott Hughes22869a92012-03-27 14:08:24 -0700425 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700426 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700427
Daniel Mihalyidfafeef2014-10-20 11:47:56 +0200428 {
429 ScopedObjectAccess soa(self);
430 Dbg::PostThreadStart(self);
431 }
432
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700433 return self;
434}
435
Ian Rogers365c1022012-06-22 15:05:28 -0700436void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
437 Runtime* runtime = Runtime::Current();
438 CHECK(runtime->IsStarted());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700439 JNIEnv* env = tlsPtr_.jni_env;
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700440
Dave Allison0aded082013-11-07 13:15:11 -0800441 if (thread_group == nullptr) {
Ian Rogers365c1022012-06-22 15:05:28 -0700442 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -0700443 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700444 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Mathieu Chartiere07fd172014-11-10 16:58:19 -0800445 // Add missing null check in case of OOM b/18297817
Vladimir Marko44512052014-11-12 15:41:57 +0000446 if (name != nullptr && thread_name.get() == nullptr) {
Mathieu Chartiere07fd172014-11-10 16:58:19 -0800447 CHECK(IsExceptionPending());
448 return;
449 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700450 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700451 jboolean thread_is_daemon = as_daemon;
452
Elliott Hugheseac76672012-05-24 21:56:51 -0700453 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Dave Allison0aded082013-11-07 13:15:11 -0800454 if (peer.get() == nullptr) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700455 CHECK(IsExceptionPending());
456 return;
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700457 }
Ian Rogerscfaa4552012-11-26 21:00:08 -0800458 {
459 ScopedObjectAccess soa(this);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700460 tlsPtr_.opeer = soa.Decode<mirror::Object*>(peer.get());
Ian Rogerscfaa4552012-11-26 21:00:08 -0800461 }
Elliott Hugheseac76672012-05-24 21:56:51 -0700462 env->CallNonvirtualVoidMethod(peer.get(),
463 WellKnownClasses::java_lang_Thread,
464 WellKnownClasses::java_lang_Thread_init,
Ian Rogers365c1022012-06-22 15:05:28 -0700465 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466 AssertNoPendingException();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700467
Ian Rogers120f1c72012-09-28 17:17:10 -0700468 Thread* self = this;
469 DCHECK_EQ(self, Thread::Current());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700470 env->SetLongField(peer.get(), WellKnownClasses::java_lang_Thread_nativePeer,
471 reinterpret_cast<jlong>(self));
Ian Rogers120f1c72012-09-28 17:17:10 -0700472
473 ScopedObjectAccess soa(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700474 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -0700475 MutableHandle<mirror::String> peer_thread_name(hs.NewHandle(GetThreadName(soa)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700476 if (peer_thread_name.Get() == nullptr) {
Brian Carlstrom00fae582011-10-28 01:16:28 -0700477 // The Thread constructor should have set the Thread.name to a
478 // non-null value. However, because we can run without code
479 // available (in the compiler, in tests), we manually assign the
480 // fields the constructor should have set.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100481 if (runtime->IsActiveTransaction()) {
482 InitPeer<true>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority);
483 } else {
484 InitPeer<false>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority);
485 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700486 peer_thread_name.Assign(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700487 }
Elliott Hughes225f5a12012-06-11 11:23:48 -0700488 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700489 if (peer_thread_name.Get() != nullptr) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800490 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700491 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700492}
493
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100494template<bool kTransactionActive>
495void Thread::InitPeer(ScopedObjectAccess& soa, jboolean thread_is_daemon, jobject thread_group,
496 jobject thread_name, jint thread_priority) {
497 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700498 SetBoolean<kTransactionActive>(tlsPtr_.opeer, thread_is_daemon);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100499 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700500 SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_group));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100501 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700502 SetObject<kTransactionActive>(tlsPtr_.opeer, soa.Decode<mirror::Object*>(thread_name));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100503 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->
Ian Rogersdd7624d2014-03-14 17:43:00 -0700504 SetInt<kTransactionActive>(tlsPtr_.opeer, thread_priority);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100505}
506
Elliott Hughes899e7892012-01-24 14:57:32 -0800507void Thread::SetThreadName(const char* name) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700508 tlsPtr_.name->assign(name);
Elliott Hughes899e7892012-01-24 14:57:32 -0800509 ::art::SetThreadName(name);
510 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
511}
512
Ian Rogersf4d4da12014-11-11 16:10:33 -0800513bool Thread::InitStackHwm() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700514 void* read_stack_base;
515 size_t read_stack_size;
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700516 size_t read_guard_size;
517 GetThreadStack(tlsPtr_.pthread_self, &read_stack_base, &read_stack_size, &read_guard_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700518
Ian Rogers13735952014-10-08 12:43:28 -0700519 tlsPtr_.stack_begin = reinterpret_cast<uint8_t*>(read_stack_base);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700520 tlsPtr_.stack_size = read_stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -0700521
Dave Allison648d7112014-07-25 16:15:27 -0700522 // The minimum stack size we can cope with is the overflow reserved bytes (typically
523 // 8K) + the protected region size (4K) + another page (4K). Typically this will
524 // be 8+4+4 = 16K. The thread won't be able to do much with this stack even the GC takes
525 // between 8K and 12K.
526 uint32_t min_stack = GetStackOverflowReservedBytes(kRuntimeISA) + kStackOverflowProtectedSize
527 + 4 * KB;
528 if (read_stack_size <= min_stack) {
Ian Rogersf4d4da12014-11-11 16:10:33 -0800529 // Note, as we know the stack is small, avoid operations that could use a lot of stack.
530 LogMessage::LogLineLowStack(__PRETTY_FUNCTION__, __LINE__, ERROR,
531 "Attempt to attach a thread with a too-small stack");
532 return false;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700533 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700534
Vladimir Markob8f2f632015-01-02 14:23:26 +0000535 // This is included in the SIGQUIT output, but it's useful here for thread debugging.
536 VLOG(threads) << StringPrintf("Native stack is at %p (%s with %s guard)",
537 read_stack_base,
538 PrettySize(read_stack_size).c_str(),
539 PrettySize(read_guard_size).c_str());
540
Ian Rogers932746a2011-09-22 18:57:50 -0700541 // Set stack_end_ to the bottom of the stack saving space of stack overflows
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700542
543 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800544 bool implicit_stack_check = !runtime->ExplicitStackOverflowChecks() && !runtime->IsAotCompiler();
Dave Allisonb090a182014-08-14 17:02:48 +0000545 ResetDefaultStackEnd();
Dave Allisonf9439142014-03-27 15:10:22 -0700546
547 // Install the protected region if we are doing implicit overflow checks.
548 if (implicit_stack_check) {
Dave Allison648d7112014-07-25 16:15:27 -0700549 // The thread might have protected region at the bottom. We need
550 // to install our own region so we need to move the limits
551 // of the stack to make room for it.
Dave Allison216cf232014-08-18 15:49:51 -0700552
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700553 tlsPtr_.stack_begin += read_guard_size + kStackOverflowProtectedSize;
554 tlsPtr_.stack_end += read_guard_size + kStackOverflowProtectedSize;
555 tlsPtr_.stack_size -= read_guard_size;
Dave Allison648d7112014-07-25 16:15:27 -0700556
557 InstallImplicitProtection();
Dave Allisonf9439142014-03-27 15:10:22 -0700558 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700559
560 // Sanity check.
561 int stack_variable;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700562 CHECK_GT(&stack_variable, reinterpret_cast<void*>(tlsPtr_.stack_end));
Ian Rogersf4d4da12014-11-11 16:10:33 -0800563
564 return true;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700565}
566
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700567void Thread::ShortDump(std::ostream& os) const {
568 os << "Thread[";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700569 if (GetThreadId() != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700570 // If we're in kStarting, we won't have a thin lock id or tid yet.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700571 os << GetThreadId()
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -0700573 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700574 os << GetState()
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700575 << ",Thread*=" << this
Ian Rogersdd7624d2014-03-14 17:43:00 -0700576 << ",peer=" << tlsPtr_.opeer
577 << ",\"" << *tlsPtr_.name << "\""
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700578 << "]";
Elliott Hughesa0957642011-09-02 14:27:33 -0700579}
580
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581void Thread::Dump(std::ostream& os) const {
582 DumpState(os);
583 DumpStack(os);
584}
585
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700586mirror::String* Thread::GetThreadName(const ScopedObjectAccessAlreadyRunnable& soa) const {
Brian Carlstromea46f952013-07-30 01:26:50 -0700587 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700588 return (tlsPtr_.opeer != nullptr) ? reinterpret_cast<mirror::String*>(f->GetObject(tlsPtr_.opeer)) : nullptr;
Elliott Hughesfc861622011-10-17 17:57:47 -0700589}
590
Elliott Hughesffb465f2012-03-01 18:46:05 -0800591void Thread::GetThreadName(std::string& name) const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700592 name.assign(*tlsPtr_.name);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800593}
594
Jeff Hao57dac6e2013-08-15 16:36:24 -0700595uint64_t Thread::GetCpuMicroTime() const {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800596#if defined(__linux__)
Jeff Hao57dac6e2013-08-15 16:36:24 -0700597 clockid_t cpu_clock_id;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700598 pthread_getcpuclockid(tlsPtr_.pthread_self, &cpu_clock_id);
Jeff Hao57dac6e2013-08-15 16:36:24 -0700599 timespec now;
600 clock_gettime(cpu_clock_id, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700601 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughes0a18df82015-01-09 15:16:16 -0800602#else // __APPLE__
Jeff Hao57dac6e2013-08-15 16:36:24 -0700603 UNIMPLEMENTED(WARNING);
604 return -1;
605#endif
606}
607
Ian Rogers01ae5802012-09-28 16:14:01 -0700608// Attempt to rectify locks so that we dump thread list with required locks before exiting.
609static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers120f1c72012-09-28 17:17:10 -0700610 LOG(ERROR) << *thread << " suspend count already zero.";
Ian Rogers01ae5802012-09-28 16:14:01 -0700611 Locks::thread_suspend_count_lock_->Unlock(self);
612 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
613 Locks::mutator_lock_->SharedTryLock(self);
614 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
615 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
616 }
617 }
618 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
619 Locks::thread_list_lock_->TryLock(self);
620 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
621 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
622 }
623 }
624 std::ostringstream ss;
Ian Rogers7b078e82014-09-10 14:44:24 -0700625 Runtime::Current()->GetThreadList()->Dump(ss);
Ian Rogers120f1c72012-09-28 17:17:10 -0700626 LOG(FATAL) << ss.str();
Ian Rogers01ae5802012-09-28 16:14:01 -0700627}
628
629void Thread::ModifySuspendCount(Thread* self, int delta, bool for_debugger) {
Ian Rogers2966e132014-04-02 08:34:36 -0700630 if (kIsDebugBuild) {
631 DCHECK(delta == -1 || delta == +1 || delta == -tls32_.debug_suspend_count)
632 << delta << " " << tls32_.debug_suspend_count << " " << this;
633 DCHECK_GE(tls32_.suspend_count, tls32_.debug_suspend_count) << this;
634 Locks::thread_suspend_count_lock_->AssertHeld(self);
635 if (this != self && !IsSuspended()) {
636 Locks::thread_list_lock_->AssertHeld(self);
637 }
Ian Rogerscfaa4552012-11-26 21:00:08 -0800638 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700639 if (UNLIKELY(delta < 0 && tls32_.suspend_count <= 0)) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700640 UnsafeLogFatalForSuspendCount(self, this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700641 return;
642 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700643
Ian Rogersdd7624d2014-03-14 17:43:00 -0700644 tls32_.suspend_count += delta;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700645 if (for_debugger) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700646 tls32_.debug_suspend_count += delta;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700647 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700648
Ian Rogersdd7624d2014-03-14 17:43:00 -0700649 if (tls32_.suspend_count == 0) {
Ian Rogers474b6da2012-09-25 00:20:38 -0700650 AtomicClearFlag(kSuspendRequest);
651 } else {
652 AtomicSetFlag(kSuspendRequest);
Dave Allisonb373e092014-02-20 16:06:36 -0800653 TriggerSuspend();
Ian Rogers474b6da2012-09-25 00:20:38 -0700654 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700655}
656
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700657void Thread::RunCheckpointFunction() {
Dave Allison0aded082013-11-07 13:15:11 -0800658 Closure *checkpoints[kMaxCheckpoints];
659
660 // Grab the suspend_count lock and copy the current set of
661 // checkpoints. Then clear the list and the flag. The RequestCheckpoint
662 // function will also grab this lock so we prevent a race between setting
663 // the kCheckpointRequest flag and clearing it.
664 {
665 MutexLock mu(this, *Locks::thread_suspend_count_lock_);
666 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700667 checkpoints[i] = tlsPtr_.checkpoint_functions[i];
668 tlsPtr_.checkpoint_functions[i] = nullptr;
Dave Allison0aded082013-11-07 13:15:11 -0800669 }
670 AtomicClearFlag(kCheckpointRequest);
671 }
672
673 // Outside the lock, run all the checkpoint functions that
674 // we collected.
675 bool found_checkpoint = false;
676 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
677 if (checkpoints[i] != nullptr) {
678 ATRACE_BEGIN("Checkpoint function");
679 checkpoints[i]->Run(this);
680 ATRACE_END();
681 found_checkpoint = true;
682 }
683 }
684 CHECK(found_checkpoint);
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700685}
686
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700687bool Thread::RequestCheckpoint(Closure* function) {
Chris Dearman59cde532013-12-04 18:53:49 -0800688 union StateAndFlags old_state_and_flags;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700689 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700690 if (old_state_and_flags.as_struct.state != kRunnable) {
691 return false; // Fail, thread is suspended and so can't run a checkpoint.
692 }
Dave Allison0aded082013-11-07 13:15:11 -0800693
694 uint32_t available_checkpoint = kMaxCheckpoints;
695 for (uint32_t i = 0 ; i < kMaxCheckpoints; ++i) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700696 if (tlsPtr_.checkpoint_functions[i] == nullptr) {
Dave Allison0aded082013-11-07 13:15:11 -0800697 available_checkpoint = i;
698 break;
699 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700700 }
Dave Allison0aded082013-11-07 13:15:11 -0800701 if (available_checkpoint == kMaxCheckpoints) {
702 // No checkpoint functions available, we can't run a checkpoint
703 return false;
704 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700705 tlsPtr_.checkpoint_functions[available_checkpoint] = function;
Dave Allison0aded082013-11-07 13:15:11 -0800706
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700707 // Checkpoint function installed now install flag bit.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700708 // We must be runnable to request a checkpoint.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800709 DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable);
Chris Dearman59cde532013-12-04 18:53:49 -0800710 union StateAndFlags new_state_and_flags;
711 new_state_and_flags.as_int = old_state_and_flags.as_int;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700712 new_state_and_flags.as_struct.flags |= kCheckpointRequest;
Ian Rogers8c1b5f72014-07-09 22:02:36 -0700713 bool success =
714 tls32_.state_and_flags.as_atomic_int.CompareExchangeStrongSequentiallyConsistent(old_state_and_flags.as_int,
715 new_state_and_flags.as_int);
716 if (UNLIKELY(!success)) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700717 // The thread changed state before the checkpoint was installed.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700718 CHECK_EQ(tlsPtr_.checkpoint_functions[available_checkpoint], function);
719 tlsPtr_.checkpoint_functions[available_checkpoint] = nullptr;
Dave Allison0aded082013-11-07 13:15:11 -0800720 } else {
721 CHECK_EQ(ReadFlag(kCheckpointRequest), true);
Dave Allisonb373e092014-02-20 16:06:36 -0800722 TriggerSuspend();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700723 }
Ian Rogers8c1b5f72014-07-09 22:02:36 -0700724 return success;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700725}
726
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800727Closure* Thread::GetFlipFunction() {
728 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
729 Closure* func;
730 do {
731 func = atomic_func->LoadRelaxed();
732 if (func == nullptr) {
733 return nullptr;
734 }
735 } while (!atomic_func->CompareExchangeWeakSequentiallyConsistent(func, nullptr));
736 DCHECK(func != nullptr);
737 return func;
738}
739
740void Thread::SetFlipFunction(Closure* function) {
741 CHECK(function != nullptr);
742 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
743 atomic_func->StoreSequentiallyConsistent(function);
744}
745
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700746void Thread::FullSuspendCheck() {
747 VLOG(threads) << this << " self-suspending";
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700748 ATRACE_BEGIN("Full suspend check");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700749 // Make thread appear suspended to other threads, release mutator_lock_.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800750 tls32_.suspended_at_suspend_check = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700751 TransitionFromRunnableToSuspended(kSuspended);
752 // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
753 TransitionFromSuspendedToRunnable();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800754 tls32_.suspended_at_suspend_check = false;
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700755 ATRACE_END();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700756 VLOG(threads) << this << " self-reviving";
757}
758
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700759void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700760 std::string group_name;
761 int priority;
762 bool is_daemon = false;
Ian Rogers81d425b2012-09-27 16:03:43 -0700763 Thread* self = Thread::Current();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700764
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800765 // If flip_function is not null, it means we have run a checkpoint
766 // before the thread wakes up to execute the flip function and the
767 // thread roots haven't been forwarded. So the following access to
768 // the roots (opeer or methods in the frames) would be bad. Run it
769 // here. TODO: clean up.
770 if (thread != nullptr) {
771 ScopedObjectAccessUnchecked soa(self);
772 Thread* this_thread = const_cast<Thread*>(thread);
773 Closure* flip_func = this_thread->GetFlipFunction();
774 if (flip_func != nullptr) {
775 flip_func->Run(this_thread);
776 }
777 }
778
Mathieu Chartierc7a966d2014-04-10 18:06:32 -0700779 // Don't do this if we are aborting since the GC may have all the threads suspended. This will
780 // cause ScopedObjectAccessUnchecked to deadlock.
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000781 if (gAborting == 0 && self != nullptr && thread != nullptr && thread->tlsPtr_.opeer != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800782 ScopedObjectAccessUnchecked soa(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700783 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)
784 ->GetInt(thread->tlsPtr_.opeer);
785 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)
786 ->GetBoolean(thread->tlsPtr_.opeer);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700787
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800788 mirror::Object* thread_group =
Ian Rogersdd7624d2014-03-14 17:43:00 -0700789 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(thread->tlsPtr_.opeer);
Ian Rogers120f1c72012-09-28 17:17:10 -0700790
Dave Allison0aded082013-11-07 13:15:11 -0800791 if (thread_group != nullptr) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700792 mirror::ArtField* group_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800793 soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
794 mirror::String* group_name_string =
795 reinterpret_cast<mirror::String*>(group_name_field->GetObject(thread_group));
Dave Allison0aded082013-11-07 13:15:11 -0800796 group_name = (group_name_string != nullptr) ? group_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughesd369bb72011-09-12 14:41:14 -0700797 }
798 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700799 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700800 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700801
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700802 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700803 if (scheduler_group_name.empty()) {
804 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700805 }
806
Dave Allison0aded082013-11-07 13:15:11 -0800807 if (thread != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700808 os << '"' << *thread->tlsPtr_.name << '"';
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700809 if (is_daemon) {
810 os << " daemon";
811 }
812 os << " prio=" << priority
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700813 << " tid=" << thread->GetThreadId()
Elliott Hughes80537bb2013-01-04 16:37:26 -0800814 << " " << thread->GetState();
815 if (thread->IsStillStarting()) {
816 os << " (still starting up)";
817 }
818 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700819 } else {
Elliott Hughes289be852012-06-12 13:57:20 -0700820 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700821 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700822 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700823 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700824
Dave Allison0aded082013-11-07 13:15:11 -0800825 if (thread != nullptr) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700826 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700827 os << " | group=\"" << group_name << "\""
Ian Rogersdd7624d2014-03-14 17:43:00 -0700828 << " sCount=" << thread->tls32_.suspend_count
829 << " dsCount=" << thread->tls32_.debug_suspend_count
830 << " obj=" << reinterpret_cast<void*>(thread->tlsPtr_.opeer)
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700831 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
832 }
Elliott Hughes0d39c122012-06-06 16:41:17 -0700833
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700834 os << " | sysTid=" << tid
835 << " nice=" << getpriority(PRIO_PROCESS, tid)
Elliott Hughes0d39c122012-06-06 16:41:17 -0700836 << " cgrp=" << scheduler_group_name;
Dave Allison0aded082013-11-07 13:15:11 -0800837 if (thread != nullptr) {
Elliott Hughes0d39c122012-06-06 16:41:17 -0700838 int policy;
839 sched_param sp;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700840 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->tlsPtr_.pthread_self, &policy, &sp),
841 __FUNCTION__);
Elliott Hughes0d39c122012-06-06 16:41:17 -0700842 os << " sched=" << policy << "/" << sp.sched_priority
Ian Rogersdd7624d2014-03-14 17:43:00 -0700843 << " handle=" << reinterpret_cast<void*>(thread->tlsPtr_.pthread_self);
Elliott Hughes0d39c122012-06-06 16:41:17 -0700844 }
845 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700846
847 // Grab the scheduler stats for this thread.
848 std::string scheduler_stats;
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700849 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700850 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
Elliott Hughesd92bec42011-09-02 17:04:36 -0700851 } else {
852 scheduler_stats = "0 0 0";
853 }
854
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700855 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -0700856 int utime = 0;
857 int stime = 0;
858 int task_cpu = 0;
Brian Carlstrom29212012013-09-12 22:18:30 -0700859 GetTaskStats(tid, &native_thread_state, &utime, &stime, &task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700860
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700861 os << " | state=" << native_thread_state
862 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -0700863 << " utm=" << utime
864 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700865 << " core=" << task_cpu
866 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
Dave Allison0aded082013-11-07 13:15:11 -0800867 if (thread != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700868 os << " | stack=" << reinterpret_cast<void*>(thread->tlsPtr_.stack_begin) << "-"
869 << reinterpret_cast<void*>(thread->tlsPtr_.stack_end) << " stackSize="
870 << PrettySize(thread->tlsPtr_.stack_size) << "\n";
Mathieu Chartier9db911e2014-06-04 11:23:58 -0700871 // Dump the held mutexes.
872 os << " | held mutexes=";
873 for (size_t i = 0; i < kLockLevelCount; ++i) {
874 if (i != kMonitorLock) {
875 BaseMutex* mutex = thread->GetHeldMutex(static_cast<LockLevel>(i));
876 if (mutex != nullptr) {
877 os << " \"" << mutex->GetName() << "\"";
878 if (mutex->IsReaderWriterMutex()) {
879 ReaderWriterMutex* rw_mutex = down_cast<ReaderWriterMutex*>(mutex);
Ian Rogersa9d8c4c2014-07-07 21:38:36 -0700880 if (rw_mutex->GetExclusiveOwnerTid() == static_cast<uint64_t>(tid)) {
Mathieu Chartier9db911e2014-06-04 11:23:58 -0700881 os << "(exclusive held)";
882 } else {
Mathieu Chartier9db911e2014-06-04 11:23:58 -0700883 os << "(shared held)";
884 }
885 }
886 }
887 }
888 }
889 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700890 }
891}
892
893void Thread::DumpState(std::ostream& os) const {
894 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700895}
896
Ian Rogers0399dde2012-06-06 17:09:28 -0700897struct StackDumpVisitor : public StackVisitor {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800898 StackDumpVisitor(std::ostream& os_in, Thread* thread_in, Context* context, bool can_allocate_in)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700899 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800900 : StackVisitor(thread_in, context), os(os_in), thread(thread_in),
901 can_allocate(can_allocate_in), last_method(nullptr), last_line_number(0),
902 repetition_count(0), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700903 }
904
Ian Rogersbdb03912011-09-14 00:55:44 -0700905 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -0700906 if (frame_count == 0) {
907 os << " (no managed stack frames)\n";
908 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700909 }
910
Ian Rogersb726dcb2012-09-05 08:57:23 -0700911 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700912 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -0700913 if (m->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700914 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700915 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700916 const int kMaxRepetition = 3;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800917 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800918 mirror::DexCache* dex_cache = c->GetDexCache();
Ian Rogersb861dc02011-11-14 17:00:05 -0800919 int line_number = -1;
Dave Allison0aded082013-11-07 13:15:11 -0800920 if (dex_cache != nullptr) { // be tolerant of bad input
Ian Rogers4445a7e2012-10-05 17:19:13 -0700921 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartierc751fdc2014-03-30 15:25:44 -0700922 line_number = dex_file.GetLineNumFromPC(m, GetDexPc(false));
Ian Rogersb861dc02011-11-14 17:00:05 -0800923 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700924 if (line_number == last_line_number && last_method == m) {
Dave Allison0aded082013-11-07 13:15:11 -0800925 ++repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700926 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700927 if (repetition_count >= kMaxRepetition) {
928 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
929 }
930 repetition_count = 0;
931 last_line_number = line_number;
932 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700933 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700934 if (repetition_count < kMaxRepetition) {
935 os << " at " << PrettyMethod(m, false);
936 if (m->IsNative()) {
937 os << "(Native method)";
938 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700939 const char* source_file(m->GetDeclaringClassSourceFile());
Dave Allison0aded082013-11-07 13:15:11 -0800940 os << "(" << (source_file != nullptr ? source_file : "unavailable")
Brian Carlstrom2e450bf2013-09-06 15:39:46 -0700941 << ":" << line_number << ")";
Ian Rogers28ad40d2011-10-27 15:19:26 -0700942 }
943 os << "\n";
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700944 if (frame_count == 0) {
945 Monitor::DescribeWait(os, thread);
946 }
947 if (can_allocate) {
Andreas Gampe956a5222014-08-16 13:41:10 -0700948 // Visit locks, but do not abort on errors. This would trigger a nested abort.
949 Monitor::VisitLocks(this, DumpLockedObject, &os, false);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700950 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700951 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700952
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700953 ++frame_count;
Elliott Hughes530fa002012-03-12 11:44:49 -0700954 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700955 }
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800956
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800957 static void DumpLockedObject(mirror::Object* o, void* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800958 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
959 std::ostream& os = *reinterpret_cast<std::ostream*>(context);
Ian Rogersd803bc72014-04-01 15:33:03 -0700960 os << " - locked ";
961 if (o == nullptr) {
962 os << "an unknown object";
963 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700964 if ((o->GetLockWord(false).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700965 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
966 // Getting the identity hashcode here would result in lock inflation and suspension of the
967 // current thread, which isn't safe if this is the only runnable thread.
968 os << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)", reinterpret_cast<intptr_t>(o),
969 PrettyTypeOf(o).c_str());
970 } else {
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -0800971 // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
972 // we get the pretty type beofre we call IdentityHashCode.
973 const std::string pretty_type(PrettyTypeOf(o));
974 os << StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -0700975 }
976 }
977 os << "\n";
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800978 }
979
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700980 std::ostream& os;
981 const Thread* thread;
Ian Rogers0878d652013-04-18 17:38:35 -0700982 const bool can_allocate;
Brian Carlstromea46f952013-07-30 01:26:50 -0700983 mirror::ArtMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700984 int last_line_number;
985 int repetition_count;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700986 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700987};
988
Ian Rogers33e95662013-05-20 20:29:14 -0700989static bool ShouldShowNativeStack(const Thread* thread)
990 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaef701d2013-04-05 18:15:40 -0700991 ThreadState state = thread->GetState();
992
993 // In native code somewhere in the VM (one of the kWaitingFor* states)? That's interesting.
994 if (state > kWaiting && state < kStarting) {
995 return true;
996 }
997
998 // In an Object.wait variant or Thread.sleep? That's not interesting.
999 if (state == kTimedWaiting || state == kSleeping || state == kWaiting) {
1000 return false;
1001 }
1002
Christopher Ferris2366f4e2014-09-19 17:23:59 -07001003 // Threads with no managed stack frames should be shown.
1004 const ManagedStack* managed_stack = thread->GetManagedStack();
1005 if (managed_stack == NULL || (managed_stack->GetTopQuickFrame() == NULL &&
1006 managed_stack->GetTopShadowFrame() == NULL)) {
1007 return true;
1008 }
1009
Elliott Hughesaef701d2013-04-05 18:15:40 -07001010 // In some other native method? That's interesting.
1011 // We don't just check kNative because native methods will be in state kSuspended if they're
1012 // calling back into the VM, or kBlocked if they're blocked on a monitor, or one of the
1013 // thread-startup states if it's early enough in their life cycle (http://b/7432159).
Dave Allison0aded082013-11-07 13:15:11 -08001014 mirror::ArtMethod* current_method = thread->GetCurrentMethod(nullptr);
1015 return current_method != nullptr && current_method->IsNative();
Elliott Hughesaef701d2013-04-05 18:15:40 -07001016}
1017
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001018void Thread::DumpJavaStack(std::ostream& os) const {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001019 // If flip_function is not null, it means we have run a checkpoint
1020 // before the thread wakes up to execute the flip function and the
1021 // thread roots haven't been forwarded. So the following access to
1022 // the roots (locks or methods in the frames) would be bad. Run it
1023 // here. TODO: clean up.
1024 {
1025 Thread* this_thread = const_cast<Thread*>(this);
1026 Closure* flip_func = this_thread->GetFlipFunction();
1027 if (flip_func != nullptr) {
1028 flip_func->Run(this_thread);
1029 }
1030 }
1031
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001032 // Dumping the Java stack involves the verifier for locks. The verifier operates under the
1033 // assumption that there is no exception pending on entry. Thus, stash any pending exception.
Mathieu Chartierbef89c92015-01-09 09:46:49 -08001034 // Thread::Current() instead of this in case a thread is dumping the stack of another suspended
1035 // thread.
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001036 StackHandleScope<1> scope(Thread::Current());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001037 Handle<mirror::Throwable> exc;
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001038 bool have_exception = false;
1039 if (IsExceptionPending()) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001040 exc = scope.NewHandle(GetException());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001041 const_cast<Thread*>(this)->ClearException();
1042 have_exception = true;
1043 }
1044
Ian Rogers700a4022014-05-19 16:49:03 -07001045 std::unique_ptr<Context> context(Context::Create());
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001046 StackDumpVisitor dumper(os, const_cast<Thread*>(this), context.get(),
1047 !tls32_.throwing_OutOfMemoryError);
1048 dumper.WalkStack();
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001049
1050 if (have_exception) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001051 const_cast<Thread*>(this)->SetException(exc.Get());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07001052 }
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001053}
1054
Elliott Hughesd92bec42011-09-02 17:04:36 -07001055void Thread::DumpStack(std::ostream& os) const {
Jeff Haoed1790e2013-04-12 09:58:14 -07001056 // TODO: we call this code when dying but may not have suspended the thread ourself. The
1057 // IsSuspended check is therefore racy with the use for dumping (normally we inhibit
1058 // the race with the thread_suspend_count_lock_).
Ian Rogerseef2e542014-06-24 22:48:01 -07001059 bool dump_for_abort = (gAborting > 0);
1060 bool safe_to_dump = (this == Thread::Current() || IsSuspended());
1061 if (!kIsDebugBuild) {
1062 // We always want to dump the stack for an abort, however, there is no point dumping another
1063 // thread's stack in debug builds where we'll hit the not suspended check in the stack walk.
1064 safe_to_dump = (safe_to_dump || dump_for_abort);
1065 }
1066 if (safe_to_dump) {
Ian Rogersf08e4732013-04-09 09:45:49 -07001067 // If we're currently in native code, dump that stack before dumping the managed stack.
Ian Rogersd090cf42013-06-06 15:35:18 -07001068 if (dump_for_abort || ShouldShowNativeStack(this)) {
Ian Rogersf08e4732013-04-09 09:45:49 -07001069 DumpKernelStack(os, GetTid(), " kernel: ", false);
Andreas Gampeb2f5dbb2014-09-16 15:15:13 -07001070 DumpNativeStack(os, GetTid(), " native: ", GetCurrentMethod(nullptr, !dump_for_abort));
Ian Rogersf08e4732013-04-09 09:45:49 -07001071 }
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07001072 DumpJavaStack(os);
Ian Rogersf08e4732013-04-09 09:45:49 -07001073 } else {
1074 os << "Not able to dump stack of thread that isn't suspended";
Elliott Hughesffb465f2012-03-01 18:46:05 -08001075 }
Elliott Hughese27955c2011-08-26 15:21:24 -07001076}
1077
Elliott Hughesbe759c62011-09-08 19:38:21 -07001078void Thread::ThreadExitCallback(void* arg) {
1079 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001080 if (self->tls32_.thread_exit_check_count == 0) {
1081 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's "
1082 "going to use a pthread_key_create destructor?): " << *self;
Ian Rogers0878d652013-04-18 17:38:35 -07001083 CHECK(is_started_);
Elliott Hughes6a607ad2012-07-13 20:40:00 -07001084 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
Ian Rogersdd7624d2014-03-14 17:43:00 -07001085 self->tls32_.thread_exit_check_count = 1;
Elliott Hughes6a607ad2012-07-13 20:40:00 -07001086 } else {
1087 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
1088 }
Carl Shapirob5573532011-07-12 18:22:59 -07001089}
1090
Elliott Hughesbe759c62011-09-08 19:38:21 -07001091void Thread::Startup() {
Ian Rogers0878d652013-04-18 17:38:35 -07001092 CHECK(!is_started_);
1093 is_started_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001094 {
Brian Carlstrom6d69f592013-07-16 17:18:16 -07001095 // MutexLock to keep annotalysis happy.
1096 //
Dave Allison0aded082013-11-07 13:15:11 -08001097 // Note we use nullptr for the thread because Thread::Current can
Brian Carlstrom6d69f592013-07-16 17:18:16 -07001098 // return garbage since (is_started_ == true) and
1099 // Thread::pthread_key_self_ is not yet initialized.
1100 // This was seen on glibc.
Dave Allison0aded082013-11-07 13:15:11 -08001101 MutexLock mu(nullptr, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07001102 resume_cond_ = new ConditionVariable("Thread resumption condition variable",
1103 *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001104 }
1105
Carl Shapirob5573532011-07-12 18:22:59 -07001106 // Allocate a TLS slot.
Ian Rogersf4d4da12014-11-11 16:10:33 -08001107 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback),
1108 "self key");
Carl Shapirob5573532011-07-12 18:22:59 -07001109
1110 // Double-check the TLS slot allocation.
Dave Allison0aded082013-11-07 13:15:11 -08001111 if (pthread_getspecific(pthread_key_self_) != nullptr) {
1112 LOG(FATAL) << "Newly-created pthread TLS slot is not nullptr";
Carl Shapirob5573532011-07-12 18:22:59 -07001113 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001114}
Carl Shapirob5573532011-07-12 18:22:59 -07001115
Elliott Hughes038a8062011-09-18 14:12:41 -07001116void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -07001117 Runtime* runtime = Runtime::Current();
1118 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -07001119
Elliott Hughes01158d72011-09-19 19:47:10 -07001120 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001121 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -07001122 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -05001123
Elliott Hughesaf8d15a2012-05-29 09:12:18 -07001124 Runtime::Current()->GetClassLinker()->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -07001125}
1126
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001127void Thread::Shutdown() {
Ian Rogers0878d652013-04-18 17:38:35 -07001128 CHECK(is_started_);
1129 is_started_ = false;
Elliott Hughes8d768a92011-09-14 16:35:25 -07001130 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Ian Rogers33e95662013-05-20 20:29:14 -07001131 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -08001132 if (resume_cond_ != nullptr) {
Ian Rogers0878d652013-04-18 17:38:35 -07001133 delete resume_cond_;
Dave Allison0aded082013-11-07 13:15:11 -08001134 resume_cond_ = nullptr;
Ian Rogers0878d652013-04-18 17:38:35 -07001135 }
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001136}
1137
Ian Rogersdd7624d2014-03-14 17:43:00 -07001138Thread::Thread(bool daemon) : tls32_(daemon), wait_monitor_(nullptr), interrupted_(false) {
1139 wait_mutex_ = new Mutex("a thread wait mutex");
1140 wait_cond_ = new ConditionVariable("a thread wait condition variable", *wait_mutex_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001141 tlsPtr_.instrumentation_stack = new std::deque<instrumentation::InstrumentationStackFrame>;
1142 tlsPtr_.name = new std::string(kThreadNameDuringStartup);
Dave Allison8ce6b902014-08-26 11:07:58 -07001143 tlsPtr_.nested_signal_state = static_cast<jmp_buf*>(malloc(sizeof(jmp_buf)));
Ian Rogersdd7624d2014-03-14 17:43:00 -07001144
Elliott Hughesf5a7a472011-10-07 14:31:02 -07001145 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001146 tls32_.state_and_flags.as_struct.flags = 0;
1147 tls32_.state_and_flags.as_struct.state = kNative;
1148 memset(&tlsPtr_.held_mutexes[0], 0, sizeof(tlsPtr_.held_mutexes));
Mathieu Chartier0651d412014-04-29 14:37:57 -07001149 std::fill(tlsPtr_.rosalloc_runs,
Ian Rogerse63db272014-07-15 15:36:11 -07001150 tlsPtr_.rosalloc_runs + kNumRosAllocThreadLocalSizeBrackets,
Mathieu Chartier73d1e172014-04-11 17:53:48 -07001151 gc::allocator::RosAlloc::GetDedicatedFullRun());
Dave Allison0aded082013-11-07 13:15:11 -08001152 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001153 tlsPtr_.checkpoint_functions[i] = nullptr;
Dave Allison0aded082013-11-07 13:15:11 -08001154 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001155 tlsPtr_.flip_function = nullptr;
1156 tls32_.suspended_at_suspend_check = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001157}
1158
Elliott Hughes7dc51662012-05-16 14:48:43 -07001159bool Thread::IsStillStarting() const {
1160 // You might think you can check whether the state is kStarting, but for much of thread startup,
Elliott Hughes80537bb2013-01-04 16:37:26 -08001161 // the thread is in kNative; it might also be in kVmWait.
Dave Allison0aded082013-11-07 13:15:11 -08001162 // You might think you can check whether the peer is nullptr, but the peer is actually created and
Elliott Hughes7dc51662012-05-16 14:48:43 -07001163 // assigned fairly early on, and needs to be.
1164 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
1165 // this thread _ever_ entered kRunnable".
Ian Rogersdd7624d2014-03-14 17:43:00 -07001166 return (tlsPtr_.jpeer == nullptr && tlsPtr_.opeer == nullptr) ||
1167 (*tlsPtr_.name == kThreadNameDuringStartup);
Elliott Hughes7dc51662012-05-16 14:48:43 -07001168}
1169
Andreas Gamped9efea62014-07-21 22:56:08 -07001170void Thread::AssertPendingException() const {
1171 if (UNLIKELY(!IsExceptionPending())) {
1172 LOG(FATAL) << "Pending exception expected.";
1173 }
1174}
1175
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001176void Thread::AssertNoPendingException() const {
1177 if (UNLIKELY(IsExceptionPending())) {
1178 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001179 mirror::Throwable* exception = GetException();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001180 LOG(FATAL) << "No pending exception expected: " << exception->Dump();
1181 }
1182}
1183
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001184void Thread::AssertNoPendingExceptionForNewException(const char* msg) const {
1185 if (UNLIKELY(IsExceptionPending())) {
1186 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001187 mirror::Throwable* exception = GetException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07001188 LOG(FATAL) << "Throwing new exception '" << msg << "' with unexpected pending exception: "
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001189 << exception->Dump();
1190 }
1191}
1192
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001193static void MonitorExitVisitor(mirror::Object** object, void* arg, const RootInfo& /*root_info*/)
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001194 NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001195 Thread* self = reinterpret_cast<Thread*>(arg);
Mathieu Chartier815873e2014-02-13 18:02:13 -08001196 mirror::Object* entered_monitor = *object;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001197 if (self->HoldsLock(entered_monitor)) {
1198 LOG(WARNING) << "Calling MonitorExit on object "
Mathieu Chartier815873e2014-02-13 18:02:13 -08001199 << object << " (" << PrettyTypeOf(entered_monitor) << ")"
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001200 << " left locked by native thread "
1201 << *Thread::Current() << " which is detaching";
1202 entered_monitor->MonitorExit(self);
1203 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001204}
1205
Elliott Hughesc0f09332012-03-26 13:27:06 -07001206void Thread::Destroy() {
Ian Rogers120f1c72012-09-28 17:17:10 -07001207 Thread* self = this;
1208 DCHECK_EQ(self, Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07001209
Ian Rogers68d8b422014-07-17 11:09:10 -07001210 if (tlsPtr_.jni_env != nullptr) {
1211 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001212 tlsPtr_.jni_env->monitors.VisitRoots(MonitorExitVisitor, self, RootInfo(kRootVMInternal));
Ian Rogers68d8b422014-07-17 11:09:10 -07001213 // Release locally held global references which releasing may require the mutator lock.
1214 if (tlsPtr_.jpeer != nullptr) {
1215 // If pthread_create fails we don't have a jni env here.
1216 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.jpeer);
1217 tlsPtr_.jpeer = nullptr;
1218 }
1219 if (tlsPtr_.class_loader_override != nullptr) {
1220 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.class_loader_override);
1221 tlsPtr_.class_loader_override = nullptr;
1222 }
1223 }
1224
Ian Rogersdd7624d2014-03-14 17:43:00 -07001225 if (tlsPtr_.opeer != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001226 ScopedObjectAccess soa(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001227 // We may need to call user-supplied managed code, do this before final clean-up.
Ian Rogerscfaa4552012-11-26 21:00:08 -08001228 HandleUncaughtExceptions(soa);
1229 RemoveFromThreadGroup(soa);
Elliott Hughes534da072012-03-27 15:17:42 -07001230
Anwar Ghuloum3c50a4b2013-06-21 13:05:23 -07001231 // this.nativePeer = 0;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001232 if (Runtime::Current()->IsActiveTransaction()) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001233 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer)
1234 ->SetLong<true>(tlsPtr_.opeer, 0);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001235 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001236 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer)
1237 ->SetLong<false>(tlsPtr_.opeer, 0);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001238 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001239 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001240
Ian Rogerscfaa4552012-11-26 21:00:08 -08001241 // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone
1242 // who is waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001243 mirror::Object* lock =
Ian Rogersdd7624d2014-03-14 17:43:00 -07001244 soa.DecodeField(WellKnownClasses::java_lang_Thread_lock)->GetObject(tlsPtr_.opeer);
Elliott Hughes038a8062011-09-18 14:12:41 -07001245 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001246 if (lock != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001247 StackHandleScope<1> hs(self);
1248 Handle<mirror::Object> h_obj(hs.NewHandle(lock));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001249 ObjectLock<mirror::Object> locker(self, h_obj);
Yevgeny Rouban63e8a682014-04-16 18:26:09 +07001250 locker.NotifyAll();
Elliott Hughes5f791332011-09-15 17:45:30 -07001251 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001252 tlsPtr_.opeer = nullptr;
Elliott Hughes5f791332011-09-15 17:45:30 -07001253 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001254
Hiroshi Yamauchia1b94c62014-12-17 15:49:56 -08001255 {
1256 ScopedObjectAccess soa(self);
1257 Runtime::Current()->GetHeap()->RevokeThreadLocalBuffers(this);
1258 }
Elliott Hughesc0f09332012-03-26 13:27:06 -07001259}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001260
Elliott Hughesc0f09332012-03-26 13:27:06 -07001261Thread::~Thread() {
Ian Rogers68d8b422014-07-17 11:09:10 -07001262 CHECK(tlsPtr_.class_loader_override == nullptr);
1263 CHECK(tlsPtr_.jpeer == nullptr);
1264 CHECK(tlsPtr_.opeer == nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001265 bool initialized = (tlsPtr_.jni_env != nullptr); // Did Thread::Init run?
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001266 if (initialized) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001267 delete tlsPtr_.jni_env;
1268 tlsPtr_.jni_env = nullptr;
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001269 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001270 CHECK_NE(GetState(), kRunnable);
Dave Allison0aded082013-11-07 13:15:11 -08001271 CHECK_NE(ReadFlag(kCheckpointRequest), true);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001272 CHECK(tlsPtr_.checkpoint_functions[0] == nullptr);
1273 CHECK(tlsPtr_.checkpoint_functions[1] == nullptr);
1274 CHECK(tlsPtr_.checkpoint_functions[2] == nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001275 CHECK(tlsPtr_.flip_function == nullptr);
1276 CHECK_EQ(tls32_.suspended_at_suspend_check, false);
Dave Allison0aded082013-11-07 13:15:11 -08001277
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001278 // We may be deleting a still born thread.
1279 SetStateUnsafe(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001280
1281 delete wait_cond_;
1282 delete wait_mutex_;
1283
Ian Rogersdd7624d2014-03-14 17:43:00 -07001284 if (tlsPtr_.long_jump_context != nullptr) {
1285 delete tlsPtr_.long_jump_context;
Ian Rogersc928de92013-02-27 14:30:44 -08001286 }
Elliott Hughes475fc232011-10-25 15:00:35 -07001287
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001288 if (initialized) {
1289 CleanupCpu();
1290 }
1291
Sebastien Hertz597c4f02015-01-26 17:37:14 +01001292 if (tlsPtr_.single_step_control != nullptr) {
1293 delete tlsPtr_.single_step_control;
1294 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001295 delete tlsPtr_.instrumentation_stack;
1296 delete tlsPtr_.name;
1297 delete tlsPtr_.stack_trace_sample;
Dave Allison8ce6b902014-08-26 11:07:58 -07001298 free(tlsPtr_.nested_signal_state);
Elliott Hughesd8af1592012-04-16 20:40:15 -07001299
Ian Rogers68d8b422014-07-17 11:09:10 -07001300 Runtime::Current()->GetHeap()->AssertThreadLocalBuffersAreRevoked(this);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001301
Elliott Hughesd8af1592012-04-16 20:40:15 -07001302 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001303}
1304
Ian Rogerscfaa4552012-11-26 21:00:08 -08001305void Thread::HandleUncaughtExceptions(ScopedObjectAccess& soa) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001306 if (!IsExceptionPending()) {
1307 return;
1308 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001309 ScopedLocalRef<jobject> peer(tlsPtr_.jni_env, soa.AddLocalReference<jobject>(tlsPtr_.opeer));
Ian Rogerscfaa4552012-11-26 21:00:08 -08001310 ScopedThreadStateChange tsc(this, kNative);
Ian Rogers120f1c72012-09-28 17:17:10 -07001311
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001312 // Get and clear the exception.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001313 ScopedLocalRef<jthrowable> exception(tlsPtr_.jni_env, tlsPtr_.jni_env->ExceptionOccurred());
1314 tlsPtr_.jni_env->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001315
1316 // If the thread has its own handler, use that.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001317 ScopedLocalRef<jobject> handler(tlsPtr_.jni_env,
1318 tlsPtr_.jni_env->GetObjectField(peer.get(),
1319 WellKnownClasses::java_lang_Thread_uncaughtHandler));
Dave Allison0aded082013-11-07 13:15:11 -08001320 if (handler.get() == nullptr) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001321 // Otherwise use the thread group's default handler.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001322 handler.reset(tlsPtr_.jni_env->GetObjectField(peer.get(),
1323 WellKnownClasses::java_lang_Thread_group));
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001324 }
1325
1326 // Call the handler.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001327 tlsPtr_.jni_env->CallVoidMethod(handler.get(),
Andreas Gampec8ccf682014-09-29 20:07:43 -07001328 WellKnownClasses::java_lang_Thread__UncaughtExceptionHandler_uncaughtException,
Ian Rogersdd7624d2014-03-14 17:43:00 -07001329 peer.get(), exception.get());
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001330
1331 // If the handler threw, clear that exception too.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001332 tlsPtr_.jni_env->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001333}
1334
Ian Rogerscfaa4552012-11-26 21:00:08 -08001335void Thread::RemoveFromThreadGroup(ScopedObjectAccess& soa) {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001336 // this.group.removeThread(this);
1337 // group can be null if we're in the compiler or a test.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001338 mirror::Object* ogroup = soa.DecodeField(WellKnownClasses::java_lang_Thread_group)
1339 ->GetObject(tlsPtr_.opeer);
Dave Allison0aded082013-11-07 13:15:11 -08001340 if (ogroup != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001341 ScopedLocalRef<jobject> group(soa.Env(), soa.AddLocalReference<jobject>(ogroup));
Ian Rogersdd7624d2014-03-14 17:43:00 -07001342 ScopedLocalRef<jobject> peer(soa.Env(), soa.AddLocalReference<jobject>(tlsPtr_.opeer));
Ian Rogerscfaa4552012-11-26 21:00:08 -08001343 ScopedThreadStateChange tsc(soa.Self(), kNative);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001344 tlsPtr_.jni_env->CallVoidMethod(group.get(),
1345 WellKnownClasses::java_lang_ThreadGroup_removeThread,
1346 peer.get());
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001347 }
1348}
1349
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001350size_t Thread::NumHandleReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001351 size_t count = 0;
Ian Rogersc0542af2014-09-03 16:16:56 -07001352 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur != nullptr; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001353 count += cur->NumberOfReferences();
1354 }
1355 return count;
1356}
1357
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001358bool Thread::HandleScopeContains(jobject obj) const {
1359 StackReference<mirror::Object>* hs_entry =
Ian Rogersef7d42f2014-01-06 12:55:46 -08001360 reinterpret_cast<StackReference<mirror::Object>*>(obj);
Ian Rogersc0542af2014-09-03 16:16:56 -07001361 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur!= nullptr; cur = cur->GetLink()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001362 if (cur->Contains(hs_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001363 return true;
1364 }
1365 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001366 // JNI code invoked from portable code uses shadow frames rather than the handle scope.
1367 return tlsPtr_.managed_stack.ShadowFramesContain(hs_entry);
TDYa12728f1a142012-03-15 21:51:52 -07001368}
1369
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001370void Thread::HandleScopeVisitRoots(RootCallback* visitor, void* arg, uint32_t thread_id) {
1371 for (HandleScope* cur = tlsPtr_.top_handle_scope; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001372 size_t num_refs = cur->NumberOfReferences();
Dave Allison0aded082013-11-07 13:15:11 -08001373 for (size_t j = 0; j < num_refs; ++j) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001374 mirror::Object* object = cur->GetReference(j);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001375 if (object != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08001376 mirror::Object* old_obj = object;
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001377 visitor(&object, arg, RootInfo(kRootNativeStack, thread_id));
Mathieu Chartier815873e2014-02-13 18:02:13 -08001378 if (old_obj != object) {
1379 cur->SetReference(j, object);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001380 }
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -07001381 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001382 }
1383 }
1384}
1385
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001386mirror::Object* Thread::DecodeJObject(jobject obj) const {
Dave Allison0aded082013-11-07 13:15:11 -08001387 if (obj == nullptr) {
1388 return nullptr;
Ian Rogers408f79a2011-08-23 18:22:33 -07001389 }
1390 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1391 IndirectRefKind kind = GetIndirectRefKind(ref);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001392 mirror::Object* result;
Ian Rogersc0542af2014-09-03 16:16:56 -07001393 bool expect_null = false;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001394 // The "kinds" below are sorted by the frequency we expect to encounter them.
1395 if (kind == kLocal) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001396 IndirectReferenceTable& locals = tlsPtr_.jni_env->locals;
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -07001397 // Local references do not need a read barrier.
1398 result = locals.Get<kWithoutReadBarrier>(ref);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001399 } else if (kind == kHandleScopeOrInvalid) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001400 // TODO: make stack indirect reference table lookup more efficient.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001401 // Check if this is a local reference in the handle scope.
1402 if (LIKELY(HandleScopeContains(obj))) {
1403 // Read from handle scope.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001404 result = reinterpret_cast<StackReference<mirror::Object>*>(obj)->AsMirrorPtr();
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08001405 VerifyObject(result);
Ian Rogers408f79a2011-08-23 18:22:33 -07001406 } else {
Ian Rogersc0542af2014-09-03 16:16:56 -07001407 tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of invalid jobject %p", obj);
1408 expect_null = true;
1409 result = nullptr;
Ian Rogers408f79a2011-08-23 18:22:33 -07001410 }
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001411 } else if (kind == kGlobal) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001412 result = tlsPtr_.jni_env->vm->DecodeGlobal(const_cast<Thread*>(this), ref);
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001413 } else {
1414 DCHECK_EQ(kind, kWeakGlobal);
Ian Rogers68d8b422014-07-17 11:09:10 -07001415 result = tlsPtr_.jni_env->vm->DecodeWeakGlobal(const_cast<Thread*>(this), ref);
Ian Rogersc0542af2014-09-03 16:16:56 -07001416 if (Runtime::Current()->IsClearedJniWeakGlobal(result)) {
Dave Allison0aded082013-11-07 13:15:11 -08001417 // This is a special case where it's okay to return nullptr.
Ian Rogersc0542af2014-09-03 16:16:56 -07001418 expect_null = true;
1419 result = nullptr;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001420 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001421 }
1422
Ian Rogersc0542af2014-09-03 16:16:56 -07001423 if (UNLIKELY(!expect_null && result == nullptr)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001424 tlsPtr_.jni_env->vm->JniAbortF(nullptr, "use of deleted %s %p",
1425 ToStr<IndirectRefKind>(kind).c_str(), obj);
Ian Rogers408f79a2011-08-23 18:22:33 -07001426 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001427 return result;
1428}
1429
Ian Rogers81d425b2012-09-27 16:03:43 -07001430// Implements java.lang.Thread.interrupted.
1431bool Thread::Interrupted() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001432 MutexLock mu(Thread::Current(), *wait_mutex_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001433 bool interrupted = IsInterruptedLocked();
1434 SetInterruptedLocked(false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001435 return interrupted;
1436}
1437
1438// Implements java.lang.Thread.isInterrupted.
1439bool Thread::IsInterrupted() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001440 MutexLock mu(Thread::Current(), *wait_mutex_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001441 return IsInterruptedLocked();
Ian Rogers81d425b2012-09-27 16:03:43 -07001442}
1443
Ian Rogersdd7624d2014-03-14 17:43:00 -07001444void Thread::Interrupt(Thread* self) {
Ian Rogersc604d732012-10-14 16:09:54 -07001445 MutexLock mu(self, *wait_mutex_);
Ian Rogers81d425b2012-09-27 16:03:43 -07001446 if (interrupted_) {
1447 return;
1448 }
1449 interrupted_ = true;
Ian Rogersc604d732012-10-14 16:09:54 -07001450 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001451}
1452
1453void Thread::Notify() {
Ian Rogersc604d732012-10-14 16:09:54 -07001454 Thread* self = Thread::Current();
1455 MutexLock mu(self, *wait_mutex_);
1456 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001457}
1458
Ian Rogersc604d732012-10-14 16:09:54 -07001459void Thread::NotifyLocked(Thread* self) {
Dave Allison0aded082013-11-07 13:15:11 -08001460 if (wait_monitor_ != nullptr) {
Ian Rogersc604d732012-10-14 16:09:54 -07001461 wait_cond_->Signal(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001462 }
1463}
1464
Ian Rogers68d8b422014-07-17 11:09:10 -07001465void Thread::SetClassLoaderOverride(jobject class_loader_override) {
1466 if (tlsPtr_.class_loader_override != nullptr) {
1467 GetJniEnv()->DeleteGlobalRef(tlsPtr_.class_loader_override);
1468 }
1469 tlsPtr_.class_loader_override = GetJniEnv()->NewGlobalRef(class_loader_override);
1470}
1471
Ian Rogers0399dde2012-06-06 17:09:28 -07001472class CountStackDepthVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001473 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001474 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001475 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Dave Allison0aded082013-11-07 13:15:11 -08001476 : StackVisitor(thread, nullptr),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001477 depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001478
Ian Rogersb726dcb2012-09-05 08:57:23 -07001479 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001480 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001481 // Note we also skip the frame if it doesn't have a method (namely the callee
1482 // save frame)
Brian Carlstromea46f952013-07-30 01:26:50 -07001483 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001484 if (skipping_ && !m->IsRuntimeMethod() &&
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001485 !mirror::Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001486 skipping_ = false;
1487 }
1488 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001489 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001490 ++depth_;
1491 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001492 } else {
1493 ++skip_depth_;
1494 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001495 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001496 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001497
1498 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001499 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001500 }
1501
Elliott Hughes29f27422011-09-18 16:02:18 -07001502 int GetSkipDepth() const {
1503 return skip_depth_;
1504 }
1505
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001506 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001507 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001508 uint32_t skip_depth_;
1509 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001510};
1511
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001512template<bool kTransactionActive>
Ian Rogers0399dde2012-06-06 17:09:28 -07001513class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001514 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001515 explicit BuildInternalStackTraceVisitor(Thread* self, Thread* thread, int skip_depth)
Dave Allison0aded082013-11-07 13:15:11 -08001516 : StackVisitor(thread, nullptr), self_(self),
1517 skip_depth_(skip_depth), count_(0), dex_pc_trace_(nullptr), method_trace_(nullptr) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08001518
Ian Rogers1f539342012-10-03 21:09:42 -07001519 bool Init(int depth)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001520 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001521 // Allocate method trace with an extra slot that will hold the PC trace
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001522 StackHandleScope<1> hs(self_);
1523 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1524 Handle<mirror::ObjectArray<mirror::Object>> method_trace(
1525 hs.NewHandle(class_linker->AllocObjectArray<mirror::Object>(self_, depth + 1)));
1526 if (method_trace.Get() == nullptr) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001527 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001528 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001529 mirror::IntArray* dex_pc_trace = mirror::IntArray::Alloc(self_, depth);
Dave Allison0aded082013-11-07 13:15:11 -08001530 if (dex_pc_trace == nullptr) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001531 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001532 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001533 // Save PC trace in last element of method trace, also places it into the
1534 // object graph.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001535 // We are called from native: use non-transactional mode.
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001536 method_trace->Set<kTransactionActive>(depth, dex_pc_trace);
Ian Rogers0399dde2012-06-06 17:09:28 -07001537 // Set the Object*s and assert that no thread suspension is now possible.
Ian Rogers52673ff2012-06-27 23:25:34 -07001538 const char* last_no_suspend_cause =
Ian Rogers1f539342012-10-03 21:09:42 -07001539 self_->StartAssertNoThreadSuspension("Building internal stack trace");
Dave Allison0aded082013-11-07 13:15:11 -08001540 CHECK(last_no_suspend_cause == nullptr) << last_no_suspend_cause;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001541 method_trace_ = method_trace.Get();
Ian Rogers0399dde2012-06-06 17:09:28 -07001542 dex_pc_trace_ = dex_pc_trace;
Ian Rogers283ed0d2012-02-16 15:25:09 -08001543 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001544 }
1545
Ian Rogers0399dde2012-06-06 17:09:28 -07001546 virtual ~BuildInternalStackTraceVisitor() {
Dave Allison0aded082013-11-07 13:15:11 -08001547 if (method_trace_ != nullptr) {
1548 self_->EndAssertNoThreadSuspension(nullptr);
Ian Rogers52673ff2012-06-27 23:25:34 -07001549 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001550 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001551
Ian Rogersb726dcb2012-09-05 08:57:23 -07001552 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Dave Allison0aded082013-11-07 13:15:11 -08001553 if (method_trace_ == nullptr || dex_pc_trace_ == nullptr) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001554 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001555 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001556 if (skip_depth_ > 0) {
1557 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001558 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001559 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001560 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001561 if (m->IsRuntimeMethod()) {
1562 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001563 }
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001564 method_trace_->Set<kTransactionActive>(count_, m);
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001565 dex_pc_trace_->Set<kTransactionActive>(count_,
1566 m->IsProxyMethod() ? DexFile::kDexNoIndex : GetDexPc());
Ian Rogersaaa20802011-09-11 21:47:37 -07001567 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001568 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001569 }
1570
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001571 mirror::ObjectArray<mirror::Object>* GetInternalStackTrace() const {
Ian Rogers0399dde2012-06-06 17:09:28 -07001572 return method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001573 }
1574
1575 private:
Ian Rogers1f539342012-10-03 21:09:42 -07001576 Thread* const self_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001577 // How many more frames to skip.
1578 int32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001579 // Current position down stack trace.
Ian Rogersaaa20802011-09-11 21:47:37 -07001580 uint32_t count_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001581 // Array of dex PC values.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001582 mirror::IntArray* dex_pc_trace_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001583 // An array of the methods on the stack, the last entry is a reference to the PC trace.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001584 mirror::ObjectArray<mirror::Object>* method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001585};
1586
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001587template<bool kTransactionActive>
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07001588jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001589 // Compute depth of stack
Ian Rogers7a22fa62013-01-23 12:16:16 -08001590 CountStackDepthVisitor count_visitor(const_cast<Thread*>(this));
Ian Rogers0399dde2012-06-06 17:09:28 -07001591 count_visitor.WalkStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001592 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001593 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001594
Ian Rogers1f539342012-10-03 21:09:42 -07001595 // Build internal stack trace.
Sebastien Hertzee1d79a2014-02-21 15:46:30 +01001596 BuildInternalStackTraceVisitor<kTransactionActive> build_trace_visitor(soa.Self(),
1597 const_cast<Thread*>(this),
1598 skip_depth);
Ian Rogers1f539342012-10-03 21:09:42 -07001599 if (!build_trace_visitor.Init(depth)) {
Dave Allison0aded082013-11-07 13:15:11 -08001600 return nullptr; // Allocation failed.
Ian Rogers283ed0d2012-02-16 15:25:09 -08001601 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001602 build_trace_visitor.WalkStack();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001603 mirror::ObjectArray<mirror::Object>* trace = build_trace_visitor.GetInternalStackTrace();
Ian Rogers7a22fa62013-01-23 12:16:16 -08001604 if (kIsDebugBuild) {
1605 for (int32_t i = 0; i < trace->GetLength(); ++i) {
Dave Allison0aded082013-11-07 13:15:11 -08001606 CHECK(trace->Get(i) != nullptr);
Ian Rogers7a22fa62013-01-23 12:16:16 -08001607 }
1608 }
1609 return soa.AddLocalReference<jobjectArray>(trace);
Ian Rogersaaa20802011-09-11 21:47:37 -07001610}
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07001611template jobject Thread::CreateInternalStackTrace<false>(
1612 const ScopedObjectAccessAlreadyRunnable& soa) const;
1613template jobject Thread::CreateInternalStackTrace<true>(
1614 const ScopedObjectAccessAlreadyRunnable& soa) const;
Ian Rogersaaa20802011-09-11 21:47:37 -07001615
Nicolas Geoffray7642cfc2015-02-26 10:56:09 +00001616bool Thread::IsExceptionThrownByCurrentMethod(mirror::Throwable* exception) const {
1617 CountStackDepthVisitor count_visitor(const_cast<Thread*>(this));
1618 count_visitor.WalkStack();
1619 return count_visitor.GetDepth() == exception->GetStackDepth();
1620}
1621
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07001622jobjectArray Thread::InternalStackTraceToStackTraceElementArray(
1623 const ScopedObjectAccessAlreadyRunnable& soa, jobject internal, jobjectArray output_array,
1624 int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001625 // Decode the internal stack trace into the depth, method trace and PC trace
Mathieu Chartier530825b2013-09-25 17:56:49 -07001626 int32_t depth = soa.Decode<mirror::ObjectArray<mirror::Object>*>(internal)->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001627
1628 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1629
Elliott Hughes01158d72011-09-19 19:47:10 -07001630 jobjectArray result;
Mathieu Chartier530825b2013-09-25 17:56:49 -07001631
Dave Allison0aded082013-11-07 13:15:11 -08001632 if (output_array != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07001633 // Reuse the array we were given.
1634 result = output_array;
Elliott Hughes01158d72011-09-19 19:47:10 -07001635 // ...adjusting the number of frames we'll write to not exceed the array length.
Mathieu Chartier530825b2013-09-25 17:56:49 -07001636 const int32_t traces_length =
1637 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->GetLength();
1638 depth = std::min(depth, traces_length);
Elliott Hughes01158d72011-09-19 19:47:10 -07001639 } else {
1640 // Create java_trace array and place in local reference table
Mathieu Chartier530825b2013-09-25 17:56:49 -07001641 mirror::ObjectArray<mirror::StackTraceElement>* java_traces =
1642 class_linker->AllocStackTraceElementArray(soa.Self(), depth);
Dave Allison0aded082013-11-07 13:15:11 -08001643 if (java_traces == nullptr) {
1644 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001645 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001646 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07001647 }
1648
Dave Allison0aded082013-11-07 13:15:11 -08001649 if (stack_depth != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07001650 *stack_depth = depth;
1651 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001652
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001653 for (int32_t i = 0; i < depth; ++i) {
Mathieu Chartier530825b2013-09-25 17:56:49 -07001654 mirror::ObjectArray<mirror::Object>* method_trace =
1655 soa.Decode<mirror::ObjectArray<mirror::Object>*>(internal);
Ian Rogersaaa20802011-09-11 21:47:37 -07001656 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Brian Carlstromea46f952013-07-30 01:26:50 -07001657 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(method_trace->Get(i));
Jeff Hao228d6b82013-12-03 15:00:05 -08001658 int32_t line_number;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001659 StackHandleScope<3> hs(soa.Self());
1660 auto class_name_object(hs.NewHandle<mirror::String>(nullptr));
1661 auto source_name_object(hs.NewHandle<mirror::String>(nullptr));
Jeff Hao228d6b82013-12-03 15:00:05 -08001662 if (method->IsProxyMethod()) {
1663 line_number = -1;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001664 class_name_object.Assign(method->GetDeclaringClass()->GetName());
Jeff Hao228d6b82013-12-03 15:00:05 -08001665 // source_name_object intentionally left null for proxy methods
1666 } else {
1667 mirror::IntArray* pc_trace = down_cast<mirror::IntArray*>(method_trace->Get(depth));
1668 uint32_t dex_pc = pc_trace->Get(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001669 line_number = method->GetLineNumFromDexPC(dex_pc);
Jeff Hao228d6b82013-12-03 15:00:05 -08001670 // Allocate element, potentially triggering GC
1671 // TODO: reuse class_name_object via Class::name_?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001672 const char* descriptor = method->GetDeclaringClassDescriptor();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001673 CHECK(descriptor != nullptr);
Jeff Hao228d6b82013-12-03 15:00:05 -08001674 std::string class_name(PrettyDescriptor(descriptor));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001675 class_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), class_name.c_str()));
1676 if (class_name_object.Get() == nullptr) {
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001677 return nullptr;
Jeff Hao228d6b82013-12-03 15:00:05 -08001678 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001679 const char* source_file = method->GetDeclaringClassSourceFile();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001680 if (source_file != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001681 source_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), source_file));
1682 if (source_name_object.Get() == nullptr) {
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001683 return nullptr;
1684 }
Jeff Hao228d6b82013-12-03 15:00:05 -08001685 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001686 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001687 const char* method_name = method->GetName();
Dave Allison0aded082013-11-07 13:15:11 -08001688 CHECK(method_name != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001689 Handle<mirror::String> method_name_object(
1690 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), method_name)));
1691 if (method_name_object.Get() == nullptr) {
Dave Allison0aded082013-11-07 13:15:11 -08001692 return nullptr;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001693 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001694 mirror::StackTraceElement* obj = mirror::StackTraceElement::Alloc(
1695 soa.Self(), class_name_object, method_name_object, source_name_object, line_number);
Dave Allison0aded082013-11-07 13:15:11 -08001696 if (obj == nullptr) {
1697 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001698 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001699 // We are called from native: use non-transactional mode.
1700 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->Set<false>(i, obj);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001701 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001702 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001703}
1704
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001705void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001706 va_list args;
1707 va_start(args, fmt);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001708 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001709 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001710}
1711
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001712void Thread::ThrowNewExceptionV(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08001713 const char* fmt, va_list ap) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001714 std::string msg;
1715 StringAppendV(&msg, fmt, ap);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001716 ThrowNewException(exception_class_descriptor, msg.c_str());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001717}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001718
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001719void Thread::ThrowNewException(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08001720 const char* msg) {
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001721 // Callers should either clear or call ThrowNewWrappedException.
1722 AssertNoPendingExceptionForNewException(msg);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001723 ThrowNewWrappedException(exception_class_descriptor, msg);
Elliott Hughesa4f94742012-05-29 16:28:38 -07001724}
1725
Nicolas Geoffrayee077032015-03-09 14:56:37 +00001726static mirror::ClassLoader* GetCurrentClassLoader(Thread* self)
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001727 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffrayee077032015-03-09 14:56:37 +00001728 mirror::ArtMethod* method = self->GetCurrentMethod(nullptr);
1729 return method != nullptr
1730 ? method->GetDeclaringClass()->GetClassLoader()
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001731 : nullptr;
1732}
1733
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001734void Thread::ThrowNewWrappedException(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08001735 const char* msg) {
1736 DCHECK_EQ(this, Thread::Current());
Ian Rogers53b8b092014-03-13 23:45:53 -07001737 ScopedObjectAccessUnchecked soa(this);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001738 StackHandleScope<3> hs(soa.Self());
Nicolas Geoffrayee077032015-03-09 14:56:37 +00001739 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(GetCurrentClassLoader(soa.Self())));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001740 ScopedLocalRef<jobject> cause(GetJniEnv(), soa.AddLocalReference<jobject>(GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08001741 ClearException();
1742 Runtime* runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001743 Handle<mirror::Class> exception_class(
1744 hs.NewHandle(runtime->GetClassLinker()->FindClass(this, exception_class_descriptor,
1745 class_loader)));
1746 if (UNLIKELY(exception_class.Get() == nullptr)) {
Elliott Hughes30646832011-10-13 16:59:46 -07001747 CHECK(IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08001748 LOG(ERROR) << "No exception class " << PrettyDescriptor(exception_class_descriptor);
Elliott Hughes30646832011-10-13 16:59:46 -07001749 return;
1750 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001751
Ian Rogers7b078e82014-09-10 14:44:24 -07001752 if (UNLIKELY(!runtime->GetClassLinker()->EnsureInitialized(soa.Self(), exception_class, true,
1753 true))) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001754 DCHECK(IsExceptionPending());
1755 return;
1756 }
1757 DCHECK(!runtime->IsStarted() || exception_class->IsThrowableClass());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001758 Handle<mirror::Throwable> exception(
1759 hs.NewHandle(down_cast<mirror::Throwable*>(exception_class->AllocObject(this))));
Ian Rogers62d6c772013-02-27 08:32:07 -08001760
Mathieu Chartier590fee92013-09-13 13:46:47 -07001761 // If we couldn't allocate the exception, throw the pre-allocated out of memory exception.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001762 if (exception.Get() == nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001763 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001764 return;
1765 }
1766
Ian Rogers62d6c772013-02-27 08:32:07 -08001767 // Choose an appropriate constructor and set up the arguments.
1768 const char* signature;
Ian Rogers53b8b092014-03-13 23:45:53 -07001769 ScopedLocalRef<jstring> msg_string(GetJniEnv(), nullptr);
Dave Allison0aded082013-11-07 13:15:11 -08001770 if (msg != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001771 // Ensure we remember this and the method over the String allocation.
Ian Rogers53b8b092014-03-13 23:45:53 -07001772 msg_string.reset(
1773 soa.AddLocalReference<jstring>(mirror::String::AllocFromModifiedUtf8(this, msg)));
Dave Allison0aded082013-11-07 13:15:11 -08001774 if (UNLIKELY(msg_string.get() == nullptr)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001775 CHECK(IsExceptionPending()); // OOME.
1776 return;
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001777 }
Dave Allison0aded082013-11-07 13:15:11 -08001778 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001779 signature = "(Ljava/lang/String;)V";
1780 } else {
1781 signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V";
1782 }
1783 } else {
Dave Allison0aded082013-11-07 13:15:11 -08001784 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001785 signature = "()V";
1786 } else {
1787 signature = "(Ljava/lang/Throwable;)V";
1788 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001789 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001790 mirror::ArtMethod* exception_init_method =
Ian Rogers62d6c772013-02-27 08:32:07 -08001791 exception_class->FindDeclaredDirectMethod("<init>", signature);
1792
Dave Allison0aded082013-11-07 13:15:11 -08001793 CHECK(exception_init_method != nullptr) << "No <init>" << signature << " in "
Ian Rogers62d6c772013-02-27 08:32:07 -08001794 << PrettyDescriptor(exception_class_descriptor);
1795
1796 if (UNLIKELY(!runtime->IsStarted())) {
1797 // Something is trying to throw an exception without a started runtime, which is the common
1798 // case in the compiler. We won't be able to invoke the constructor of the exception, so set
1799 // the exception fields directly.
Dave Allison0aded082013-11-07 13:15:11 -08001800 if (msg != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001801 exception->SetDetailMessage(down_cast<mirror::String*>(DecodeJObject(msg_string.get())));
Ian Rogers62d6c772013-02-27 08:32:07 -08001802 }
Dave Allison0aded082013-11-07 13:15:11 -08001803 if (cause.get() != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001804 exception->SetCause(down_cast<mirror::Throwable*>(DecodeJObject(cause.get())));
Ian Rogers62d6c772013-02-27 08:32:07 -08001805 }
Ian Rogersc45b8b52014-05-03 01:39:59 -07001806 ScopedLocalRef<jobject> trace(GetJniEnv(),
1807 Runtime::Current()->IsActiveTransaction()
1808 ? CreateInternalStackTrace<true>(soa)
1809 : CreateInternalStackTrace<false>(soa));
1810 if (trace.get() != nullptr) {
1811 exception->SetStackState(down_cast<mirror::Throwable*>(DecodeJObject(trace.get())));
1812 }
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001813 SetException(exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08001814 } else {
Ian Rogers53b8b092014-03-13 23:45:53 -07001815 jvalue jv_args[2];
1816 size_t i = 0;
1817
Dave Allison0aded082013-11-07 13:15:11 -08001818 if (msg != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001819 jv_args[i].l = msg_string.get();
1820 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08001821 }
Dave Allison0aded082013-11-07 13:15:11 -08001822 if (cause.get() != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001823 jv_args[i].l = cause.get();
1824 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08001825 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001826 InvokeWithJValues(soa, exception.Get(), soa.EncodeMethod(exception_init_method), jv_args);
Ian Rogers62d6c772013-02-27 08:32:07 -08001827 if (LIKELY(!IsExceptionPending())) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001828 SetException(exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08001829 }
Elliott Hughes30646832011-10-13 16:59:46 -07001830 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001831}
1832
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001833void Thread::ThrowOutOfMemoryError(const char* msg) {
Andreas Gampee4301ff2015-02-17 19:25:29 -08001834 LOG(WARNING) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
Ian Rogersdd7624d2014-03-14 17:43:00 -07001835 msg, (tls32_.throwing_OutOfMemoryError ? " (recursive case)" : ""));
Ian Rogersdd7624d2014-03-14 17:43:00 -07001836 if (!tls32_.throwing_OutOfMemoryError) {
1837 tls32_.throwing_OutOfMemoryError = true;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001838 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001839 tls32_.throwing_OutOfMemoryError = false;
Elliott Hughes418dfe72011-10-06 18:56:27 -07001840 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08001841 Dump(LOG(WARNING)); // The pre-allocated OOME has no stack, so help out and log one.
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001842 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Elliott Hughes418dfe72011-10-06 18:56:27 -07001843 }
Elliott Hughes79082e32011-08-25 12:07:32 -07001844}
1845
Elliott Hughes498508c2011-10-17 14:58:22 -07001846Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001847 return Thread::Current();
1848}
1849
1850void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001851 std::ostringstream ss;
1852 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001853 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001854 // log to stderr for debugging command line processes
1855 std::cerr << str;
1856#ifdef HAVE_ANDROID_OS
1857 // log to logcat for debugging frameworks processes
1858 LOG(INFO) << str;
1859#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001860}
1861
Ian Rogersdd7624d2014-03-14 17:43:00 -07001862// Explicitly instantiate 32 and 64bit thread offset dumping support.
1863template void Thread::DumpThreadOffset<4>(std::ostream& os, uint32_t offset);
1864template void Thread::DumpThreadOffset<8>(std::ostream& os, uint32_t offset);
Elliott Hughes98e20172012-04-24 15:38:13 -07001865
Ian Rogersdd7624d2014-03-14 17:43:00 -07001866template<size_t ptr_size>
1867void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset) {
1868#define DO_THREAD_OFFSET(x, y) \
1869 if (offset == x.Uint32Value()) { \
1870 os << y; \
Brian Carlstromf69863b2013-07-17 21:53:13 -07001871 return; \
1872 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001873 DO_THREAD_OFFSET(ThreadFlagsOffset<ptr_size>(), "state_and_flags")
1874 DO_THREAD_OFFSET(CardTableOffset<ptr_size>(), "card_table")
1875 DO_THREAD_OFFSET(ExceptionOffset<ptr_size>(), "exception")
1876 DO_THREAD_OFFSET(PeerOffset<ptr_size>(), "peer");
1877 DO_THREAD_OFFSET(JniEnvOffset<ptr_size>(), "jni_env")
1878 DO_THREAD_OFFSET(SelfOffset<ptr_size>(), "self")
1879 DO_THREAD_OFFSET(StackEndOffset<ptr_size>(), "stack_end")
1880 DO_THREAD_OFFSET(ThinLockIdOffset<ptr_size>(), "thin_lock_thread_id")
1881 DO_THREAD_OFFSET(TopOfManagedStackOffset<ptr_size>(), "top_quick_frame_method")
Ian Rogersdd7624d2014-03-14 17:43:00 -07001882 DO_THREAD_OFFSET(TopShadowFrameOffset<ptr_size>(), "top_shadow_frame")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001883 DO_THREAD_OFFSET(TopHandleScopeOffset<ptr_size>(), "top_handle_scope")
Ian Rogersdd7624d2014-03-14 17:43:00 -07001884 DO_THREAD_OFFSET(ThreadSuspendTriggerOffset<ptr_size>(), "suspend_trigger")
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001885#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07001886
Ian Rogersdd7624d2014-03-14 17:43:00 -07001887#define INTERPRETER_ENTRY_POINT_INFO(x) \
1888 if (INTERPRETER_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
1889 os << #x; \
1890 return; \
Elliott Hughes98e20172012-04-24 15:38:13 -07001891 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001892 INTERPRETER_ENTRY_POINT_INFO(pInterpreterToInterpreterBridge)
1893 INTERPRETER_ENTRY_POINT_INFO(pInterpreterToCompiledCodeBridge)
1894#undef INTERPRETER_ENTRY_POINT_INFO
1895
1896#define JNI_ENTRY_POINT_INFO(x) \
1897 if (JNI_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
1898 os << #x; \
1899 return; \
1900 }
1901 JNI_ENTRY_POINT_INFO(pDlsymLookup)
1902#undef JNI_ENTRY_POINT_INFO
1903
Ian Rogersdd7624d2014-03-14 17:43:00 -07001904#define QUICK_ENTRY_POINT_INFO(x) \
1905 if (QUICK_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
1906 os << #x; \
1907 return; \
1908 }
1909 QUICK_ENTRY_POINT_INFO(pAllocArray)
1910 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved)
1911 QUICK_ENTRY_POINT_INFO(pAllocArrayWithAccessCheck)
1912 QUICK_ENTRY_POINT_INFO(pAllocObject)
1913 QUICK_ENTRY_POINT_INFO(pAllocObjectResolved)
1914 QUICK_ENTRY_POINT_INFO(pAllocObjectInitialized)
1915 QUICK_ENTRY_POINT_INFO(pAllocObjectWithAccessCheck)
1916 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArray)
1917 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArrayWithAccessCheck)
1918 QUICK_ENTRY_POINT_INFO(pInstanceofNonTrivial)
1919 QUICK_ENTRY_POINT_INFO(pCheckCast)
1920 QUICK_ENTRY_POINT_INFO(pInitializeStaticStorage)
1921 QUICK_ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccess)
1922 QUICK_ENTRY_POINT_INFO(pInitializeType)
1923 QUICK_ENTRY_POINT_INFO(pResolveString)
Fred Shih37f05ef2014-07-16 18:38:08 -07001924 QUICK_ENTRY_POINT_INFO(pSet8Instance)
1925 QUICK_ENTRY_POINT_INFO(pSet8Static)
1926 QUICK_ENTRY_POINT_INFO(pSet16Instance)
1927 QUICK_ENTRY_POINT_INFO(pSet16Static)
Ian Rogersdd7624d2014-03-14 17:43:00 -07001928 QUICK_ENTRY_POINT_INFO(pSet32Instance)
1929 QUICK_ENTRY_POINT_INFO(pSet32Static)
1930 QUICK_ENTRY_POINT_INFO(pSet64Instance)
1931 QUICK_ENTRY_POINT_INFO(pSet64Static)
1932 QUICK_ENTRY_POINT_INFO(pSetObjInstance)
1933 QUICK_ENTRY_POINT_INFO(pSetObjStatic)
Fred Shih37f05ef2014-07-16 18:38:08 -07001934 QUICK_ENTRY_POINT_INFO(pGetByteInstance)
1935 QUICK_ENTRY_POINT_INFO(pGetBooleanInstance)
1936 QUICK_ENTRY_POINT_INFO(pGetByteStatic)
1937 QUICK_ENTRY_POINT_INFO(pGetBooleanStatic)
1938 QUICK_ENTRY_POINT_INFO(pGetShortInstance)
1939 QUICK_ENTRY_POINT_INFO(pGetCharInstance)
1940 QUICK_ENTRY_POINT_INFO(pGetShortStatic)
1941 QUICK_ENTRY_POINT_INFO(pGetCharStatic)
Ian Rogersdd7624d2014-03-14 17:43:00 -07001942 QUICK_ENTRY_POINT_INFO(pGet32Instance)
1943 QUICK_ENTRY_POINT_INFO(pGet32Static)
1944 QUICK_ENTRY_POINT_INFO(pGet64Instance)
1945 QUICK_ENTRY_POINT_INFO(pGet64Static)
1946 QUICK_ENTRY_POINT_INFO(pGetObjInstance)
1947 QUICK_ENTRY_POINT_INFO(pGetObjStatic)
1948 QUICK_ENTRY_POINT_INFO(pAputObjectWithNullAndBoundCheck)
1949 QUICK_ENTRY_POINT_INFO(pAputObjectWithBoundCheck)
1950 QUICK_ENTRY_POINT_INFO(pAputObject)
1951 QUICK_ENTRY_POINT_INFO(pHandleFillArrayData)
1952 QUICK_ENTRY_POINT_INFO(pJniMethodStart)
1953 QUICK_ENTRY_POINT_INFO(pJniMethodStartSynchronized)
1954 QUICK_ENTRY_POINT_INFO(pJniMethodEnd)
1955 QUICK_ENTRY_POINT_INFO(pJniMethodEndSynchronized)
1956 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReference)
1957 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized)
1958 QUICK_ENTRY_POINT_INFO(pQuickGenericJniTrampoline)
1959 QUICK_ENTRY_POINT_INFO(pLockObject)
1960 QUICK_ENTRY_POINT_INFO(pUnlockObject)
1961 QUICK_ENTRY_POINT_INFO(pCmpgDouble)
1962 QUICK_ENTRY_POINT_INFO(pCmpgFloat)
1963 QUICK_ENTRY_POINT_INFO(pCmplDouble)
1964 QUICK_ENTRY_POINT_INFO(pCmplFloat)
1965 QUICK_ENTRY_POINT_INFO(pFmod)
Ian Rogersdd7624d2014-03-14 17:43:00 -07001966 QUICK_ENTRY_POINT_INFO(pL2d)
1967 QUICK_ENTRY_POINT_INFO(pFmodf)
1968 QUICK_ENTRY_POINT_INFO(pL2f)
1969 QUICK_ENTRY_POINT_INFO(pD2iz)
1970 QUICK_ENTRY_POINT_INFO(pF2iz)
1971 QUICK_ENTRY_POINT_INFO(pIdivmod)
1972 QUICK_ENTRY_POINT_INFO(pD2l)
1973 QUICK_ENTRY_POINT_INFO(pF2l)
1974 QUICK_ENTRY_POINT_INFO(pLdiv)
1975 QUICK_ENTRY_POINT_INFO(pLmod)
1976 QUICK_ENTRY_POINT_INFO(pLmul)
1977 QUICK_ENTRY_POINT_INFO(pShlLong)
1978 QUICK_ENTRY_POINT_INFO(pShrLong)
1979 QUICK_ENTRY_POINT_INFO(pUshrLong)
1980 QUICK_ENTRY_POINT_INFO(pIndexOf)
Ian Rogersdd7624d2014-03-14 17:43:00 -07001981 QUICK_ENTRY_POINT_INFO(pStringCompareTo)
1982 QUICK_ENTRY_POINT_INFO(pMemcpy)
1983 QUICK_ENTRY_POINT_INFO(pQuickImtConflictTrampoline)
1984 QUICK_ENTRY_POINT_INFO(pQuickResolutionTrampoline)
1985 QUICK_ENTRY_POINT_INFO(pQuickToInterpreterBridge)
1986 QUICK_ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck)
1987 QUICK_ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck)
1988 QUICK_ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck)
1989 QUICK_ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck)
1990 QUICK_ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck)
Ian Rogersdd7624d2014-03-14 17:43:00 -07001991 QUICK_ENTRY_POINT_INFO(pTestSuspend)
1992 QUICK_ENTRY_POINT_INFO(pDeliverException)
1993 QUICK_ENTRY_POINT_INFO(pThrowArrayBounds)
1994 QUICK_ENTRY_POINT_INFO(pThrowDivZero)
1995 QUICK_ENTRY_POINT_INFO(pThrowNoSuchMethod)
1996 QUICK_ENTRY_POINT_INFO(pThrowNullPointer)
1997 QUICK_ENTRY_POINT_INFO(pThrowStackOverflow)
Douglas Leungd9cb8ae2014-07-09 14:28:35 -07001998 QUICK_ENTRY_POINT_INFO(pA64Load)
1999 QUICK_ENTRY_POINT_INFO(pA64Store)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002000#undef QUICK_ENTRY_POINT_INFO
2001
Elliott Hughes98e20172012-04-24 15:38:13 -07002002 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07002003}
2004
jeffhao94d6df42012-11-26 16:02:12 -08002005void Thread::QuickDeliverException() {
Ian Rogers62d6c772013-02-27 08:32:07 -08002006 // Get exception from thread.
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002007 mirror::Throwable* exception = GetException();
Dave Allison0aded082013-11-07 13:15:11 -08002008 CHECK(exception != nullptr);
Ian Rogers28ad40d2011-10-27 15:19:26 -07002009 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08002010 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07002011 ClearException();
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002012 bool is_deoptimization = (exception == GetDeoptimizationException());
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002013 QuickExceptionHandler exception_handler(this, is_deoptimization);
2014 if (is_deoptimization) {
2015 exception_handler.DeoptimizeStack();
2016 } else {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002017 exception_handler.FindCatch(exception);
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002018 }
2019 exception_handler.UpdateInstrumentationStack();
2020 exception_handler.DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07002021}
2022
Ian Rogersbdb03912011-09-14 00:55:44 -07002023Context* Thread::GetLongJumpContext() {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002024 Context* result = tlsPtr_.long_jump_context;
Dave Allison0aded082013-11-07 13:15:11 -08002025 if (result == nullptr) {
Ian Rogersbdb03912011-09-14 00:55:44 -07002026 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07002027 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002028 tlsPtr_.long_jump_context = nullptr; // Avoid context being shared.
Mathieu Chartier67022432012-11-29 18:04:50 -08002029 result->Reset();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07002030 }
Ian Rogersbdb03912011-09-14 00:55:44 -07002031 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07002032}
2033
Andreas Gampe4a8c3fa2014-07-16 22:20:31 -07002034// Note: this visitor may return with a method set, but dex_pc_ being DexFile:kDexNoIndex. This is
2035// so we don't abort in a special situation (thinlocked monitor) when dumping the Java stack.
Ian Rogerse0dcd462014-03-08 15:21:04 -08002036struct CurrentMethodVisitor FINAL : public StackVisitor {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002037 CurrentMethodVisitor(Thread* thread, Context* context, bool abort_on_error)
Ian Rogers62d6c772013-02-27 08:32:07 -08002038 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Andreas Gampef9df5c12014-07-25 03:07:06 -07002039 : StackVisitor(thread, context), this_object_(nullptr), method_(nullptr), dex_pc_(0),
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002040 abort_on_error_(abort_on_error) {}
Ian Rogerse0dcd462014-03-08 15:21:04 -08002041 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002042 mirror::ArtMethod* m = GetMethod();
Ian Rogers62d6c772013-02-27 08:32:07 -08002043 if (m->IsRuntimeMethod()) {
2044 // Continue if this is a runtime method.
2045 return true;
Ian Rogers0399dde2012-06-06 17:09:28 -07002046 }
Dave Allison0aded082013-11-07 13:15:11 -08002047 if (context_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002048 this_object_ = GetThisObject();
2049 }
2050 method_ = m;
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002051 dex_pc_ = GetDexPc(abort_on_error_);
Ian Rogers62d6c772013-02-27 08:32:07 -08002052 return false;
2053 }
2054 mirror::Object* this_object_;
Brian Carlstromea46f952013-07-30 01:26:50 -07002055 mirror::ArtMethod* method_;
Ian Rogers62d6c772013-02-27 08:32:07 -08002056 uint32_t dex_pc_;
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002057 const bool abort_on_error_;
Ian Rogers62d6c772013-02-27 08:32:07 -08002058};
Ian Rogers0399dde2012-06-06 17:09:28 -07002059
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -07002060mirror::ArtMethod* Thread::GetCurrentMethod(uint32_t* dex_pc, bool abort_on_error) const {
2061 CurrentMethodVisitor visitor(const_cast<Thread*>(this), nullptr, abort_on_error);
Ian Rogers0399dde2012-06-06 17:09:28 -07002062 visitor.WalkStack(false);
Dave Allison0aded082013-11-07 13:15:11 -08002063 if (dex_pc != nullptr) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002064 *dex_pc = visitor.dex_pc_;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07002065 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002066 return visitor.method_;
jeffhao33dc7712011-11-09 17:54:24 -08002067}
2068
Ian Rogersdd7624d2014-03-14 17:43:00 -07002069bool Thread::HoldsLock(mirror::Object* object) const {
Dave Allison0aded082013-11-07 13:15:11 -08002070 if (object == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -07002071 return false;
2072 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002073 return object->GetLockOwnerThreadId() == GetThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07002074}
2075
Ian Rogers40e3bac2012-11-20 00:09:14 -08002076// RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor).
2077template <typename RootVisitor>
Ian Rogers0399dde2012-06-06 17:09:28 -07002078class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07002079 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08002080 ReferenceMapVisitor(Thread* thread, Context* context, const RootVisitor& visitor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002081 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08002082 : StackVisitor(thread, context), visitor_(visitor) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07002083
Ian Rogersb726dcb2012-09-05 08:57:23 -07002084 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07002085 if (false) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002086 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
Sebastien Hertz714f1752014-04-28 15:03:08 +02002087 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07002088 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002089 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
Dave Allison0aded082013-11-07 13:15:11 -08002090 if (shadow_frame != nullptr) {
Sebastien Hertz714f1752014-04-28 15:03:08 +02002091 VisitShadowFrame(shadow_frame);
2092 } else {
2093 VisitQuickFrame();
2094 }
2095 return true;
2096 }
2097
2098 void VisitShadowFrame(ShadowFrame* shadow_frame) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi92d1a662014-05-15 21:43:59 -07002099 mirror::ArtMethod** method_addr = shadow_frame->GetMethodAddress();
2100 visitor_(reinterpret_cast<mirror::Object**>(method_addr), 0 /*ignored*/, this);
2101 mirror::ArtMethod* m = *method_addr;
2102 DCHECK(m != nullptr);
Sebastien Hertz714f1752014-04-28 15:03:08 +02002103 size_t num_regs = shadow_frame->NumberOfVRegs();
2104 if (m->IsNative() || shadow_frame->HasReferenceArray()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002105 // handle scope for JNI or References for interpreter.
Sebastien Hertz714f1752014-04-28 15:03:08 +02002106 for (size_t reg = 0; reg < num_regs; ++reg) {
2107 mirror::Object* ref = shadow_frame->GetVRegReference(reg);
2108 if (ref != nullptr) {
2109 mirror::Object* new_ref = ref;
2110 visitor_(&new_ref, reg, this);
2111 if (new_ref != ref) {
2112 shadow_frame->SetVRegReference(reg, new_ref);
2113 }
2114 }
2115 }
2116 } else {
2117 // Java method.
2118 // Portable path use DexGcMap and store in Method.native_gc_map_.
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002119 const uint8_t* gc_map = m->GetNativeGcMap(sizeof(void*));
Sebastien Hertz714f1752014-04-28 15:03:08 +02002120 CHECK(gc_map != nullptr) << PrettyMethod(m);
2121 verifier::DexPcToReferenceMap dex_gc_map(gc_map);
2122 uint32_t dex_pc = shadow_frame->GetDexPC();
2123 const uint8_t* reg_bitmap = dex_gc_map.FindBitMap(dex_pc);
2124 DCHECK(reg_bitmap != nullptr);
2125 num_regs = std::min(dex_gc_map.RegWidth() * 8, num_regs);
2126 for (size_t reg = 0; reg < num_regs; ++reg) {
2127 if (TestBitmap(reg, reg_bitmap)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002128 mirror::Object* ref = shadow_frame->GetVRegReference(reg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002129 if (ref != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08002130 mirror::Object* new_ref = ref;
2131 visitor_(&new_ref, reg, this);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002132 if (new_ref != ref) {
Sebastien Hertz714f1752014-04-28 15:03:08 +02002133 shadow_frame->SetVRegReference(reg, new_ref);
TDYa127ce4cc0d2012-11-18 16:59:53 -08002134 }
2135 }
2136 }
2137 }
Sebastien Hertz714f1752014-04-28 15:03:08 +02002138 }
2139 }
2140
2141 private:
2142 void VisitQuickFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampecf4035a2014-05-28 22:43:01 -07002143 StackReference<mirror::ArtMethod>* cur_quick_frame = GetCurrentQuickFrame();
2144 mirror::ArtMethod* m = cur_quick_frame->AsMirrorPtr();
2145 mirror::ArtMethod* old_method = m;
2146 visitor_(reinterpret_cast<mirror::Object**>(&m), 0 /*ignored*/, this);
2147 if (m != old_method) {
2148 cur_quick_frame->Assign(m);
2149 }
2150
Sebastien Hertz714f1752014-04-28 15:03:08 +02002151 // Process register map (which native and runtime methods don't have)
2152 if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002153 if (m->IsOptimized(sizeof(void*))) {
Vladimir Marko4c1c5102014-05-14 16:51:16 +01002154 Runtime* runtime = Runtime::Current();
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002155 const void* entry_point = runtime->GetInstrumentation()->GetQuickCodeFor(m, sizeof(void*));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002156 uintptr_t native_pc_offset = m->NativeQuickPcOffset(GetCurrentQuickFramePc(), entry_point);
Nicolas Geoffray39468442014-09-02 15:17:15 +01002157 StackMap map = m->GetStackMap(native_pc_offset);
2158 MemoryRegion mask = map.GetStackMask();
Nicolas Geoffray98893962015-01-21 12:32:32 +00002159 // Visit stack entries that hold pointers.
Nicolas Geoffray39468442014-09-02 15:17:15 +01002160 for (size_t i = 0; i < mask.size_in_bits(); ++i) {
2161 if (mask.LoadBit(i)) {
2162 StackReference<mirror::Object>* ref_addr =
2163 reinterpret_cast<StackReference<mirror::Object>*>(cur_quick_frame) + i;
2164 mirror::Object* ref = ref_addr->AsMirrorPtr();
2165 if (ref != nullptr) {
2166 mirror::Object* new_ref = ref;
2167 visitor_(&new_ref, -1, this);
2168 if (ref != new_ref) {
2169 ref_addr->Assign(new_ref);
Sebastien Hertz714f1752014-04-28 15:03:08 +02002170 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01002171 }
2172 }
2173 }
Nicolas Geoffray98893962015-01-21 12:32:32 +00002174 // Visit callee-save registers that hold pointers.
2175 uint32_t register_mask = map.GetRegisterMask();
2176 for (size_t i = 0; i < BitSizeOf<uint32_t>(); ++i) {
2177 if (register_mask & (1 << i)) {
2178 mirror::Object** ref_addr = reinterpret_cast<mirror::Object**>(GetGPRAddress(i));
2179 if (*ref_addr != nullptr) {
2180 visitor_(ref_addr, -1, this);
2181 }
2182 }
2183 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01002184 } else {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002185 const uint8_t* native_gc_map = m->GetNativeGcMap(sizeof(void*));
Nicolas Geoffray39468442014-09-02 15:17:15 +01002186 CHECK(native_gc_map != nullptr) << PrettyMethod(m);
2187 const DexFile::CodeItem* code_item = m->GetCodeItem();
2188 // Can't be nullptr or how would we compile its instructions?
2189 DCHECK(code_item != nullptr) << PrettyMethod(m);
2190 NativePcOffsetToReferenceMap map(native_gc_map);
2191 size_t num_regs = std::min(map.RegWidth() * 8,
2192 static_cast<size_t>(code_item->registers_size_));
2193 if (num_regs > 0) {
2194 Runtime* runtime = Runtime::Current();
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002195 const void* entry_point = runtime->GetInstrumentation()->GetQuickCodeFor(m, sizeof(void*));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002196 uintptr_t native_pc_offset = m->NativeQuickPcOffset(GetCurrentQuickFramePc(), entry_point);
Nicolas Geoffray39468442014-09-02 15:17:15 +01002197 const uint8_t* reg_bitmap = map.FindBitMap(native_pc_offset);
2198 DCHECK(reg_bitmap != nullptr);
2199 const void* code_pointer = mirror::ArtMethod::EntryPointToCodePointer(entry_point);
Mathieu Chartiera7dd0382014-11-20 17:08:58 -08002200 const VmapTable vmap_table(m->GetVmapTable(code_pointer, sizeof(void*)));
Nicolas Geoffray39468442014-09-02 15:17:15 +01002201 QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
2202 // For all dex registers in the bitmap
Nicolas Geoffray39468442014-09-02 15:17:15 +01002203 DCHECK(cur_quick_frame != nullptr);
2204 for (size_t reg = 0; reg < num_regs; ++reg) {
2205 // Does this register hold a reference?
2206 if (TestBitmap(reg, reg_bitmap)) {
2207 uint32_t vmap_offset;
2208 if (vmap_table.IsInContext(reg, kReferenceVReg, &vmap_offset)) {
2209 int vmap_reg = vmap_table.ComputeRegister(frame_info.CoreSpillMask(), vmap_offset,
2210 kReferenceVReg);
2211 // This is sound as spilled GPRs will be word sized (ie 32 or 64bit).
2212 mirror::Object** ref_addr =
2213 reinterpret_cast<mirror::Object**>(GetGPRAddress(vmap_reg));
2214 if (*ref_addr != nullptr) {
2215 visitor_(ref_addr, reg, this);
2216 }
2217 } else {
2218 StackReference<mirror::Object>* ref_addr =
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00002219 reinterpret_cast<StackReference<mirror::Object>*>(GetVRegAddrFromQuickCode(
2220 cur_quick_frame, code_item, frame_info.CoreSpillMask(),
2221 frame_info.FpSpillMask(), frame_info.FrameSizeInBytes(), reg));
Nicolas Geoffray39468442014-09-02 15:17:15 +01002222 mirror::Object* ref = ref_addr->AsMirrorPtr();
2223 if (ref != nullptr) {
2224 mirror::Object* new_ref = ref;
2225 visitor_(&new_ref, reg, this);
2226 if (ref != new_ref) {
2227 ref_addr->Assign(new_ref);
2228 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002229 }
Ian Rogers0c7abda2012-09-19 13:33:42 -07002230 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002231 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07002232 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002233 }
2234 }
2235 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002236 }
2237
Mathieu Chartier815873e2014-02-13 18:02:13 -08002238 static bool TestBitmap(size_t reg, const uint8_t* reg_vector) {
2239 return ((reg_vector[reg / kBitsPerByte] >> (reg % kBitsPerByte)) & 0x01) != 0;
Ian Rogersd6b1f612011-09-27 13:38:14 -07002240 }
2241
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002242 // Visitor for when we visit a root.
Ian Rogers40e3bac2012-11-20 00:09:14 -08002243 const RootVisitor& visitor_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07002244};
2245
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002246class RootCallbackVisitor {
2247 public:
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002248 RootCallbackVisitor(RootCallback* callback, void* arg, uint32_t tid)
2249 : callback_(callback), arg_(arg), tid_(tid) {}
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002250
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002251 void operator()(mirror::Object** obj, size_t vreg, const StackVisitor* stack_visitor) const {
2252 callback_(obj, arg_, JavaFrameRootInfo(tid_, stack_visitor, vreg));
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002253 }
2254
2255 private:
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002256 RootCallback* const callback_;
Ian Rogers40e3bac2012-11-20 00:09:14 -08002257 void* const arg_;
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002258 const uint32_t tid_;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002259};
2260
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002261void Thread::VisitRoots(RootCallback* visitor, void* arg) {
2262 uint32_t thread_id = GetThreadId();
Ian Rogersdd7624d2014-03-14 17:43:00 -07002263 if (tlsPtr_.opeer != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002264 visitor(&tlsPtr_.opeer, arg, RootInfo(kRootThreadObject, thread_id));
Ian Rogerscfaa4552012-11-26 21:00:08 -08002265 }
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02002266 if (tlsPtr_.exception != nullptr && tlsPtr_.exception != GetDeoptimizationException()) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002267 visitor(reinterpret_cast<mirror::Object**>(&tlsPtr_.exception), arg,
2268 RootInfo(kRootNativeStack, thread_id));
Elliott Hughesd369bb72011-09-12 14:41:14 -07002269 }
Mathieu Chartier43d8bb82014-04-03 09:57:36 -07002270 if (tlsPtr_.monitor_enter_object != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002271 visitor(&tlsPtr_.monitor_enter_object, arg, RootInfo(kRootNativeStack, thread_id));
Mathieu Chartier43d8bb82014-04-03 09:57:36 -07002272 }
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002273 tlsPtr_.jni_env->locals.VisitRoots(visitor, arg, RootInfo(kRootJNILocal, thread_id));
2274 tlsPtr_.jni_env->monitors.VisitRoots(visitor, arg, RootInfo(kRootJNIMonitor, thread_id));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002275 HandleScopeVisitRoots(visitor, arg, thread_id);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002276 if (tlsPtr_.debug_invoke_req != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002277 tlsPtr_.debug_invoke_req->VisitRoots(visitor, arg, RootInfo(kRootDebugger, thread_id));
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07002278 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002279 if (tlsPtr_.single_step_control != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002280 tlsPtr_.single_step_control->VisitRoots(visitor, arg, RootInfo(kRootDebugger, thread_id));
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07002281 }
Sebastien Hertz714f1752014-04-28 15:03:08 +02002282 if (tlsPtr_.deoptimization_shadow_frame != nullptr) {
2283 RootCallbackVisitor visitorToCallback(visitor, arg, thread_id);
2284 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, nullptr, visitorToCallback);
2285 for (ShadowFrame* shadow_frame = tlsPtr_.deoptimization_shadow_frame; shadow_frame != nullptr;
2286 shadow_frame = shadow_frame->GetLink()) {
2287 mapper.VisitShadowFrame(shadow_frame);
2288 }
2289 }
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -07002290 if (tlsPtr_.shadow_frame_under_construction != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002291 RootCallbackVisitor visitor_to_callback(visitor, arg, thread_id);
2292 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, nullptr, visitor_to_callback);
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -07002293 for (ShadowFrame* shadow_frame = tlsPtr_.shadow_frame_under_construction;
2294 shadow_frame != nullptr;
2295 shadow_frame = shadow_frame->GetLink()) {
2296 mapper.VisitShadowFrame(shadow_frame);
2297 }
2298 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002299 // Visit roots on this thread's stack
Ian Rogers0399dde2012-06-06 17:09:28 -07002300 Context* context = GetLongJumpContext();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002301 RootCallbackVisitor visitor_to_callback(visitor, arg, thread_id);
2302 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context, visitor_to_callback);
Ian Rogers0399dde2012-06-06 17:09:28 -07002303 mapper.WalkStack();
2304 ReleaseLongJumpContext(context);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002305 for (instrumentation::InstrumentationStackFrame& frame : *GetInstrumentationStack()) {
2306 if (frame.this_object_ != nullptr) {
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002307 visitor(&frame.this_object_, arg, RootInfo(kRootVMInternal, thread_id));
Ian Rogers62d6c772013-02-27 08:32:07 -08002308 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002309 DCHECK(frame.method_ != nullptr);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002310 visitor(reinterpret_cast<mirror::Object**>(&frame.method_), arg,
2311 RootInfo(kRootVMInternal, thread_id));
Ian Rogers62d6c772013-02-27 08:32:07 -08002312 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07002313}
2314
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002315static void VerifyRoot(mirror::Object** root, void* /*arg*/, const RootInfo& /*root_info*/)
2316 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08002317 VerifyObject(*root);
jeffhao25045522012-03-13 19:34:37 -07002318}
2319
Ian Rogers04d7aa92013-03-16 14:29:17 -07002320void Thread::VerifyStackImpl() {
Ian Rogers700a4022014-05-19 16:49:03 -07002321 std::unique_ptr<Context> context(Context::Create());
Mathieu Chartier89bb1442014-02-12 10:06:23 -08002322 RootCallbackVisitor visitorToCallback(VerifyRoot, Runtime::Current()->GetHeap(), GetThreadId());
Ian Rogers04d7aa92013-03-16 14:29:17 -07002323 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context.get(), visitorToCallback);
Ian Rogers0399dde2012-06-06 17:09:28 -07002324 mapper.WalkStack();
jeffhao25045522012-03-13 19:34:37 -07002325}
jeffhao25045522012-03-13 19:34:37 -07002326
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002327// Set the stack end to that to be used during a stack overflow
2328void Thread::SetStackEndForStackOverflow() {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002329 // During stack overflow we allow use of the full stack.
Ian Rogersdd7624d2014-03-14 17:43:00 -07002330 if (tlsPtr_.stack_end == tlsPtr_.stack_begin) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002331 // However, we seem to have already extended to use the full stack.
2332 LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently "
Andreas Gampe7ea6f792014-07-14 16:21:44 -07002333 << GetStackOverflowReservedBytes(kRuntimeISA) << ")?";
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002334 DumpStack(LOG(ERROR));
2335 LOG(FATAL) << "Recursive stack overflow.";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002336 }
2337
Ian Rogersdd7624d2014-03-14 17:43:00 -07002338 tlsPtr_.stack_end = tlsPtr_.stack_begin;
Dave Allison648d7112014-07-25 16:15:27 -07002339
2340 // Remove the stack overflow protection if is it set up.
2341 bool implicit_stack_check = !Runtime::Current()->ExplicitStackOverflowChecks();
2342 if (implicit_stack_check) {
2343 if (!UnprotectStack()) {
2344 LOG(ERROR) << "Unable to remove stack protection for stack overflow";
2345 }
2346 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002347}
2348
Ian Rogers13735952014-10-08 12:43:28 -07002349void Thread::SetTlab(uint8_t* start, uint8_t* end) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002350 DCHECK_LE(start, end);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002351 tlsPtr_.thread_local_start = start;
2352 tlsPtr_.thread_local_pos = tlsPtr_.thread_local_start;
2353 tlsPtr_.thread_local_end = end;
2354 tlsPtr_.thread_local_objects = 0;
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002355}
2356
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002357bool Thread::HasTlab() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002358 bool has_tlab = tlsPtr_.thread_local_pos != nullptr;
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002359 if (has_tlab) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002360 DCHECK(tlsPtr_.thread_local_start != nullptr && tlsPtr_.thread_local_end != nullptr);
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002361 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002362 DCHECK(tlsPtr_.thread_local_start == nullptr && tlsPtr_.thread_local_end == nullptr);
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002363 }
2364 return has_tlab;
2365}
2366
Elliott Hughes330304d2011-08-12 14:28:05 -07002367std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002368 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07002369 return os;
2370}
2371
Dave Allison648d7112014-07-25 16:15:27 -07002372void Thread::ProtectStack() {
2373 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
2374 VLOG(threads) << "Protecting stack at " << pregion;
2375 if (mprotect(pregion, kStackOverflowProtectedSize, PROT_NONE) == -1) {
2376 LOG(FATAL) << "Unable to create protected region in stack for implicit overflow check. "
2377 "Reason: "
2378 << strerror(errno) << " size: " << kStackOverflowProtectedSize;
2379 }
2380}
2381
2382bool Thread::UnprotectStack() {
2383 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
2384 VLOG(threads) << "Unprotecting stack at " << pregion;
2385 return mprotect(pregion, kStackOverflowProtectedSize, PROT_READ|PROT_WRITE) == 0;
2386}
2387
Sebastien Hertz597c4f02015-01-26 17:37:14 +01002388void Thread::ActivateSingleStepControl(SingleStepControl* ssc) {
2389 CHECK(Dbg::IsDebuggerActive());
2390 CHECK(GetSingleStepControl() == nullptr) << "Single step already active in thread " << *this;
2391 CHECK(ssc != nullptr);
2392 tlsPtr_.single_step_control = ssc;
2393}
2394
2395void Thread::DeactivateSingleStepControl() {
2396 CHECK(Dbg::IsDebuggerActive());
2397 CHECK(GetSingleStepControl() != nullptr) << "Single step not active in thread " << *this;
2398 SingleStepControl* ssc = GetSingleStepControl();
2399 tlsPtr_.single_step_control = nullptr;
2400 delete ssc;
2401}
Dave Allison648d7112014-07-25 16:15:27 -07002402
Sebastien Hertz1558b572015-02-25 15:05:59 +01002403void Thread::SetDebugInvokeReq(DebugInvokeReq* req) {
2404 CHECK(Dbg::IsDebuggerActive());
2405 CHECK(GetInvokeReq() == nullptr) << "Debug invoke req already active in thread " << *this;
2406 CHECK(Thread::Current() != this) << "Debug invoke can't be dispatched by the thread itself";
2407 CHECK(req != nullptr);
2408 tlsPtr_.debug_invoke_req = req;
2409}
2410
2411void Thread::ClearDebugInvokeReq() {
2412 CHECK(Dbg::IsDebuggerActive());
2413 CHECK(GetInvokeReq() != nullptr) << "Debug invoke req not active in thread " << *this;
2414 CHECK(Thread::Current() == this) << "Debug invoke must be finished by the thread itself";
2415 // We do not own the DebugInvokeReq* so we must not delete it, it is the responsibility of
2416 // the owner (the JDWP thread).
2417 tlsPtr_.debug_invoke_req = nullptr;
2418}
2419
Elliott Hughes8daa0922011-09-11 13:46:25 -07002420} // namespace art