blob: 3692b9fd62bcf8ea0c507130d48440a4f1ba0b50 [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>
Carl Shapirob5573532011-07-12 18:22:59 -070032
Ian Rogers166db042013-07-26 12:05:57 -070033#include "arch/context.h"
Elliott Hughes76b61672012-12-12 17:47:30 -080034#include "base/mutex.h"
Sebastien Hertzd45a1f52014-01-09 14:56:54 +010035#include "catch_finder.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070036#include "class_linker.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "class_linker-inl.h"
Ian Rogers474b6da2012-09-25 00:20:38 -070038#include "cutils/atomic.h"
39#include "cutils/atomic-inline.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"
46#include "gc/heap.h"
47#include "gc/space/space.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070048#include "jni_internal.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070049#include "mirror/art_field-inl.h"
50#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080051#include "mirror/class-inl.h"
52#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "mirror/object_array-inl.h"
54#include "mirror/stack_trace_element.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070055#include "monitor.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080056#include "object_utils.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -050057#include "reflection.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070058#include "runtime.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070059#include "scoped_thread_state_change.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070060#include "ScopedLocalRef.h"
Anwar Ghuloum3c539ff2013-06-20 08:58:23 -070061#include "ScopedUtfChars.h"
Ian Rogers1f539342012-10-03 21:09:42 -070062#include "sirt_ref.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070063#include "stack.h"
64#include "stack_indirect_reference_table.h"
Ian Rogers693ff612013-02-01 10:56:12 -080065#include "thread-inl.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070066#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070067#include "utils.h"
TDYa127ce4cc0d2012-11-18 16:59:53 -080068#include "verifier/dex_gc_map.h"
Mathieu Chartier4e305412014-02-19 10:54:44 -080069#include "verify_object-inl.h"
Ian Rogers1809a722013-08-09 22:05:32 -070070#include "vmap_table.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070071#include "well_known_classes.h"
Carl Shapirob5573532011-07-12 18:22:59 -070072
73namespace art {
74
Ian Rogers0878d652013-04-18 17:38:35 -070075bool Thread::is_started_ = false;
Carl Shapirob5573532011-07-12 18:22:59 -070076pthread_key_t Thread::pthread_key_self_;
Dave Allison0aded082013-11-07 13:15:11 -080077ConditionVariable* Thread::resume_cond_ = nullptr;
Carl Shapirob5573532011-07-12 18:22:59 -070078
Elliott Hughes7dc51662012-05-16 14:48:43 -070079static const char* kThreadNameDuringStartup = "<native thread without managed peer>";
80
Ian Rogers5d76c432011-10-31 21:42:49 -070081void Thread::InitCardTable() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080082 card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -070083}
84
Elliott Hughes99250ba2012-04-17 11:09:17 -070085#if !defined(__APPLE__)
Elliott Hughes3ea0f422012-04-16 17:01:43 -070086static void UnimplementedEntryPoint() {
87 UNIMPLEMENTED(FATAL);
88}
Elliott Hughes99250ba2012-04-17 11:09:17 -070089#endif
Elliott Hughes3ea0f422012-04-16 17:01:43 -070090
Ian Rogers848871b2013-08-05 10:56:33 -070091void InitEntryPoints(InterpreterEntryPoints* ipoints, JniEntryPoints* jpoints,
92 PortableEntryPoints* ppoints, QuickEntryPoints* qpoints);
Ian Rogers7655f292013-07-29 11:07:13 -070093
Ian Rogers848871b2013-08-05 10:56:33 -070094void Thread::InitTlsEntryPoints() {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070095#if !defined(__APPLE__) // The Mac GCC is too old to accept this code.
Elliott Hughes3ea0f422012-04-16 17:01:43 -070096 // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
Ian Rogers848871b2013-08-05 10:56:33 -070097 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&interpreter_entrypoints_);
Ian Rogers7655f292013-07-29 11:07:13 -070098 uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(begin) + sizeof(quick_entrypoints_));
99 for (uintptr_t* it = begin; it != end; ++it) {
100 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
101 }
Ian Rogers848871b2013-08-05 10:56:33 -0700102 begin = reinterpret_cast<uintptr_t*>(&interpreter_entrypoints_);
Ian Rogers7655f292013-07-29 11:07:13 -0700103 end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(begin) + sizeof(portable_entrypoints_));
Elliott Hughes3ea0f422012-04-16 17:01:43 -0700104 for (uintptr_t* it = begin; it != end; ++it) {
105 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
106 }
Elliott Hughes99250ba2012-04-17 11:09:17 -0700107#endif
Ian Rogers848871b2013-08-05 10:56:33 -0700108 InitEntryPoints(&interpreter_entrypoints_, &jni_entrypoints_, &portable_entrypoints_,
109 &quick_entrypoints_);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700110}
111
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700112void Thread::ResetQuickAllocEntryPointsForThread() {
113 ResetQuickAllocEntryPoints(&quick_entrypoints_);
114}
115
Ian Rogers62d6c772013-02-27 08:32:07 -0800116void Thread::SetDeoptimizationShadowFrame(ShadowFrame* sf) {
117 deoptimization_shadow_frame_ = sf;
buzbee3ea4ec52011-08-22 17:37:19 -0700118}
119
Ian Rogers62d6c772013-02-27 08:32:07 -0800120void Thread::SetDeoptimizationReturnValue(const JValue& ret_val) {
Ian Rogers306057f2012-11-26 12:45:53 -0800121 deoptimization_return_value_.SetJ(ret_val.GetJ());
122}
123
124ShadowFrame* Thread::GetAndClearDeoptimizationShadowFrame(JValue* ret_val) {
125 ShadowFrame* sf = deoptimization_shadow_frame_;
Dave Allison0aded082013-11-07 13:15:11 -0800126 deoptimization_shadow_frame_ = nullptr;
Ian Rogers306057f2012-11-26 12:45:53 -0800127 ret_val->SetJ(deoptimization_return_value_.GetJ());
128 return sf;
129}
130
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700131void Thread::InitTid() {
132 tid_ = ::art::GetTid();
133}
134
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700135void Thread::InitAfterFork() {
Elliott Hughes8029cbe2012-05-22 09:13:08 -0700136 // One thread (us) survived the fork, but we have a new tid so we need to
137 // update the value stashed in this Thread*.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700138 InitTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700139}
140
Brian Carlstrom78128a62011-09-15 17:21:19 -0700141void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700142 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogers120f1c72012-09-28 17:17:10 -0700143 Runtime* runtime = Runtime::Current();
Dave Allison0aded082013-11-07 13:15:11 -0800144 if (runtime == nullptr) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700145 LOG(ERROR) << "Thread attaching to non-existent runtime: " << *self;
Dave Allison0aded082013-11-07 13:15:11 -0800146 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700147 }
148 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700149 // TODO: pass self to MutexLock - requires self to equal Thread::Current(), which is only true
150 // after self->Init().
Dave Allison0aded082013-11-07 13:15:11 -0800151 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700152 // Check that if we got here we cannot be shutting down (as shutdown should never have started
153 // while threads are being born).
Mathieu Chartier590fee92013-09-13 13:46:47 -0700154 CHECK(!runtime->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700155 self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
156 Runtime::Current()->EndThreadBirth();
157 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700158 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700159 ScopedObjectAccess soa(self);
Ian Rogerscfaa4552012-11-26 21:00:08 -0800160
161 // Copy peer into self, deleting global reference when done.
Dave Allison0aded082013-11-07 13:15:11 -0800162 CHECK(self->jpeer_ != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800163 self->opeer_ = soa.Decode<mirror::Object*>(self->jpeer_);
Ian Rogerscfaa4552012-11-26 21:00:08 -0800164 self->GetJniEnv()->DeleteGlobalRef(self->jpeer_);
Dave Allison0aded082013-11-07 13:15:11 -0800165 self->jpeer_ = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800166
Ian Rogers365c1022012-06-22 15:05:28 -0700167 {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800168 SirtRef<mirror::String> thread_name(self, self->GetThreadName(soa));
Ian Rogers365c1022012-06-22 15:05:28 -0700169 self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
170 }
Ian Rogers365c1022012-06-22 15:05:28 -0700171 Dbg::PostThreadStart(self);
172
173 // Invoke the 'run' method of our java.lang.Thread.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800174 mirror::Object* receiver = self->opeer_;
Ian Rogers365c1022012-06-22 15:05:28 -0700175 jmethodID mid = WellKnownClasses::java_lang_Thread_run;
Ian Rogers53b8b092014-03-13 23:45:53 -0700176 InvokeVirtualOrInterfaceWithJValues(soa, receiver, mid, nullptr);
Elliott Hughes47179f72011-10-27 16:44:39 -0700177 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700178 // Detach and delete self.
179 Runtime::Current()->GetThreadList()->Unregister(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700180
Dave Allison0aded082013-11-07 13:15:11 -0800181 return nullptr;
Carl Shapirob5573532011-07-12 18:22:59 -0700182}
183
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800184Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa,
185 mirror::Object* thread_peer) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700186 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800187 Thread* result = reinterpret_cast<Thread*>(static_cast<uintptr_t>(f->GetLong(thread_peer)));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700188 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_
189 // to stop it from going away.
Ian Rogers81d425b2012-09-27 16:03:43 -0700190 if (kIsDebugBuild) {
191 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -0800192 if (result != nullptr && !result->IsSuspended()) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700193 Locks::thread_list_lock_->AssertHeld(soa.Self());
194 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700195 }
196 return result;
Elliott Hughes761928d2011-11-16 18:33:03 -0800197}
198
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700199Thread* Thread::FromManagedThread(const ScopedObjectAccessUnchecked& soa, jobject java_thread) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800200 return FromManagedThread(soa, soa.Decode<mirror::Object*>(java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700201}
202
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700203static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700204 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700205 if (stack_size == 0) {
206 stack_size = Runtime::Current()->GetDefaultStackSize();
207 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700208
Brian Carlstrom6414a972012-04-14 14:20:04 -0700209 // Dalvik used the bionic pthread default stack size for native threads,
210 // so include that here to support apps that expect large native stacks.
211 stack_size += 1 * MB;
212
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700213 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
214 if (stack_size < PTHREAD_STACK_MIN) {
215 stack_size = PTHREAD_STACK_MIN;
216 }
217
Dave Allisonf9439142014-03-27 15:10:22 -0700218 if (Runtime::Current()->ExplicitStackOverflowChecks()) {
219 // It's likely that callers are trying to ensure they have at least a certain amount of
220 // stack space, so we should add our reserved space on top of what they requested, rather
221 // than implicitly take it away from them.
222 stack_size += Thread::kStackOverflowReservedBytes;
223 } else {
224 // If we are going to use implicit stack checks, allocate space for the protected
225 // region at the bottom of the stack.
226 stack_size += Thread::kStackOverflowImplicitCheckSize;
227 }
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700228
229 // Some systems require the stack size to be a multiple of the system page size, so round up.
230 stack_size = RoundUp(stack_size, kPageSize);
231
232 return stack_size;
233}
234
Dave Allisonf9439142014-03-27 15:10:22 -0700235// Install a protected region in the stack. This is used to trigger a SIGSEGV if a stack
236// overflow is detected. It is located right below the stack_end_. Just below that
237// is the StackOverflow reserved region used when creating the StackOverflow
238// exception.
239void Thread::InstallImplicitProtection(bool is_main_stack) {
240 byte* pregion = stack_end_;
241
242 constexpr uint32_t kMarker = 0xdadadada;
243 uintptr_t *marker = reinterpret_cast<uintptr_t*>(pregion);
244 if (*marker == kMarker) {
245 // The region has already been set up.
246 return;
247 }
248 // Add marker so that we can detect a second attempt to do this.
249 *marker = kMarker;
250
251 pregion -= kStackOverflowProtectedSize;
252
253 // Touch the pages in the region to map them in. Otherwise mprotect fails. Only
254 // need to do this on the main stack.
255 if (is_main_stack) {
256 memset(pregion, 0x55, kStackOverflowProtectedSize);
257 }
258 VLOG(threads) << "installing stack protected region at " << std::hex <<
259 static_cast<void*>(pregion) << " to " <<
260 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1);
261
262 if (mprotect(pregion, kStackOverflowProtectedSize, PROT_NONE) == -1) {
263 LOG(FATAL) << "Unable to create protected region in stack for implicit overflow check. Reason:"
264 << strerror(errno);
265 }
266}
267
Ian Rogers120f1c72012-09-28 17:17:10 -0700268void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
Dave Allison0aded082013-11-07 13:15:11 -0800269 CHECK(java_peer != nullptr);
Ian Rogers120f1c72012-09-28 17:17:10 -0700270 Thread* self = static_cast<JNIEnvExt*>(env)->self;
271 Runtime* runtime = Runtime::Current();
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700272
Ian Rogers120f1c72012-09-28 17:17:10 -0700273 // Atomically start the birth of the thread ensuring the runtime isn't shutting down.
274 bool thread_start_during_shutdown = false;
Elliott Hughes47179f72011-10-27 16:44:39 -0700275 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700276 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700277 if (runtime->IsShuttingDownLocked()) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700278 thread_start_during_shutdown = true;
279 } else {
280 runtime->StartThreadBirth();
281 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700282 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700283 if (thread_start_during_shutdown) {
284 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError"));
285 env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown");
286 return;
287 }
288
289 Thread* child_thread = new Thread(is_daemon);
290 // Use global JNI ref to hold peer live while child thread starts.
Ian Rogerscfaa4552012-11-26 21:00:08 -0800291 child_thread->jpeer_ = env->NewGlobalRef(java_peer);
Ian Rogers120f1c72012-09-28 17:17:10 -0700292 stack_size = FixStackSize(stack_size);
293
Anwar Ghuloum3c50a4b2013-06-21 13:05:23 -0700294 // 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 -0700295 // assign it.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800296 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer,
297 reinterpret_cast<jlong>(child_thread));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700298
299 pthread_t new_pthread;
300 pthread_attr_t attr;
301 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
302 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
303 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
Ian Rogers120f1c72012-09-28 17:17:10 -0700304 int pthread_create_result = pthread_create(&new_pthread, &attr, Thread::CreateCallback, child_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700305 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
306
Ian Rogers120f1c72012-09-28 17:17:10 -0700307 if (pthread_create_result != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700308 // pthread_create(3) failed, so clean up.
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700309 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700310 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
311 runtime->EndThreadBirth();
312 }
313 // Manually delete the global reference since Thread::Init will not have been run.
Ian Rogerscfaa4552012-11-26 21:00:08 -0800314 env->DeleteGlobalRef(child_thread->jpeer_);
Dave Allison0aded082013-11-07 13:15:11 -0800315 child_thread->jpeer_ = nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700316 delete child_thread;
Dave Allison0aded082013-11-07 13:15:11 -0800317 child_thread = nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700318 // TODO: remove from thread group?
Ian Rogersef7d42f2014-01-06 12:55:46 -0800319 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 0);
Ian Rogers120f1c72012-09-28 17:17:10 -0700320 {
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700321 std::string msg(StringPrintf("pthread_create (%s stack) failed: %s",
322 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
Ian Rogers120f1c72012-09-28 17:17:10 -0700323 ScopedObjectAccess soa(env);
324 soa.Self()->ThrowOutOfMemoryError(msg.c_str());
Brian Carlstrom9efc3e02012-08-17 17:47:17 -0700325 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700326 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700327}
328
Ian Rogers120f1c72012-09-28 17:17:10 -0700329void Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700330 // This function does all the initialization that must be run by the native thread it applies to.
331 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
332 // we can handshake with the corresponding native thread when it's ready.) Check this native
333 // thread hasn't been through here already...
Dave Allison0aded082013-11-07 13:15:11 -0800334 CHECK(Thread::Current() == nullptr);
Elliott Hughesd8af1592012-04-16 20:40:15 -0700335 SetUpAlternateSignalStack();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700336 InitCpu();
Ian Rogers848871b2013-08-05 10:56:33 -0700337 InitTlsEntryPoints();
Dave Allisonb373e092014-02-20 16:06:36 -0800338 RemoveSuspendTrigger();
Ian Rogers5d76c432011-10-31 21:42:49 -0700339 InitCardTable();
Ian Rogers01ae5802012-09-28 16:14:01 -0700340 InitTid();
Ian Rogers120f1c72012-09-28 17:17:10 -0700341 // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this
342 // avoids pthread_self_ ever being invalid when discovered from Thread::Current().
Elliott Hughes0d39c122012-06-06 16:41:17 -0700343 pthread_self_ = pthread_self();
Ian Rogers0878d652013-04-18 17:38:35 -0700344 CHECK(is_started_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700345 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
346 DCHECK_EQ(Thread::Current(), this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700347
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700348 thin_lock_thread_id_ = thread_list->AllocThreadId(this);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700349 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700350
Ian Rogers120f1c72012-09-28 17:17:10 -0700351 jni_env_ = new JNIEnvExt(this, java_vm);
352 thread_list->Register(this);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700353}
354
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800355Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group,
356 bool create_peer) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700357 Thread* self;
358 Runtime* runtime = Runtime::Current();
Dave Allison0aded082013-11-07 13:15:11 -0800359 if (runtime == nullptr) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700360 LOG(ERROR) << "Thread attaching to non-existent runtime: " << thread_name;
Dave Allison0aded082013-11-07 13:15:11 -0800361 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700362 }
363 {
Dave Allison0aded082013-11-07 13:15:11 -0800364 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700365 if (runtime->IsShuttingDownLocked()) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700366 LOG(ERROR) << "Thread attaching while runtime is shutting down: " << thread_name;
Dave Allison0aded082013-11-07 13:15:11 -0800367 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700368 } else {
369 Runtime::Current()->StartThreadBirth();
370 self = new Thread(as_daemon);
371 self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
372 Runtime::Current()->EndThreadBirth();
373 }
374 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700375
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700376 CHECK_NE(self->GetState(), kRunnable);
377 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700378
Elliott Hughescac6cc72011-11-03 20:31:21 -0700379 // If we're the main thread, ClassLinker won't be created until after we're attached,
380 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800381 // In the compiler, all threads need this hack, because no-one's going to be getting
382 // a native peer!
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800383 if (create_peer) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700384 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800385 } else {
386 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Dave Allison0aded082013-11-07 13:15:11 -0800387 if (thread_name != nullptr) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700388 self->name_->assign(thread_name);
389 ::art::SetThreadName(thread_name);
390 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700391 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700392
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700393 return self;
394}
395
Ian Rogers365c1022012-06-22 15:05:28 -0700396void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
397 Runtime* runtime = Runtime::Current();
398 CHECK(runtime->IsStarted());
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700399 JNIEnv* env = jni_env_;
400
Dave Allison0aded082013-11-07 13:15:11 -0800401 if (thread_group == nullptr) {
Ian Rogers365c1022012-06-22 15:05:28 -0700402 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -0700403 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700404 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Elliott Hughes8daa0922011-09-11 13:46:25 -0700405 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700406 jboolean thread_is_daemon = as_daemon;
407
Elliott Hugheseac76672012-05-24 21:56:51 -0700408 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Dave Allison0aded082013-11-07 13:15:11 -0800409 if (peer.get() == nullptr) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700410 CHECK(IsExceptionPending());
411 return;
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700412 }
Ian Rogerscfaa4552012-11-26 21:00:08 -0800413 {
414 ScopedObjectAccess soa(this);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800415 opeer_ = soa.Decode<mirror::Object*>(peer.get());
Ian Rogerscfaa4552012-11-26 21:00:08 -0800416 }
Elliott Hugheseac76672012-05-24 21:56:51 -0700417 env->CallNonvirtualVoidMethod(peer.get(),
418 WellKnownClasses::java_lang_Thread,
419 WellKnownClasses::java_lang_Thread_init,
Ian Rogers365c1022012-06-22 15:05:28 -0700420 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700421 AssertNoPendingException();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700422
Ian Rogers120f1c72012-09-28 17:17:10 -0700423 Thread* self = this;
424 DCHECK_EQ(self, Thread::Current());
Ian Rogersef7d42f2014-01-06 12:55:46 -0800425 jni_env_->SetLongField(peer.get(), WellKnownClasses::java_lang_Thread_nativePeer,
426 reinterpret_cast<jlong>(self));
Ian Rogers120f1c72012-09-28 17:17:10 -0700427
428 ScopedObjectAccess soa(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800429 SirtRef<mirror::String> peer_thread_name(soa.Self(), GetThreadName(soa));
Dave Allison0aded082013-11-07 13:15:11 -0800430 if (peer_thread_name.get() == nullptr) {
Brian Carlstrom00fae582011-10-28 01:16:28 -0700431 // The Thread constructor should have set the Thread.name to a
432 // non-null value. However, because we can run without code
433 // available (in the compiler, in tests), we manually assign the
434 // fields the constructor should have set.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100435 if (runtime->IsActiveTransaction()) {
436 InitPeer<true>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority);
437 } else {
438 InitPeer<false>(soa, thread_is_daemon, thread_group, thread_name.get(), thread_priority);
439 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700440 peer_thread_name.reset(GetThreadName(soa));
Brian Carlstrom00fae582011-10-28 01:16:28 -0700441 }
Elliott Hughes225f5a12012-06-11 11:23:48 -0700442 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Dave Allison0aded082013-11-07 13:15:11 -0800443 if (peer_thread_name.get() != nullptr) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800444 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700445 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700446}
447
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100448template<bool kTransactionActive>
449void Thread::InitPeer(ScopedObjectAccess& soa, jboolean thread_is_daemon, jobject thread_group,
450 jobject thread_name, jint thread_priority) {
451 soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->
452 SetBoolean<kTransactionActive>(opeer_, thread_is_daemon);
453 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->
454 SetObject<kTransactionActive>(opeer_, soa.Decode<mirror::Object*>(thread_group));
455 soa.DecodeField(WellKnownClasses::java_lang_Thread_name)->
456 SetObject<kTransactionActive>(opeer_, soa.Decode<mirror::Object*>(thread_name));
457 soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->
458 SetInt<kTransactionActive>(opeer_, thread_priority);
459}
460
Elliott Hughes899e7892012-01-24 14:57:32 -0800461void Thread::SetThreadName(const char* name) {
462 name_->assign(name);
463 ::art::SetThreadName(name);
464 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
465}
466
Elliott Hughesbe759c62011-09-08 19:38:21 -0700467void Thread::InitStackHwm() {
Elliott Hughese1884192012-04-23 12:38:15 -0700468 void* stack_base;
469 size_t stack_size;
Brian Carlstrom29212012013-09-12 22:18:30 -0700470 GetThreadStack(pthread_self_, &stack_base, &stack_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700471
472 // TODO: include this in the thread dumps; potentially useful in SIGQUIT output?
Elliott Hughese1884192012-04-23 12:38:15 -0700473 VLOG(threads) << StringPrintf("Native stack is at %p (%s)", stack_base, PrettySize(stack_size).c_str());
474
475 stack_begin_ = reinterpret_cast<byte*>(stack_base);
476 stack_size_ = stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -0700477
Ian Rogers932746a2011-09-22 18:57:50 -0700478 if (stack_size_ <= kStackOverflowReservedBytes) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800479 LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700480 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700481
Elliott Hughese1884192012-04-23 12:38:15 -0700482 // TODO: move this into the Linux GetThreadStack implementation.
483#if !defined(__APPLE__)
Elliott Hughes36ecb782012-04-17 16:55:45 -0700484 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
485 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
486 // will be broken because we'll die long before we get close to 2GB.
Ian Rogers120f1c72012-09-28 17:17:10 -0700487 bool is_main_thread = (::art::GetTid() == getpid());
488 if (is_main_thread) {
Elliott Hughes36ecb782012-04-17 16:55:45 -0700489 rlimit stack_limit;
490 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
491 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
492 }
493 if (stack_limit.rlim_cur == RLIM_INFINITY) {
494 // Find the default stack size for new threads...
495 pthread_attr_t default_attributes;
496 size_t default_stack_size;
497 CHECK_PTHREAD_CALL(pthread_attr_init, (&default_attributes), "default stack size query");
498 CHECK_PTHREAD_CALL(pthread_attr_getstacksize, (&default_attributes, &default_stack_size),
499 "default stack size query");
500 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&default_attributes), "default stack size query");
501
502 // ...and use that as our limit.
503 size_t old_stack_size = stack_size_;
504 stack_size_ = default_stack_size;
505 stack_begin_ += (old_stack_size - stack_size_);
Elliott Hughesfaf4ba02012-05-02 16:12:19 -0700506 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
507 << " to " << PrettySize(stack_size_)
508 << " with base " << reinterpret_cast<void*>(stack_begin_);
Elliott Hughes36ecb782012-04-17 16:55:45 -0700509 }
510 }
Elliott Hughese1884192012-04-23 12:38:15 -0700511#endif
Elliott Hughes36ecb782012-04-17 16:55:45 -0700512
Ian Rogers932746a2011-09-22 18:57:50 -0700513 // Set stack_end_ to the bottom of the stack saving space of stack overflows
Dave Allisonf9439142014-03-27 15:10:22 -0700514 bool implicit_stack_check = !Runtime::Current()->ExplicitStackOverflowChecks();
515 ResetDefaultStackEnd(implicit_stack_check);
516
517 // Install the protected region if we are doing implicit overflow checks.
518 if (implicit_stack_check) {
519 if (is_main_thread) {
520 // The main thread has a 16K protected region at the bottom. We need
521 // to install our own region so we need to move the limits
522 // of the stack to make room for it.
523 constexpr uint32_t kDelta = 16 * KB;
524 stack_begin_ += kDelta;
525 stack_end_ += kDelta;
526 stack_size_ -= kDelta;
527 }
528 InstallImplicitProtection(is_main_thread);
529 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700530
531 // Sanity check.
532 int stack_variable;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700533 CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
Elliott Hughesbe759c62011-09-08 19:38:21 -0700534}
535
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700536void Thread::ShortDump(std::ostream& os) const {
537 os << "Thread[";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700538 if (GetThreadId() != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700539 // If we're in kStarting, we won't have a thin lock id or tid yet.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700540 os << GetThreadId()
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700541 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -0700542 }
Ian Rogers474b6da2012-09-25 00:20:38 -0700543 os << GetState()
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700544 << ",Thread*=" << this
Ian Rogerscfaa4552012-11-26 21:00:08 -0800545 << ",peer=" << opeer_
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700546 << ",\"" << *name_ << "\""
547 << "]";
Elliott Hughesa0957642011-09-02 14:27:33 -0700548}
549
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700550void Thread::Dump(std::ostream& os) const {
551 DumpState(os);
552 DumpStack(os);
553}
554
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800555mirror::String* Thread::GetThreadName(const ScopedObjectAccessUnchecked& soa) const {
Brian Carlstromea46f952013-07-30 01:26:50 -0700556 mirror::ArtField* f = soa.DecodeField(WellKnownClasses::java_lang_Thread_name);
Dave Allison0aded082013-11-07 13:15:11 -0800557 return (opeer_ != nullptr) ? reinterpret_cast<mirror::String*>(f->GetObject(opeer_)) : nullptr;
Elliott Hughesfc861622011-10-17 17:57:47 -0700558}
559
Elliott Hughesffb465f2012-03-01 18:46:05 -0800560void Thread::GetThreadName(std::string& name) const {
561 name.assign(*name_);
562}
563
Jeff Hao57dac6e2013-08-15 16:36:24 -0700564uint64_t Thread::GetCpuMicroTime() const {
565#if defined(HAVE_POSIX_CLOCKS)
566 clockid_t cpu_clock_id;
567 pthread_getcpuclockid(pthread_self_, &cpu_clock_id);
568 timespec now;
569 clock_gettime(cpu_clock_id, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700570 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Jeff Hao57dac6e2013-08-15 16:36:24 -0700571#else
572 UNIMPLEMENTED(WARNING);
573 return -1;
574#endif
575}
576
Ian Rogers474b6da2012-09-25 00:20:38 -0700577void Thread::AtomicSetFlag(ThreadFlag flag) {
Ian Rogers30e173f2012-09-26 14:35:03 -0700578 android_atomic_or(flag, &state_and_flags_.as_int);
Ian Rogers474b6da2012-09-25 00:20:38 -0700579}
580
581void Thread::AtomicClearFlag(ThreadFlag flag) {
Ian Rogers30e173f2012-09-26 14:35:03 -0700582 android_atomic_and(-1 ^ flag, &state_and_flags_.as_int);
Ian Rogers474b6da2012-09-25 00:20:38 -0700583}
584
Ian Rogers01ae5802012-09-28 16:14:01 -0700585// Attempt to rectify locks so that we dump thread list with required locks before exiting.
586static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers120f1c72012-09-28 17:17:10 -0700587 LOG(ERROR) << *thread << " suspend count already zero.";
Ian Rogers01ae5802012-09-28 16:14:01 -0700588 Locks::thread_suspend_count_lock_->Unlock(self);
589 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
590 Locks::mutator_lock_->SharedTryLock(self);
591 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
592 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
593 }
594 }
595 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
596 Locks::thread_list_lock_->TryLock(self);
597 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
598 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
599 }
600 }
601 std::ostringstream ss;
602 Runtime::Current()->GetThreadList()->DumpLocked(ss);
Ian Rogers120f1c72012-09-28 17:17:10 -0700603 LOG(FATAL) << ss.str();
Ian Rogers01ae5802012-09-28 16:14:01 -0700604}
605
606void Thread::ModifySuspendCount(Thread* self, int delta, bool for_debugger) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700607 DCHECK(delta == -1 || delta == +1 || delta == -debug_suspend_count_)
608 << delta << " " << debug_suspend_count_ << " " << this;
609 DCHECK_GE(suspend_count_, debug_suspend_count_) << this;
Ian Rogers01ae5802012-09-28 16:14:01 -0700610 Locks::thread_suspend_count_lock_->AssertHeld(self);
Ian Rogerscfaa4552012-11-26 21:00:08 -0800611 if (this != self && !IsSuspended()) {
612 Locks::thread_list_lock_->AssertHeld(self);
613 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700614 if (UNLIKELY(delta < 0 && suspend_count_ <= 0)) {
615 UnsafeLogFatalForSuspendCount(self, this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700616 return;
617 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700618
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700619 suspend_count_ += delta;
620 if (for_debugger) {
621 debug_suspend_count_ += delta;
622 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700623
Ian Rogers474b6da2012-09-25 00:20:38 -0700624 if (suspend_count_ == 0) {
625 AtomicClearFlag(kSuspendRequest);
626 } else {
627 AtomicSetFlag(kSuspendRequest);
Dave Allisonb373e092014-02-20 16:06:36 -0800628 TriggerSuspend();
Ian Rogers474b6da2012-09-25 00:20:38 -0700629 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700630}
631
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700632void Thread::RunCheckpointFunction() {
Dave Allison0aded082013-11-07 13:15:11 -0800633 Closure *checkpoints[kMaxCheckpoints];
634
635 // Grab the suspend_count lock and copy the current set of
636 // checkpoints. Then clear the list and the flag. The RequestCheckpoint
637 // function will also grab this lock so we prevent a race between setting
638 // the kCheckpointRequest flag and clearing it.
639 {
640 MutexLock mu(this, *Locks::thread_suspend_count_lock_);
641 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
642 checkpoints[i] = checkpoint_functions_[i];
643 checkpoint_functions_[i] = nullptr;
644 }
645 AtomicClearFlag(kCheckpointRequest);
646 }
647
648 // Outside the lock, run all the checkpoint functions that
649 // we collected.
650 bool found_checkpoint = false;
651 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
652 if (checkpoints[i] != nullptr) {
653 ATRACE_BEGIN("Checkpoint function");
654 checkpoints[i]->Run(this);
655 ATRACE_END();
656 found_checkpoint = true;
657 }
658 }
659 CHECK(found_checkpoint);
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700660}
661
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700662bool Thread::RequestCheckpoint(Closure* function) {
Chris Dearman59cde532013-12-04 18:53:49 -0800663 union StateAndFlags old_state_and_flags;
664 old_state_and_flags.as_int = state_and_flags_.as_int;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700665 if (old_state_and_flags.as_struct.state != kRunnable) {
666 return false; // Fail, thread is suspended and so can't run a checkpoint.
667 }
Dave Allison0aded082013-11-07 13:15:11 -0800668
669 uint32_t available_checkpoint = kMaxCheckpoints;
670 for (uint32_t i = 0 ; i < kMaxCheckpoints; ++i) {
671 if (checkpoint_functions_[i] == nullptr) {
672 available_checkpoint = i;
673 break;
674 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700675 }
Dave Allison0aded082013-11-07 13:15:11 -0800676 if (available_checkpoint == kMaxCheckpoints) {
677 // No checkpoint functions available, we can't run a checkpoint
678 return false;
679 }
680 checkpoint_functions_[available_checkpoint] = function;
681
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700682 // Checkpoint function installed now install flag bit.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700683 // We must be runnable to request a checkpoint.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800684 DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable);
Chris Dearman59cde532013-12-04 18:53:49 -0800685 union StateAndFlags new_state_and_flags;
686 new_state_and_flags.as_int = old_state_and_flags.as_int;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700687 new_state_and_flags.as_struct.flags |= kCheckpointRequest;
Dave Allison0aded082013-11-07 13:15:11 -0800688 int succeeded = android_atomic_acquire_cas(old_state_and_flags.as_int, new_state_and_flags.as_int,
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700689 &state_and_flags_.as_int);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700690 if (UNLIKELY(succeeded != 0)) {
691 // The thread changed state before the checkpoint was installed.
Dave Allison0aded082013-11-07 13:15:11 -0800692 CHECK_EQ(checkpoint_functions_[available_checkpoint], function);
693 checkpoint_functions_[available_checkpoint] = nullptr;
694 } else {
695 CHECK_EQ(ReadFlag(kCheckpointRequest), true);
Dave Allisonb373e092014-02-20 16:06:36 -0800696 TriggerSuspend();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700697 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700698 return succeeded == 0;
699}
700
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700701void Thread::FullSuspendCheck() {
702 VLOG(threads) << this << " self-suspending";
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700703 ATRACE_BEGIN("Full suspend check");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700704 // Make thread appear suspended to other threads, release mutator_lock_.
705 TransitionFromRunnableToSuspended(kSuspended);
706 // Transition back to runnable noting requests to suspend, re-acquire share on mutator_lock_.
707 TransitionFromSuspendedToRunnable();
Mathieu Chartier752a0e62013-06-27 11:03:27 -0700708 ATRACE_END();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700709 VLOG(threads) << this << " self-reviving";
710}
711
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700712void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700713 std::string group_name;
714 int priority;
715 bool is_daemon = false;
Ian Rogers81d425b2012-09-27 16:03:43 -0700716 Thread* self = Thread::Current();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700717
Dave Allison0aded082013-11-07 13:15:11 -0800718 if (self != nullptr && thread != nullptr && thread->opeer_ != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800719 ScopedObjectAccessUnchecked soa(self);
720 priority = soa.DecodeField(WellKnownClasses::java_lang_Thread_priority)->GetInt(thread->opeer_);
721 is_daemon = soa.DecodeField(WellKnownClasses::java_lang_Thread_daemon)->GetBoolean(thread->opeer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700722
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800723 mirror::Object* thread_group =
Ian Rogerscfaa4552012-11-26 21:00:08 -0800724 soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(thread->opeer_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700725
Dave Allison0aded082013-11-07 13:15:11 -0800726 if (thread_group != nullptr) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700727 mirror::ArtField* group_name_field =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800728 soa.DecodeField(WellKnownClasses::java_lang_ThreadGroup_name);
729 mirror::String* group_name_string =
730 reinterpret_cast<mirror::String*>(group_name_field->GetObject(thread_group));
Dave Allison0aded082013-11-07 13:15:11 -0800731 group_name = (group_name_string != nullptr) ? group_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughesd369bb72011-09-12 14:41:14 -0700732 }
733 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700734 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700735 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700736
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700737 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700738 if (scheduler_group_name.empty()) {
739 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700740 }
741
Dave Allison0aded082013-11-07 13:15:11 -0800742 if (thread != nullptr) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700743 os << '"' << *thread->name_ << '"';
744 if (is_daemon) {
745 os << " daemon";
746 }
747 os << " prio=" << priority
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700748 << " tid=" << thread->GetThreadId()
Elliott Hughes80537bb2013-01-04 16:37:26 -0800749 << " " << thread->GetState();
750 if (thread->IsStillStarting()) {
751 os << " (still starting up)";
752 }
753 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700754 } else {
Elliott Hughes289be852012-06-12 13:57:20 -0700755 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700756 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700757 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700758 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700759
Dave Allison0aded082013-11-07 13:15:11 -0800760 if (thread != nullptr) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700761 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700762 os << " | group=\"" << group_name << "\""
763 << " sCount=" << thread->suspend_count_
764 << " dsCount=" << thread->debug_suspend_count_
Ian Rogerscfaa4552012-11-26 21:00:08 -0800765 << " obj=" << reinterpret_cast<void*>(thread->opeer_)
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700766 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
767 }
Elliott Hughes0d39c122012-06-06 16:41:17 -0700768
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700769 os << " | sysTid=" << tid
770 << " nice=" << getpriority(PRIO_PROCESS, tid)
Elliott Hughes0d39c122012-06-06 16:41:17 -0700771 << " cgrp=" << scheduler_group_name;
Dave Allison0aded082013-11-07 13:15:11 -0800772 if (thread != nullptr) {
Elliott Hughes0d39c122012-06-06 16:41:17 -0700773 int policy;
774 sched_param sp;
775 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->pthread_self_, &policy, &sp), __FUNCTION__);
776 os << " sched=" << policy << "/" << sp.sched_priority
777 << " handle=" << reinterpret_cast<void*>(thread->pthread_self_);
778 }
779 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700780
781 // Grab the scheduler stats for this thread.
782 std::string scheduler_stats;
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700783 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid), &scheduler_stats)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700784 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
Elliott Hughesd92bec42011-09-02 17:04:36 -0700785 } else {
786 scheduler_stats = "0 0 0";
787 }
788
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700789 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -0700790 int utime = 0;
791 int stime = 0;
792 int task_cpu = 0;
Brian Carlstrom29212012013-09-12 22:18:30 -0700793 GetTaskStats(tid, &native_thread_state, &utime, &stime, &task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700794
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700795 os << " | state=" << native_thread_state
796 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -0700797 << " utm=" << utime
798 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700799 << " core=" << task_cpu
800 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
Dave Allison0aded082013-11-07 13:15:11 -0800801 if (thread != nullptr) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700802 os << " | stack=" << reinterpret_cast<void*>(thread->stack_begin_) << "-" << reinterpret_cast<void*>(thread->stack_end_)
803 << " stackSize=" << PrettySize(thread->stack_size_) << "\n";
804 }
805}
806
807void Thread::DumpState(std::ostream& os) const {
808 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700809}
810
Ian Rogers0399dde2012-06-06 17:09:28 -0700811struct StackDumpVisitor : public StackVisitor {
Ian Rogers7a22fa62013-01-23 12:16:16 -0800812 StackDumpVisitor(std::ostream& os, Thread* thread, Context* context, bool can_allocate)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700813 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -0800814 : StackVisitor(thread, context), os(os), thread(thread), can_allocate(can_allocate),
Dave Allison0aded082013-11-07 13:15:11 -0800815 last_method(nullptr), last_line_number(0), repetition_count(0), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700816 }
817
Ian Rogersbdb03912011-09-14 00:55:44 -0700818 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -0700819 if (frame_count == 0) {
820 os << " (no managed stack frames)\n";
821 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700822 }
823
Ian Rogersb726dcb2012-09-05 08:57:23 -0700824 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700825 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -0700826 if (m->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700827 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700828 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700829 const int kMaxRepetition = 3;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800830 mirror::Class* c = m->GetDeclaringClass();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800831 mirror::DexCache* dex_cache = c->GetDexCache();
Ian Rogersb861dc02011-11-14 17:00:05 -0800832 int line_number = -1;
Dave Allison0aded082013-11-07 13:15:11 -0800833 if (dex_cache != nullptr) { // be tolerant of bad input
Ian Rogers4445a7e2012-10-05 17:19:13 -0700834 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers0399dde2012-06-06 17:09:28 -0700835 line_number = dex_file.GetLineNumFromPC(m, GetDexPc());
Ian Rogersb861dc02011-11-14 17:00:05 -0800836 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700837 if (line_number == last_line_number && last_method == m) {
Dave Allison0aded082013-11-07 13:15:11 -0800838 ++repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700839 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700840 if (repetition_count >= kMaxRepetition) {
841 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
842 }
843 repetition_count = 0;
844 last_line_number = line_number;
845 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700846 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700847 if (repetition_count < kMaxRepetition) {
848 os << " at " << PrettyMethod(m, false);
849 if (m->IsNative()) {
850 os << "(Native method)";
851 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800852 mh.ChangeMethod(m);
853 const char* source_file(mh.GetDeclaringClassSourceFile());
Dave Allison0aded082013-11-07 13:15:11 -0800854 os << "(" << (source_file != nullptr ? source_file : "unavailable")
Brian Carlstrom2e450bf2013-09-06 15:39:46 -0700855 << ":" << line_number << ")";
Ian Rogers28ad40d2011-10-27 15:19:26 -0700856 }
857 os << "\n";
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700858 if (frame_count == 0) {
859 Monitor::DescribeWait(os, thread);
860 }
861 if (can_allocate) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800862 Monitor::VisitLocks(this, DumpLockedObject, &os);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700863 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700864 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700865
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700866 ++frame_count;
Elliott Hughes530fa002012-03-12 11:44:49 -0700867 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700868 }
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800869
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800870 static void DumpLockedObject(mirror::Object* o, void* context)
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800871 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
872 std::ostream& os = *reinterpret_cast<std::ostream*>(context);
873 os << " - locked <" << o << "> (a " << PrettyTypeOf(o) << ")\n";
874 }
875
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700876 std::ostream& os;
877 const Thread* thread;
Ian Rogers0878d652013-04-18 17:38:35 -0700878 const bool can_allocate;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800879 MethodHelper mh;
Brian Carlstromea46f952013-07-30 01:26:50 -0700880 mirror::ArtMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700881 int last_line_number;
882 int repetition_count;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700883 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700884};
885
Ian Rogers33e95662013-05-20 20:29:14 -0700886static bool ShouldShowNativeStack(const Thread* thread)
887 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesaef701d2013-04-05 18:15:40 -0700888 ThreadState state = thread->GetState();
889
890 // In native code somewhere in the VM (one of the kWaitingFor* states)? That's interesting.
891 if (state > kWaiting && state < kStarting) {
892 return true;
893 }
894
895 // In an Object.wait variant or Thread.sleep? That's not interesting.
896 if (state == kTimedWaiting || state == kSleeping || state == kWaiting) {
897 return false;
898 }
899
900 // In some other native method? That's interesting.
901 // We don't just check kNative because native methods will be in state kSuspended if they're
902 // calling back into the VM, or kBlocked if they're blocked on a monitor, or one of the
903 // thread-startup states if it's early enough in their life cycle (http://b/7432159).
Dave Allison0aded082013-11-07 13:15:11 -0800904 mirror::ArtMethod* current_method = thread->GetCurrentMethod(nullptr);
905 return current_method != nullptr && current_method->IsNative();
Elliott Hughesaef701d2013-04-05 18:15:40 -0700906}
907
Elliott Hughesd92bec42011-09-02 17:04:36 -0700908void Thread::DumpStack(std::ostream& os) const {
Jeff Haoed1790e2013-04-12 09:58:14 -0700909 // TODO: we call this code when dying but may not have suspended the thread ourself. The
910 // IsSuspended check is therefore racy with the use for dumping (normally we inhibit
911 // the race with the thread_suspend_count_lock_).
Ian Rogers65530492013-08-19 08:54:22 -0700912 // No point dumping for an abort in debug builds where we'll hit the not suspended check in stack.
913 bool dump_for_abort = (gAborting > 0) && !kIsDebugBuild;
Ian Rogersd090cf42013-06-06 15:35:18 -0700914 if (this == Thread::Current() || IsSuspended() || dump_for_abort) {
Ian Rogersf08e4732013-04-09 09:45:49 -0700915 // If we're currently in native code, dump that stack before dumping the managed stack.
Ian Rogersd090cf42013-06-06 15:35:18 -0700916 if (dump_for_abort || ShouldShowNativeStack(this)) {
Ian Rogersf08e4732013-04-09 09:45:49 -0700917 DumpKernelStack(os, GetTid(), " kernel: ", false);
Kenny Root067d20f2014-03-05 14:57:21 -0800918 SirtRef<mirror::ArtMethod> method_ref(Thread::Current(), GetCurrentMethod(nullptr));
919 DumpNativeStack(os, GetTid(), " native: ", false, method_ref.get());
Ian Rogersf08e4732013-04-09 09:45:49 -0700920 }
921 UniquePtr<Context> context(Context::Create());
922 StackDumpVisitor dumper(os, const_cast<Thread*>(this), context.get(), !throwing_OutOfMemoryError_);
923 dumper.WalkStack();
924 } else {
925 os << "Not able to dump stack of thread that isn't suspended";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800926 }
Elliott Hughese27955c2011-08-26 15:21:24 -0700927}
928
Elliott Hughesbe759c62011-09-08 19:38:21 -0700929void Thread::ThreadExitCallback(void* arg) {
930 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700931 if (self->thread_exit_check_count_ == 0) {
932 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's going to use a pthread_key_create destructor?): " << *self;
Ian Rogers0878d652013-04-18 17:38:35 -0700933 CHECK(is_started_);
Elliott Hughes6a607ad2012-07-13 20:40:00 -0700934 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
935 self->thread_exit_check_count_ = 1;
936 } else {
937 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
938 }
Carl Shapirob5573532011-07-12 18:22:59 -0700939}
940
Elliott Hughesbe759c62011-09-08 19:38:21 -0700941void Thread::Startup() {
Ian Rogers0878d652013-04-18 17:38:35 -0700942 CHECK(!is_started_);
943 is_started_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700944 {
Brian Carlstrom6d69f592013-07-16 17:18:16 -0700945 // MutexLock to keep annotalysis happy.
946 //
Dave Allison0aded082013-11-07 13:15:11 -0800947 // Note we use nullptr for the thread because Thread::Current can
Brian Carlstrom6d69f592013-07-16 17:18:16 -0700948 // return garbage since (is_started_ == true) and
949 // Thread::pthread_key_self_ is not yet initialized.
950 // This was seen on glibc.
Dave Allison0aded082013-11-07 13:15:11 -0800951 MutexLock mu(nullptr, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700952 resume_cond_ = new ConditionVariable("Thread resumption condition variable",
953 *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700954 }
955
Carl Shapirob5573532011-07-12 18:22:59 -0700956 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700957 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700958
959 // Double-check the TLS slot allocation.
Dave Allison0aded082013-11-07 13:15:11 -0800960 if (pthread_getspecific(pthread_key_self_) != nullptr) {
961 LOG(FATAL) << "Newly-created pthread TLS slot is not nullptr";
Carl Shapirob5573532011-07-12 18:22:59 -0700962 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700963}
Carl Shapirob5573532011-07-12 18:22:59 -0700964
Elliott Hughes038a8062011-09-18 14:12:41 -0700965void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -0700966 Runtime* runtime = Runtime::Current();
967 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700968
Elliott Hughes01158d72011-09-19 19:47:10 -0700969 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700970 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -0700971 Thread::Current()->CreatePeer("main", false, runtime->GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500972
Elliott Hughesaf8d15a2012-05-29 09:12:18 -0700973 Runtime::Current()->GetClassLinker()->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700974}
975
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700976void Thread::Shutdown() {
Ian Rogers0878d652013-04-18 17:38:35 -0700977 CHECK(is_started_);
978 is_started_ = false;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700979 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Ian Rogers33e95662013-05-20 20:29:14 -0700980 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -0800981 if (resume_cond_ != nullptr) {
Ian Rogers0878d652013-04-18 17:38:35 -0700982 delete resume_cond_;
Dave Allison0aded082013-11-07 13:15:11 -0800983 resume_cond_ = nullptr;
Ian Rogers0878d652013-04-18 17:38:35 -0700984 }
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700985}
986
Ian Rogers52673ff2012-06-27 23:25:34 -0700987Thread::Thread(bool daemon)
Ian Rogers0399dde2012-06-06 17:09:28 -0700988 : suspend_count_(0),
Dave Allison0aded082013-11-07 13:15:11 -0800989 card_table_(nullptr),
990 exception_(nullptr),
991 stack_end_(nullptr),
Ian Rogers0399dde2012-06-06 17:09:28 -0700992 managed_stack_(),
Dave Allison0aded082013-11-07 13:15:11 -0800993 jni_env_(nullptr),
994 self_(nullptr),
995 opeer_(nullptr),
996 jpeer_(nullptr),
997 stack_begin_(nullptr),
Ian Rogers0399dde2012-06-06 17:09:28 -0700998 stack_size_(0),
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700999 thin_lock_thread_id_(0),
Dave Allison0aded082013-11-07 13:15:11 -08001000 stack_trace_sample_(nullptr),
Jeff Hao5ce4b172013-08-16 16:27:18 -07001001 trace_clock_base_(0),
Ian Rogers0399dde2012-06-06 17:09:28 -07001002 tid_(0),
Elliott Hughese62934d2012-04-09 11:24:29 -07001003 wait_mutex_(new Mutex("a thread wait mutex")),
Ian Rogersc604d732012-10-14 16:09:54 -07001004 wait_cond_(new ConditionVariable("a thread wait condition variable", *wait_mutex_)),
Dave Allison0aded082013-11-07 13:15:11 -08001005 wait_monitor_(nullptr),
Elliott Hughes8daa0922011-09-11 13:46:25 -07001006 interrupted_(false),
Dave Allison0aded082013-11-07 13:15:11 -08001007 wait_next_(nullptr),
1008 monitor_enter_object_(nullptr),
1009 top_sirt_(nullptr),
1010 runtime_(nullptr),
1011 class_loader_override_(nullptr),
1012 long_jump_context_(nullptr),
Elliott Hughes726079d2011-10-07 18:43:44 -07001013 throwing_OutOfMemoryError_(false),
Ian Rogers0399dde2012-06-06 17:09:28 -07001014 debug_suspend_count_(0),
jeffhaoe343b762011-12-05 16:36:44 -08001015 debug_invoke_req_(new DebugInvokeReq),
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01001016 single_step_control_(new SingleStepControl),
Dave Allison0aded082013-11-07 13:15:11 -08001017 deoptimization_shadow_frame_(nullptr),
Ian Rogers62d6c772013-02-27 08:32:07 -08001018 instrumentation_stack_(new std::deque<instrumentation::InstrumentationStackFrame>),
Ian Rogers0399dde2012-06-06 17:09:28 -07001019 name_(new std::string(kThreadNameDuringStartup)),
Ian Rogers52673ff2012-06-27 23:25:34 -07001020 daemon_(daemon),
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001021 pthread_self_(0),
Ian Rogers52673ff2012-06-27 23:25:34 -07001022 no_thread_suspension_(0),
Dave Allison0aded082013-11-07 13:15:11 -08001023 last_no_thread_suspension_cause_(nullptr),
Dave Allisonf9439142014-03-27 15:10:22 -07001024 suspend_trigger_(reinterpret_cast<uintptr_t*>(&suspend_trigger_)),
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001025 thread_exit_check_count_(0),
1026 thread_local_start_(nullptr),
1027 thread_local_pos_(nullptr),
1028 thread_local_end_(nullptr),
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001029 thread_local_objects_(0),
1030 thread_local_alloc_stack_top_(nullptr),
1031 thread_local_alloc_stack_end_(nullptr) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -07001032 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Ian Rogers30e173f2012-09-26 14:35:03 -07001033 state_and_flags_.as_struct.flags = 0;
1034 state_and_flags_.as_struct.state = kNative;
Elliott Hughesffb465f2012-03-01 18:46:05 -08001035 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001036 memset(rosalloc_runs_, 0, sizeof(rosalloc_runs_));
Dave Allison0aded082013-11-07 13:15:11 -08001037 for (uint32_t i = 0; i < kMaxCheckpoints; ++i) {
1038 checkpoint_functions_[i] = nullptr;
1039 }
Elliott Hughesdcc24742011-09-07 14:02:44 -07001040}
1041
Elliott Hughes7dc51662012-05-16 14:48:43 -07001042bool Thread::IsStillStarting() const {
1043 // You might think you can check whether the state is kStarting, but for much of thread startup,
Elliott Hughes80537bb2013-01-04 16:37:26 -08001044 // the thread is in kNative; it might also be in kVmWait.
Dave Allison0aded082013-11-07 13:15:11 -08001045 // 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 -07001046 // assigned fairly early on, and needs to be.
1047 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
1048 // this thread _ever_ entered kRunnable".
Dave Allison0aded082013-11-07 13:15:11 -08001049 return (jpeer_ == nullptr && opeer_ == nullptr) || (*name_ == kThreadNameDuringStartup);
Elliott Hughes7dc51662012-05-16 14:48:43 -07001050}
1051
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001052void Thread::AssertNoPendingException() const {
1053 if (UNLIKELY(IsExceptionPending())) {
1054 ScopedObjectAccess soa(Thread::Current());
Dave Allison0aded082013-11-07 13:15:11 -08001055 mirror::Throwable* exception = GetException(nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001056 LOG(FATAL) << "No pending exception expected: " << exception->Dump();
1057 }
1058}
1059
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001060void Thread::AssertNoPendingExceptionForNewException(const char* msg) const {
1061 if (UNLIKELY(IsExceptionPending())) {
1062 ScopedObjectAccess soa(Thread::Current());
1063 mirror::Throwable* exception = GetException(nullptr);
1064 LOG(FATAL) << "Throwing new exception " << msg << " with unexpected pending exception: "
1065 << exception->Dump();
1066 }
1067}
1068
Mathieu Chartier815873e2014-02-13 18:02:13 -08001069static void MonitorExitVisitor(mirror::Object** object, void* arg, uint32_t /*thread_id*/,
1070 RootType /*root_type*/)
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001071 NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001072 Thread* self = reinterpret_cast<Thread*>(arg);
Mathieu Chartier815873e2014-02-13 18:02:13 -08001073 mirror::Object* entered_monitor = *object;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001074 if (self->HoldsLock(entered_monitor)) {
1075 LOG(WARNING) << "Calling MonitorExit on object "
Mathieu Chartier815873e2014-02-13 18:02:13 -08001076 << object << " (" << PrettyTypeOf(entered_monitor) << ")"
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001077 << " left locked by native thread "
1078 << *Thread::Current() << " which is detaching";
1079 entered_monitor->MonitorExit(self);
1080 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07001081}
1082
Elliott Hughesc0f09332012-03-26 13:27:06 -07001083void Thread::Destroy() {
Ian Rogers120f1c72012-09-28 17:17:10 -07001084 Thread* self = this;
1085 DCHECK_EQ(self, Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07001086
Dave Allison0aded082013-11-07 13:15:11 -08001087 if (opeer_ != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001088 ScopedObjectAccess soa(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001089 // We may need to call user-supplied managed code, do this before final clean-up.
Ian Rogerscfaa4552012-11-26 21:00:08 -08001090 HandleUncaughtExceptions(soa);
1091 RemoveFromThreadGroup(soa);
Elliott Hughes534da072012-03-27 15:17:42 -07001092
Anwar Ghuloum3c50a4b2013-06-21 13:05:23 -07001093 // this.nativePeer = 0;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001094 if (Runtime::Current()->IsActiveTransaction()) {
1095 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer)->SetLong<true>(opeer_, 0);
1096 } else {
1097 soa.DecodeField(WellKnownClasses::java_lang_Thread_nativePeer)->SetLong<false>(opeer_, 0);
1098 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001099 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001100
Ian Rogerscfaa4552012-11-26 21:00:08 -08001101 // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone
1102 // who is waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001103 mirror::Object* lock =
1104 soa.DecodeField(WellKnownClasses::java_lang_Thread_lock)->GetObject(opeer_);
Elliott Hughes038a8062011-09-18 14:12:41 -07001105 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001106 if (lock != nullptr) {
1107 SirtRef<mirror::Object> sirt_obj(self, lock);
1108 ObjectLock<mirror::Object> locker(self, &sirt_obj);
Ian Rogers05f30572013-02-20 12:13:11 -08001109 locker.Notify();
Elliott Hughes5f791332011-09-15 17:45:30 -07001110 }
1111 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001112
1113 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Dave Allison0aded082013-11-07 13:15:11 -08001114 if (jni_env_ != nullptr) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001115 jni_env_->monitors.VisitRoots(MonitorExitVisitor, self, 0, kRootVMInternal);
Ian Rogers120f1c72012-09-28 17:17:10 -07001116 }
Elliott Hughesc0f09332012-03-26 13:27:06 -07001117}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001118
Elliott Hughesc0f09332012-03-26 13:27:06 -07001119Thread::~Thread() {
Dave Allison0aded082013-11-07 13:15:11 -08001120 if (jni_env_ != nullptr && jpeer_ != nullptr) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001121 // If pthread_create fails we don't have a jni env here.
Ian Rogerscfaa4552012-11-26 21:00:08 -08001122 jni_env_->DeleteGlobalRef(jpeer_);
Dave Allison0aded082013-11-07 13:15:11 -08001123 jpeer_ = nullptr;
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001124 }
Dave Allison0aded082013-11-07 13:15:11 -08001125 opeer_ = nullptr;
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001126
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001127 bool initialized = (jni_env_ != nullptr); // Did Thread::Init run?
1128 if (initialized) {
1129 delete jni_env_;
1130 jni_env_ = nullptr;
1131 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001132 CHECK_NE(GetState(), kRunnable);
Dave Allison0aded082013-11-07 13:15:11 -08001133 CHECK_NE(ReadFlag(kCheckpointRequest), true);
1134 CHECK(checkpoint_functions_[0] == nullptr);
1135 CHECK(checkpoint_functions_[1] == nullptr);
1136 CHECK(checkpoint_functions_[2] == nullptr);
1137
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001138 // We may be deleting a still born thread.
1139 SetStateUnsafe(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001140
1141 delete wait_cond_;
1142 delete wait_mutex_;
1143
Dave Allison0aded082013-11-07 13:15:11 -08001144 if (long_jump_context_ != nullptr) {
Ian Rogersc928de92013-02-27 14:30:44 -08001145 delete long_jump_context_;
1146 }
Elliott Hughes475fc232011-10-25 15:00:35 -07001147
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07001148 if (initialized) {
1149 CleanupCpu();
1150 }
1151
Elliott Hughes475fc232011-10-25 15:00:35 -07001152 delete debug_invoke_req_;
Sebastien Hertz61b7f1b2013-11-15 15:59:30 +01001153 delete single_step_control_;
jeffhao725a9572012-11-13 18:20:12 -08001154 delete instrumentation_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -08001155 delete name_;
Jeff Hao5ce4b172013-08-16 16:27:18 -07001156 delete stack_trace_sample_;
Elliott Hughesd8af1592012-04-16 20:40:15 -07001157
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07001158 Runtime::Current()->GetHeap()->RevokeThreadLocalBuffers(this);
1159
Elliott Hughesd8af1592012-04-16 20:40:15 -07001160 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001161}
1162
Ian Rogerscfaa4552012-11-26 21:00:08 -08001163void Thread::HandleUncaughtExceptions(ScopedObjectAccess& soa) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001164 if (!IsExceptionPending()) {
1165 return;
1166 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001167 ScopedLocalRef<jobject> peer(jni_env_, soa.AddLocalReference<jobject>(opeer_));
1168 ScopedThreadStateChange tsc(this, kNative);
Ian Rogers120f1c72012-09-28 17:17:10 -07001169
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001170 // Get and clear the exception.
Ian Rogers120f1c72012-09-28 17:17:10 -07001171 ScopedLocalRef<jthrowable> exception(jni_env_, jni_env_->ExceptionOccurred());
1172 jni_env_->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001173
1174 // If the thread has its own handler, use that.
Ian Rogers120f1c72012-09-28 17:17:10 -07001175 ScopedLocalRef<jobject> handler(jni_env_,
Ian Rogerscfaa4552012-11-26 21:00:08 -08001176 jni_env_->GetObjectField(peer.get(),
Ian Rogers120f1c72012-09-28 17:17:10 -07001177 WellKnownClasses::java_lang_Thread_uncaughtHandler));
Dave Allison0aded082013-11-07 13:15:11 -08001178 if (handler.get() == nullptr) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001179 // Otherwise use the thread group's default handler.
Ian Rogerscfaa4552012-11-26 21:00:08 -08001180 handler.reset(jni_env_->GetObjectField(peer.get(), WellKnownClasses::java_lang_Thread_group));
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001181 }
1182
1183 // Call the handler.
Ian Rogers120f1c72012-09-28 17:17:10 -07001184 jni_env_->CallVoidMethod(handler.get(),
1185 WellKnownClasses::java_lang_Thread$UncaughtExceptionHandler_uncaughtException,
Ian Rogerscfaa4552012-11-26 21:00:08 -08001186 peer.get(), exception.get());
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001187
1188 // If the handler threw, clear that exception too.
Ian Rogers120f1c72012-09-28 17:17:10 -07001189 jni_env_->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001190}
1191
Ian Rogerscfaa4552012-11-26 21:00:08 -08001192void Thread::RemoveFromThreadGroup(ScopedObjectAccess& soa) {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001193 // this.group.removeThread(this);
1194 // group can be null if we're in the compiler or a test.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001195 mirror::Object* ogroup = soa.DecodeField(WellKnownClasses::java_lang_Thread_group)->GetObject(opeer_);
Dave Allison0aded082013-11-07 13:15:11 -08001196 if (ogroup != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001197 ScopedLocalRef<jobject> group(soa.Env(), soa.AddLocalReference<jobject>(ogroup));
1198 ScopedLocalRef<jobject> peer(soa.Env(), soa.AddLocalReference<jobject>(opeer_));
1199 ScopedThreadStateChange tsc(soa.Self(), kNative);
Ian Rogers120f1c72012-09-28 17:17:10 -07001200 jni_env_->CallVoidMethod(group.get(), WellKnownClasses::java_lang_ThreadGroup_removeThread,
Ian Rogerscfaa4552012-11-26 21:00:08 -08001201 peer.get());
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001202 }
1203}
1204
Ian Rogers408f79a2011-08-23 18:22:33 -07001205size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001206 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001207 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001208 count += cur->NumberOfReferences();
1209 }
1210 return count;
1211}
1212
Ian Rogerscfaa4552012-11-26 21:00:08 -08001213bool Thread::SirtContains(jobject obj) const {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001214 StackReference<mirror::Object>* sirt_entry =
1215 reinterpret_cast<StackReference<mirror::Object>*>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001216 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
1217 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001218 return true;
1219 }
1220 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001221 // JNI code invoked from portable code uses shadow frames rather than the SIRT.
1222 return managed_stack_.ShadowFramesContain(sirt_entry);
TDYa12728f1a142012-03-15 21:51:52 -07001223}
1224
Mathieu Chartier89bb1442014-02-12 10:06:23 -08001225void Thread::SirtVisitRoots(RootCallback* visitor, void* arg, uint32_t thread_id) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001226 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001227 size_t num_refs = cur->NumberOfReferences();
Dave Allison0aded082013-11-07 13:15:11 -08001228 for (size_t j = 0; j < num_refs; ++j) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001229 mirror::Object* object = cur->GetReference(j);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001230 if (object != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08001231 mirror::Object* old_obj = object;
1232 visitor(&object, arg, thread_id, kRootNativeStack);
1233 if (old_obj != object) {
1234 cur->SetReference(j, object);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001235 }
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -07001236 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001237 }
1238 }
1239}
1240
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001241mirror::Object* Thread::DecodeJObject(jobject obj) const {
Ian Rogers81d425b2012-09-27 16:03:43 -07001242 Locks::mutator_lock_->AssertSharedHeld(this);
Dave Allison0aded082013-11-07 13:15:11 -08001243 if (obj == nullptr) {
1244 return nullptr;
Ian Rogers408f79a2011-08-23 18:22:33 -07001245 }
1246 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1247 IndirectRefKind kind = GetIndirectRefKind(ref);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001248 mirror::Object* result;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001249 // The "kinds" below are sorted by the frequency we expect to encounter them.
1250 if (kind == kLocal) {
1251 IndirectReferenceTable& locals = jni_env_->locals;
Mathieu Chartier6dda8982014-03-06 11:11:48 -08001252 result = locals.Get(ref);
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001253 } else if (kind == kSirtOrInvalid) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001254 // TODO: make stack indirect reference table lookup more efficient.
1255 // Check if this is a local reference in the SIRT.
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001256 if (LIKELY(SirtContains(obj))) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001257 // Read from SIRT.
1258 result = reinterpret_cast<StackReference<mirror::Object>*>(obj)->AsMirrorPtr();
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08001259 VerifyObject(result);
Elliott Hughesc2dc62d2012-01-17 20:06:12 -08001260 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001261 // Assume an invalid local reference is actually a direct pointer.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001262 result = reinterpret_cast<mirror::Object*>(obj);
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08001263 VerifyObject(result);
Ian Rogers408f79a2011-08-23 18:22:33 -07001264 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001265 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001266 }
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001267 } else if (kind == kGlobal) {
1268 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1269 IndirectReferenceTable& globals = vm->globals;
Ian Rogersb8a0b942013-08-20 18:09:52 -07001270 ReaderMutexLock mu(const_cast<Thread*>(this), vm->globals_lock);
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001271 result = const_cast<mirror::Object*>(globals.Get(ref));
1272 } else {
1273 DCHECK_EQ(kind, kWeakGlobal);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001274 result = Runtime::Current()->GetJavaVM()->DecodeWeakGlobal(const_cast<Thread*>(this), ref);
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001275 if (result == kClearedJniWeakGlobal) {
Dave Allison0aded082013-11-07 13:15:11 -08001276 // This is a special case where it's okay to return nullptr.
Mathieu Chartiere8c48db2013-12-19 14:59:00 -08001277 return nullptr;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07001278 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001279 }
1280
Dave Allison0aded082013-11-07 13:15:11 -08001281 if (UNLIKELY(result == nullptr)) {
1282 JniAbortF(nullptr, "use of deleted %s %p", ToStr<IndirectRefKind>(kind).c_str(), obj);
Ian Rogers408f79a2011-08-23 18:22:33 -07001283 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001284 return result;
1285}
1286
Ian Rogers81d425b2012-09-27 16:03:43 -07001287// Implements java.lang.Thread.interrupted.
1288bool Thread::Interrupted() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001289 MutexLock mu(Thread::Current(), *wait_mutex_);
Ian Rogers81d425b2012-09-27 16:03:43 -07001290 bool interrupted = interrupted_;
1291 interrupted_ = false;
1292 return interrupted;
1293}
1294
1295// Implements java.lang.Thread.isInterrupted.
1296bool Thread::IsInterrupted() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001297 MutexLock mu(Thread::Current(), *wait_mutex_);
Ian Rogers81d425b2012-09-27 16:03:43 -07001298 return interrupted_;
1299}
1300
1301void Thread::Interrupt() {
Ian Rogersc604d732012-10-14 16:09:54 -07001302 Thread* self = Thread::Current();
1303 MutexLock mu(self, *wait_mutex_);
Ian Rogers81d425b2012-09-27 16:03:43 -07001304 if (interrupted_) {
1305 return;
1306 }
1307 interrupted_ = true;
Ian Rogersc604d732012-10-14 16:09:54 -07001308 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001309}
1310
1311void Thread::Notify() {
Ian Rogersc604d732012-10-14 16:09:54 -07001312 Thread* self = Thread::Current();
1313 MutexLock mu(self, *wait_mutex_);
1314 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001315}
1316
Ian Rogersc604d732012-10-14 16:09:54 -07001317void Thread::NotifyLocked(Thread* self) {
Dave Allison0aded082013-11-07 13:15:11 -08001318 if (wait_monitor_ != nullptr) {
Ian Rogersc604d732012-10-14 16:09:54 -07001319 wait_cond_->Signal(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07001320 }
1321}
1322
Ian Rogers0399dde2012-06-06 17:09:28 -07001323class CountStackDepthVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001324 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001325 explicit CountStackDepthVisitor(Thread* thread)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001326 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Dave Allison0aded082013-11-07 13:15:11 -08001327 : StackVisitor(thread, nullptr),
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001328 depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001329
Ian Rogersb726dcb2012-09-05 08:57:23 -07001330 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001331 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001332 // Note we also skip the frame if it doesn't have a method (namely the callee
1333 // save frame)
Brian Carlstromea46f952013-07-30 01:26:50 -07001334 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001335 if (skipping_ && !m->IsRuntimeMethod() &&
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001336 !mirror::Throwable::GetJavaLangThrowable()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001337 skipping_ = false;
1338 }
1339 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001340 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001341 ++depth_;
1342 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001343 } else {
1344 ++skip_depth_;
1345 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001346 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001347 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001348
1349 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001350 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001351 }
1352
Elliott Hughes29f27422011-09-18 16:02:18 -07001353 int GetSkipDepth() const {
1354 return skip_depth_;
1355 }
1356
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001357 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001358 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001359 uint32_t skip_depth_;
1360 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001361};
1362
Ian Rogers0399dde2012-06-06 17:09:28 -07001363class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001364 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001365 explicit BuildInternalStackTraceVisitor(Thread* self, Thread* thread, int skip_depth)
Dave Allison0aded082013-11-07 13:15:11 -08001366 : StackVisitor(thread, nullptr), self_(self),
1367 skip_depth_(skip_depth), count_(0), dex_pc_trace_(nullptr), method_trace_(nullptr) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08001368
Ian Rogers1f539342012-10-03 21:09:42 -07001369 bool Init(int depth)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001370 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001371 // Allocate method trace with an extra slot that will hold the PC trace
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001372 SirtRef<mirror::ObjectArray<mirror::Object> >
Ian Rogers1f539342012-10-03 21:09:42 -07001373 method_trace(self_,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001374 Runtime::Current()->GetClassLinker()->AllocObjectArray<mirror::Object>(self_,
1375 depth + 1));
Dave Allison0aded082013-11-07 13:15:11 -08001376 if (method_trace.get() == nullptr) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001377 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001378 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001379 mirror::IntArray* dex_pc_trace = mirror::IntArray::Alloc(self_, depth);
Dave Allison0aded082013-11-07 13:15:11 -08001380 if (dex_pc_trace == nullptr) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001381 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001382 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001383 // Save PC trace in last element of method trace, also places it into the
1384 // object graph.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001385 // We are called from native: use non-transactional mode.
1386 method_trace->Set<false>(depth, dex_pc_trace);
Ian Rogers0399dde2012-06-06 17:09:28 -07001387 // Set the Object*s and assert that no thread suspension is now possible.
Ian Rogers52673ff2012-06-27 23:25:34 -07001388 const char* last_no_suspend_cause =
Ian Rogers1f539342012-10-03 21:09:42 -07001389 self_->StartAssertNoThreadSuspension("Building internal stack trace");
Dave Allison0aded082013-11-07 13:15:11 -08001390 CHECK(last_no_suspend_cause == nullptr) << last_no_suspend_cause;
Ian Rogers0399dde2012-06-06 17:09:28 -07001391 method_trace_ = method_trace.get();
1392 dex_pc_trace_ = dex_pc_trace;
Ian Rogers283ed0d2012-02-16 15:25:09 -08001393 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001394 }
1395
Ian Rogers0399dde2012-06-06 17:09:28 -07001396 virtual ~BuildInternalStackTraceVisitor() {
Dave Allison0aded082013-11-07 13:15:11 -08001397 if (method_trace_ != nullptr) {
1398 self_->EndAssertNoThreadSuspension(nullptr);
Ian Rogers52673ff2012-06-27 23:25:34 -07001399 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001400 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001401
Ian Rogersb726dcb2012-09-05 08:57:23 -07001402 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Dave Allison0aded082013-11-07 13:15:11 -08001403 if (method_trace_ == nullptr || dex_pc_trace_ == nullptr) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001404 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001405 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001406 if (skip_depth_ > 0) {
1407 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001408 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001409 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001410 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001411 if (m->IsRuntimeMethod()) {
1412 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08001413 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001414 // TODO dedup this code.
1415 if (Runtime::Current()->IsActiveTransaction()) {
1416 method_trace_->Set<true>(count_, m);
1417 dex_pc_trace_->Set<true>(count_, m->IsProxyMethod() ? DexFile::kDexNoIndex : GetDexPc());
1418 } else {
1419 method_trace_->Set<false>(count_, m);
1420 dex_pc_trace_->Set<false>(count_, m->IsProxyMethod() ? DexFile::kDexNoIndex : GetDexPc());
1421 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001422 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001423 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001424 }
1425
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001426 mirror::ObjectArray<mirror::Object>* GetInternalStackTrace() const {
Ian Rogers0399dde2012-06-06 17:09:28 -07001427 return method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001428 }
1429
1430 private:
Ian Rogers1f539342012-10-03 21:09:42 -07001431 Thread* const self_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001432 // How many more frames to skip.
1433 int32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001434 // Current position down stack trace.
Ian Rogersaaa20802011-09-11 21:47:37 -07001435 uint32_t count_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001436 // Array of dex PC values.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001437 mirror::IntArray* dex_pc_trace_;
Ian Rogers0399dde2012-06-06 17:09:28 -07001438 // 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 -08001439 mirror::ObjectArray<mirror::Object>* method_trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001440};
1441
Ian Rogers64b6d142012-10-29 16:34:15 -07001442jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessUnchecked& soa) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001443 // Compute depth of stack
Ian Rogers7a22fa62013-01-23 12:16:16 -08001444 CountStackDepthVisitor count_visitor(const_cast<Thread*>(this));
Ian Rogers0399dde2012-06-06 17:09:28 -07001445 count_visitor.WalkStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001446 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001447 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001448
Ian Rogers1f539342012-10-03 21:09:42 -07001449 // Build internal stack trace.
Ian Rogers7a22fa62013-01-23 12:16:16 -08001450 BuildInternalStackTraceVisitor build_trace_visitor(soa.Self(), const_cast<Thread*>(this),
1451 skip_depth);
Ian Rogers1f539342012-10-03 21:09:42 -07001452 if (!build_trace_visitor.Init(depth)) {
Dave Allison0aded082013-11-07 13:15:11 -08001453 return nullptr; // Allocation failed.
Ian Rogers283ed0d2012-02-16 15:25:09 -08001454 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001455 build_trace_visitor.WalkStack();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001456 mirror::ObjectArray<mirror::Object>* trace = build_trace_visitor.GetInternalStackTrace();
Ian Rogers7a22fa62013-01-23 12:16:16 -08001457 if (kIsDebugBuild) {
1458 for (int32_t i = 0; i < trace->GetLength(); ++i) {
Dave Allison0aded082013-11-07 13:15:11 -08001459 CHECK(trace->Get(i) != nullptr);
Ian Rogers7a22fa62013-01-23 12:16:16 -08001460 }
1461 }
1462 return soa.AddLocalReference<jobjectArray>(trace);
Ian Rogersaaa20802011-09-11 21:47:37 -07001463}
1464
Ian Rogers53b8b092014-03-13 23:45:53 -07001465jobjectArray Thread::InternalStackTraceToStackTraceElementArray(const ScopedObjectAccess& soa,
1466 jobject internal, jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001467 // Decode the internal stack trace into the depth, method trace and PC trace
Mathieu Chartier530825b2013-09-25 17:56:49 -07001468 int32_t depth = soa.Decode<mirror::ObjectArray<mirror::Object>*>(internal)->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001469
1470 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1471
Elliott Hughes01158d72011-09-19 19:47:10 -07001472 jobjectArray result;
Mathieu Chartier530825b2013-09-25 17:56:49 -07001473
Dave Allison0aded082013-11-07 13:15:11 -08001474 if (output_array != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07001475 // Reuse the array we were given.
1476 result = output_array;
Elliott Hughes01158d72011-09-19 19:47:10 -07001477 // ...adjusting the number of frames we'll write to not exceed the array length.
Mathieu Chartier530825b2013-09-25 17:56:49 -07001478 const int32_t traces_length =
1479 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->GetLength();
1480 depth = std::min(depth, traces_length);
Elliott Hughes01158d72011-09-19 19:47:10 -07001481 } else {
1482 // Create java_trace array and place in local reference table
Mathieu Chartier530825b2013-09-25 17:56:49 -07001483 mirror::ObjectArray<mirror::StackTraceElement>* java_traces =
1484 class_linker->AllocStackTraceElementArray(soa.Self(), depth);
Dave Allison0aded082013-11-07 13:15:11 -08001485 if (java_traces == nullptr) {
1486 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001487 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001488 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07001489 }
1490
Dave Allison0aded082013-11-07 13:15:11 -08001491 if (stack_depth != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07001492 *stack_depth = depth;
1493 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001494
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001495 for (int32_t i = 0; i < depth; ++i) {
Mathieu Chartier530825b2013-09-25 17:56:49 -07001496 mirror::ObjectArray<mirror::Object>* method_trace =
1497 soa.Decode<mirror::ObjectArray<mirror::Object>*>(internal);
Ian Rogersaaa20802011-09-11 21:47:37 -07001498 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Brian Carlstromea46f952013-07-30 01:26:50 -07001499 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(method_trace->Get(i));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001500 MethodHelper mh(method);
Jeff Hao228d6b82013-12-03 15:00:05 -08001501 int32_t line_number;
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001502 SirtRef<mirror::String> class_name_object(soa.Self(), nullptr);
1503 SirtRef<mirror::String> source_name_object(soa.Self(), nullptr);
Jeff Hao228d6b82013-12-03 15:00:05 -08001504 if (method->IsProxyMethod()) {
1505 line_number = -1;
1506 class_name_object.reset(method->GetDeclaringClass()->GetName());
1507 // source_name_object intentionally left null for proxy methods
1508 } else {
1509 mirror::IntArray* pc_trace = down_cast<mirror::IntArray*>(method_trace->Get(depth));
1510 uint32_t dex_pc = pc_trace->Get(i);
1511 line_number = mh.GetLineNumFromDexPC(dex_pc);
1512 // Allocate element, potentially triggering GC
1513 // TODO: reuse class_name_object via Class::name_?
1514 const char* descriptor = mh.GetDeclaringClassDescriptor();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001515 CHECK(descriptor != nullptr);
Jeff Hao228d6b82013-12-03 15:00:05 -08001516 std::string class_name(PrettyDescriptor(descriptor));
1517 class_name_object.reset(mirror::String::AllocFromModifiedUtf8(soa.Self(), class_name.c_str()));
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001518 if (class_name_object.get() == nullptr) {
1519 return nullptr;
Jeff Hao228d6b82013-12-03 15:00:05 -08001520 }
1521 const char* source_file = mh.GetDeclaringClassSourceFile();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001522 if (source_file != nullptr) {
1523 source_name_object.reset(mirror::String::AllocFromModifiedUtf8(soa.Self(), source_file));
1524 if (source_name_object.get() == nullptr) {
1525 return nullptr;
1526 }
Jeff Hao228d6b82013-12-03 15:00:05 -08001527 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001528 }
Ian Rogers48601312011-12-07 16:45:19 -08001529 const char* method_name = mh.GetName();
Dave Allison0aded082013-11-07 13:15:11 -08001530 CHECK(method_name != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001531 SirtRef<mirror::String> method_name_object(soa.Self(),
1532 mirror::String::AllocFromModifiedUtf8(soa.Self(),
1533 method_name));
Dave Allison0aded082013-11-07 13:15:11 -08001534 if (method_name_object.get() == nullptr) {
1535 return nullptr;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001536 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001537 mirror::StackTraceElement* obj = mirror::StackTraceElement::Alloc(
1538 soa.Self(), class_name_object, method_name_object, source_name_object, line_number);
Dave Allison0aded082013-11-07 13:15:11 -08001539 if (obj == nullptr) {
1540 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001541 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001542 // We are called from native: use non-transactional mode.
1543 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>*>(result)->Set<false>(i, obj);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001544 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001545 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001546}
1547
Ian Rogers62d6c772013-02-27 08:32:07 -08001548void Thread::ThrowNewExceptionF(const ThrowLocation& throw_location,
1549 const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001550 va_list args;
1551 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -08001552 ThrowNewExceptionV(throw_location, exception_class_descriptor,
1553 fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001554 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001555}
1556
Ian Rogers62d6c772013-02-27 08:32:07 -08001557void Thread::ThrowNewExceptionV(const ThrowLocation& throw_location,
1558 const char* exception_class_descriptor,
1559 const char* fmt, va_list ap) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001560 std::string msg;
1561 StringAppendV(&msg, fmt, ap);
Ian Rogers62d6c772013-02-27 08:32:07 -08001562 ThrowNewException(throw_location, exception_class_descriptor, msg.c_str());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001563}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001564
Ian Rogers62d6c772013-02-27 08:32:07 -08001565void Thread::ThrowNewException(const ThrowLocation& throw_location, const char* exception_class_descriptor,
1566 const char* msg) {
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08001567 // Callers should either clear or call ThrowNewWrappedException.
1568 AssertNoPendingExceptionForNewException(msg);
Ian Rogers62d6c772013-02-27 08:32:07 -08001569 ThrowNewWrappedException(throw_location, exception_class_descriptor, msg);
Elliott Hughesa4f94742012-05-29 16:28:38 -07001570}
1571
Ian Rogers62d6c772013-02-27 08:32:07 -08001572void Thread::ThrowNewWrappedException(const ThrowLocation& throw_location,
1573 const char* exception_class_descriptor,
1574 const char* msg) {
1575 DCHECK_EQ(this, Thread::Current());
Ian Rogers53b8b092014-03-13 23:45:53 -07001576 ScopedObjectAccessUnchecked soa(this);
Ian Rogers62d6c772013-02-27 08:32:07 -08001577 // Ensure we don't forget arguments over object allocation.
1578 SirtRef<mirror::Object> saved_throw_this(this, throw_location.GetThis());
Brian Carlstromea46f952013-07-30 01:26:50 -07001579 SirtRef<mirror::ArtMethod> saved_throw_method(this, throw_location.GetMethod());
Ian Rogers62d6c772013-02-27 08:32:07 -08001580 // Ignore the cause throw location. TODO: should we report this as a re-throw?
Ian Rogers53b8b092014-03-13 23:45:53 -07001581 ScopedLocalRef<jobject> cause(GetJniEnv(), soa.AddLocalReference<jobject>(GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08001582 ClearException();
1583 Runtime* runtime = Runtime::Current();
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001584
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001585 mirror::ClassLoader* cl = nullptr;
1586 if (saved_throw_method.get() != nullptr) {
1587 cl = saved_throw_method.get()->GetDeclaringClass()->GetClassLoader();
Ian Rogers62d6c772013-02-27 08:32:07 -08001588 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001589 SirtRef<mirror::ClassLoader> class_loader(this, cl);
Ian Rogers62d6c772013-02-27 08:32:07 -08001590 SirtRef<mirror::Class>
Ian Rogers98379392014-02-24 16:53:16 -08001591 exception_class(this, runtime->GetClassLinker()->FindClass(this, exception_class_descriptor,
Mathieu Chartier590fee92013-09-13 13:46:47 -07001592 class_loader));
Dave Allison0aded082013-11-07 13:15:11 -08001593 if (UNLIKELY(exception_class.get() == nullptr)) {
Elliott Hughes30646832011-10-13 16:59:46 -07001594 CHECK(IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08001595 LOG(ERROR) << "No exception class " << PrettyDescriptor(exception_class_descriptor);
Elliott Hughes30646832011-10-13 16:59:46 -07001596 return;
1597 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001598
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001599 if (UNLIKELY(!runtime->GetClassLinker()->EnsureInitialized(exception_class, true, true))) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001600 DCHECK(IsExceptionPending());
1601 return;
1602 }
1603 DCHECK(!runtime->IsStarted() || exception_class->IsThrowableClass());
1604 SirtRef<mirror::Throwable> exception(this,
1605 down_cast<mirror::Throwable*>(exception_class->AllocObject(this)));
1606
Mathieu Chartier590fee92013-09-13 13:46:47 -07001607 // If we couldn't allocate the exception, throw the pre-allocated out of memory exception.
1608 if (exception.get() == nullptr) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001609 ThrowLocation gc_safe_throw_location(saved_throw_this.get(), saved_throw_method.get(),
1610 throw_location.GetDexPc());
1611 SetException(gc_safe_throw_location, Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001612 return;
1613 }
1614
Ian Rogers62d6c772013-02-27 08:32:07 -08001615 // Choose an appropriate constructor and set up the arguments.
1616 const char* signature;
Ian Rogers53b8b092014-03-13 23:45:53 -07001617 ScopedLocalRef<jstring> msg_string(GetJniEnv(), nullptr);
Dave Allison0aded082013-11-07 13:15:11 -08001618 if (msg != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001619 // Ensure we remember this and the method over the String allocation.
Ian Rogers53b8b092014-03-13 23:45:53 -07001620 msg_string.reset(
1621 soa.AddLocalReference<jstring>(mirror::String::AllocFromModifiedUtf8(this, msg)));
Dave Allison0aded082013-11-07 13:15:11 -08001622 if (UNLIKELY(msg_string.get() == nullptr)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001623 CHECK(IsExceptionPending()); // OOME.
1624 return;
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001625 }
Dave Allison0aded082013-11-07 13:15:11 -08001626 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001627 signature = "(Ljava/lang/String;)V";
1628 } else {
1629 signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V";
1630 }
1631 } else {
Dave Allison0aded082013-11-07 13:15:11 -08001632 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001633 signature = "()V";
1634 } else {
1635 signature = "(Ljava/lang/Throwable;)V";
1636 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001637 }
Brian Carlstromea46f952013-07-30 01:26:50 -07001638 mirror::ArtMethod* exception_init_method =
Ian Rogers62d6c772013-02-27 08:32:07 -08001639 exception_class->FindDeclaredDirectMethod("<init>", signature);
1640
Dave Allison0aded082013-11-07 13:15:11 -08001641 CHECK(exception_init_method != nullptr) << "No <init>" << signature << " in "
Ian Rogers62d6c772013-02-27 08:32:07 -08001642 << PrettyDescriptor(exception_class_descriptor);
1643
1644 if (UNLIKELY(!runtime->IsStarted())) {
1645 // Something is trying to throw an exception without a started runtime, which is the common
1646 // case in the compiler. We won't be able to invoke the constructor of the exception, so set
1647 // the exception fields directly.
Dave Allison0aded082013-11-07 13:15:11 -08001648 if (msg != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001649 exception->SetDetailMessage(down_cast<mirror::String*>(DecodeJObject(msg_string.get())));
Ian Rogers62d6c772013-02-27 08:32:07 -08001650 }
Dave Allison0aded082013-11-07 13:15:11 -08001651 if (cause.get() != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001652 exception->SetCause(down_cast<mirror::Throwable*>(DecodeJObject(cause.get())));
Ian Rogers62d6c772013-02-27 08:32:07 -08001653 }
1654 ThrowLocation gc_safe_throw_location(saved_throw_this.get(), saved_throw_method.get(),
1655 throw_location.GetDexPc());
1656 SetException(gc_safe_throw_location, exception.get());
1657 } else {
Ian Rogers53b8b092014-03-13 23:45:53 -07001658 jvalue jv_args[2];
1659 size_t i = 0;
1660
Dave Allison0aded082013-11-07 13:15:11 -08001661 if (msg != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001662 jv_args[i].l = msg_string.get();
1663 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08001664 }
Dave Allison0aded082013-11-07 13:15:11 -08001665 if (cause.get() != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07001666 jv_args[i].l = cause.get();
1667 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08001668 }
Ian Rogers53b8b092014-03-13 23:45:53 -07001669 InvokeWithJValues(soa, exception.get(), soa.EncodeMethod(exception_init_method), jv_args);
Ian Rogers62d6c772013-02-27 08:32:07 -08001670 if (LIKELY(!IsExceptionPending())) {
1671 ThrowLocation gc_safe_throw_location(saved_throw_this.get(), saved_throw_method.get(),
1672 throw_location.GetDexPc());
1673 SetException(gc_safe_throw_location, exception.get());
1674 }
Elliott Hughes30646832011-10-13 16:59:46 -07001675 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001676}
1677
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001678void Thread::ThrowOutOfMemoryError(const char* msg) {
1679 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1680 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Ian Rogers62d6c772013-02-27 08:32:07 -08001681 ThrowLocation throw_location = GetCurrentLocationForThrow();
Elliott Hughes726079d2011-10-07 18:43:44 -07001682 if (!throwing_OutOfMemoryError_) {
1683 throwing_OutOfMemoryError_ = true;
Ian Rogers62d6c772013-02-27 08:32:07 -08001684 ThrowNewException(throw_location, "Ljava/lang/OutOfMemoryError;", msg);
Ian Rogers33e15bc2013-05-20 20:04:20 -07001685 throwing_OutOfMemoryError_ = false;
Elliott Hughes418dfe72011-10-06 18:56:27 -07001686 } else {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001687 Dump(LOG(ERROR)); // The pre-allocated OOME has no stack, so help out and log one.
Ian Rogers62d6c772013-02-27 08:32:07 -08001688 SetException(throw_location, Runtime::Current()->GetPreAllocatedOutOfMemoryError());
Elliott Hughes418dfe72011-10-06 18:56:27 -07001689 }
Elliott Hughes79082e32011-08-25 12:07:32 -07001690}
1691
Elliott Hughes498508c2011-10-17 14:58:22 -07001692Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001693 return Thread::Current();
1694}
1695
1696void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001697 std::ostringstream ss;
1698 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001699 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001700 // log to stderr for debugging command line processes
1701 std::cerr << str;
1702#ifdef HAVE_ANDROID_OS
1703 // log to logcat for debugging frameworks processes
1704 LOG(INFO) << str;
1705#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001706}
1707
Elliott Hughes98e20172012-04-24 15:38:13 -07001708struct EntryPointInfo {
1709 uint32_t offset;
1710 const char* name;
1711};
Ian Rogers848871b2013-08-05 10:56:33 -07001712#define INTERPRETER_ENTRY_POINT_INFO(x) { INTERPRETER_ENTRYPOINT_OFFSET(x).Uint32Value(), #x }
1713#define JNI_ENTRY_POINT_INFO(x) { JNI_ENTRYPOINT_OFFSET(x).Uint32Value(), #x }
1714#define PORTABLE_ENTRY_POINT_INFO(x) { PORTABLE_ENTRYPOINT_OFFSET(x).Uint32Value(), #x }
1715#define QUICK_ENTRY_POINT_INFO(x) { QUICK_ENTRYPOINT_OFFSET(x).Uint32Value(), #x }
Elliott Hughes98e20172012-04-24 15:38:13 -07001716static const EntryPointInfo gThreadEntryPointInfo[] = {
Ian Rogers848871b2013-08-05 10:56:33 -07001717 INTERPRETER_ENTRY_POINT_INFO(pInterpreterToInterpreterBridge),
1718 INTERPRETER_ENTRY_POINT_INFO(pInterpreterToCompiledCodeBridge),
1719 JNI_ENTRY_POINT_INFO(pDlsymLookup),
Jeff Hao88474b42013-10-23 16:24:40 -07001720 PORTABLE_ENTRY_POINT_INFO(pPortableImtConflictTrampoline),
Ian Rogers848871b2013-08-05 10:56:33 -07001721 PORTABLE_ENTRY_POINT_INFO(pPortableResolutionTrampoline),
1722 PORTABLE_ENTRY_POINT_INFO(pPortableToInterpreterBridge),
1723 QUICK_ENTRY_POINT_INFO(pAllocArray),
Hiroshi Yamauchibb8f0ab2014-01-27 16:50:29 -08001724 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved),
Ian Rogers848871b2013-08-05 10:56:33 -07001725 QUICK_ENTRY_POINT_INFO(pAllocArrayWithAccessCheck),
1726 QUICK_ENTRY_POINT_INFO(pAllocObject),
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001727 QUICK_ENTRY_POINT_INFO(pAllocObjectResolved),
1728 QUICK_ENTRY_POINT_INFO(pAllocObjectInitialized),
Ian Rogers848871b2013-08-05 10:56:33 -07001729 QUICK_ENTRY_POINT_INFO(pAllocObjectWithAccessCheck),
1730 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArray),
1731 QUICK_ENTRY_POINT_INFO(pCheckAndAllocArrayWithAccessCheck),
1732 QUICK_ENTRY_POINT_INFO(pInstanceofNonTrivial),
Ian Rogers848871b2013-08-05 10:56:33 -07001733 QUICK_ENTRY_POINT_INFO(pCheckCast),
Ian Rogers7655f292013-07-29 11:07:13 -07001734 QUICK_ENTRY_POINT_INFO(pInitializeStaticStorage),
Ian Rogers848871b2013-08-05 10:56:33 -07001735 QUICK_ENTRY_POINT_INFO(pInitializeTypeAndVerifyAccess),
1736 QUICK_ENTRY_POINT_INFO(pInitializeType),
1737 QUICK_ENTRY_POINT_INFO(pResolveString),
Ian Rogers7655f292013-07-29 11:07:13 -07001738 QUICK_ENTRY_POINT_INFO(pSet32Instance),
1739 QUICK_ENTRY_POINT_INFO(pSet32Static),
1740 QUICK_ENTRY_POINT_INFO(pSet64Instance),
1741 QUICK_ENTRY_POINT_INFO(pSet64Static),
1742 QUICK_ENTRY_POINT_INFO(pSetObjInstance),
1743 QUICK_ENTRY_POINT_INFO(pSetObjStatic),
1744 QUICK_ENTRY_POINT_INFO(pGet32Instance),
1745 QUICK_ENTRY_POINT_INFO(pGet32Static),
1746 QUICK_ENTRY_POINT_INFO(pGet64Instance),
1747 QUICK_ENTRY_POINT_INFO(pGet64Static),
1748 QUICK_ENTRY_POINT_INFO(pGetObjInstance),
1749 QUICK_ENTRY_POINT_INFO(pGetObjStatic),
Ian Rogersa9a82542013-10-04 11:17:26 -07001750 QUICK_ENTRY_POINT_INFO(pAputObjectWithNullAndBoundCheck),
1751 QUICK_ENTRY_POINT_INFO(pAputObjectWithBoundCheck),
1752 QUICK_ENTRY_POINT_INFO(pAputObject),
Ian Rogers848871b2013-08-05 10:56:33 -07001753 QUICK_ENTRY_POINT_INFO(pHandleFillArrayData),
Ian Rogers7655f292013-07-29 11:07:13 -07001754 QUICK_ENTRY_POINT_INFO(pJniMethodStart),
1755 QUICK_ENTRY_POINT_INFO(pJniMethodStartSynchronized),
1756 QUICK_ENTRY_POINT_INFO(pJniMethodEnd),
1757 QUICK_ENTRY_POINT_INFO(pJniMethodEndSynchronized),
1758 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReference),
1759 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized),
Ian Rogers6cbd2712014-03-04 16:06:50 -08001760 QUICK_ENTRY_POINT_INFO(pQuickGenericJniTrampoline),
Ian Rogers848871b2013-08-05 10:56:33 -07001761 QUICK_ENTRY_POINT_INFO(pLockObject),
1762 QUICK_ENTRY_POINT_INFO(pUnlockObject),
Ian Rogers7655f292013-07-29 11:07:13 -07001763 QUICK_ENTRY_POINT_INFO(pCmpgDouble),
1764 QUICK_ENTRY_POINT_INFO(pCmpgFloat),
1765 QUICK_ENTRY_POINT_INFO(pCmplDouble),
1766 QUICK_ENTRY_POINT_INFO(pCmplFloat),
1767 QUICK_ENTRY_POINT_INFO(pFmod),
1768 QUICK_ENTRY_POINT_INFO(pSqrt),
1769 QUICK_ENTRY_POINT_INFO(pL2d),
1770 QUICK_ENTRY_POINT_INFO(pFmodf),
1771 QUICK_ENTRY_POINT_INFO(pL2f),
1772 QUICK_ENTRY_POINT_INFO(pD2iz),
1773 QUICK_ENTRY_POINT_INFO(pF2iz),
1774 QUICK_ENTRY_POINT_INFO(pIdivmod),
1775 QUICK_ENTRY_POINT_INFO(pD2l),
1776 QUICK_ENTRY_POINT_INFO(pF2l),
1777 QUICK_ENTRY_POINT_INFO(pLdiv),
Ian Rogersa9a82542013-10-04 11:17:26 -07001778 QUICK_ENTRY_POINT_INFO(pLmod),
Ian Rogers7655f292013-07-29 11:07:13 -07001779 QUICK_ENTRY_POINT_INFO(pLmul),
1780 QUICK_ENTRY_POINT_INFO(pShlLong),
1781 QUICK_ENTRY_POINT_INFO(pShrLong),
1782 QUICK_ENTRY_POINT_INFO(pUshrLong),
Ian Rogers7655f292013-07-29 11:07:13 -07001783 QUICK_ENTRY_POINT_INFO(pIndexOf),
1784 QUICK_ENTRY_POINT_INFO(pMemcmp16),
1785 QUICK_ENTRY_POINT_INFO(pStringCompareTo),
1786 QUICK_ENTRY_POINT_INFO(pMemcpy),
Jeff Hao88474b42013-10-23 16:24:40 -07001787 QUICK_ENTRY_POINT_INFO(pQuickImtConflictTrampoline),
Ian Rogers848871b2013-08-05 10:56:33 -07001788 QUICK_ENTRY_POINT_INFO(pQuickResolutionTrampoline),
1789 QUICK_ENTRY_POINT_INFO(pQuickToInterpreterBridge),
Ian Rogers7655f292013-07-29 11:07:13 -07001790 QUICK_ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck),
Ian Rogers7655f292013-07-29 11:07:13 -07001791 QUICK_ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck),
1792 QUICK_ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck),
1793 QUICK_ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck),
1794 QUICK_ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck),
Ian Rogers848871b2013-08-05 10:56:33 -07001795 QUICK_ENTRY_POINT_INFO(pCheckSuspend),
1796 QUICK_ENTRY_POINT_INFO(pTestSuspend),
Ian Rogers7655f292013-07-29 11:07:13 -07001797 QUICK_ENTRY_POINT_INFO(pDeliverException),
Ian Rogers848871b2013-08-05 10:56:33 -07001798 QUICK_ENTRY_POINT_INFO(pThrowArrayBounds),
1799 QUICK_ENTRY_POINT_INFO(pThrowDivZero),
1800 QUICK_ENTRY_POINT_INFO(pThrowNoSuchMethod),
1801 QUICK_ENTRY_POINT_INFO(pThrowNullPointer),
1802 QUICK_ENTRY_POINT_INFO(pThrowStackOverflow),
Elliott Hughes98e20172012-04-24 15:38:13 -07001803};
Ian Rogers7655f292013-07-29 11:07:13 -07001804#undef QUICK_ENTRY_POINT_INFO
Elliott Hughes98e20172012-04-24 15:38:13 -07001805
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001806void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset, size_t size_of_pointers) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001807 CHECK_EQ(size_of_pointers, 4U); // TODO: support 64-bit targets.
Elliott Hughes98e20172012-04-24 15:38:13 -07001808
Brian Carlstromf69863b2013-07-17 21:53:13 -07001809#define DO_THREAD_OFFSET(x) \
1810 if (offset == static_cast<uint32_t>(OFFSETOF_VOLATILE_MEMBER(Thread, x))) { \
1811 os << # x; \
1812 return; \
1813 }
Ian Rogers474b6da2012-09-25 00:20:38 -07001814 DO_THREAD_OFFSET(state_and_flags_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001815 DO_THREAD_OFFSET(card_table_);
1816 DO_THREAD_OFFSET(exception_);
Ian Rogers07ec8e12012-12-01 01:26:51 -08001817 DO_THREAD_OFFSET(opeer_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001818 DO_THREAD_OFFSET(jni_env_);
1819 DO_THREAD_OFFSET(self_);
1820 DO_THREAD_OFFSET(stack_end_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001821 DO_THREAD_OFFSET(suspend_count_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001822 DO_THREAD_OFFSET(thin_lock_thread_id_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001823 // DO_THREAD_OFFSET(top_of_managed_stack_);
1824 // DO_THREAD_OFFSET(top_of_managed_stack_pc_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001825 DO_THREAD_OFFSET(top_sirt_);
Dave Allisonb373e092014-02-20 16:06:36 -08001826 DO_THREAD_OFFSET(suspend_trigger_);
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001827#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07001828
1829 size_t entry_point_count = arraysize(gThreadEntryPointInfo);
Ian Rogers7655f292013-07-29 11:07:13 -07001830 CHECK_EQ(entry_point_count * size_of_pointers,
Ian Rogers848871b2013-08-05 10:56:33 -07001831 sizeof(InterpreterEntryPoints) + sizeof(JniEntryPoints) + sizeof(PortableEntryPoints) +
1832 sizeof(QuickEntryPoints));
1833 uint32_t expected_offset = OFFSETOF_MEMBER(Thread, interpreter_entrypoints_);
Elliott Hughes98e20172012-04-24 15:38:13 -07001834 for (size_t i = 0; i < entry_point_count; ++i) {
Ian Rogers474b6da2012-09-25 00:20:38 -07001835 CHECK_EQ(gThreadEntryPointInfo[i].offset, expected_offset) << gThreadEntryPointInfo[i].name;
Elliott Hughes98e20172012-04-24 15:38:13 -07001836 expected_offset += size_of_pointers;
1837 if (gThreadEntryPointInfo[i].offset == offset) {
1838 os << gThreadEntryPointInfo[i].name;
1839 return;
1840 }
1841 }
1842 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001843}
1844
jeffhao94d6df42012-11-26 16:02:12 -08001845void Thread::QuickDeliverException() {
Ian Rogers62d6c772013-02-27 08:32:07 -08001846 // Get exception from thread.
1847 ThrowLocation throw_location;
1848 mirror::Throwable* exception = GetException(&throw_location);
Dave Allison0aded082013-11-07 13:15:11 -08001849 CHECK(exception != nullptr);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001850 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001851 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001852 ClearException();
Ian Rogers62d6c772013-02-27 08:32:07 -08001853 bool is_deoptimization = (exception == reinterpret_cast<mirror::Throwable*>(-1));
Ian Rogers28ad40d2011-10-27 15:19:26 -07001854 if (kDebugExceptionDelivery) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001855 if (!is_deoptimization) {
1856 mirror::String* msg = exception->GetDetailMessage();
Dave Allison0aded082013-11-07 13:15:11 -08001857 std::string str_msg(msg != nullptr ? msg->ToModifiedUtf8() : "");
Ian Rogers62d6c772013-02-27 08:32:07 -08001858 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
1859 << ": " << str_msg << "\n");
1860 } else {
1861 DumpStack(LOG(INFO) << "Deoptimizing: ");
1862 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07001863 }
Sebastien Hertzd45a1f52014-01-09 14:56:54 +01001864 CatchFinder catch_finder(this, throw_location, exception, is_deoptimization);
1865 catch_finder.FindCatch();
1866 catch_finder.UpdateInstrumentationStack();
Ian Rogers0399dde2012-06-06 17:09:28 -07001867 catch_finder.DoLongJump();
Ian Rogers9a8a8882012-03-08 02:30:55 -08001868 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001869}
1870
Ian Rogersbdb03912011-09-14 00:55:44 -07001871Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001872 Context* result = long_jump_context_;
Dave Allison0aded082013-11-07 13:15:11 -08001873 if (result == nullptr) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001874 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07001875 } else {
Dave Allison0aded082013-11-07 13:15:11 -08001876 long_jump_context_ = nullptr; // Avoid context being shared.
Mathieu Chartier67022432012-11-29 18:04:50 -08001877 result->Reset();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001878 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001879 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001880}
1881
Ian Rogerse0dcd462014-03-08 15:21:04 -08001882struct CurrentMethodVisitor FINAL : public StackVisitor {
Ian Rogers62d6c772013-02-27 08:32:07 -08001883 CurrentMethodVisitor(Thread* thread, Context* context)
1884 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Dave Allison0aded082013-11-07 13:15:11 -08001885 : StackVisitor(thread, context), this_object_(nullptr), method_(nullptr), dex_pc_(0) {}
Ian Rogerse0dcd462014-03-08 15:21:04 -08001886 bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001887 mirror::ArtMethod* m = GetMethod();
Ian Rogers62d6c772013-02-27 08:32:07 -08001888 if (m->IsRuntimeMethod()) {
1889 // Continue if this is a runtime method.
1890 return true;
Ian Rogers0399dde2012-06-06 17:09:28 -07001891 }
Dave Allison0aded082013-11-07 13:15:11 -08001892 if (context_ != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001893 this_object_ = GetThisObject();
1894 }
1895 method_ = m;
1896 dex_pc_ = GetDexPc();
1897 return false;
1898 }
1899 mirror::Object* this_object_;
Brian Carlstromea46f952013-07-30 01:26:50 -07001900 mirror::ArtMethod* method_;
Ian Rogers62d6c772013-02-27 08:32:07 -08001901 uint32_t dex_pc_;
1902};
Ian Rogers0399dde2012-06-06 17:09:28 -07001903
Brian Carlstromea46f952013-07-30 01:26:50 -07001904mirror::ArtMethod* Thread::GetCurrentMethod(uint32_t* dex_pc) const {
Dave Allison0aded082013-11-07 13:15:11 -08001905 CurrentMethodVisitor visitor(const_cast<Thread*>(this), nullptr);
Ian Rogers0399dde2012-06-06 17:09:28 -07001906 visitor.WalkStack(false);
Dave Allison0aded082013-11-07 13:15:11 -08001907 if (dex_pc != nullptr) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001908 *dex_pc = visitor.dex_pc_;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001909 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001910 return visitor.method_;
jeffhao33dc7712011-11-09 17:54:24 -08001911}
1912
Ian Rogers62d6c772013-02-27 08:32:07 -08001913ThrowLocation Thread::GetCurrentLocationForThrow() {
1914 Context* context = GetLongJumpContext();
1915 CurrentMethodVisitor visitor(this, context);
1916 visitor.WalkStack(false);
1917 ReleaseLongJumpContext(context);
1918 return ThrowLocation(visitor.this_object_, visitor.method_, visitor.dex_pc_);
1919}
1920
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001921bool Thread::HoldsLock(mirror::Object* object) {
Dave Allison0aded082013-11-07 13:15:11 -08001922 if (object == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -07001923 return false;
1924 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001925 return object->GetLockOwnerThreadId() == thin_lock_thread_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001926}
1927
Ian Rogers40e3bac2012-11-20 00:09:14 -08001928// RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor).
1929template <typename RootVisitor>
Ian Rogers0399dde2012-06-06 17:09:28 -07001930class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001931 public:
Ian Rogers7a22fa62013-01-23 12:16:16 -08001932 ReferenceMapVisitor(Thread* thread, Context* context, const RootVisitor& visitor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001933 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers7a22fa62013-01-23 12:16:16 -08001934 : StackVisitor(thread, context), visitor_(visitor) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07001935
Ian Rogersb726dcb2012-09-05 08:57:23 -07001936 bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001937 if (false) {
Ian Rogers0399dde2012-06-06 17:09:28 -07001938 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(GetMethod())
1939 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001940 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001941 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
Dave Allison0aded082013-11-07 13:15:11 -08001942 if (shadow_frame != nullptr) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001943 mirror::ArtMethod* m = shadow_frame->GetMethod();
TDYa127ce4cc0d2012-11-18 16:59:53 -08001944 size_t num_regs = shadow_frame->NumberOfVRegs();
1945 if (m->IsNative() || shadow_frame->HasReferenceArray()) {
1946 // SIRT for JNI or References for interpreter.
1947 for (size_t reg = 0; reg < num_regs; ++reg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001948 mirror::Object* ref = shadow_frame->GetVRegReference(reg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001949 if (ref != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08001950 mirror::Object* new_ref = ref;
1951 visitor_(&new_ref, reg, this);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001952 if (new_ref != ref) {
1953 shadow_frame->SetVRegReference(reg, new_ref);
1954 }
TDYa127ce4cc0d2012-11-18 16:59:53 -08001955 }
1956 }
1957 } else {
1958 // Java method.
1959 // Portable path use DexGcMap and store in Method.native_gc_map_.
1960 const uint8_t* gc_map = m->GetNativeGcMap();
Brian Carlstrom7c6aca22014-01-31 18:44:56 -08001961 CHECK(gc_map != nullptr) << PrettyMethod(m);
Vladimir Marko8171fc32013-11-26 17:05:58 +00001962 verifier::DexPcToReferenceMap dex_gc_map(gc_map);
TDYa127ce4cc0d2012-11-18 16:59:53 -08001963 uint32_t dex_pc = GetDexPc();
1964 const uint8_t* reg_bitmap = dex_gc_map.FindBitMap(dex_pc);
Dave Allison0aded082013-11-07 13:15:11 -08001965 DCHECK(reg_bitmap != nullptr);
TDYa127ce4cc0d2012-11-18 16:59:53 -08001966 num_regs = std::min(dex_gc_map.RegWidth() * 8, num_regs);
1967 for (size_t reg = 0; reg < num_regs; ++reg) {
1968 if (TestBitmap(reg, reg_bitmap)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001969 mirror::Object* ref = shadow_frame->GetVRegReference(reg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001970 if (ref != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08001971 mirror::Object* new_ref = ref;
1972 visitor_(&new_ref, reg, this);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001973 if (new_ref != ref) {
1974 shadow_frame->SetVRegReference(reg, new_ref);
1975 }
TDYa127ce4cc0d2012-11-18 16:59:53 -08001976 }
1977 }
1978 }
1979 }
Ian Rogers0399dde2012-06-06 17:09:28 -07001980 } else {
Brian Carlstromea46f952013-07-30 01:26:50 -07001981 mirror::ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07001982 // Process register map (which native and runtime methods don't have)
Ian Rogers640495b2012-06-22 15:15:47 -07001983 if (!m->IsNative() && !m->IsRuntimeMethod() && !m->IsProxyMethod()) {
Ian Rogers0c7abda2012-09-19 13:33:42 -07001984 const uint8_t* native_gc_map = m->GetNativeGcMap();
Dave Allison0aded082013-11-07 13:15:11 -08001985 CHECK(native_gc_map != nullptr) << PrettyMethod(m);
Ian Rogers0c7abda2012-09-19 13:33:42 -07001986 mh_.ChangeMethod(m);
1987 const DexFile::CodeItem* code_item = mh_.GetCodeItem();
Dave Allison0aded082013-11-07 13:15:11 -08001988 DCHECK(code_item != nullptr) << PrettyMethod(m); // Can't be nullptr or how would we compile its instructions?
Ian Rogers0c7abda2012-09-19 13:33:42 -07001989 NativePcOffsetToReferenceMap map(native_gc_map);
Ian Rogers0399dde2012-06-06 17:09:28 -07001990 size_t num_regs = std::min(map.RegWidth() * 8,
1991 static_cast<size_t>(code_item->registers_size_));
Ian Rogers0c7abda2012-09-19 13:33:42 -07001992 if (num_regs > 0) {
1993 const uint8_t* reg_bitmap = map.FindBitMap(GetNativePcOffset());
Dave Allison0aded082013-11-07 13:15:11 -08001994 DCHECK(reg_bitmap != nullptr);
Ian Rogers1809a722013-08-09 22:05:32 -07001995 const VmapTable vmap_table(m->GetVmapTable());
Ian Rogers0c7abda2012-09-19 13:33:42 -07001996 uint32_t core_spills = m->GetCoreSpillMask();
1997 uint32_t fp_spills = m->GetFpSpillMask();
1998 size_t frame_size = m->GetFrameSizeInBytes();
1999 // For all dex registers in the bitmap
Brian Carlstromea46f952013-07-30 01:26:50 -07002000 mirror::ArtMethod** cur_quick_frame = GetCurrentQuickFrame();
Dave Allison0aded082013-11-07 13:15:11 -08002001 DCHECK(cur_quick_frame != nullptr);
Ian Rogers0c7abda2012-09-19 13:33:42 -07002002 for (size_t reg = 0; reg < num_regs; ++reg) {
2003 // Does this register hold a reference?
2004 if (TestBitmap(reg, reg_bitmap)) {
2005 uint32_t vmap_offset;
Ian Rogers1809a722013-08-09 22:05:32 -07002006 if (vmap_table.IsInContext(reg, kReferenceVReg, &vmap_offset)) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002007 int vmap_reg = vmap_table.ComputeRegister(core_spills, vmap_offset, kReferenceVReg);
Mathieu Chartier815873e2014-02-13 18:02:13 -08002008 // This is sound as spilled GPRs will be word sized (ie 32 or 64bit).
2009 mirror::Object** ref_addr = reinterpret_cast<mirror::Object**>(GetGPRAddress(vmap_reg));
2010 if (*ref_addr != nullptr) {
2011 visitor_(ref_addr, reg, this);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002012 }
Ian Rogers0c7abda2012-09-19 13:33:42 -07002013 } else {
Mathieu Chartier815873e2014-02-13 18:02:13 -08002014 StackReference<mirror::Object>* ref_addr =
2015 reinterpret_cast<StackReference<mirror::Object>*>(
2016 GetVRegAddr(cur_quick_frame, code_item, core_spills, fp_spills, frame_size,
2017 reg));
2018 mirror::Object* ref = ref_addr->AsMirrorPtr();
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002019 if (ref != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08002020 mirror::Object* new_ref = ref;
2021 visitor_(&new_ref, reg, this);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002022 if (ref != new_ref) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08002023 ref_addr->Assign(new_ref);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002024 }
2025 }
Ian Rogers0c7abda2012-09-19 13:33:42 -07002026 }
Ian Rogers0399dde2012-06-06 17:09:28 -07002027 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07002028 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002029 }
2030 }
2031 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002032 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07002033 }
2034
2035 private:
Mathieu Chartier815873e2014-02-13 18:02:13 -08002036 static bool TestBitmap(size_t reg, const uint8_t* reg_vector) {
2037 return ((reg_vector[reg / kBitsPerByte] >> (reg % kBitsPerByte)) & 0x01) != 0;
Ian Rogersd6b1f612011-09-27 13:38:14 -07002038 }
2039
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002040 // Visitor for when we visit a root.
Ian Rogers40e3bac2012-11-20 00:09:14 -08002041 const RootVisitor& visitor_;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002042
Ian Rogers0c7abda2012-09-19 13:33:42 -07002043 // A method helper we keep around to avoid dex file/cache re-computations.
2044 MethodHelper mh_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07002045};
2046
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002047class RootCallbackVisitor {
2048 public:
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002049 RootCallbackVisitor(RootCallback* callback, void* arg, uint32_t tid)
2050 : callback_(callback), arg_(arg), tid_(tid) {}
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002051
Mathieu Chartier815873e2014-02-13 18:02:13 -08002052 void operator()(mirror::Object** obj, size_t, const StackVisitor*) const {
2053 callback_(obj, arg_, tid_, kRootJavaFrame);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002054 }
2055
2056 private:
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002057 RootCallback* const callback_;
Ian Rogers40e3bac2012-11-20 00:09:14 -08002058 void* const arg_;
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002059 const uint32_t tid_;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07002060};
2061
Mathieu Chartier590fee92013-09-13 13:46:47 -07002062void Thread::SetClassLoaderOverride(mirror::ClassLoader* class_loader_override) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08002063 VerifyObject(class_loader_override);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002064 class_loader_override_ = class_loader_override;
2065}
2066
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002067void Thread::VisitRoots(RootCallback* visitor, void* arg) {
2068 uint32_t thread_id = GetThreadId();
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002069 if (opeer_ != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08002070 visitor(&opeer_, arg, thread_id, kRootThreadObject);
Ian Rogerscfaa4552012-11-26 21:00:08 -08002071 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002072 if (exception_ != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08002073 visitor(reinterpret_cast<mirror::Object**>(&exception_), arg, thread_id, kRootNativeStack);
Elliott Hughesd369bb72011-09-12 14:41:14 -07002074 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002075 throw_location_.VisitRoots(visitor, arg);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002076 if (class_loader_override_ != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08002077 visitor(reinterpret_cast<mirror::Object**>(&class_loader_override_), arg, thread_id,
2078 kRootNativeStack);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002079 }
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002080 jni_env_->locals.VisitRoots(visitor, arg, thread_id, kRootJNILocal);
2081 jni_env_->monitors.VisitRoots(visitor, arg, thread_id, kRootJNIMonitor);
Mathieu Chartier89bb1442014-02-12 10:06:23 -08002082 SirtVisitRoots(visitor, arg, thread_id);
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07002083 if (debug_invoke_req_ != nullptr) {
2084 debug_invoke_req_->VisitRoots(visitor, arg, thread_id, kRootDebugger);
2085 }
2086 if (single_step_control_ != nullptr) {
2087 single_step_control_->VisitRoots(visitor, arg, thread_id, kRootDebugger);
2088 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07002089 // Visit roots on this thread's stack
Ian Rogers0399dde2012-06-06 17:09:28 -07002090 Context* context = GetLongJumpContext();
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08002091 RootCallbackVisitor visitorToCallback(visitor, arg, thread_id);
Ian Rogers7a22fa62013-01-23 12:16:16 -08002092 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context, visitorToCallback);
Ian Rogers0399dde2012-06-06 17:09:28 -07002093 mapper.WalkStack();
2094 ReleaseLongJumpContext(context);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002095 for (instrumentation::InstrumentationStackFrame& frame : *GetInstrumentationStack()) {
2096 if (frame.this_object_ != nullptr) {
Mathieu Chartier815873e2014-02-13 18:02:13 -08002097 visitor(&frame.this_object_, arg, thread_id, kRootJavaFrame);
Ian Rogers62d6c772013-02-27 08:32:07 -08002098 }
Mathieu Chartier423d2a32013-09-12 17:33:56 -07002099 DCHECK(frame.method_ != nullptr);
Mathieu Chartier815873e2014-02-13 18:02:13 -08002100 visitor(reinterpret_cast<mirror::Object**>(&frame.method_), arg, thread_id, kRootJavaFrame);
Ian Rogers62d6c772013-02-27 08:32:07 -08002101 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07002102}
2103
Mathieu Chartier4e305412014-02-19 10:54:44 -08002104static void VerifyRoot(mirror::Object** root, void* /*arg*/, uint32_t /*thread_id*/,
2105 RootType /*root_type*/) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2106 VerifyObject(*root);
jeffhao25045522012-03-13 19:34:37 -07002107}
2108
Ian Rogers04d7aa92013-03-16 14:29:17 -07002109void Thread::VerifyStackImpl() {
jeffhaoe66ac792012-03-19 16:08:46 -07002110 UniquePtr<Context> context(Context::Create());
Mathieu Chartier89bb1442014-02-12 10:06:23 -08002111 RootCallbackVisitor visitorToCallback(VerifyRoot, Runtime::Current()->GetHeap(), GetThreadId());
Ian Rogers04d7aa92013-03-16 14:29:17 -07002112 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context.get(), visitorToCallback);
Ian Rogers0399dde2012-06-06 17:09:28 -07002113 mapper.WalkStack();
jeffhao25045522012-03-13 19:34:37 -07002114}
jeffhao25045522012-03-13 19:34:37 -07002115
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002116// Set the stack end to that to be used during a stack overflow
2117void Thread::SetStackEndForStackOverflow() {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002118 // During stack overflow we allow use of the full stack.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002119 if (stack_end_ == stack_begin_) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07002120 // However, we seem to have already extended to use the full stack.
2121 LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently "
2122 << kStackOverflowReservedBytes << ")?";
2123 DumpStack(LOG(ERROR));
2124 LOG(FATAL) << "Recursive stack overflow.";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002125 }
2126
2127 stack_end_ = stack_begin_;
2128}
2129
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002130void Thread::SetTlab(byte* start, byte* end) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002131 DCHECK_LE(start, end);
2132 thread_local_start_ = start;
2133 thread_local_pos_ = thread_local_start_;
2134 thread_local_end_ = end;
2135 thread_local_objects_ = 0;
2136}
2137
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002138bool Thread::HasTlab() const {
2139 bool has_tlab = thread_local_pos_ != nullptr;
2140 if (has_tlab) {
2141 DCHECK(thread_local_start_ != nullptr && thread_local_end_ != nullptr);
2142 } else {
2143 DCHECK(thread_local_start_ == nullptr && thread_local_end_ == nullptr);
2144 }
2145 return has_tlab;
2146}
2147
Elliott Hughes330304d2011-08-12 14:28:05 -07002148std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002149 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07002150 return os;
2151}
2152
Elliott Hughes8daa0922011-09-11 13:46:25 -07002153} // namespace art