blob: 5233dd11162675118a1fc3921f0e991243e12e75 [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
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
Elliott Hughes8d768a92011-09-14 16:35:25 -070019#include <dynamic_annotations.h>
Ian Rogersb033c752011-07-20 12:22:35 -070020#include <pthread.h>
21#include <sys/mman.h>
Brian Carlstromdbf05b72011-12-15 00:55:24 -080022#include <sys/resource.h>
23#include <sys/time.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070024
Carl Shapirob5573532011-07-12 18:22:59 -070025#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070026#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070027#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070028#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070029#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070030
Elliott Hughes872d4ec2011-10-21 17:07:15 -070031#include "debugger.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070032#include "class_linker.h"
Brian Carlstromdf143242011-10-10 18:05:34 -070033#include "class_loader.h"
Ian Rogersd6b1f612011-09-27 13:38:14 -070034#include "dex_verifier.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070035#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070036#include "jni_internal.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070037#include "monitor.h"
Ian Rogers57b86d42012-03-27 16:05:41 -070038#include "oat/runtime/context.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070039#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080040#include "object_utils.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -050041#include "reflection.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070042#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070043#include "runtime_support.h"
Elliott Hughes726079d2011-10-07 18:43:44 -070044#include "ScopedLocalRef.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070045#include "scoped_jni_thread_state.h"
Logan Chienf7ad17e2012-03-15 03:10:03 +080046#include "shadow_frame.h"
Ian Rogers30fab402012-01-23 15:43:46 -080047#include "space.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070048#include "stack.h"
49#include "stack_indirect_reference_table.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070050#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070051#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070052
53namespace art {
54
55pthread_key_t Thread::pthread_key_self_;
56
Elliott Hughes462c9442012-03-23 18:47:50 -070057static Class* gThreadGroup = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -070058static Class* gThreadLock = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070059static Field* gThread_daemon = NULL;
60static Field* gThread_group = NULL;
61static Field* gThread_lock = NULL;
62static Field* gThread_name = NULL;
63static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070064static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070065static Field* gThread_vmData = NULL;
Elliott Hughes462c9442012-03-23 18:47:50 -070066static Field* gThreadGroup_mMain = NULL;
67static Field* gThreadGroup_mSystem = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070068static Field* gThreadGroup_name = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -070069static Field* gThreadLock_thread = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070070static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070071static Method* gThreadGroup_removeThread = NULL;
72static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070073
Ian Rogers5d76c432011-10-31 21:42:49 -070074void Thread::InitCardTable() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080075 card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -070076}
77
buzbee3ea4ec52011-08-22 17:37:19 -070078void Thread::InitFunctionPointers() {
Ian Rogers57b86d42012-03-27 16:05:41 -070079 InitEntryPoints(&entrypoints_);
Elliott Hughesc0f09332012-03-26 13:27:06 -070080}
81
82void Thread::SetDebuggerUpdatesEnabled(bool enabled) {
83 LOG(INFO) << "Turning debugger updates " << (enabled ? "on" : "off") << " for " << *this;
Ian Rogers57b86d42012-03-27 16:05:41 -070084 ChangeDebuggerEntryPoint(&entrypoints_, enabled);
buzbee3ea4ec52011-08-22 17:37:19 -070085}
86
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070087void Thread::InitTid() {
88 tid_ = ::art::GetTid();
89}
90
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070091void Thread::InitAfterFork() {
92 InitTid();
Elliott Hughes3147a232011-10-12 15:55:07 -070093#if defined(__BIONIC__)
94 // Work around a bionic bug.
95 struct bionic_pthread_internal_t {
96 void* next;
97 void** pref;
98 pthread_attr_t attr;
99 pid_t kernel_id;
100 // et cetera. we just need 'kernel_id' so we can stop here.
101 };
102 reinterpret_cast<bionic_pthread_internal_t*>(pthread_self())->kernel_id = tid_;
103#endif
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700104}
105
Brian Carlstrom78128a62011-09-15 17:21:19 -0700106void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700107 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes462c9442012-03-23 18:47:50 -0700108 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700109
Elliott Hughes93e74e82011-09-13 11:07:03 -0700110 // Wait until it's safe to start running code. (There may have been a suspend-all
111 // in progress while we were starting up.)
Elliott Hughes462c9442012-03-23 18:47:50 -0700112 Runtime* runtime = Runtime::Current();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700113 runtime->GetThreadList()->WaitForGo();
114
Elliott Hughes47179f72011-10-27 16:44:39 -0700115 {
116 CHECK_EQ(self->GetState(), Thread::kRunnable);
Elliott Hughes899e7892012-01-24 14:57:32 -0800117 SirtRef<String> thread_name(self->GetThreadName());
118 self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
Elliott Hughes47179f72011-10-27 16:44:39 -0700119 }
120
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700121 Dbg::PostThreadStart(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700122
123 // Invoke the 'run' method of our java.lang.Thread.
124 CHECK(self->peer_ != NULL);
125 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700126 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700127 m->Invoke(self, receiver, NULL, NULL);
128
129 // Detach.
130 runtime->GetThreadList()->Unregister();
131
Carl Shapirob5573532011-07-12 18:22:59 -0700132 return NULL;
133}
134
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700135static void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700136 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700137}
138
Elliott Hughes761928d2011-11-16 18:33:03 -0800139Thread* Thread::FromManagedThread(Object* thread_peer) {
140 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread_peer)));
141}
142
Elliott Hughes01158d72011-09-19 19:47:10 -0700143Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
Elliott Hughes761928d2011-11-16 18:33:03 -0800144 return FromManagedThread(Decode<Object*>(env, java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700145}
146
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700147static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700148 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700149 if (stack_size == 0) {
150 stack_size = Runtime::Current()->GetDefaultStackSize();
151 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700152
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700153 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
154 if (stack_size < PTHREAD_STACK_MIN) {
155 stack_size = PTHREAD_STACK_MIN;
156 }
157
158 // It's likely that callers are trying to ensure they have at least a certain amount of
159 // stack space, so we should add our reserved space on top of what they requested, rather
160 // than implicitly take it away from them.
161 stack_size += Thread::kStackOverflowReservedBytes;
162
163 // Some systems require the stack size to be a multiple of the system page size, so round up.
164 stack_size = RoundUp(stack_size, kPageSize);
165
166 return stack_size;
167}
168
169void Thread::Create(Object* peer, size_t stack_size) {
170 CHECK(peer != NULL);
171
172 stack_size = FixStackSize(stack_size);
173
Elliott Hughes93e74e82011-09-13 11:07:03 -0700174 Thread* native_thread = new Thread;
175 native_thread->peer_ = peer;
176
177 // Thread.start is synchronized, so we know that vmData is 0,
178 // and know that we're not racing to assign it.
179 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700180
Elliott Hughes47179f72011-10-27 16:44:39 -0700181 {
182 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
183 pthread_t new_pthread;
184 pthread_attr_t attr;
185 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
186 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
187 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
188 CHECK_PTHREAD_CALL(pthread_create, (&new_pthread, &attr, Thread::CreateCallback, native_thread), "new thread");
189 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
190 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700191
192 // Let the child know when it's safe to start running.
193 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700194}
195
Elliott Hughes462c9442012-03-23 18:47:50 -0700196void Thread::Init() {
197 // This function does all the initialization that must be run by the native thread it applies to.
198 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
199 // we can handshake with the corresponding native thread when it's ready.) Check this native
200 // thread hasn't been through here already...
Elliott Hughescac6cc72011-11-03 20:31:21 -0700201 CHECK(Thread::Current() == NULL);
202
Elliott Hughes93e74e82011-09-13 11:07:03 -0700203 InitCpu();
204 InitFunctionPointers();
Ian Rogers5d76c432011-10-31 21:42:49 -0700205 InitCardTable();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700206
Elliott Hughes462c9442012-03-23 18:47:50 -0700207 Runtime* runtime = Runtime::Current();
208 CHECK(runtime != NULL);
209
210 thin_lock_id_ = runtime->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700211
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700212 InitTid();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700213 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700214
Elliott Hughes3147a232011-10-12 15:55:07 -0700215 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700216
Elliott Hughes93e74e82011-09-13 11:07:03 -0700217 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700218
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700219 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700220}
221
Elliott Hughes462c9442012-03-23 18:47:50 -0700222Thread* Thread::Attach(const char* thread_name, bool as_daemon, Object* thread_group) {
Elliott Hughescac6cc72011-11-03 20:31:21 -0700223 Thread* self = new Thread;
Elliott Hughes462c9442012-03-23 18:47:50 -0700224 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700225
Elliott Hughescac6cc72011-11-03 20:31:21 -0700226 self->SetState(Thread::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700227
Elliott Hughescac6cc72011-11-03 20:31:21 -0700228 // If we're the main thread, ClassLinker won't be created until after we're attached,
229 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800230 // In the compiler, all threads need this hack, because no-one's going to be getting
231 // a native peer!
232 if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700233 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800234 } else {
235 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Elliott Hughes22869a92012-03-27 14:08:24 -0700236 if (thread_name != NULL) {
237 self->name_->assign(thread_name);
238 ::art::SetThreadName(thread_name);
239 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700240 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700241
242 self->GetJniEnv()->locals.AssertEmpty();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700243 return self;
244}
245
Elliott Hughes462c9442012-03-23 18:47:50 -0700246Object* Thread::GetMainThreadGroup() {
Ian Rogers0045a292012-03-31 21:08:41 -0700247 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(gThreadGroup, true, true)) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700248 return NULL;
249 }
250 return gThreadGroup_mMain->GetObject(NULL);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700251}
252
Elliott Hughes462c9442012-03-23 18:47:50 -0700253Object* Thread::GetSystemThreadGroup() {
Ian Rogers0045a292012-03-31 21:08:41 -0700254 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(gThreadGroup, true, true)) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700255 return NULL;
256 }
257 return gThreadGroup_mSystem->GetObject(NULL);
258}
259
260void Thread::CreatePeer(const char* name, bool as_daemon, Object* thread_group) {
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500261 CHECK(Runtime::Current()->IsStarted());
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700262 JNIEnv* env = jni_env_;
263
Elliott Hughes462c9442012-03-23 18:47:50 -0700264 if (thread_group == NULL) {
265 thread_group = Thread::GetMainThreadGroup();
266 }
267 ScopedLocalRef<jobject> java_thread_group(env, AddLocalReference<jobject>(env, thread_group));
Elliott Hughes726079d2011-10-07 18:43:44 -0700268 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Elliott Hughes8daa0922011-09-11 13:46:25 -0700269 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700270 jboolean thread_is_daemon = as_daemon;
271
Elliott Hughes726079d2011-10-07 18:43:44 -0700272 ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/Thread"));
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700273 ScopedLocalRef<jobject> peer(env, env->AllocObject(c.get()));
Elliott Hughes726079d2011-10-07 18:43:44 -0700274 peer_ = DecodeJObject(peer.get());
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700275 if (peer_ == NULL) {
276 CHECK(IsExceptionPending());
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700277 return;
278 }
279 jmethodID mid = env->GetMethodID(c.get(), "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes462c9442012-03-23 18:47:50 -0700280 env->CallNonvirtualVoidMethod(peer.get(), c.get(), mid, java_thread_group.get(), thread_name.get(), thread_priority, thread_is_daemon);
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500281 CHECK(!IsExceptionPending()) << " " << PrettyTypeOf(GetException());
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700282 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700283
Elliott Hughes899e7892012-01-24 14:57:32 -0800284 SirtRef<String> peer_thread_name(GetThreadName());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700285 if (peer_thread_name.get() == NULL) {
286 // The Thread constructor should have set the Thread.name to a
287 // non-null value. However, because we can run without code
288 // available (in the compiler, in tests), we manually assign the
289 // fields the constructor should have set.
290 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
Elliott Hughes462c9442012-03-23 18:47:50 -0700291 gThread_group->SetObject(peer_, thread_group);
Brian Carlstrom00fae582011-10-28 01:16:28 -0700292 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name.get()));
293 gThread_priority->SetInt(peer_, thread_priority);
Elliott Hughes899e7892012-01-24 14:57:32 -0800294 peer_thread_name.reset(GetThreadName());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700295 }
296 // thread_name may have been null, so don't trust this to be non-null
297 if (peer_thread_name.get() != NULL) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800298 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700299 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700300
301 // Pre-allocate an OutOfMemoryError for the double-OOME case.
302 ThrowNewException("Ljava/lang/OutOfMemoryError;",
303 "OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available");
304 ScopedLocalRef<jthrowable> exception(env, env->ExceptionOccurred());
305 env->ExceptionClear();
306 pre_allocated_OutOfMemoryError_ = Decode<Throwable*>(env, exception.get());
Carl Shapiro61e019d2011-07-14 16:53:09 -0700307}
308
Elliott Hughes899e7892012-01-24 14:57:32 -0800309void Thread::SetThreadName(const char* name) {
310 name_->assign(name);
311 ::art::SetThreadName(name);
312 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
313}
314
Elliott Hughesbe759c62011-09-08 19:38:21 -0700315void Thread::InitStackHwm() {
Elliott Hughes215f3142012-01-19 00:22:47 -0800316#if defined(__APPLE__)
Elliott Hughes6cc332e2012-01-20 22:59:20 -0800317 // Only needed to run code. Try implementing this with pthread_get_stacksize_np and pthread_get_stackaddr_np.
318 UNIMPLEMENTED(WARNING);
Elliott Hughes215f3142012-01-19 00:22:47 -0800319#else
Elliott Hughesbe759c62011-09-08 19:38:21 -0700320 pthread_attr_t attributes;
Elliott Hughes3147a232011-10-12 15:55:07 -0700321 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700322
Ian Rogers932746a2011-09-22 18:57:50 -0700323 void* temp_stack_base;
324 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
325 __FUNCTION__);
Ian Rogers30fab402012-01-23 15:43:46 -0800326 stack_begin_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700327
Ian Rogers932746a2011-09-22 18:57:50 -0700328 if (stack_size_ <= kStackOverflowReservedBytes) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800329 LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700330 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700331
Ian Rogers932746a2011-09-22 18:57:50 -0700332 // Set stack_end_ to the bottom of the stack saving space of stack overflows
333 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700334
335 // Sanity check.
336 int stack_variable;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700337 CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
Elliott Hughesbe759c62011-09-08 19:38:21 -0700338
Elliott Hughes8d768a92011-09-14 16:35:25 -0700339 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes215f3142012-01-19 00:22:47 -0800340#endif
Elliott Hughesbe759c62011-09-08 19:38:21 -0700341}
342
Elliott Hughes899e7892012-01-24 14:57:32 -0800343void Thread::Dump(std::ostream& os, bool full) const {
344 if (full) {
345 DumpState(os);
346 DumpStack(os);
347 } else {
348 os << "Thread[";
349 if (GetThinLockId() != 0) {
350 // If we're in kStarting, we won't have a thin lock id or tid yet.
351 os << GetThinLockId()
352 << ",tid=" << GetTid() << ',';
353 }
354 os << GetState()
355 << ",Thread*=" << this
Elliott Hughesffb465f2012-03-01 18:46:05 -0800356 << ",peer=" << peer_
Elliott Hughes899e7892012-01-24 14:57:32 -0800357 << ",\"" << *name_ << "\""
358 << "]";
Elliott Hughese0918552011-10-28 17:18:29 -0700359 }
Elliott Hughesa0957642011-09-02 14:27:33 -0700360}
361
Elliott Hughes899e7892012-01-24 14:57:32 -0800362String* Thread::GetThreadName() const {
Elliott Hughesfc861622011-10-17 17:57:47 -0700363 return (peer_ != NULL) ? reinterpret_cast<String*>(gThread_name->GetObject(peer_)) : NULL;
364}
365
Elliott Hughesffb465f2012-03-01 18:46:05 -0800366void Thread::GetThreadName(std::string& name) const {
367 name.assign(*name_);
368}
369
Elliott Hughesd92bec42011-09-02 17:04:36 -0700370void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700371 std::string group_name;
372 int priority;
373 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700374
Elliott Hughesd369bb72011-09-12 14:41:14 -0700375 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700376 priority = gThread_priority->GetInt(peer_);
377 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700378
Elliott Hughesa2155262011-11-16 16:26:58 -0800379 Object* thread_group = GetThreadGroup();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700380 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700381 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700382 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
383 }
384 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700385 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700386 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700387
388 int policy;
389 sched_param sp;
Elliott Hughes3147a232011-10-12 15:55:07 -0700390 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_self(), &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700391
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700392 std::string scheduler_group_name(GetSchedulerGroupName(GetTid()));
393 if (scheduler_group_name.empty()) {
394 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700395 }
396
Elliott Hughes899e7892012-01-24 14:57:32 -0800397 os << '"' << *name_ << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700398 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700399 os << " daemon";
400 }
401 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700402 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700403 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700404
Elliott Hughesd92bec42011-09-02 17:04:36 -0700405 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700406 << " sCount=" << suspend_count_
Elliott Hughes234ab152011-10-26 14:02:26 -0700407 << " dsCount=" << debug_suspend_count_
Elliott Hughesdcc24742011-09-07 14:02:44 -0700408 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700409 << " self=" << reinterpret_cast<const void*>(this) << "\n";
410 os << " | sysTid=" << GetTid()
411 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
412 << " sched=" << policy << "/" << sp.sched_priority
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700413 << " cgrp=" << scheduler_group_name
Elliott Hughes3147a232011-10-12 15:55:07 -0700414 << " handle=" << pthread_self() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700415
416 // Grab the scheduler stats for this thread.
417 std::string scheduler_stats;
418 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
419 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
420 } else {
421 scheduler_stats = "0 0 0";
422 }
423
424 int utime = 0;
425 int stime = 0;
426 int task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700427 GetTaskStats(GetTid(), utime, stime, task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700428
429 os << " | schedstat=( " << scheduler_stats << " )"
430 << " utm=" << utime
431 << " stm=" << stime
432 << " core=" << task_cpu
433 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
434}
435
Ian Rogersb04f69f2011-10-17 00:40:54 -0700436void Thread::PushNativeToManagedRecord(NativeToManagedRecord* record) {
437 Method **sp = top_of_managed_stack_.GetSP();
438#ifndef NDEBUG
439 if (sp != NULL) {
440 Method* m = *sp;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800441 Runtime::Current()->GetHeap()->VerifyObject(m);
Ian Rogersb04f69f2011-10-17 00:40:54 -0700442 DCHECK((m == NULL) || m->IsMethod());
443 }
444#endif
445 record->last_top_of_managed_stack_ = reinterpret_cast<void*>(sp);
446 record->last_top_of_managed_stack_pc_ = top_of_managed_stack_pc_;
447 record->link_ = native_to_managed_record_;
448 native_to_managed_record_ = record;
449 top_of_managed_stack_.SetSP(NULL);
450}
451
452void Thread::PopNativeToManagedRecord(const NativeToManagedRecord& record) {
453 native_to_managed_record_ = record.link_;
454 top_of_managed_stack_.SetSP(reinterpret_cast<Method**>(record.last_top_of_managed_stack_));
455 top_of_managed_stack_pc_ = record.last_top_of_managed_stack_pc_;
456}
457
Elliott Hughesd369bb72011-09-12 14:41:14 -0700458struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700459 StackDumpVisitor(std::ostream& os, const Thread* thread)
Ian Rogers28ad40d2011-10-27 15:19:26 -0700460 : last_method(NULL), last_line_number(0), repetition_count(0), os(os), thread(thread),
461 frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700462 }
463
Ian Rogersbdb03912011-09-14 00:55:44 -0700464 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700465 }
466
Elliott Hughes530fa002012-03-12 11:44:49 -0700467 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700468 if (!frame.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700469 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700470 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700471 const int kMaxRepetition = 3;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700472 Method* m = frame.GetMethod();
473 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700474 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersb861dc02011-11-14 17:00:05 -0800475 const DexCache* dex_cache = c->GetDexCache();
476 int line_number = -1;
477 if (dex_cache != NULL) { // be tolerant of bad input
478 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
479 line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
480 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700481 if (line_number == last_line_number && last_method == m) {
482 repetition_count++;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700483 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700484 if (repetition_count >= kMaxRepetition) {
485 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
486 }
487 repetition_count = 0;
488 last_line_number = line_number;
489 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700490 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700491 if (repetition_count < kMaxRepetition) {
492 os << " at " << PrettyMethod(m, false);
493 if (m->IsNative()) {
494 os << "(Native method)";
495 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800496 mh.ChangeMethod(m);
497 const char* source_file(mh.GetDeclaringClassSourceFile());
498 os << "(" << (source_file != NULL ? source_file : "unavailable")
Ian Rogers28ad40d2011-10-27 15:19:26 -0700499 << ":" << line_number << ")";
500 }
501 os << "\n";
502 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700503
504 if (frame_count++ == 0) {
505 Monitor::DescribeWait(os, thread);
506 }
Elliott Hughes530fa002012-03-12 11:44:49 -0700507 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700508 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800509 MethodHelper mh;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700510 Method* last_method;
511 int last_line_number;
512 int repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700513 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700514 const Thread* thread;
515 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700516};
517
Elliott Hughesd92bec42011-09-02 17:04:36 -0700518void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800519 // If we're currently in native code, dump that stack before dumping the managed stack.
520 if (GetState() == Thread::kNative || GetState() == Thread::kVmWait) {
521 DumpNativeStack(os);
522 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700523 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700524 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700525}
526
Elliott Hughesa4060e52012-03-02 16:51:35 -0800527void Thread::SetStateWithoutSuspendCheck(Thread::State new_state) {
528 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
529 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
530 android_atomic_release_store(new_state, addr);
531}
532
Elliott Hughes8d768a92011-09-14 16:35:25 -0700533Thread::State Thread::SetState(Thread::State new_state) {
534 Thread::State old_state = state_;
535 if (old_state == new_state) {
536 return old_state;
537 }
538
539 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
540 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
541
542 if (new_state == Thread::kRunnable) {
543 /*
544 * Change our status to Thread::kRunnable. The transition requires
Elliott Hughes81ff3182012-03-23 20:35:56 -0700545 * that we check for pending suspension, because the runtime considers
Elliott Hughes8d768a92011-09-14 16:35:25 -0700546 * us to be "asleep" in all other states, and another thread could
547 * be performing a GC now.
548 *
549 * The order of operations is very significant here. One way to
550 * do this wrong is:
551 *
552 * GCing thread Our thread (in kNative)
553 * ------------ ----------------------
554 * check suspend count (== 0)
555 * SuspendAllThreads()
556 * grab suspend-count lock
557 * increment all suspend counts
558 * release suspend-count lock
559 * check thread state (== kNative)
560 * all are suspended, begin GC
561 * set state to kRunnable
562 * (continue executing)
563 *
564 * We can correct this by grabbing the suspend-count lock and
565 * performing both of our operations (check suspend count, set
566 * state) while holding it, now we need to grab a mutex on every
567 * transition to kRunnable.
568 *
569 * What we do instead is change the order of operations so that
570 * the transition to kRunnable happens first. If we then detect
571 * that the suspend count is nonzero, we switch to kSuspended.
572 *
573 * Appropriate compiler and memory barriers are required to ensure
574 * that the operations are observed in the expected order.
575 *
576 * This does create a small window of opportunity where a GC in
577 * progress could observe what appears to be a running thread (if
578 * it happens to look between when we set to kRunnable and when we
579 * switch to kSuspended). At worst this only affects assertions
580 * and thread logging. (We could work around it with some sort
581 * of intermediate "pre-running" state that is generally treated
582 * as equivalent to running, but that doesn't seem worthwhile.)
583 *
584 * We can also solve this by combining the "status" and "suspend
585 * count" fields into a single 32-bit value. This trades the
586 * store/load barrier on transition to kRunnable for an atomic RMW
587 * op on all transitions and all suspend count updates (also, all
588 * accesses to status or the thread count require bit-fiddling).
589 * It also eliminates the brief transition through kRunnable when
590 * the thread is supposed to be suspended. This is possibly faster
591 * on SMP and slightly more correct, but less convenient.
592 */
593 android_atomic_acquire_store(new_state, addr);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800594 ANNOTATE_IGNORE_READS_BEGIN();
595 int suspend_count = suspend_count_;
596 ANNOTATE_IGNORE_READS_END();
597 if (suspend_count != 0) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700598 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
599 }
600 } else {
601 /*
602 * Not changing to Thread::kRunnable. No additional work required.
603 *
604 * We use a releasing store to ensure that, if we were runnable,
605 * any updates we previously made to objects on the managed heap
606 * will be observed before the state change.
607 */
608 android_atomic_release_store(new_state, addr);
609 }
610
611 return old_state;
612}
613
Elliott Hughes761928d2011-11-16 18:33:03 -0800614bool Thread::IsSuspended() {
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800615 ANNOTATE_IGNORE_READS_BEGIN();
616 int suspend_count = suspend_count_;
617 ANNOTATE_IGNORE_READS_END();
618 return suspend_count != 0 && GetState() != Thread::kRunnable;
Elliott Hughes761928d2011-11-16 18:33:03 -0800619}
620
Elliott Hughesff738062012-02-03 15:00:42 -0800621static void ReportThreadSuspendTimeout(Thread* waiting_thread) {
622 Runtime* runtime = Runtime::Current();
623 std::ostringstream ss;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800624 ss << "Thread suspend timeout waiting for thread " << *waiting_thread << "\n";
Elliott Hughesff738062012-02-03 15:00:42 -0800625 runtime->DumpLockHolders(ss);
626 ss << "\n";
627 runtime->GetThreadList()->DumpLocked(ss);
628 LOG(FATAL) << ss.str();
629}
630
Elliott Hughes8d768a92011-09-14 16:35:25 -0700631void Thread::WaitUntilSuspended() {
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800632 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
633
634 useconds_t total_delay = 0;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700635 useconds_t delay = 0;
636 while (GetState() == Thread::kRunnable) {
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800637 if (total_delay >= kTimeoutUs) {
Elliott Hughesff738062012-02-03 15:00:42 -0800638 ReportThreadSuspendTimeout(this);
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800639 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700640 useconds_t new_delay = delay * 2;
641 CHECK_GE(new_delay, delay);
642 delay = new_delay;
643 if (delay == 0) {
644 sched_yield();
645 delay = 10000;
646 } else {
647 usleep(delay);
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800648 total_delay += delay;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700649 }
650 }
651}
652
Elliott Hughesbe759c62011-09-08 19:38:21 -0700653void Thread::ThreadExitCallback(void* arg) {
654 Thread* self = reinterpret_cast<Thread*>(arg);
655 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700656}
657
Elliott Hughesbe759c62011-09-08 19:38:21 -0700658void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700659 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700660 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700661
662 // Double-check the TLS slot allocation.
663 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800664 LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700665 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700666}
Carl Shapirob5573532011-07-12 18:22:59 -0700667
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700668// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700669static Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700670 Class* c = class_linker->FindSystemClass(descriptor);
671 CHECK(c != NULL) << descriptor;
672 return c;
673}
674
675// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700676static Field* FindFieldOrDie(Class* c, const char* name, const char* descriptor) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700677 Field* f = c->FindDeclaredInstanceField(name, descriptor);
678 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700679 return f;
680}
681
682// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700683static Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700684 Method* m = c->FindVirtualMethod(name, signature);
685 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
686 return m;
687}
688
Elliott Hughes462c9442012-03-23 18:47:50 -0700689// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700690static Field* FindStaticFieldOrDie(Class* c, const char* name, const char* descriptor) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700691 Field* f = c->FindDeclaredStaticField(name, descriptor);
692 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
693 return f;
694}
695
Elliott Hughes038a8062011-09-18 14:12:41 -0700696void Thread::FinishStartup() {
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500697 CHECK(Runtime::Current()->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700698 Thread* self = Thread::Current();
699
700 // Need to be kRunnable for FindClass
701 ScopedThreadStateChange tsc(self, Thread::kRunnable);
702
Elliott Hughes038a8062011-09-18 14:12:41 -0700703 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
704 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700705
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700706 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700707 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
Elliott Hughes462c9442012-03-23 18:47:50 -0700708 gThreadGroup = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700709 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700710
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700711 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", "Z");
712 gThread_group = FindFieldOrDie(Thread_class, "group", "Ljava/lang/ThreadGroup;");
713 gThread_lock = FindFieldOrDie(Thread_class, "lock", "Ljava/lang/ThreadLock;");
714 gThread_name = FindFieldOrDie(Thread_class, "name", "Ljava/lang/String;");
715 gThread_priority = FindFieldOrDie(Thread_class, "priority", "I");
716 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
717 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", "I");
Elliott Hughes462c9442012-03-23 18:47:50 -0700718 gThreadGroup_name = FindFieldOrDie(gThreadGroup, "name", "Ljava/lang/String;");
719 gThreadGroup_mMain = FindStaticFieldOrDie(gThreadGroup, "mMain", "Ljava/lang/ThreadGroup;");
720 gThreadGroup_mSystem = FindStaticFieldOrDie(gThreadGroup, "mSystem", "Ljava/lang/ThreadGroup;");
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700721 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", "Ljava/lang/Thread;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700722
723 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
Elliott Hughes462c9442012-03-23 18:47:50 -0700724 gThreadGroup_removeThread = FindMethodOrDie(gThreadGroup, "removeThread", "(Ljava/lang/Thread;)V");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700725 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
726 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700727
728 // Finish attaching the main thread.
Elliott Hughes462c9442012-03-23 18:47:50 -0700729 Thread::Current()->CreatePeer("main", false, Thread::GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500730
731 InitBoxingMethods();
732 class_linker->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700733}
734
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700735void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700736 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700737}
738
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700739uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
740 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
741 return ThreadList::kInvalidId;
742 }
743 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
744 if (managed_thread == NULL) {
745 return ThreadList::kInvalidId;
746 }
747 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
748 Thread* thread = reinterpret_cast<Thread*>(vmData);
749 if (thread == NULL) {
750 return ThreadList::kInvalidId;
751 }
752 return thread->GetThinLockId();
753}
754
Elliott Hughesdcc24742011-09-07 14:02:44 -0700755Thread::Thread()
Elliott Hughes47179f72011-10-27 16:44:39 -0700756 : thin_lock_id_(0),
757 tid_(0),
758 peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700759 top_of_managed_stack_(),
760 top_of_managed_stack_pc_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700761 wait_mutex_(new Mutex("Thread wait mutex")),
762 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700763 wait_monitor_(NULL),
764 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700765 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700766 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700767 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700768 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700769 native_to_managed_record_(NULL),
770 top_sirt_(NULL),
Logan Chienf7ad17e2012-03-15 03:10:03 +0800771 top_shadow_frame_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700772 jni_env_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700773 state_(Thread::kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700774 self_(NULL),
775 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700776 exception_(NULL),
777 suspend_count_(0),
Elliott Hughes234ab152011-10-26 14:02:26 -0700778 debug_suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700779 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700780 long_jump_context_(NULL),
Elliott Hughes726079d2011-10-07 18:43:44 -0700781 throwing_OutOfMemoryError_(false),
Elliott Hughes475fc232011-10-25 15:00:35 -0700782 pre_allocated_OutOfMemoryError_(NULL),
jeffhaoe343b762011-12-05 16:36:44 -0800783 debug_invoke_req_(new DebugInvokeReq),
Elliott Hughes899e7892012-01-24 14:57:32 -0800784 trace_stack_(new std::vector<TraceStackFrame>),
785 name_(new std::string("<native thread without managed peer>")) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700786 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800787 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700788}
789
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700790static void MonitorExitVisitor(const Object* object, void*) {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700791 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700792 LOG(WARNING) << "Calling MonitorExit on object " << object << " (" << PrettyTypeOf(object) << ")"
793 << " left locked by native thread " << *Thread::Current() << " which is detaching";
Elliott Hughes5f791332011-09-15 17:45:30 -0700794 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700795}
796
Elliott Hughesc0f09332012-03-26 13:27:06 -0700797void Thread::Destroy() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700798 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700799 if (jni_env_ != NULL) {
800 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
801 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700802
Elliott Hughes93e74e82011-09-13 11:07:03 -0700803 if (peer_ != NULL) {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700804 Thread* self = this;
Elliott Hughes29f27422011-09-18 16:02:18 -0700805
Elliott Hughes534da072012-03-27 15:17:42 -0700806 // We may need to call user-supplied managed code.
807 SetState(Thread::kRunnable);
808
809 HandleUncaughtExceptions();
810 RemoveFromThreadGroup();
811
Elliott Hughes29f27422011-09-18 16:02:18 -0700812 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700813 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700814
Elliott Hughesc0f09332012-03-26 13:27:06 -0700815 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700816
Elliott Hughes29f27422011-09-18 16:02:18 -0700817 // Thread.join() is implemented as an Object.wait() on the Thread.lock
818 // object. Signal anyone who is waiting.
Elliott Hughes038a8062011-09-18 14:12:41 -0700819 Object* lock = gThread_lock->GetObject(peer_);
820 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700821 if (lock != NULL) {
822 lock->MonitorEnter(self);
823 lock->NotifyAll();
824 lock->MonitorExit(self);
825 }
826 }
Elliott Hughesc0f09332012-03-26 13:27:06 -0700827}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700828
Elliott Hughesc0f09332012-03-26 13:27:06 -0700829Thread::~Thread() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700830 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700831 jni_env_ = NULL;
832
833 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700834
835 delete wait_cond_;
836 delete wait_mutex_;
837
838 delete long_jump_context_;
Elliott Hughes475fc232011-10-25 15:00:35 -0700839
840 delete debug_invoke_req_;
jeffhaoe343b762011-12-05 16:36:44 -0800841 delete trace_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -0800842 delete name_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700843}
844
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700845void Thread::HandleUncaughtExceptions() {
846 if (!IsExceptionPending()) {
847 return;
848 }
849
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700850 // Get and clear the exception.
851 Object* exception = GetException();
852 ClearException();
853
854 // If the thread has its own handler, use that.
855 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
856 if (handler == NULL) {
857 // Otherwise use the thread group's default handler.
Elliott Hughesa2155262011-11-16 16:26:58 -0800858 handler = GetThreadGroup();
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700859 }
860
861 // Call the handler.
862 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
Elliott Hughes77405792012-03-15 15:22:12 -0700863 JValue args[2];
864 args[0].l = peer_;
865 args[1].l = exception;
866 m->Invoke(this, handler, args, NULL);
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700867
868 // If the handler threw, clear that exception too.
869 ClearException();
870}
871
Elliott Hughesa2155262011-11-16 16:26:58 -0800872Object* Thread::GetThreadGroup() const {
873 return gThread_group->GetObject(peer_);
874}
875
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700876void Thread::RemoveFromThreadGroup() {
877 // this.group.removeThread(this);
878 // group can be null if we're in the compiler or a test.
Elliott Hughesa2155262011-11-16 16:26:58 -0800879 Object* group = GetThreadGroup();
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700880 if (group != NULL) {
881 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
Elliott Hughes77405792012-03-15 15:22:12 -0700882 JValue args[1];
883 args[0].l = peer_;
884 m->Invoke(this, group, args, NULL);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700885 }
886}
887
Ian Rogers408f79a2011-08-23 18:22:33 -0700888size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700889 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700890 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700891 count += cur->NumberOfReferences();
892 }
893 return count;
894}
895
TDYa12728f1a142012-03-15 21:51:52 -0700896size_t Thread::NumShadowFrameReferences() {
897 size_t count = 0;
898 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
899 count += cur->NumberOfReferences();
900 }
901 return count;
902}
903
Ian Rogers408f79a2011-08-23 18:22:33 -0700904bool Thread::SirtContains(jobject obj) {
905 Object** sirt_entry = reinterpret_cast<Object**>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700906 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
907 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700908 return true;
909 }
910 }
911 return false;
912}
913
TDYa12728f1a142012-03-15 21:51:52 -0700914bool Thread::ShadowFrameContains(jobject obj) {
915 Object** shadow_frame_entry = reinterpret_cast<Object**>(obj);
916 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
917 if (cur->Contains(shadow_frame_entry)) {
918 return true;
919 }
920 }
921 return false;
922}
923
924bool Thread::StackReferencesContain(jobject obj) {
925 return SirtContains(obj) || ShadowFrameContains(obj);
926}
927
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700928void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700929 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700930 size_t num_refs = cur->NumberOfReferences();
931 for (size_t j = 0; j < num_refs; j++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700932 Object* object = cur->GetReference(j);
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -0700933 if (object != NULL) {
934 visitor(object, arg);
935 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700936 }
937 }
938}
939
Logan Chienf7ad17e2012-03-15 03:10:03 +0800940void Thread::ShadowFrameVisitRoots(Heap::RootVisitor* visitor, void* arg) {
941 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
942 size_t num_refs = cur->NumberOfReferences();
943 for (size_t j = 0; j < num_refs; j++) {
944 Object* object = cur->GetReference(j);
945 if (object != NULL) {
946 visitor(object, arg);
947 }
948 }
949 }
950}
951
Ian Rogers408f79a2011-08-23 18:22:33 -0700952Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700953 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700954 if (obj == NULL) {
955 return NULL;
956 }
957 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
958 IndirectRefKind kind = GetIndirectRefKind(ref);
959 Object* result;
960 switch (kind) {
961 case kLocal:
962 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700963 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700964 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700965 break;
966 }
967 case kGlobal:
968 {
969 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
970 IndirectReferenceTable& globals = vm->globals;
971 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700972 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700973 break;
974 }
975 case kWeakGlobal:
976 {
977 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
978 IndirectReferenceTable& weak_globals = vm->weak_globals;
979 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700980 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700981 if (result == kClearedJniWeakGlobal) {
982 // This is a special case where it's okay to return NULL.
983 return NULL;
984 }
985 break;
986 }
987 case kSirtOrInvalid:
988 default:
989 // TODO: make stack indirect reference table lookup more efficient
990 // Check if this is a local reference in the SIRT
TDYa12728f1a142012-03-15 21:51:52 -0700991 if (StackReferencesContain(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700992 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc2dc62d2012-01-17 20:06:12 -0800993 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700994 // Assume an invalid local reference is actually a direct pointer.
995 result = reinterpret_cast<Object*>(obj);
996 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700997 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700998 }
999 }
1000
1001 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001002 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1003 JniAbort(NULL);
1004 } else {
1005 if (result != kInvalidIndirectRefObject) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001006 Runtime::Current()->GetHeap()->VerifyObject(result);
Elliott Hughesa2501992011-08-26 19:39:54 -07001007 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001008 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001009 return result;
1010}
1011
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001012class CountStackDepthVisitor : public Thread::StackVisitor {
1013 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001014 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001015
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001016 bool VisitFrame(const Frame& frame, uintptr_t /*pc*/) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001017 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001018 // Note we also skip the frame if it doesn't have a method (namely the callee
1019 // save frame)
Ian Rogers5167c972012-02-03 10:41:20 -08001020 if (skipping_ && frame.HasMethod() &&
1021 !Throwable::GetJavaLangThrowable()->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001022 skipping_ = false;
1023 }
1024 if (!skipping_) {
Ian Rogers6b0870d2011-12-15 19:38:12 -08001025 if (frame.HasMethod()) { // ignore callee save frames
1026 ++depth_;
1027 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001028 } else {
1029 ++skip_depth_;
1030 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001031 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001032 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001033
1034 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001035 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001036 }
1037
Elliott Hughes29f27422011-09-18 16:02:18 -07001038 int GetSkipDepth() const {
1039 return skip_depth_;
1040 }
1041
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001042 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001043 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001044 uint32_t skip_depth_;
1045 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001046};
1047
Ian Rogersaaa20802011-09-11 21:47:37 -07001048class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001049 public:
Ian Rogers283ed0d2012-02-16 15:25:09 -08001050 explicit BuildInternalStackTraceVisitor(int skip_depth)
Elliott Hughes726079d2011-10-07 18:43:44 -07001051 : skip_depth_(skip_depth), count_(0), pc_trace_(NULL), method_trace_(NULL), local_ref_(NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001052 }
1053
1054 bool Init(int depth, ScopedJniThreadState& ts) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001055 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001056 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Elliott Hughes726079d2011-10-07 18:43:44 -07001057 if (method_trace_ == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001058 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001059 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001060 // Register a local reference as IntArray::Alloc may trigger GC
1061 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1062 pc_trace_ = IntArray::Alloc(depth);
Elliott Hughes726079d2011-10-07 18:43:44 -07001063 if (pc_trace_ == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001064 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001065 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001066#ifdef MOVING_GARBAGE_COLLECTOR
1067 // Re-read after potential GC
Brian Carlstrom26736442012-02-16 18:24:26 -08001068 method_trace_ = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
Ian Rogersaaa20802011-09-11 21:47:37 -07001069#endif
1070 // Save PC trace in last element of method trace, also places it into the
1071 // object graph.
1072 method_trace_->Set(depth, pc_trace_);
Ian Rogers283ed0d2012-02-16 15:25:09 -08001073 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001074 }
1075
Ian Rogersaaa20802011-09-11 21:47:37 -07001076 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001077
Elliott Hughes530fa002012-03-12 11:44:49 -07001078 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes726079d2011-10-07 18:43:44 -07001079 if (method_trace_ == NULL || pc_trace_ == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001080 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001081 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001082 if (skip_depth_ > 0) {
1083 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001084 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001085 }
Ian Rogers6b0870d2011-12-15 19:38:12 -08001086 if (!frame.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001087 return true; // ignore callee save frames
Ian Rogers6b0870d2011-12-15 19:38:12 -08001088 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001089 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001090 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001091 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001092 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001093 }
1094
Ian Rogersaaa20802011-09-11 21:47:37 -07001095 jobject GetInternalStackTrace() const {
1096 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001097 }
1098
1099 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001100 // How many more frames to skip.
1101 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001102 // Current position down stack trace
1103 uint32_t count_;
1104 // Array of return PC values
1105 IntArray* pc_trace_;
1106 // An array of the methods on the stack, the last entry is a reference to the
1107 // PC trace
1108 ObjectArray<Object>* method_trace_;
1109 // Local indirect reference table entry for method trace
1110 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001111};
1112
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001113// TODO: remove this.
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001114static uintptr_t ManglePc(uintptr_t pc) {
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001115 // Move the PC back 2 bytes as a call will frequently terminate the
1116 // decoding of a particular instruction and we want to make sure we
1117 // get the Dex PC of the instruction with the call and not the
1118 // instruction following.
1119 if (pc > 0) { pc -= 2; }
1120 return pc;
1121}
1122
1123// TODO: remove this.
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001124static uintptr_t DemanglePc(uintptr_t pc) {
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001125 // Revert mangling for the case where we need the PC to return to the upcall
Ian Rogers9a8a8882012-03-08 02:30:55 -08001126 if (pc > 0) { pc += 2; }
1127 return pc;
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001128}
Ian Rogersf57c47c2011-10-06 00:06:17 -07001129
Logan Chienf7ad17e2012-03-15 03:10:03 +08001130void Thread::PushShadowFrame(ShadowFrame* frame) {
1131 frame->SetLink(top_shadow_frame_);
1132 top_shadow_frame_ = frame;
1133}
1134
1135ShadowFrame* Thread::PopShadowFrame() {
1136 CHECK(top_shadow_frame_ != NULL);
1137 ShadowFrame* frame = top_shadow_frame_;
1138 top_shadow_frame_ = frame->GetLink();
1139 return frame;
1140}
1141
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001142void Thread::PushSirt(StackIndirectReferenceTable* sirt) {
1143 sirt->SetLink(top_sirt_);
1144 top_sirt_ = sirt;
1145}
1146
1147StackIndirectReferenceTable* Thread::PopSirt() {
1148 CHECK(top_sirt_ != NULL);
1149 StackIndirectReferenceTable* sirt = top_sirt_;
1150 top_sirt_ = top_sirt_->GetLink();
1151 return sirt;
1152}
1153
TDYa1279b2ba2e2012-03-19 10:12:32 -07001154#if !defined(ART_USE_LLVM_COMPILER) // LLVM use ShadowFrame
1155
Elliott Hughes530fa002012-03-12 11:44:49 -07001156void Thread::WalkStack(StackVisitor* visitor, bool include_upcalls) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001157 Frame frame = GetTopOfStack();
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001158 uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001159 uint32_t trace_stack_depth = 0;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001160 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1161 // CHECK(native_to_managed_record_ != NULL);
1162 NativeToManagedRecord* record = native_to_managed_record_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001163 bool method_tracing_active = Runtime::Current()->IsMethodTracingActive();
Elliott Hughes530fa002012-03-12 11:44:49 -07001164 while (frame.GetSP() != NULL) {
1165 for ( ; frame.GetMethod() != NULL; frame.Next()) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07001166 frame.GetMethod()->AssertPcIsWithinCode(pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001167 bool should_continue = visitor->VisitFrame(frame, pc);
Ian Rogers57b86d42012-03-27 16:05:41 -07001168 if (UNLIKELY(!should_continue)) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001169 return;
1170 }
Ian Rogers57b86d42012-03-27 16:05:41 -07001171 uintptr_t return_pc = frame.GetReturnPC();
1172 if (LIKELY(!method_tracing_active)) {
1173 pc = ManglePc(return_pc);
1174 } else {
1175 if (IsTraceExitPc(return_pc)) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001176 TraceStackFrame trace_frame = GetTraceStackFrame(trace_stack_depth++);
jeffhao26c0a1a2012-01-17 16:28:33 -08001177 CHECK(trace_frame.method_ == frame.GetMethod());
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001178 pc = ManglePc(trace_frame.return_pc_);
Ian Rogers57b86d42012-03-27 16:05:41 -07001179 } else {
1180 pc = ManglePc(return_pc);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001181 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001182 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001183 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001184 if (include_upcalls) {
1185 bool should_continue = visitor->VisitFrame(frame, pc);
1186 if (!should_continue) {
1187 return;
1188 }
1189 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001190 if (record == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001191 return;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001192 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001193 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001194 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001195 pc = ManglePc(record->last_top_of_managed_stack_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001196 record = record->link_;
1197 }
1198}
1199
TDYa1279b2ba2e2012-03-19 10:12:32 -07001200#else // defined(ART_USE_LLVM_COMPILER) // LLVM uses ShadowFrame
1201
1202void Thread::WalkStack(StackVisitor* visitor, bool /*include_upcalls*/) const {
1203 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
1204 Frame frame;
1205 frame.SetSP(reinterpret_cast<Method**>(reinterpret_cast<byte*>(cur) +
1206 ShadowFrame::MethodOffset()));
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001207 bool should_continue = visitor->VisitFrame(frame, cur->GetLineNumber());
TDYa1279b2ba2e2012-03-19 10:12:32 -07001208 if (!should_continue) {
1209 return;
1210 }
1211 }
1212}
1213
1214/*
1215 * | |
1216 * | |
1217 * | |
1218 * | . |
1219 * | . |
1220 * | . |
1221 * | . |
1222 * | Method* |
1223 * | . |
1224 * | . | <-- top_shadow_frame_ (ShadowFrame*)
1225 * / +------------------------+
1226 * ->| . |
1227 * . | . |
1228 * . | . |
1229 * /+------------------------+
1230 * / | . |
1231 * / | . |
1232 * --- | | . |
1233 * | | | . |
1234 * | | Method* | <-- frame.GetSP() (Method**)
1235 * ShadowFrame \ | . |
1236 * | ->| . | <-- cur (ShadowFrame*)
1237 * --- /+------------------------+
1238 * / | . |
1239 * / | . |
1240 * --- | | . |
1241 * | cur->GetLink() | | . |
1242 * | | Method* |
1243 * ShadowFrame \ | . |
1244 * | ->| . |
1245 * --- +------------------------+
1246 * | . |
1247 * | . |
1248 * | . |
1249 * +========================+
1250 */
1251
1252#endif
1253
Elliott Hughes01158d72011-09-19 19:47:10 -07001254jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001255 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001256 CountStackDepthVisitor count_visitor;
1257 WalkStack(&count_visitor);
1258 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001259 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001260
Ian Rogersaaa20802011-09-11 21:47:37 -07001261 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001262 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001263
1264 // Build internal stack trace
Ian Rogers77f74c12012-02-16 22:35:30 -08001265 BuildInternalStackTraceVisitor build_trace_visitor(skip_depth);
1266 if (!build_trace_visitor.Init(depth, ts)) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001267 return NULL; // Allocation failed
Ian Rogers283ed0d2012-02-16 15:25:09 -08001268 }
Brian Carlstrom26736442012-02-16 18:24:26 -08001269 WalkStack(&build_trace_visitor);
1270 return build_trace_visitor.GetInternalStackTrace();
Ian Rogersaaa20802011-09-11 21:47:37 -07001271}
1272
Elliott Hughes01158d72011-09-19 19:47:10 -07001273jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1274 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001275 // Transition into runnable state to work on Object*/Array*
1276 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001277 // Decode the internal stack trace into the depth, method trace and PC trace
1278 ObjectArray<Object>* method_trace =
1279 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
Ian Rogers9074b992011-10-26 17:41:55 -07001280 int32_t depth = method_trace->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001281 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1282
1283 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1284
Elliott Hughes01158d72011-09-19 19:47:10 -07001285 jobjectArray result;
1286 ObjectArray<StackTraceElement>* java_traces;
1287 if (output_array != NULL) {
1288 // Reuse the array we were given.
1289 result = output_array;
1290 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1291 output_array));
1292 // ...adjusting the number of frames we'll write to not exceed the array length.
1293 depth = std::min(depth, java_traces->GetLength());
1294 } else {
1295 // Create java_trace array and place in local reference table
1296 java_traces = class_linker->AllocStackTraceElementArray(depth);
Elliott Hughes30646832011-10-13 16:59:46 -07001297 if (java_traces == NULL) {
1298 return NULL;
1299 }
Elliott Hughes01158d72011-09-19 19:47:10 -07001300 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1301 }
1302
1303 if (stack_depth != NULL) {
1304 *stack_depth = depth;
1305 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001306
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001307 MethodHelper mh;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001308 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001309 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1310 Method* method = down_cast<Method*>(method_trace->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001311 mh.ChangeMethod(method);
Ian Rogersaaa20802011-09-11 21:47:37 -07001312 uint32_t native_pc = pc_trace->Get(i);
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001313#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001314 int32_t line_number = mh.GetLineNumFromNativePC(native_pc);
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001315#else
1316 int32_t line_number = native_pc; // LLVM stored line_number in the ShadowFrame
1317#endif
Ian Rogersaaa20802011-09-11 21:47:37 -07001318 // Allocate element, potentially triggering GC
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001319 // TODO: reuse class_name_object via Class::name_?
Ian Rogers48601312011-12-07 16:45:19 -08001320 const char* descriptor = mh.GetDeclaringClassDescriptor();
1321 CHECK(descriptor != NULL);
1322 std::string class_name(PrettyDescriptor(descriptor));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001323 SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
1324 if (class_name_object.get() == NULL) {
1325 return NULL;
1326 }
Ian Rogers48601312011-12-07 16:45:19 -08001327 const char* method_name = mh.GetName();
1328 CHECK(method_name != NULL);
1329 SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001330 if (method_name_object.get() == NULL) {
1331 return NULL;
1332 }
Ian Rogers48601312011-12-07 16:45:19 -08001333 const char* source_file = mh.GetDeclaringClassSourceFile();
1334 SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001335 StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001336 method_name_object.get(),
1337 source_name_object.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001338 line_number);
Elliott Hughes30646832011-10-13 16:59:46 -07001339 if (obj == NULL) {
1340 return NULL;
1341 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001342#ifdef MOVING_GARBAGE_COLLECTOR
1343 // Re-read after potential GC
1344 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1345 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1346 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1347#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001348 java_traces->Set(i, obj);
1349 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001350 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001351}
1352
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001353void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001354 va_list args;
1355 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001356 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001357 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001358}
1359
1360void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1361 std::string msg;
1362 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001363 ThrowNewException(exception_class_descriptor, msg.c_str());
1364}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001365
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001366void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001367 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001368 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001369 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001370 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001371 descriptor.erase(descriptor.length() - 1);
1372
1373 JNIEnv* env = GetJniEnv();
Elliott Hughes726079d2011-10-07 18:43:44 -07001374 ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001375 if (exception_class.get() == NULL) {
1376 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1377 << PrettyTypeOf(GetException());
1378 CHECK(IsExceptionPending());
1379 return;
1380 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001381 if (!Runtime::Current()->IsStarted()) {
1382 // Something is trying to throw an exception without a started
1383 // runtime, which is the common case in the compiler. We won't be
1384 // able to invoke the constructor of the exception, so use
1385 // AllocObject which will not invoke a constructor.
1386 ScopedLocalRef<jthrowable> exception(
1387 env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1388 if (exception.get() != NULL) {
1389 ScopedJniThreadState ts(env);
1390 Throwable* t = reinterpret_cast<Throwable*>(ts.Self()->DecodeJObject(exception.get()));
Ian Rogers02fbef02012-01-31 22:15:33 -08001391 t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001392 ts.Self()->SetException(t);
1393 } else {
1394 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1395 << PrettyTypeOf(GetException());
1396 CHECK(IsExceptionPending());
1397 }
1398 return;
1399 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001400 int rc = env->ThrowNew(exception_class.get(), msg);
Elliott Hughes30646832011-10-13 16:59:46 -07001401 if (rc != JNI_OK) {
1402 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1403 << PrettyTypeOf(GetException());
1404 CHECK(IsExceptionPending());
Elliott Hughes30646832011-10-13 16:59:46 -07001405 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001406}
1407
Elliott Hughes418dfe72011-10-06 18:56:27 -07001408void Thread::ThrowOutOfMemoryError(Class* c, size_t byte_count) {
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001409 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s", byte_count,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001410 PrettyDescriptor(c).c_str()));
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001411 ThrowOutOfMemoryError(msg.c_str());
1412}
1413
1414void Thread::ThrowOutOfMemoryError(const char* msg) {
1415 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1416 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Elliott Hughes726079d2011-10-07 18:43:44 -07001417 if (!throwing_OutOfMemoryError_) {
1418 throwing_OutOfMemoryError_ = true;
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001419 ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001420 } else {
Elliott Hughes726079d2011-10-07 18:43:44 -07001421 SetException(pre_allocated_OutOfMemoryError_);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001422 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001423 throwing_OutOfMemoryError_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001424}
1425
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001426
Elliott Hughes498508c2011-10-17 14:58:22 -07001427Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001428 return Thread::Current();
1429}
1430
1431void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001432 std::ostringstream ss;
1433 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001434 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001435 // log to stderr for debugging command line processes
1436 std::cerr << str;
1437#ifdef HAVE_ANDROID_OS
1438 // log to logcat for debugging frameworks processes
1439 LOG(INFO) << str;
1440#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001441}
1442
Ian Rogersbdb03912011-09-14 00:55:44 -07001443class CatchBlockStackVisitor : public Thread::StackVisitor {
1444 public:
1445 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers57b86d42012-03-27 16:05:41 -07001446 : to_find_(to_find), long_jump_context_(ljc), native_method_count_(0),
1447 method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001448#ifndef NDEBUG
1449 handler_pc_ = 0xEBADC0DE;
1450 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1451#endif
1452 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001453
Elliott Hughes530fa002012-03-12 11:44:49 -07001454 bool VisitFrame(const Frame& fr, uintptr_t pc) {
1455 Method* method = fr.GetMethod();
1456 if (method == NULL) {
1457 // This is the upcall, we remember the frame and last_pc so that we may
1458 // long jump to them
1459 handler_pc_ = DemanglePc(pc);
1460 handler_frame_ = fr;
Ian Rogers57b86d42012-03-27 16:05:41 -07001461 return false; // End stack walk.
Elliott Hughes530fa002012-03-12 11:44:49 -07001462 }
1463 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers57b86d42012-03-27 16:05:41 -07001464 if (method->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001465 // ignore callee save method
Ian Rogers57b86d42012-03-27 16:05:41 -07001466 DCHECK(method->IsCalleeSaveMethod());
Elliott Hughes530fa002012-03-12 11:44:49 -07001467 } else if (method->IsNative()) {
1468 native_method_count_++;
1469 } else {
1470 // Unwind stack during method tracing
Ian Rogers57b86d42012-03-27 16:05:41 -07001471 if (UNLIKELY(method_tracing_active_)) {
1472 if (IsTraceExitPc(DemanglePc(pc))) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001473 pc = ManglePc(TraceMethodUnwindFromCode(Thread::Current()));
1474 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001475 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001476 dex_pc = method->ToDexPC(pc);
1477 }
1478 if (dex_pc != DexFile::kDexNoIndex) {
1479 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1480 if (found_dex_pc != DexFile::kDexNoIndex) {
1481 handler_pc_ = method->ToNativePC(found_dex_pc);
1482 handler_frame_ = fr;
Ian Rogers57b86d42012-03-27 16:05:41 -07001483 return false; // End stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001484 }
1485 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001486 // Caller may be handler, fill in callee saves in context
1487 long_jump_context_->FillCalleeSaves(fr);
Ian Rogers57b86d42012-03-27 16:05:41 -07001488 return true; // Continue stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001489 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001490
Ian Rogersbdb03912011-09-14 00:55:44 -07001491 // The type of the exception catch block to find
1492 Class* to_find_;
1493 // Frame with found handler or last frame if no handler found
1494 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001495 // PC to branch to for the handler
1496 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001497 // Context that will be the target of the long jump
1498 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001499 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1500 uint32_t native_method_count_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001501 // Is method tracing active?
1502 const bool method_tracing_active_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001503};
1504
Ian Rogersff1ed472011-09-20 13:46:24 -07001505void Thread::DeliverException() {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001506 const bool kDebugExceptionDelivery = false;
Elliott Hughesd07986f2011-12-06 18:27:45 -08001507 Throwable* exception = GetException(); // Get exception from thread
Ian Rogersff1ed472011-09-20 13:46:24 -07001508 CHECK(exception != NULL);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001509 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001510 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001511 ClearException();
1512 if (kDebugExceptionDelivery) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001513 String* msg = exception->GetDetailMessage();
1514 std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1515 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
1516 << ": " << str_msg << std::endl);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001517 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001518
1519 Context* long_jump_context = GetLongJumpContext();
1520 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Elliott Hughes530fa002012-03-12 11:44:49 -07001521 WalkStack(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001522
Elliott Hughesd07986f2011-12-06 18:27:45 -08001523 Method** sp;
1524 uintptr_t throw_native_pc;
1525 Method* throw_method = GetCurrentMethod(&throw_native_pc, &sp);
1526 uintptr_t catch_native_pc = catch_finder.handler_pc_;
1527 Method* catch_method = catch_finder.handler_frame_.GetMethod();
1528 Dbg::PostException(sp, throw_method, throw_native_pc, catch_method, catch_native_pc, exception);
1529
Ian Rogers28ad40d2011-10-27 15:19:26 -07001530 if (kDebugExceptionDelivery) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001531 if (catch_method == NULL) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001532 LOG(INFO) << "Handler is upcall";
1533 } else {
1534 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1535 const DexFile& dex_file =
Elliott Hughesd07986f2011-12-06 18:27:45 -08001536 class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1537 int line_number = dex_file.GetLineNumFromPC(catch_method,
1538 catch_method->ToDexPC(catch_finder.handler_pc_));
1539 LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
Ian Rogers28ad40d2011-10-27 15:19:26 -07001540 }
1541 }
1542 SetException(exception);
Ian Rogers9a8a8882012-03-08 02:30:55 -08001543 CHECK_NE(catch_native_pc, 0u);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001544 long_jump_context->SetSP(reinterpret_cast<uintptr_t>(catch_finder.handler_frame_.GetSP()));
Ian Rogers9a8a8882012-03-08 02:30:55 -08001545 long_jump_context->SetPC(catch_native_pc);
Ian Rogersbdb03912011-09-14 00:55:44 -07001546 long_jump_context->DoLongJump();
Ian Rogers9a8a8882012-03-08 02:30:55 -08001547 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001548}
1549
Ian Rogersbdb03912011-09-14 00:55:44 -07001550Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001551 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001552 if (result == NULL) {
1553 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001554 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001555 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001556 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001557}
1558
Elliott Hughesd07986f2011-12-06 18:27:45 -08001559Method* Thread::GetCurrentMethod(uintptr_t* pc, Method*** sp) const {
1560 Frame f = top_of_managed_stack_;
1561 Method* m = f.GetMethod();
Elliott Hughes8be2d402012-02-23 14:22:41 -08001562 uintptr_t native_pc = top_of_managed_stack_pc_;
1563
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001564 // We use JNI internally for exception throwing, so it's possible to arrive
1565 // here via a "FromCode" function, in which case there's a synthetic
1566 // callee-save method at the top of the stack. These shouldn't be user-visible,
1567 // so if we find one, skip it and return the compiled method underneath.
jeffhao33dc7712011-11-09 17:54:24 -08001568 if (m != NULL && m->IsCalleeSaveMethod()) {
Elliott Hughes8be2d402012-02-23 14:22:41 -08001569 native_pc = f.GetReturnPC();
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001570 f.Next();
1571 m = f.GetMethod();
1572 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001573 if (pc != NULL) {
Elliott Hughes8be2d402012-02-23 14:22:41 -08001574 *pc = (m != NULL) ? ManglePc(native_pc) : 0;
jeffhao33dc7712011-11-09 17:54:24 -08001575 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001576 if (sp != NULL) {
1577 *sp = f.GetSP();
1578 }
1579 return m;
jeffhao33dc7712011-11-09 17:54:24 -08001580}
1581
Elliott Hughes5f791332011-09-15 17:45:30 -07001582bool Thread::HoldsLock(Object* object) {
1583 if (object == NULL) {
1584 return false;
1585 }
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07001586 return object->GetThinLockId() == thin_lock_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001587}
1588
Elliott Hughes038a8062011-09-18 14:12:41 -07001589bool Thread::IsDaemon() {
1590 return gThread_daemon->GetBoolean(peer_);
1591}
1592
Ian Rogersd6b1f612011-09-27 13:38:14 -07001593class ReferenceMapVisitor : public Thread::StackVisitor {
1594 public:
1595 ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1596 context_(context), root_visitor_(root_visitor), arg_(arg) {
1597 }
1598
Elliott Hughes530fa002012-03-12 11:44:49 -07001599 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001600 Method* m = frame.GetMethod();
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001601 if (false) {
jeffhao25045522012-03-13 19:34:37 -07001602 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m)
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001603 << StringPrintf("@ PC:%04x", m->ToDexPC(pc));
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001604 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001605 // Process register map (which native and callee save methods don't have)
Ian Rogers3891c772011-12-06 15:38:28 -08001606 if (!m->IsNative() && !m->IsCalleeSaveMethod() && !m->IsProxyMethod()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001607 CHECK(m->GetGcMap() != NULL) << PrettyMethod(m);
1608 CHECK_NE(0U, m->GetGcMapLength()) << PrettyMethod(m);
1609 verifier::PcToReferenceMap map(m->GetGcMap(), m->GetGcMapLength());
Ian Rogersd81871c2011-10-03 13:57:23 -07001610 const uint8_t* reg_bitmap = map.FindBitMap(m->ToDexPC(pc));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001611 CHECK(reg_bitmap != NULL);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001612 const VmapTable vmap_table(m->GetVmapTableRaw());
Elliott Hughes11d1b0c2012-01-23 16:57:47 -08001613 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001614 DCHECK(code_item != NULL); // can't be NULL or how would we compile its instructions?
1615 uint32_t core_spills = m->GetCoreSpillMask();
1616 uint32_t fp_spills = m->GetFpSpillMask();
1617 size_t frame_size = m->GetFrameSizeInBytes();
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001618 // For all dex registers in the bitmap
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001619 size_t num_regs = std::min(map.RegWidth() * 8,
1620 static_cast<size_t>(code_item->registers_size_));
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001621 for (size_t reg = 0; reg < num_regs; ++reg) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001622 // Does this register hold a reference?
1623 if (TestBitmap(reg, reg_bitmap)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001624 uint32_t vmap_offset;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001625 Object* ref;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001626 if (vmap_table.IsInContext(reg, vmap_offset)) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001627 // Compute the register we need to load from the context
1628 uint32_t spill_mask = m->GetCoreSpillMask();
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001629 CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
Ian Rogersf57c47c2011-10-06 00:06:17 -07001630 uint32_t matches = 0;
1631 uint32_t spill_shifts = 0;
1632 while (matches != (vmap_offset + 1)) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001633 DCHECK_NE(spill_mask, 0u);
Ian Rogersf57c47c2011-10-06 00:06:17 -07001634 matches += spill_mask & 1; // Add 1 if the low bit is set
1635 spill_mask >>= 1;
1636 spill_shifts++;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001637 }
Ian Rogersf57c47c2011-10-06 00:06:17 -07001638 spill_shifts--; // wind back one as we want the last match
1639 ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001640 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001641 ref = reinterpret_cast<Object*>(frame.GetVReg(code_item, core_spills, fp_spills,
1642 frame_size, reg));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001643 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001644 if (ref != NULL) {
1645 root_visitor_(ref, arg_);
1646 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001647 }
1648 }
1649 }
1650 context_->FillCalleeSaves(frame);
Elliott Hughes530fa002012-03-12 11:44:49 -07001651 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001652 }
1653
1654 private:
1655 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1656 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1657 }
1658
1659 // Context used to build up picture of callee saves
1660 Context* context_;
1661 // Call-back when we visit a root
1662 Heap::RootVisitor* root_visitor_;
1663 // Argument to call-back
1664 void* arg_;
1665};
1666
1667void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001668 if (exception_ != NULL) {
1669 visitor(exception_, arg);
1670 }
1671 if (peer_ != NULL) {
1672 visitor(peer_, arg);
1673 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001674 if (pre_allocated_OutOfMemoryError_ != NULL) {
1675 visitor(pre_allocated_OutOfMemoryError_, arg);
1676 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001677 if (class_loader_override_ != NULL) {
1678 visitor(class_loader_override_, arg);
1679 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001680 jni_env_->locals.VisitRoots(visitor, arg);
1681 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001682
1683 SirtVisitRoots(visitor, arg);
Logan Chienf7ad17e2012-03-15 03:10:03 +08001684 ShadowFrameVisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001685
Ian Rogersd6b1f612011-09-27 13:38:14 -07001686 // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1687 // delivery.
1688 Context* context = GetLongJumpContext();
1689 // Visit roots on this thread's stack
1690 ReferenceMapVisitor mapper(context, visitor, arg);
1691 WalkStack(&mapper);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001692}
1693
jeffhao25045522012-03-13 19:34:37 -07001694#if VERIFY_OBJECT_ENABLED
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001695static void VerifyObject(const Object* obj, void*) {
jeffhao25045522012-03-13 19:34:37 -07001696 Runtime::Current()->GetHeap()->VerifyObject(obj);
1697}
1698
1699void Thread::VerifyStack() {
jeffhaoe66ac792012-03-19 16:08:46 -07001700 UniquePtr<Context> context(Context::Create());
1701 ReferenceMapVisitor mapper(context.get(), VerifyObject, NULL);
jeffhao25045522012-03-13 19:34:37 -07001702 WalkStack(&mapper);
1703}
1704#endif
1705
Ian Rogersb033c752011-07-20 12:22:35 -07001706static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001707 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001708 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001709 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001710 "Blocked",
1711 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001712 "Initializing",
1713 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001714 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001715 "VmWait",
1716 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001717};
1718std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001719 int32_t int_state = static_cast<int32_t>(state);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001720 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1721 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001722 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001723 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001724 }
1725 return os;
1726}
1727
Elliott Hughes330304d2011-08-12 14:28:05 -07001728std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Elliott Hughes899e7892012-01-24 14:57:32 -08001729 thread.Dump(os, false);
Elliott Hughes330304d2011-08-12 14:28:05 -07001730 return os;
1731}
1732
Elliott Hughesa4060e52012-03-02 16:51:35 -08001733void Thread::CheckSafeToLockOrUnlock(MutexRank rank, bool is_locking) {
Elliott Hughesffb465f2012-03-01 18:46:05 -08001734 if (is_locking) {
1735 if (held_mutexes_[rank] == 0) {
1736 bool bad_mutexes_held = false;
1737 for (int i = kMaxMutexRank; i > rank; --i) {
1738 if (held_mutexes_[i] != 0) {
1739 LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while " << (is_locking ? "locking" : "unlocking") << " " << rank;
1740 bad_mutexes_held = true;
1741 }
1742 }
Elliott Hughesb5db3bb2012-03-29 20:00:31 -07001743 CHECK(!bad_mutexes_held) << rank;
Elliott Hughesffb465f2012-03-01 18:46:05 -08001744 }
1745 ++held_mutexes_[rank];
1746 } else {
Elliott Hughesb5db3bb2012-03-29 20:00:31 -07001747 CHECK_GT(held_mutexes_[rank], 0U) << rank;
Elliott Hughesffb465f2012-03-01 18:46:05 -08001748 --held_mutexes_[rank];
1749 }
1750}
1751
Elliott Hughesa4060e52012-03-02 16:51:35 -08001752void Thread::CheckSafeToWait(MutexRank rank) {
1753 bool bad_mutexes_held = false;
1754 for (int i = kMaxMutexRank; i >= 0; --i) {
1755 if (i != rank && held_mutexes_[i] != 0) {
1756 LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while doing condition variable wait on " << rank;
1757 bad_mutexes_held = true;
1758 }
1759 }
1760 if (held_mutexes_[rank] == 0) {
1761 LOG(ERROR) << "*not* holding " << rank << " while doing condition variable wait on it";
1762 bad_mutexes_held = true;
1763 }
1764 CHECK(!bad_mutexes_held);
1765}
1766
Elliott Hughes8daa0922011-09-11 13:46:25 -07001767} // namespace art