blob: 125480e2973ffd0a73521321a0092d69ebe453f1 [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
TDYa127ee0d3fb2012-04-01 14:55:33 -0700436#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersb04f69f2011-10-17 00:40:54 -0700437void Thread::PushNativeToManagedRecord(NativeToManagedRecord* record) {
438 Method **sp = top_of_managed_stack_.GetSP();
439#ifndef NDEBUG
440 if (sp != NULL) {
441 Method* m = *sp;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800442 Runtime::Current()->GetHeap()->VerifyObject(m);
Ian Rogersb04f69f2011-10-17 00:40:54 -0700443 DCHECK((m == NULL) || m->IsMethod());
444 }
445#endif
446 record->last_top_of_managed_stack_ = reinterpret_cast<void*>(sp);
447 record->last_top_of_managed_stack_pc_ = top_of_managed_stack_pc_;
448 record->link_ = native_to_managed_record_;
449 native_to_managed_record_ = record;
450 top_of_managed_stack_.SetSP(NULL);
451}
TDYa127ee0d3fb2012-04-01 14:55:33 -0700452#else
453void Thread::PushNativeToManagedRecord(NativeToManagedRecord*) {
454 LOG(FATAL) << "Called non-LLVM method with LLVM";
455}
456#endif
Ian Rogersb04f69f2011-10-17 00:40:54 -0700457
TDYa127ee0d3fb2012-04-01 14:55:33 -0700458#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersb04f69f2011-10-17 00:40:54 -0700459void Thread::PopNativeToManagedRecord(const NativeToManagedRecord& record) {
460 native_to_managed_record_ = record.link_;
461 top_of_managed_stack_.SetSP(reinterpret_cast<Method**>(record.last_top_of_managed_stack_));
462 top_of_managed_stack_pc_ = record.last_top_of_managed_stack_pc_;
463}
TDYa127ee0d3fb2012-04-01 14:55:33 -0700464#else
465void Thread::PopNativeToManagedRecord(const NativeToManagedRecord&) {
466 LOG(FATAL) << "Called non-LLVM method with LLVM";
467}
468#endif
Ian Rogersb04f69f2011-10-17 00:40:54 -0700469
Elliott Hughesd369bb72011-09-12 14:41:14 -0700470struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700471 StackDumpVisitor(std::ostream& os, const Thread* thread)
Ian Rogers28ad40d2011-10-27 15:19:26 -0700472 : last_method(NULL), last_line_number(0), repetition_count(0), os(os), thread(thread),
473 frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700474 }
475
Ian Rogersbdb03912011-09-14 00:55:44 -0700476 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700477 }
478
Elliott Hughes530fa002012-03-12 11:44:49 -0700479 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700480 if (!frame.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700481 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700482 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700483 const int kMaxRepetition = 3;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700484 Method* m = frame.GetMethod();
TDYa127540a5b72012-04-03 18:56:08 -0700485#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700486 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700487 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersb861dc02011-11-14 17:00:05 -0800488 const DexCache* dex_cache = c->GetDexCache();
489 int line_number = -1;
490 if (dex_cache != NULL) { // be tolerant of bad input
491 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
492 line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
493 }
TDYa127540a5b72012-04-03 18:56:08 -0700494#else
495 // Compiler_LLVM stores line_number in the ShadowFrame, and passes it to visitor.
496 int line_number = static_cast<int>(pc);
497#endif
Ian Rogers28ad40d2011-10-27 15:19:26 -0700498 if (line_number == last_line_number && last_method == m) {
499 repetition_count++;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700500 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700501 if (repetition_count >= kMaxRepetition) {
502 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
503 }
504 repetition_count = 0;
505 last_line_number = line_number;
506 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700507 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700508 if (repetition_count < kMaxRepetition) {
509 os << " at " << PrettyMethod(m, false);
510 if (m->IsNative()) {
511 os << "(Native method)";
512 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800513 mh.ChangeMethod(m);
514 const char* source_file(mh.GetDeclaringClassSourceFile());
515 os << "(" << (source_file != NULL ? source_file : "unavailable")
Ian Rogers28ad40d2011-10-27 15:19:26 -0700516 << ":" << line_number << ")";
517 }
518 os << "\n";
519 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700520
521 if (frame_count++ == 0) {
522 Monitor::DescribeWait(os, thread);
523 }
Elliott Hughes530fa002012-03-12 11:44:49 -0700524 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700525 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800526 MethodHelper mh;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700527 Method* last_method;
528 int last_line_number;
529 int repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700530 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700531 const Thread* thread;
532 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700533};
534
Elliott Hughesd92bec42011-09-02 17:04:36 -0700535void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800536 // If we're currently in native code, dump that stack before dumping the managed stack.
537 if (GetState() == Thread::kNative || GetState() == Thread::kVmWait) {
538 DumpNativeStack(os);
539 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700540 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700541 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700542}
543
Elliott Hughesa4060e52012-03-02 16:51:35 -0800544void Thread::SetStateWithoutSuspendCheck(Thread::State new_state) {
545 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
546 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
547 android_atomic_release_store(new_state, addr);
548}
549
Elliott Hughes8d768a92011-09-14 16:35:25 -0700550Thread::State Thread::SetState(Thread::State new_state) {
551 Thread::State old_state = state_;
552 if (old_state == new_state) {
553 return old_state;
554 }
555
556 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
557 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
558
559 if (new_state == Thread::kRunnable) {
560 /*
561 * Change our status to Thread::kRunnable. The transition requires
Elliott Hughes81ff3182012-03-23 20:35:56 -0700562 * that we check for pending suspension, because the runtime considers
Elliott Hughes8d768a92011-09-14 16:35:25 -0700563 * us to be "asleep" in all other states, and another thread could
564 * be performing a GC now.
565 *
566 * The order of operations is very significant here. One way to
567 * do this wrong is:
568 *
569 * GCing thread Our thread (in kNative)
570 * ------------ ----------------------
571 * check suspend count (== 0)
572 * SuspendAllThreads()
573 * grab suspend-count lock
574 * increment all suspend counts
575 * release suspend-count lock
576 * check thread state (== kNative)
577 * all are suspended, begin GC
578 * set state to kRunnable
579 * (continue executing)
580 *
581 * We can correct this by grabbing the suspend-count lock and
582 * performing both of our operations (check suspend count, set
583 * state) while holding it, now we need to grab a mutex on every
584 * transition to kRunnable.
585 *
586 * What we do instead is change the order of operations so that
587 * the transition to kRunnable happens first. If we then detect
588 * that the suspend count is nonzero, we switch to kSuspended.
589 *
590 * Appropriate compiler and memory barriers are required to ensure
591 * that the operations are observed in the expected order.
592 *
593 * This does create a small window of opportunity where a GC in
594 * progress could observe what appears to be a running thread (if
595 * it happens to look between when we set to kRunnable and when we
596 * switch to kSuspended). At worst this only affects assertions
597 * and thread logging. (We could work around it with some sort
598 * of intermediate "pre-running" state that is generally treated
599 * as equivalent to running, but that doesn't seem worthwhile.)
600 *
601 * We can also solve this by combining the "status" and "suspend
602 * count" fields into a single 32-bit value. This trades the
603 * store/load barrier on transition to kRunnable for an atomic RMW
604 * op on all transitions and all suspend count updates (also, all
605 * accesses to status or the thread count require bit-fiddling).
606 * It also eliminates the brief transition through kRunnable when
607 * the thread is supposed to be suspended. This is possibly faster
608 * on SMP and slightly more correct, but less convenient.
609 */
610 android_atomic_acquire_store(new_state, addr);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800611 ANNOTATE_IGNORE_READS_BEGIN();
612 int suspend_count = suspend_count_;
613 ANNOTATE_IGNORE_READS_END();
614 if (suspend_count != 0) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700615 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
616 }
617 } else {
618 /*
619 * Not changing to Thread::kRunnable. No additional work required.
620 *
621 * We use a releasing store to ensure that, if we were runnable,
622 * any updates we previously made to objects on the managed heap
623 * will be observed before the state change.
624 */
625 android_atomic_release_store(new_state, addr);
626 }
627
628 return old_state;
629}
630
Elliott Hughes761928d2011-11-16 18:33:03 -0800631bool Thread::IsSuspended() {
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800632 ANNOTATE_IGNORE_READS_BEGIN();
633 int suspend_count = suspend_count_;
634 ANNOTATE_IGNORE_READS_END();
635 return suspend_count != 0 && GetState() != Thread::kRunnable;
Elliott Hughes761928d2011-11-16 18:33:03 -0800636}
637
Elliott Hughesff738062012-02-03 15:00:42 -0800638static void ReportThreadSuspendTimeout(Thread* waiting_thread) {
639 Runtime* runtime = Runtime::Current();
640 std::ostringstream ss;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800641 ss << "Thread suspend timeout waiting for thread " << *waiting_thread << "\n";
Elliott Hughesff738062012-02-03 15:00:42 -0800642 runtime->DumpLockHolders(ss);
643 ss << "\n";
644 runtime->GetThreadList()->DumpLocked(ss);
645 LOG(FATAL) << ss.str();
646}
647
Elliott Hughes8d768a92011-09-14 16:35:25 -0700648void Thread::WaitUntilSuspended() {
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800649 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
650
651 useconds_t total_delay = 0;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700652 useconds_t delay = 0;
653 while (GetState() == Thread::kRunnable) {
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800654 if (total_delay >= kTimeoutUs) {
Elliott Hughesff738062012-02-03 15:00:42 -0800655 ReportThreadSuspendTimeout(this);
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800656 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700657 useconds_t new_delay = delay * 2;
658 CHECK_GE(new_delay, delay);
659 delay = new_delay;
660 if (delay == 0) {
661 sched_yield();
662 delay = 10000;
663 } else {
664 usleep(delay);
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800665 total_delay += delay;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700666 }
667 }
668}
669
Elliott Hughesbe759c62011-09-08 19:38:21 -0700670void Thread::ThreadExitCallback(void* arg) {
671 Thread* self = reinterpret_cast<Thread*>(arg);
672 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700673}
674
Elliott Hughesbe759c62011-09-08 19:38:21 -0700675void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700676 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700677 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700678
679 // Double-check the TLS slot allocation.
680 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800681 LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700682 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700683}
Carl Shapirob5573532011-07-12 18:22:59 -0700684
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700685// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700686static Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700687 Class* c = class_linker->FindSystemClass(descriptor);
688 CHECK(c != NULL) << descriptor;
689 return c;
690}
691
692// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700693static Field* FindFieldOrDie(Class* c, const char* name, const char* descriptor) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700694 Field* f = c->FindDeclaredInstanceField(name, descriptor);
695 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700696 return f;
697}
698
699// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700700static Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700701 Method* m = c->FindVirtualMethod(name, signature);
702 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
703 return m;
704}
705
Elliott Hughes462c9442012-03-23 18:47:50 -0700706// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700707static Field* FindStaticFieldOrDie(Class* c, const char* name, const char* descriptor) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700708 Field* f = c->FindDeclaredStaticField(name, descriptor);
709 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
710 return f;
711}
712
Elliott Hughes038a8062011-09-18 14:12:41 -0700713void Thread::FinishStartup() {
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500714 CHECK(Runtime::Current()->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700715 Thread* self = Thread::Current();
716
717 // Need to be kRunnable for FindClass
718 ScopedThreadStateChange tsc(self, Thread::kRunnable);
719
Elliott Hughes038a8062011-09-18 14:12:41 -0700720 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
721 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700722
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700723 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700724 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
Elliott Hughes462c9442012-03-23 18:47:50 -0700725 gThreadGroup = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700726 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700727
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700728 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", "Z");
729 gThread_group = FindFieldOrDie(Thread_class, "group", "Ljava/lang/ThreadGroup;");
730 gThread_lock = FindFieldOrDie(Thread_class, "lock", "Ljava/lang/ThreadLock;");
731 gThread_name = FindFieldOrDie(Thread_class, "name", "Ljava/lang/String;");
732 gThread_priority = FindFieldOrDie(Thread_class, "priority", "I");
733 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
734 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", "I");
Elliott Hughes462c9442012-03-23 18:47:50 -0700735 gThreadGroup_name = FindFieldOrDie(gThreadGroup, "name", "Ljava/lang/String;");
736 gThreadGroup_mMain = FindStaticFieldOrDie(gThreadGroup, "mMain", "Ljava/lang/ThreadGroup;");
737 gThreadGroup_mSystem = FindStaticFieldOrDie(gThreadGroup, "mSystem", "Ljava/lang/ThreadGroup;");
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700738 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", "Ljava/lang/Thread;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700739
740 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
Elliott Hughes462c9442012-03-23 18:47:50 -0700741 gThreadGroup_removeThread = FindMethodOrDie(gThreadGroup, "removeThread", "(Ljava/lang/Thread;)V");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700742 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
743 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700744
745 // Finish attaching the main thread.
Elliott Hughes462c9442012-03-23 18:47:50 -0700746 Thread::Current()->CreatePeer("main", false, Thread::GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500747
748 InitBoxingMethods();
749 class_linker->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700750}
751
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700752void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700753 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700754}
755
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700756uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
757 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
758 return ThreadList::kInvalidId;
759 }
760 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
761 if (managed_thread == NULL) {
762 return ThreadList::kInvalidId;
763 }
764 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
765 Thread* thread = reinterpret_cast<Thread*>(vmData);
766 if (thread == NULL) {
767 return ThreadList::kInvalidId;
768 }
769 return thread->GetThinLockId();
770}
771
Elliott Hughesdcc24742011-09-07 14:02:44 -0700772Thread::Thread()
Elliott Hughes47179f72011-10-27 16:44:39 -0700773 : thin_lock_id_(0),
774 tid_(0),
775 peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700776 top_of_managed_stack_(),
777 top_of_managed_stack_pc_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700778 wait_mutex_(new Mutex("Thread wait mutex")),
779 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700780 wait_monitor_(NULL),
781 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700782 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700783 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700784 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700785 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700786 native_to_managed_record_(NULL),
787 top_sirt_(NULL),
Logan Chienf7ad17e2012-03-15 03:10:03 +0800788 top_shadow_frame_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700789 jni_env_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700790 state_(Thread::kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700791 self_(NULL),
792 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700793 exception_(NULL),
794 suspend_count_(0),
Elliott Hughes234ab152011-10-26 14:02:26 -0700795 debug_suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700796 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700797 long_jump_context_(NULL),
Elliott Hughes726079d2011-10-07 18:43:44 -0700798 throwing_OutOfMemoryError_(false),
Elliott Hughes475fc232011-10-25 15:00:35 -0700799 pre_allocated_OutOfMemoryError_(NULL),
jeffhaoe343b762011-12-05 16:36:44 -0800800 debug_invoke_req_(new DebugInvokeReq),
Elliott Hughes899e7892012-01-24 14:57:32 -0800801 trace_stack_(new std::vector<TraceStackFrame>),
802 name_(new std::string("<native thread without managed peer>")) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700803 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800804 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700805}
806
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700807static void MonitorExitVisitor(const Object* object, void*) {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700808 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700809 LOG(WARNING) << "Calling MonitorExit on object " << object << " (" << PrettyTypeOf(object) << ")"
810 << " left locked by native thread " << *Thread::Current() << " which is detaching";
Elliott Hughes5f791332011-09-15 17:45:30 -0700811 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700812}
813
Elliott Hughesc0f09332012-03-26 13:27:06 -0700814void Thread::Destroy() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700815 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700816 if (jni_env_ != NULL) {
817 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
818 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700819
Elliott Hughes93e74e82011-09-13 11:07:03 -0700820 if (peer_ != NULL) {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700821 Thread* self = this;
Elliott Hughes29f27422011-09-18 16:02:18 -0700822
Elliott Hughes534da072012-03-27 15:17:42 -0700823 // We may need to call user-supplied managed code.
824 SetState(Thread::kRunnable);
825
826 HandleUncaughtExceptions();
827 RemoveFromThreadGroup();
828
Elliott Hughes29f27422011-09-18 16:02:18 -0700829 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700830 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700831
Elliott Hughesc0f09332012-03-26 13:27:06 -0700832 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700833
Elliott Hughes29f27422011-09-18 16:02:18 -0700834 // Thread.join() is implemented as an Object.wait() on the Thread.lock
835 // object. Signal anyone who is waiting.
Elliott Hughes038a8062011-09-18 14:12:41 -0700836 Object* lock = gThread_lock->GetObject(peer_);
837 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700838 if (lock != NULL) {
839 lock->MonitorEnter(self);
840 lock->NotifyAll();
841 lock->MonitorExit(self);
842 }
843 }
Elliott Hughesc0f09332012-03-26 13:27:06 -0700844}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700845
Elliott Hughesc0f09332012-03-26 13:27:06 -0700846Thread::~Thread() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700847 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700848 jni_env_ = NULL;
849
850 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700851
852 delete wait_cond_;
853 delete wait_mutex_;
854
855 delete long_jump_context_;
Elliott Hughes475fc232011-10-25 15:00:35 -0700856
857 delete debug_invoke_req_;
jeffhaoe343b762011-12-05 16:36:44 -0800858 delete trace_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -0800859 delete name_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700860}
861
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700862void Thread::HandleUncaughtExceptions() {
863 if (!IsExceptionPending()) {
864 return;
865 }
866
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700867 // Get and clear the exception.
868 Object* exception = GetException();
869 ClearException();
870
871 // If the thread has its own handler, use that.
872 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
873 if (handler == NULL) {
874 // Otherwise use the thread group's default handler.
Elliott Hughesa2155262011-11-16 16:26:58 -0800875 handler = GetThreadGroup();
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700876 }
877
878 // Call the handler.
879 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
Elliott Hughes77405792012-03-15 15:22:12 -0700880 JValue args[2];
881 args[0].l = peer_;
882 args[1].l = exception;
883 m->Invoke(this, handler, args, NULL);
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700884
885 // If the handler threw, clear that exception too.
886 ClearException();
887}
888
Elliott Hughesa2155262011-11-16 16:26:58 -0800889Object* Thread::GetThreadGroup() const {
890 return gThread_group->GetObject(peer_);
891}
892
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700893void Thread::RemoveFromThreadGroup() {
894 // this.group.removeThread(this);
895 // group can be null if we're in the compiler or a test.
Elliott Hughesa2155262011-11-16 16:26:58 -0800896 Object* group = GetThreadGroup();
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700897 if (group != NULL) {
898 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
Elliott Hughes77405792012-03-15 15:22:12 -0700899 JValue args[1];
900 args[0].l = peer_;
901 m->Invoke(this, group, args, NULL);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700902 }
903}
904
Ian Rogers408f79a2011-08-23 18:22:33 -0700905size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700906 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700907 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700908 count += cur->NumberOfReferences();
909 }
910 return count;
911}
912
TDYa12728f1a142012-03-15 21:51:52 -0700913size_t Thread::NumShadowFrameReferences() {
914 size_t count = 0;
915 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
916 count += cur->NumberOfReferences();
917 }
918 return count;
919}
920
Ian Rogers408f79a2011-08-23 18:22:33 -0700921bool Thread::SirtContains(jobject obj) {
922 Object** sirt_entry = reinterpret_cast<Object**>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700923 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
924 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700925 return true;
926 }
927 }
928 return false;
929}
930
TDYa12728f1a142012-03-15 21:51:52 -0700931bool Thread::ShadowFrameContains(jobject obj) {
932 Object** shadow_frame_entry = reinterpret_cast<Object**>(obj);
933 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
934 if (cur->Contains(shadow_frame_entry)) {
935 return true;
936 }
937 }
938 return false;
939}
940
941bool Thread::StackReferencesContain(jobject obj) {
942 return SirtContains(obj) || ShadowFrameContains(obj);
943}
944
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700945void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700946 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700947 size_t num_refs = cur->NumberOfReferences();
948 for (size_t j = 0; j < num_refs; j++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700949 Object* object = cur->GetReference(j);
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -0700950 if (object != NULL) {
951 visitor(object, arg);
952 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700953 }
954 }
955}
956
Logan Chienf7ad17e2012-03-15 03:10:03 +0800957void Thread::ShadowFrameVisitRoots(Heap::RootVisitor* visitor, void* arg) {
958 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
959 size_t num_refs = cur->NumberOfReferences();
960 for (size_t j = 0; j < num_refs; j++) {
961 Object* object = cur->GetReference(j);
962 if (object != NULL) {
963 visitor(object, arg);
964 }
965 }
966 }
967}
968
Ian Rogers408f79a2011-08-23 18:22:33 -0700969Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700970 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700971 if (obj == NULL) {
972 return NULL;
973 }
974 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
975 IndirectRefKind kind = GetIndirectRefKind(ref);
976 Object* result;
977 switch (kind) {
978 case kLocal:
979 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700980 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700981 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700982 break;
983 }
984 case kGlobal:
985 {
986 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
987 IndirectReferenceTable& globals = vm->globals;
988 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700989 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700990 break;
991 }
992 case kWeakGlobal:
993 {
994 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
995 IndirectReferenceTable& weak_globals = vm->weak_globals;
996 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700997 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700998 if (result == kClearedJniWeakGlobal) {
999 // This is a special case where it's okay to return NULL.
1000 return NULL;
1001 }
1002 break;
1003 }
1004 case kSirtOrInvalid:
1005 default:
1006 // TODO: make stack indirect reference table lookup more efficient
1007 // Check if this is a local reference in the SIRT
TDYa12728f1a142012-03-15 21:51:52 -07001008 if (StackReferencesContain(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001009 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc2dc62d2012-01-17 20:06:12 -08001010 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001011 // Assume an invalid local reference is actually a direct pointer.
1012 result = reinterpret_cast<Object*>(obj);
1013 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001014 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001015 }
1016 }
1017
1018 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001019 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1020 JniAbort(NULL);
1021 } else {
1022 if (result != kInvalidIndirectRefObject) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001023 Runtime::Current()->GetHeap()->VerifyObject(result);
Elliott Hughesa2501992011-08-26 19:39:54 -07001024 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001025 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001026 return result;
1027}
1028
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001029class CountStackDepthVisitor : public Thread::StackVisitor {
1030 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001031 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001032
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001033 bool VisitFrame(const Frame& frame, uintptr_t /*pc*/) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001034 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001035 // Note we also skip the frame if it doesn't have a method (namely the callee
1036 // save frame)
Ian Rogers5167c972012-02-03 10:41:20 -08001037 if (skipping_ && frame.HasMethod() &&
1038 !Throwable::GetJavaLangThrowable()->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001039 skipping_ = false;
1040 }
1041 if (!skipping_) {
Ian Rogers6b0870d2011-12-15 19:38:12 -08001042 if (frame.HasMethod()) { // ignore callee save frames
1043 ++depth_;
1044 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001045 } else {
1046 ++skip_depth_;
1047 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001048 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001049 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001050
1051 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001052 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001053 }
1054
Elliott Hughes29f27422011-09-18 16:02:18 -07001055 int GetSkipDepth() const {
1056 return skip_depth_;
1057 }
1058
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001059 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001060 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001061 uint32_t skip_depth_;
1062 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001063};
1064
Ian Rogersaaa20802011-09-11 21:47:37 -07001065class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001066 public:
Ian Rogers283ed0d2012-02-16 15:25:09 -08001067 explicit BuildInternalStackTraceVisitor(int skip_depth)
Elliott Hughes726079d2011-10-07 18:43:44 -07001068 : skip_depth_(skip_depth), count_(0), pc_trace_(NULL), method_trace_(NULL), local_ref_(NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001069 }
1070
1071 bool Init(int depth, ScopedJniThreadState& ts) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001072 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001073 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Elliott Hughes726079d2011-10-07 18:43:44 -07001074 if (method_trace_ == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001075 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001076 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001077 // Register a local reference as IntArray::Alloc may trigger GC
1078 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1079 pc_trace_ = IntArray::Alloc(depth);
Elliott Hughes726079d2011-10-07 18:43:44 -07001080 if (pc_trace_ == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001081 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001082 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001083#ifdef MOVING_GARBAGE_COLLECTOR
1084 // Re-read after potential GC
Brian Carlstrom26736442012-02-16 18:24:26 -08001085 method_trace_ = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
Ian Rogersaaa20802011-09-11 21:47:37 -07001086#endif
1087 // Save PC trace in last element of method trace, also places it into the
1088 // object graph.
1089 method_trace_->Set(depth, pc_trace_);
Ian Rogers283ed0d2012-02-16 15:25:09 -08001090 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001091 }
1092
Ian Rogersaaa20802011-09-11 21:47:37 -07001093 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001094
Elliott Hughes530fa002012-03-12 11:44:49 -07001095 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes726079d2011-10-07 18:43:44 -07001096 if (method_trace_ == NULL || pc_trace_ == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001097 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001098 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001099 if (skip_depth_ > 0) {
1100 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001101 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001102 }
Ian Rogers6b0870d2011-12-15 19:38:12 -08001103 if (!frame.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001104 return true; // ignore callee save frames
Ian Rogers6b0870d2011-12-15 19:38:12 -08001105 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001106 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001107 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001108 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001109 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001110 }
1111
Ian Rogersaaa20802011-09-11 21:47:37 -07001112 jobject GetInternalStackTrace() const {
1113 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001114 }
1115
1116 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001117 // How many more frames to skip.
1118 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001119 // Current position down stack trace
1120 uint32_t count_;
1121 // Array of return PC values
1122 IntArray* pc_trace_;
1123 // An array of the methods on the stack, the last entry is a reference to the
1124 // PC trace
1125 ObjectArray<Object>* method_trace_;
1126 // Local indirect reference table entry for method trace
1127 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001128};
1129
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001130// TODO: remove this.
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001131static uintptr_t ManglePc(uintptr_t pc) {
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001132 // Move the PC back 2 bytes as a call will frequently terminate the
1133 // decoding of a particular instruction and we want to make sure we
1134 // get the Dex PC of the instruction with the call and not the
1135 // instruction following.
1136 if (pc > 0) { pc -= 2; }
1137 return pc;
1138}
1139
1140// TODO: remove this.
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001141static uintptr_t DemanglePc(uintptr_t pc) {
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001142 // Revert mangling for the case where we need the PC to return to the upcall
Ian Rogers9a8a8882012-03-08 02:30:55 -08001143 if (pc > 0) { pc += 2; }
1144 return pc;
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001145}
Ian Rogersf57c47c2011-10-06 00:06:17 -07001146
Logan Chienf7ad17e2012-03-15 03:10:03 +08001147void Thread::PushShadowFrame(ShadowFrame* frame) {
1148 frame->SetLink(top_shadow_frame_);
1149 top_shadow_frame_ = frame;
1150}
1151
1152ShadowFrame* Thread::PopShadowFrame() {
1153 CHECK(top_shadow_frame_ != NULL);
1154 ShadowFrame* frame = top_shadow_frame_;
1155 top_shadow_frame_ = frame->GetLink();
1156 return frame;
1157}
1158
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001159void Thread::PushSirt(StackIndirectReferenceTable* sirt) {
1160 sirt->SetLink(top_sirt_);
1161 top_sirt_ = sirt;
1162}
1163
1164StackIndirectReferenceTable* Thread::PopSirt() {
1165 CHECK(top_sirt_ != NULL);
1166 StackIndirectReferenceTable* sirt = top_sirt_;
1167 top_sirt_ = top_sirt_->GetLink();
1168 return sirt;
1169}
1170
TDYa1279b2ba2e2012-03-19 10:12:32 -07001171#if !defined(ART_USE_LLVM_COMPILER) // LLVM use ShadowFrame
1172
Elliott Hughes530fa002012-03-12 11:44:49 -07001173void Thread::WalkStack(StackVisitor* visitor, bool include_upcalls) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001174 Frame frame = GetTopOfStack();
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001175 uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001176 uint32_t trace_stack_depth = 0;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001177 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1178 // CHECK(native_to_managed_record_ != NULL);
1179 NativeToManagedRecord* record = native_to_managed_record_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001180 bool method_tracing_active = Runtime::Current()->IsMethodTracingActive();
Elliott Hughes530fa002012-03-12 11:44:49 -07001181 while (frame.GetSP() != NULL) {
1182 for ( ; frame.GetMethod() != NULL; frame.Next()) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07001183 frame.GetMethod()->AssertPcIsWithinCode(pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001184 bool should_continue = visitor->VisitFrame(frame, pc);
Ian Rogers57b86d42012-03-27 16:05:41 -07001185 if (UNLIKELY(!should_continue)) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001186 return;
1187 }
Ian Rogers57b86d42012-03-27 16:05:41 -07001188 uintptr_t return_pc = frame.GetReturnPC();
1189 if (LIKELY(!method_tracing_active)) {
1190 pc = ManglePc(return_pc);
1191 } else {
jeffhao0791adc2012-04-04 11:14:32 -07001192 // While profiling, the return pc is restored from the side stack, except when walking
1193 // the stack for an exception where the side stack will be unwound in VisitFrame.
1194 if (IsTraceExitPc(return_pc) && !include_upcalls) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001195 TraceStackFrame trace_frame = GetTraceStackFrame(trace_stack_depth++);
jeffhao26c0a1a2012-01-17 16:28:33 -08001196 CHECK(trace_frame.method_ == frame.GetMethod());
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001197 pc = ManglePc(trace_frame.return_pc_);
Ian Rogers57b86d42012-03-27 16:05:41 -07001198 } else {
1199 pc = ManglePc(return_pc);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001200 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001201 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001202 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001203 if (include_upcalls) {
1204 bool should_continue = visitor->VisitFrame(frame, pc);
1205 if (!should_continue) {
1206 return;
1207 }
1208 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001209 if (record == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001210 return;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001211 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001212 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001213 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001214 pc = ManglePc(record->last_top_of_managed_stack_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001215 record = record->link_;
1216 }
1217}
1218
TDYa1279b2ba2e2012-03-19 10:12:32 -07001219#else // defined(ART_USE_LLVM_COMPILER) // LLVM uses ShadowFrame
1220
1221void Thread::WalkStack(StackVisitor* visitor, bool /*include_upcalls*/) const {
1222 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
1223 Frame frame;
1224 frame.SetSP(reinterpret_cast<Method**>(reinterpret_cast<byte*>(cur) +
1225 ShadowFrame::MethodOffset()));
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001226 bool should_continue = visitor->VisitFrame(frame, cur->GetLineNumber());
TDYa1279b2ba2e2012-03-19 10:12:32 -07001227 if (!should_continue) {
1228 return;
1229 }
1230 }
1231}
1232
1233/*
1234 * | |
1235 * | |
1236 * | |
1237 * | . |
1238 * | . |
1239 * | . |
1240 * | . |
1241 * | Method* |
1242 * | . |
1243 * | . | <-- top_shadow_frame_ (ShadowFrame*)
1244 * / +------------------------+
1245 * ->| . |
1246 * . | . |
1247 * . | . |
1248 * /+------------------------+
1249 * / | . |
1250 * / | . |
1251 * --- | | . |
1252 * | | | . |
1253 * | | Method* | <-- frame.GetSP() (Method**)
1254 * ShadowFrame \ | . |
1255 * | ->| . | <-- cur (ShadowFrame*)
1256 * --- /+------------------------+
1257 * / | . |
1258 * / | . |
1259 * --- | | . |
1260 * | cur->GetLink() | | . |
1261 * | | Method* |
1262 * ShadowFrame \ | . |
1263 * | ->| . |
1264 * --- +------------------------+
1265 * | . |
1266 * | . |
1267 * | . |
1268 * +========================+
1269 */
1270
1271#endif
1272
Elliott Hughes01158d72011-09-19 19:47:10 -07001273jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001274 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001275 CountStackDepthVisitor count_visitor;
1276 WalkStack(&count_visitor);
1277 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001278 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001279
Ian Rogersaaa20802011-09-11 21:47:37 -07001280 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001281 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001282
1283 // Build internal stack trace
Ian Rogers77f74c12012-02-16 22:35:30 -08001284 BuildInternalStackTraceVisitor build_trace_visitor(skip_depth);
1285 if (!build_trace_visitor.Init(depth, ts)) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001286 return NULL; // Allocation failed
Ian Rogers283ed0d2012-02-16 15:25:09 -08001287 }
Brian Carlstrom26736442012-02-16 18:24:26 -08001288 WalkStack(&build_trace_visitor);
1289 return build_trace_visitor.GetInternalStackTrace();
Ian Rogersaaa20802011-09-11 21:47:37 -07001290}
1291
Elliott Hughes01158d72011-09-19 19:47:10 -07001292jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1293 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001294 // Transition into runnable state to work on Object*/Array*
1295 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001296 // Decode the internal stack trace into the depth, method trace and PC trace
1297 ObjectArray<Object>* method_trace =
1298 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
Ian Rogers9074b992011-10-26 17:41:55 -07001299 int32_t depth = method_trace->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001300 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1301
1302 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1303
Elliott Hughes01158d72011-09-19 19:47:10 -07001304 jobjectArray result;
1305 ObjectArray<StackTraceElement>* java_traces;
1306 if (output_array != NULL) {
1307 // Reuse the array we were given.
1308 result = output_array;
1309 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1310 output_array));
1311 // ...adjusting the number of frames we'll write to not exceed the array length.
1312 depth = std::min(depth, java_traces->GetLength());
1313 } else {
1314 // Create java_trace array and place in local reference table
1315 java_traces = class_linker->AllocStackTraceElementArray(depth);
Elliott Hughes30646832011-10-13 16:59:46 -07001316 if (java_traces == NULL) {
1317 return NULL;
1318 }
Elliott Hughes01158d72011-09-19 19:47:10 -07001319 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1320 }
1321
1322 if (stack_depth != NULL) {
1323 *stack_depth = depth;
1324 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001325
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001326 MethodHelper mh;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001327 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001328 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1329 Method* method = down_cast<Method*>(method_trace->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001330 mh.ChangeMethod(method);
Ian Rogersaaa20802011-09-11 21:47:37 -07001331 uint32_t native_pc = pc_trace->Get(i);
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001332#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001333 int32_t line_number = mh.GetLineNumFromNativePC(native_pc);
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001334#else
1335 int32_t line_number = native_pc; // LLVM stored line_number in the ShadowFrame
1336#endif
Ian Rogersaaa20802011-09-11 21:47:37 -07001337 // Allocate element, potentially triggering GC
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001338 // TODO: reuse class_name_object via Class::name_?
Ian Rogers48601312011-12-07 16:45:19 -08001339 const char* descriptor = mh.GetDeclaringClassDescriptor();
1340 CHECK(descriptor != NULL);
1341 std::string class_name(PrettyDescriptor(descriptor));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001342 SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
1343 if (class_name_object.get() == NULL) {
1344 return NULL;
1345 }
Ian Rogers48601312011-12-07 16:45:19 -08001346 const char* method_name = mh.GetName();
1347 CHECK(method_name != NULL);
1348 SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001349 if (method_name_object.get() == NULL) {
1350 return NULL;
1351 }
Ian Rogers48601312011-12-07 16:45:19 -08001352 const char* source_file = mh.GetDeclaringClassSourceFile();
1353 SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001354 StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001355 method_name_object.get(),
1356 source_name_object.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001357 line_number);
Elliott Hughes30646832011-10-13 16:59:46 -07001358 if (obj == NULL) {
1359 return NULL;
1360 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001361#ifdef MOVING_GARBAGE_COLLECTOR
1362 // Re-read after potential GC
1363 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1364 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1365 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1366#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001367 java_traces->Set(i, obj);
1368 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001369 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001370}
1371
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001372void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001373 va_list args;
1374 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001375 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001376 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001377}
1378
1379void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1380 std::string msg;
1381 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001382 ThrowNewException(exception_class_descriptor, msg.c_str());
1383}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001384
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001385void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001386 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001387 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001388 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001389 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001390 descriptor.erase(descriptor.length() - 1);
1391
1392 JNIEnv* env = GetJniEnv();
Elliott Hughes726079d2011-10-07 18:43:44 -07001393 ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001394 if (exception_class.get() == NULL) {
1395 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1396 << PrettyTypeOf(GetException());
1397 CHECK(IsExceptionPending());
1398 return;
1399 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001400 if (!Runtime::Current()->IsStarted()) {
1401 // Something is trying to throw an exception without a started
1402 // runtime, which is the common case in the compiler. We won't be
1403 // able to invoke the constructor of the exception, so use
1404 // AllocObject which will not invoke a constructor.
1405 ScopedLocalRef<jthrowable> exception(
1406 env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1407 if (exception.get() != NULL) {
1408 ScopedJniThreadState ts(env);
1409 Throwable* t = reinterpret_cast<Throwable*>(ts.Self()->DecodeJObject(exception.get()));
Ian Rogers02fbef02012-01-31 22:15:33 -08001410 t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001411 ts.Self()->SetException(t);
1412 } else {
1413 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1414 << PrettyTypeOf(GetException());
1415 CHECK(IsExceptionPending());
1416 }
1417 return;
1418 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001419 int rc = env->ThrowNew(exception_class.get(), msg);
Elliott Hughes30646832011-10-13 16:59:46 -07001420 if (rc != JNI_OK) {
1421 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1422 << PrettyTypeOf(GetException());
1423 CHECK(IsExceptionPending());
Elliott Hughes30646832011-10-13 16:59:46 -07001424 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001425}
1426
Elliott Hughes418dfe72011-10-06 18:56:27 -07001427void Thread::ThrowOutOfMemoryError(Class* c, size_t byte_count) {
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001428 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s", byte_count,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001429 PrettyDescriptor(c).c_str()));
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001430 ThrowOutOfMemoryError(msg.c_str());
1431}
1432
1433void Thread::ThrowOutOfMemoryError(const char* msg) {
1434 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1435 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Elliott Hughes726079d2011-10-07 18:43:44 -07001436 if (!throwing_OutOfMemoryError_) {
1437 throwing_OutOfMemoryError_ = true;
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001438 ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001439 } else {
Elliott Hughes726079d2011-10-07 18:43:44 -07001440 SetException(pre_allocated_OutOfMemoryError_);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001441 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001442 throwing_OutOfMemoryError_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001443}
1444
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001445
Elliott Hughes498508c2011-10-17 14:58:22 -07001446Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001447 return Thread::Current();
1448}
1449
1450void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001451 std::ostringstream ss;
1452 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001453 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001454 // log to stderr for debugging command line processes
1455 std::cerr << str;
1456#ifdef HAVE_ANDROID_OS
1457 // log to logcat for debugging frameworks processes
1458 LOG(INFO) << str;
1459#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001460}
1461
Ian Rogersbdb03912011-09-14 00:55:44 -07001462class CatchBlockStackVisitor : public Thread::StackVisitor {
1463 public:
1464 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers57b86d42012-03-27 16:05:41 -07001465 : to_find_(to_find), long_jump_context_(ljc), native_method_count_(0),
1466 method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001467#ifndef NDEBUG
1468 handler_pc_ = 0xEBADC0DE;
1469 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1470#endif
1471 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001472
Elliott Hughes530fa002012-03-12 11:44:49 -07001473 bool VisitFrame(const Frame& fr, uintptr_t pc) {
1474 Method* method = fr.GetMethod();
1475 if (method == NULL) {
1476 // This is the upcall, we remember the frame and last_pc so that we may
1477 // long jump to them
1478 handler_pc_ = DemanglePc(pc);
1479 handler_frame_ = fr;
Ian Rogers57b86d42012-03-27 16:05:41 -07001480 return false; // End stack walk.
Elliott Hughes530fa002012-03-12 11:44:49 -07001481 }
1482 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers57b86d42012-03-27 16:05:41 -07001483 if (method->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001484 // ignore callee save method
Ian Rogers57b86d42012-03-27 16:05:41 -07001485 DCHECK(method->IsCalleeSaveMethod());
Elliott Hughes530fa002012-03-12 11:44:49 -07001486 } else if (method->IsNative()) {
1487 native_method_count_++;
1488 } else {
jeffhao0791adc2012-04-04 11:14:32 -07001489 // Unwind stack when an exception occurs during method tracing
Ian Rogers57b86d42012-03-27 16:05:41 -07001490 if (UNLIKELY(method_tracing_active_)) {
1491 if (IsTraceExitPc(DemanglePc(pc))) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001492 pc = ManglePc(TraceMethodUnwindFromCode(Thread::Current()));
1493 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001494 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001495 dex_pc = method->ToDexPC(pc);
1496 }
1497 if (dex_pc != DexFile::kDexNoIndex) {
1498 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1499 if (found_dex_pc != DexFile::kDexNoIndex) {
1500 handler_pc_ = method->ToNativePC(found_dex_pc);
1501 handler_frame_ = fr;
Ian Rogers57b86d42012-03-27 16:05:41 -07001502 return false; // End stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001503 }
1504 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001505 // Caller may be handler, fill in callee saves in context
1506 long_jump_context_->FillCalleeSaves(fr);
Ian Rogers57b86d42012-03-27 16:05:41 -07001507 return true; // Continue stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001508 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001509
Ian Rogersbdb03912011-09-14 00:55:44 -07001510 // The type of the exception catch block to find
1511 Class* to_find_;
1512 // Frame with found handler or last frame if no handler found
1513 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001514 // PC to branch to for the handler
1515 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001516 // Context that will be the target of the long jump
1517 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001518 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1519 uint32_t native_method_count_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001520 // Is method tracing active?
1521 const bool method_tracing_active_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001522};
1523
Ian Rogersff1ed472011-09-20 13:46:24 -07001524void Thread::DeliverException() {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001525 const bool kDebugExceptionDelivery = false;
Elliott Hughesd07986f2011-12-06 18:27:45 -08001526 Throwable* exception = GetException(); // Get exception from thread
Ian Rogersff1ed472011-09-20 13:46:24 -07001527 CHECK(exception != NULL);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001528 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001529 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001530 ClearException();
1531 if (kDebugExceptionDelivery) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001532 String* msg = exception->GetDetailMessage();
1533 std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1534 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
1535 << ": " << str_msg << std::endl);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001536 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001537
1538 Context* long_jump_context = GetLongJumpContext();
1539 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Elliott Hughes530fa002012-03-12 11:44:49 -07001540 WalkStack(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001541
Elliott Hughesd07986f2011-12-06 18:27:45 -08001542 Method** sp;
1543 uintptr_t throw_native_pc;
1544 Method* throw_method = GetCurrentMethod(&throw_native_pc, &sp);
1545 uintptr_t catch_native_pc = catch_finder.handler_pc_;
1546 Method* catch_method = catch_finder.handler_frame_.GetMethod();
1547 Dbg::PostException(sp, throw_method, throw_native_pc, catch_method, catch_native_pc, exception);
1548
Ian Rogers28ad40d2011-10-27 15:19:26 -07001549 if (kDebugExceptionDelivery) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001550 if (catch_method == NULL) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001551 LOG(INFO) << "Handler is upcall";
1552 } else {
1553 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1554 const DexFile& dex_file =
Elliott Hughesd07986f2011-12-06 18:27:45 -08001555 class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1556 int line_number = dex_file.GetLineNumFromPC(catch_method,
1557 catch_method->ToDexPC(catch_finder.handler_pc_));
1558 LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
Ian Rogers28ad40d2011-10-27 15:19:26 -07001559 }
1560 }
1561 SetException(exception);
Ian Rogers9a8a8882012-03-08 02:30:55 -08001562 CHECK_NE(catch_native_pc, 0u);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001563 long_jump_context->SetSP(reinterpret_cast<uintptr_t>(catch_finder.handler_frame_.GetSP()));
Ian Rogers9a8a8882012-03-08 02:30:55 -08001564 long_jump_context->SetPC(catch_native_pc);
Ian Rogersbdb03912011-09-14 00:55:44 -07001565 long_jump_context->DoLongJump();
Ian Rogers9a8a8882012-03-08 02:30:55 -08001566 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001567}
1568
Ian Rogersbdb03912011-09-14 00:55:44 -07001569Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001570 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001571 if (result == NULL) {
1572 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001573 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001574 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001575 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001576}
1577
TDYa127ee0d3fb2012-04-01 14:55:33 -07001578#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughesd07986f2011-12-06 18:27:45 -08001579Method* Thread::GetCurrentMethod(uintptr_t* pc, Method*** sp) const {
1580 Frame f = top_of_managed_stack_;
1581 Method* m = f.GetMethod();
Elliott Hughes8be2d402012-02-23 14:22:41 -08001582 uintptr_t native_pc = top_of_managed_stack_pc_;
1583
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001584 // We use JNI internally for exception throwing, so it's possible to arrive
1585 // here via a "FromCode" function, in which case there's a synthetic
1586 // callee-save method at the top of the stack. These shouldn't be user-visible,
1587 // so if we find one, skip it and return the compiled method underneath.
jeffhao33dc7712011-11-09 17:54:24 -08001588 if (m != NULL && m->IsCalleeSaveMethod()) {
Elliott Hughes8be2d402012-02-23 14:22:41 -08001589 native_pc = f.GetReturnPC();
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001590 f.Next();
1591 m = f.GetMethod();
1592 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001593 if (pc != NULL) {
Elliott Hughes8be2d402012-02-23 14:22:41 -08001594 *pc = (m != NULL) ? ManglePc(native_pc) : 0;
jeffhao33dc7712011-11-09 17:54:24 -08001595 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001596 if (sp != NULL) {
1597 *sp = f.GetSP();
1598 }
1599 return m;
jeffhao33dc7712011-11-09 17:54:24 -08001600}
TDYa127ee0d3fb2012-04-01 14:55:33 -07001601#else
1602Method* Thread::GetCurrentMethod(uintptr_t*, Method***) const {
1603 ShadowFrame* frame = top_shadow_frame_;
TDYa12720efe542012-04-03 17:40:49 -07001604 if (frame == NULL) {
1605 return NULL;
TDYa127ee0d3fb2012-04-01 14:55:33 -07001606 }
1607 return frame->GetMethod();
1608}
1609#endif
jeffhao33dc7712011-11-09 17:54:24 -08001610
Elliott Hughes5f791332011-09-15 17:45:30 -07001611bool Thread::HoldsLock(Object* object) {
1612 if (object == NULL) {
1613 return false;
1614 }
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07001615 return object->GetThinLockId() == thin_lock_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001616}
1617
Elliott Hughes038a8062011-09-18 14:12:41 -07001618bool Thread::IsDaemon() {
1619 return gThread_daemon->GetBoolean(peer_);
1620}
1621
Ian Rogersd6b1f612011-09-27 13:38:14 -07001622class ReferenceMapVisitor : public Thread::StackVisitor {
1623 public:
1624 ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1625 context_(context), root_visitor_(root_visitor), arg_(arg) {
1626 }
1627
Elliott Hughes530fa002012-03-12 11:44:49 -07001628 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001629 Method* m = frame.GetMethod();
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001630 if (false) {
jeffhao25045522012-03-13 19:34:37 -07001631 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m)
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001632 << StringPrintf("@ PC:%04x", m->ToDexPC(pc));
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001633 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001634 // Process register map (which native and callee save methods don't have)
Ian Rogers3891c772011-12-06 15:38:28 -08001635 if (!m->IsNative() && !m->IsCalleeSaveMethod() && !m->IsProxyMethod()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001636 CHECK(m->GetGcMap() != NULL) << PrettyMethod(m);
1637 CHECK_NE(0U, m->GetGcMapLength()) << PrettyMethod(m);
1638 verifier::PcToReferenceMap map(m->GetGcMap(), m->GetGcMapLength());
Ian Rogersd81871c2011-10-03 13:57:23 -07001639 const uint8_t* reg_bitmap = map.FindBitMap(m->ToDexPC(pc));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001640 CHECK(reg_bitmap != NULL);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001641 const VmapTable vmap_table(m->GetVmapTableRaw());
Elliott Hughes11d1b0c2012-01-23 16:57:47 -08001642 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001643 DCHECK(code_item != NULL); // can't be NULL or how would we compile its instructions?
1644 uint32_t core_spills = m->GetCoreSpillMask();
1645 uint32_t fp_spills = m->GetFpSpillMask();
1646 size_t frame_size = m->GetFrameSizeInBytes();
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001647 // For all dex registers in the bitmap
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001648 size_t num_regs = std::min(map.RegWidth() * 8,
1649 static_cast<size_t>(code_item->registers_size_));
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001650 for (size_t reg = 0; reg < num_regs; ++reg) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001651 // Does this register hold a reference?
1652 if (TestBitmap(reg, reg_bitmap)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001653 uint32_t vmap_offset;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001654 Object* ref;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001655 if (vmap_table.IsInContext(reg, vmap_offset)) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001656 // Compute the register we need to load from the context
1657 uint32_t spill_mask = m->GetCoreSpillMask();
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001658 CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
Ian Rogersf57c47c2011-10-06 00:06:17 -07001659 uint32_t matches = 0;
1660 uint32_t spill_shifts = 0;
1661 while (matches != (vmap_offset + 1)) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001662 DCHECK_NE(spill_mask, 0u);
Ian Rogersf57c47c2011-10-06 00:06:17 -07001663 matches += spill_mask & 1; // Add 1 if the low bit is set
1664 spill_mask >>= 1;
1665 spill_shifts++;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001666 }
Ian Rogersf57c47c2011-10-06 00:06:17 -07001667 spill_shifts--; // wind back one as we want the last match
1668 ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001669 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001670 ref = reinterpret_cast<Object*>(frame.GetVReg(code_item, core_spills, fp_spills,
1671 frame_size, reg));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001672 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001673 if (ref != NULL) {
1674 root_visitor_(ref, arg_);
1675 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001676 }
1677 }
1678 }
1679 context_->FillCalleeSaves(frame);
Elliott Hughes530fa002012-03-12 11:44:49 -07001680 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001681 }
1682
1683 private:
1684 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1685 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1686 }
1687
1688 // Context used to build up picture of callee saves
1689 Context* context_;
1690 // Call-back when we visit a root
1691 Heap::RootVisitor* root_visitor_;
1692 // Argument to call-back
1693 void* arg_;
1694};
1695
1696void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001697 if (exception_ != NULL) {
1698 visitor(exception_, arg);
1699 }
1700 if (peer_ != NULL) {
1701 visitor(peer_, arg);
1702 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001703 if (pre_allocated_OutOfMemoryError_ != NULL) {
1704 visitor(pre_allocated_OutOfMemoryError_, arg);
1705 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001706 if (class_loader_override_ != NULL) {
1707 visitor(class_loader_override_, arg);
1708 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001709 jni_env_->locals.VisitRoots(visitor, arg);
1710 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001711
1712 SirtVisitRoots(visitor, arg);
Logan Chienf7ad17e2012-03-15 03:10:03 +08001713 ShadowFrameVisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001714
TDYa127540a5b72012-04-03 18:56:08 -07001715#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersd6b1f612011-09-27 13:38:14 -07001716 // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1717 // delivery.
1718 Context* context = GetLongJumpContext();
1719 // Visit roots on this thread's stack
1720 ReferenceMapVisitor mapper(context, visitor, arg);
1721 WalkStack(&mapper);
TDYa127540a5b72012-04-03 18:56:08 -07001722#endif
Elliott Hughes410c0c82011-09-01 17:58:25 -07001723}
1724
jeffhao25045522012-03-13 19:34:37 -07001725#if VERIFY_OBJECT_ENABLED
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001726static void VerifyObject(const Object* obj, void*) {
jeffhao25045522012-03-13 19:34:37 -07001727 Runtime::Current()->GetHeap()->VerifyObject(obj);
1728}
1729
1730void Thread::VerifyStack() {
TDYa127540a5b72012-04-03 18:56:08 -07001731#if !defined(ART_USE_LLVM_COMPILER)
jeffhaoe66ac792012-03-19 16:08:46 -07001732 UniquePtr<Context> context(Context::Create());
1733 ReferenceMapVisitor mapper(context.get(), VerifyObject, NULL);
jeffhao25045522012-03-13 19:34:37 -07001734 WalkStack(&mapper);
TDYa127540a5b72012-04-03 18:56:08 -07001735#endif
jeffhao25045522012-03-13 19:34:37 -07001736}
1737#endif
1738
Ian Rogersb033c752011-07-20 12:22:35 -07001739static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001740 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001741 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001742 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001743 "Blocked",
1744 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001745 "Initializing",
1746 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001747 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001748 "VmWait",
1749 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001750};
1751std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001752 int32_t int_state = static_cast<int32_t>(state);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001753 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1754 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001755 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001756 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001757 }
1758 return os;
1759}
1760
Elliott Hughes330304d2011-08-12 14:28:05 -07001761std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Elliott Hughes899e7892012-01-24 14:57:32 -08001762 thread.Dump(os, false);
Elliott Hughes330304d2011-08-12 14:28:05 -07001763 return os;
1764}
1765
Elliott Hughesa4060e52012-03-02 16:51:35 -08001766void Thread::CheckSafeToLockOrUnlock(MutexRank rank, bool is_locking) {
Elliott Hughes17057b12012-04-03 10:22:39 -07001767 if (this == NULL) {
1768 CHECK(Runtime::Current()->IsShuttingDown());
1769 return;
1770 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001771 if (is_locking) {
1772 if (held_mutexes_[rank] == 0) {
1773 bool bad_mutexes_held = false;
1774 for (int i = kMaxMutexRank; i > rank; --i) {
1775 if (held_mutexes_[i] != 0) {
1776 LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while " << (is_locking ? "locking" : "unlocking") << " " << rank;
1777 bad_mutexes_held = true;
1778 }
1779 }
Elliott Hughesb5db3bb2012-03-29 20:00:31 -07001780 CHECK(!bad_mutexes_held) << rank;
Elliott Hughesffb465f2012-03-01 18:46:05 -08001781 }
1782 ++held_mutexes_[rank];
1783 } else {
Elliott Hughesb5db3bb2012-03-29 20:00:31 -07001784 CHECK_GT(held_mutexes_[rank], 0U) << rank;
Elliott Hughesffb465f2012-03-01 18:46:05 -08001785 --held_mutexes_[rank];
1786 }
1787}
1788
Elliott Hughesa4060e52012-03-02 16:51:35 -08001789void Thread::CheckSafeToWait(MutexRank rank) {
Elliott Hughes17057b12012-04-03 10:22:39 -07001790 if (this == NULL) {
1791 CHECK(Runtime::Current()->IsShuttingDown());
1792 return;
1793 }
Elliott Hughesa4060e52012-03-02 16:51:35 -08001794 bool bad_mutexes_held = false;
1795 for (int i = kMaxMutexRank; i >= 0; --i) {
1796 if (i != rank && held_mutexes_[i] != 0) {
1797 LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while doing condition variable wait on " << rank;
1798 bad_mutexes_held = true;
1799 }
1800 }
1801 if (held_mutexes_[rank] == 0) {
1802 LOG(ERROR) << "*not* holding " << rank << " while doing condition variable wait on it";
1803 bad_mutexes_held = true;
1804 }
1805 CHECK(!bad_mutexes_held);
1806}
1807
Elliott Hughes8daa0922011-09-11 13:46:25 -07001808} // namespace art