blob: ca8922bc69c0ef71e0e5a611da79921f86bd2b8d [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 Rogers408f79a2011-08-23 18:22:33 -070034#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070035#include "jni_internal.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070036#include "monitor.h"
Ian Rogers57b86d42012-03-27 16:05:41 -070037#include "oat/runtime/context.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070038#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080039#include "object_utils.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -050040#include "reflection.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070041#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070042#include "runtime_support.h"
Elliott Hughes726079d2011-10-07 18:43:44 -070043#include "ScopedLocalRef.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070044#include "scoped_jni_thread_state.h"
Logan Chienf7ad17e2012-03-15 03:10:03 +080045#include "shadow_frame.h"
Ian Rogers30fab402012-01-23 15:43:46 -080046#include "space.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070047#include "stack.h"
48#include "stack_indirect_reference_table.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070049#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070050#include "utils.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070051#include "verifier/gc_map.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
Elliott Hughes3ea0f422012-04-16 17:01:43 -070078static void UnimplementedEntryPoint() {
79 UNIMPLEMENTED(FATAL);
80}
81
buzbee3ea4ec52011-08-22 17:37:19 -070082void Thread::InitFunctionPointers() {
Elliott Hughes3ea0f422012-04-16 17:01:43 -070083 // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
84 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&entrypoints_);
85 uintptr_t* end = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(begin) + sizeof(entrypoints_));
86 for (uintptr_t* it = begin; it != end; ++it) {
87 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
88 }
Ian Rogers57b86d42012-03-27 16:05:41 -070089 InitEntryPoints(&entrypoints_);
Elliott Hughesc0f09332012-03-26 13:27:06 -070090}
91
92void Thread::SetDebuggerUpdatesEnabled(bool enabled) {
93 LOG(INFO) << "Turning debugger updates " << (enabled ? "on" : "off") << " for " << *this;
Ian Rogers776ac1f2012-04-13 23:36:36 -070094#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers57b86d42012-03-27 16:05:41 -070095 ChangeDebuggerEntryPoint(&entrypoints_, enabled);
Ian Rogers776ac1f2012-04-13 23:36:36 -070096#else
97 UNIMPLEMENTED(FATAL);
98#endif
buzbee3ea4ec52011-08-22 17:37:19 -070099}
100
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700101void Thread::InitTid() {
102 tid_ = ::art::GetTid();
103}
104
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700105void Thread::InitAfterFork() {
106 InitTid();
Elliott Hughes3147a232011-10-12 15:55:07 -0700107#if defined(__BIONIC__)
108 // Work around a bionic bug.
109 struct bionic_pthread_internal_t {
110 void* next;
111 void** pref;
112 pthread_attr_t attr;
113 pid_t kernel_id;
114 // et cetera. we just need 'kernel_id' so we can stop here.
115 };
116 reinterpret_cast<bionic_pthread_internal_t*>(pthread_self())->kernel_id = tid_;
117#endif
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700118}
119
Brian Carlstrom78128a62011-09-15 17:21:19 -0700120void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700121 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes462c9442012-03-23 18:47:50 -0700122 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700123
Elliott Hughes93e74e82011-09-13 11:07:03 -0700124 // Wait until it's safe to start running code. (There may have been a suspend-all
125 // in progress while we were starting up.)
Elliott Hughes462c9442012-03-23 18:47:50 -0700126 Runtime* runtime = Runtime::Current();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700127 runtime->GetThreadList()->WaitForGo();
128
Elliott Hughes47179f72011-10-27 16:44:39 -0700129 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700130 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughes899e7892012-01-24 14:57:32 -0800131 SirtRef<String> thread_name(self->GetThreadName());
132 self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
Elliott Hughes47179f72011-10-27 16:44:39 -0700133 }
134
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700135 Dbg::PostThreadStart(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700136
137 // Invoke the 'run' method of our java.lang.Thread.
138 CHECK(self->peer_ != NULL);
139 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700140 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700141 m->Invoke(self, receiver, NULL, NULL);
142
143 // Detach.
144 runtime->GetThreadList()->Unregister();
145
Carl Shapirob5573532011-07-12 18:22:59 -0700146 return NULL;
147}
148
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700149static void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700150 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700151}
152
Elliott Hughes761928d2011-11-16 18:33:03 -0800153Thread* Thread::FromManagedThread(Object* thread_peer) {
154 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread_peer)));
155}
156
Elliott Hughes01158d72011-09-19 19:47:10 -0700157Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
Elliott Hughes761928d2011-11-16 18:33:03 -0800158 return FromManagedThread(Decode<Object*>(env, java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700159}
160
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700161static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700162 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700163 if (stack_size == 0) {
164 stack_size = Runtime::Current()->GetDefaultStackSize();
165 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700166
Brian Carlstrom6414a972012-04-14 14:20:04 -0700167 // Dalvik used the bionic pthread default stack size for native threads,
168 // so include that here to support apps that expect large native stacks.
169 stack_size += 1 * MB;
170
171
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700172 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
173 if (stack_size < PTHREAD_STACK_MIN) {
174 stack_size = PTHREAD_STACK_MIN;
175 }
176
177 // It's likely that callers are trying to ensure they have at least a certain amount of
178 // stack space, so we should add our reserved space on top of what they requested, rather
179 // than implicitly take it away from them.
180 stack_size += Thread::kStackOverflowReservedBytes;
181
182 // Some systems require the stack size to be a multiple of the system page size, so round up.
183 stack_size = RoundUp(stack_size, kPageSize);
184
185 return stack_size;
186}
187
188void Thread::Create(Object* peer, size_t stack_size) {
189 CHECK(peer != NULL);
190
191 stack_size = FixStackSize(stack_size);
192
Elliott Hughes93e74e82011-09-13 11:07:03 -0700193 Thread* native_thread = new Thread;
194 native_thread->peer_ = peer;
195
196 // Thread.start is synchronized, so we know that vmData is 0,
197 // and know that we're not racing to assign it.
198 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700199
Elliott Hughes47179f72011-10-27 16:44:39 -0700200 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700201 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Elliott Hughes47179f72011-10-27 16:44:39 -0700202 pthread_t new_pthread;
203 pthread_attr_t attr;
204 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
205 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
206 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
207 CHECK_PTHREAD_CALL(pthread_create, (&new_pthread, &attr, Thread::CreateCallback, native_thread), "new thread");
208 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
209 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700210
211 // Let the child know when it's safe to start running.
212 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700213}
214
Elliott Hughes462c9442012-03-23 18:47:50 -0700215void Thread::Init() {
216 // This function does all the initialization that must be run by the native thread it applies to.
217 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
218 // we can handshake with the corresponding native thread when it's ready.) Check this native
219 // thread hasn't been through here already...
Elliott Hughescac6cc72011-11-03 20:31:21 -0700220 CHECK(Thread::Current() == NULL);
221
Elliott Hughes93e74e82011-09-13 11:07:03 -0700222 InitCpu();
223 InitFunctionPointers();
Ian Rogers5d76c432011-10-31 21:42:49 -0700224 InitCardTable();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700225
Elliott Hughes462c9442012-03-23 18:47:50 -0700226 Runtime* runtime = Runtime::Current();
227 CHECK(runtime != NULL);
228
229 thin_lock_id_ = runtime->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700230
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700231 InitTid();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700232 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700233
Elliott Hughes3147a232011-10-12 15:55:07 -0700234 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700235
Elliott Hughes93e74e82011-09-13 11:07:03 -0700236 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700237
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700238 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700239}
240
Elliott Hughes462c9442012-03-23 18:47:50 -0700241Thread* Thread::Attach(const char* thread_name, bool as_daemon, Object* thread_group) {
Elliott Hughescac6cc72011-11-03 20:31:21 -0700242 Thread* self = new Thread;
Elliott Hughes462c9442012-03-23 18:47:50 -0700243 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700244
Elliott Hughes34e06962012-04-09 13:55:55 -0700245 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700246
Elliott Hughescac6cc72011-11-03 20:31:21 -0700247 // If we're the main thread, ClassLinker won't be created until after we're attached,
248 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800249 // In the compiler, all threads need this hack, because no-one's going to be getting
250 // a native peer!
251 if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700252 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800253 } else {
254 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Elliott Hughes22869a92012-03-27 14:08:24 -0700255 if (thread_name != NULL) {
256 self->name_->assign(thread_name);
257 ::art::SetThreadName(thread_name);
258 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700259 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700260
261 self->GetJniEnv()->locals.AssertEmpty();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700262 return self;
263}
264
Elliott Hughes462c9442012-03-23 18:47:50 -0700265Object* Thread::GetMainThreadGroup() {
Ian Rogers0045a292012-03-31 21:08:41 -0700266 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(gThreadGroup, true, true)) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700267 return NULL;
268 }
269 return gThreadGroup_mMain->GetObject(NULL);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700270}
271
Elliott Hughes462c9442012-03-23 18:47:50 -0700272Object* Thread::GetSystemThreadGroup() {
Ian Rogers0045a292012-03-31 21:08:41 -0700273 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(gThreadGroup, true, true)) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700274 return NULL;
275 }
276 return gThreadGroup_mSystem->GetObject(NULL);
277}
278
279void Thread::CreatePeer(const char* name, bool as_daemon, Object* thread_group) {
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500280 CHECK(Runtime::Current()->IsStarted());
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700281 JNIEnv* env = jni_env_;
282
Elliott Hughes462c9442012-03-23 18:47:50 -0700283 if (thread_group == NULL) {
284 thread_group = Thread::GetMainThreadGroup();
285 }
286 ScopedLocalRef<jobject> java_thread_group(env, AddLocalReference<jobject>(env, thread_group));
Elliott Hughes726079d2011-10-07 18:43:44 -0700287 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Elliott Hughes8daa0922011-09-11 13:46:25 -0700288 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700289 jboolean thread_is_daemon = as_daemon;
290
Elliott Hughes726079d2011-10-07 18:43:44 -0700291 ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/Thread"));
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700292 ScopedLocalRef<jobject> peer(env, env->AllocObject(c.get()));
Elliott Hughes726079d2011-10-07 18:43:44 -0700293 peer_ = DecodeJObject(peer.get());
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700294 if (peer_ == NULL) {
295 CHECK(IsExceptionPending());
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700296 return;
297 }
298 jmethodID mid = env->GetMethodID(c.get(), "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes462c9442012-03-23 18:47:50 -0700299 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 -0500300 CHECK(!IsExceptionPending()) << " " << PrettyTypeOf(GetException());
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700301 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700302
Elliott Hughes899e7892012-01-24 14:57:32 -0800303 SirtRef<String> peer_thread_name(GetThreadName());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700304 if (peer_thread_name.get() == NULL) {
305 // The Thread constructor should have set the Thread.name to a
306 // non-null value. However, because we can run without code
307 // available (in the compiler, in tests), we manually assign the
308 // fields the constructor should have set.
309 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
Elliott Hughes462c9442012-03-23 18:47:50 -0700310 gThread_group->SetObject(peer_, thread_group);
Brian Carlstrom00fae582011-10-28 01:16:28 -0700311 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name.get()));
312 gThread_priority->SetInt(peer_, thread_priority);
Elliott Hughes899e7892012-01-24 14:57:32 -0800313 peer_thread_name.reset(GetThreadName());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700314 }
315 // thread_name may have been null, so don't trust this to be non-null
316 if (peer_thread_name.get() != NULL) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800317 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700318 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700319
320 // Pre-allocate an OutOfMemoryError for the double-OOME case.
321 ThrowNewException("Ljava/lang/OutOfMemoryError;",
322 "OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available");
323 ScopedLocalRef<jthrowable> exception(env, env->ExceptionOccurred());
324 env->ExceptionClear();
325 pre_allocated_OutOfMemoryError_ = Decode<Throwable*>(env, exception.get());
Carl Shapiro61e019d2011-07-14 16:53:09 -0700326}
327
Elliott Hughes899e7892012-01-24 14:57:32 -0800328void Thread::SetThreadName(const char* name) {
329 name_->assign(name);
330 ::art::SetThreadName(name);
331 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
332}
333
Elliott Hughesbe759c62011-09-08 19:38:21 -0700334void Thread::InitStackHwm() {
Elliott Hughes215f3142012-01-19 00:22:47 -0800335#if defined(__APPLE__)
Elliott Hughes6cc332e2012-01-20 22:59:20 -0800336 // Only needed to run code. Try implementing this with pthread_get_stacksize_np and pthread_get_stackaddr_np.
337 UNIMPLEMENTED(WARNING);
Elliott Hughes215f3142012-01-19 00:22:47 -0800338#else
Elliott Hughesbe759c62011-09-08 19:38:21 -0700339 pthread_attr_t attributes;
Elliott Hughes3147a232011-10-12 15:55:07 -0700340 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700341
Ian Rogers932746a2011-09-22 18:57:50 -0700342 void* temp_stack_base;
343 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
344 __FUNCTION__);
Ian Rogers30fab402012-01-23 15:43:46 -0800345 stack_begin_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700346
Ian Rogers932746a2011-09-22 18:57:50 -0700347 if (stack_size_ <= kStackOverflowReservedBytes) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800348 LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700349 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700350
Ian Rogers932746a2011-09-22 18:57:50 -0700351 // Set stack_end_ to the bottom of the stack saving space of stack overflows
352 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700353
354 // Sanity check.
355 int stack_variable;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700356 CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
Elliott Hughesbe759c62011-09-08 19:38:21 -0700357
Elliott Hughes8d768a92011-09-14 16:35:25 -0700358 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes215f3142012-01-19 00:22:47 -0800359#endif
Elliott Hughesbe759c62011-09-08 19:38:21 -0700360}
361
Elliott Hughes899e7892012-01-24 14:57:32 -0800362void Thread::Dump(std::ostream& os, bool full) const {
363 if (full) {
364 DumpState(os);
365 DumpStack(os);
366 } else {
367 os << "Thread[";
368 if (GetThinLockId() != 0) {
369 // If we're in kStarting, we won't have a thin lock id or tid yet.
370 os << GetThinLockId()
371 << ",tid=" << GetTid() << ',';
372 }
373 os << GetState()
374 << ",Thread*=" << this
Elliott Hughesffb465f2012-03-01 18:46:05 -0800375 << ",peer=" << peer_
Elliott Hughes899e7892012-01-24 14:57:32 -0800376 << ",\"" << *name_ << "\""
377 << "]";
Elliott Hughese0918552011-10-28 17:18:29 -0700378 }
Elliott Hughesa0957642011-09-02 14:27:33 -0700379}
380
Elliott Hughes899e7892012-01-24 14:57:32 -0800381String* Thread::GetThreadName() const {
Elliott Hughesfc861622011-10-17 17:57:47 -0700382 return (peer_ != NULL) ? reinterpret_cast<String*>(gThread_name->GetObject(peer_)) : NULL;
383}
384
Elliott Hughesffb465f2012-03-01 18:46:05 -0800385void Thread::GetThreadName(std::string& name) const {
386 name.assign(*name_);
387}
388
Elliott Hughesd92bec42011-09-02 17:04:36 -0700389void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700390 std::string group_name;
391 int priority;
392 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700393
Elliott Hughesd369bb72011-09-12 14:41:14 -0700394 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700395 priority = gThread_priority->GetInt(peer_);
396 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700397
Elliott Hughesa2155262011-11-16 16:26:58 -0800398 Object* thread_group = GetThreadGroup();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700399 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700400 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700401 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
402 }
403 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700404 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700405 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700406
407 int policy;
408 sched_param sp;
Elliott Hughes3147a232011-10-12 15:55:07 -0700409 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_self(), &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700410
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700411 std::string scheduler_group_name(GetSchedulerGroupName(GetTid()));
412 if (scheduler_group_name.empty()) {
413 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700414 }
415
Elliott Hughes899e7892012-01-24 14:57:32 -0800416 os << '"' << *name_ << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700417 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700418 os << " daemon";
419 }
420 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700421 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700422 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700423
Elliott Hughesd92bec42011-09-02 17:04:36 -0700424 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700425 << " sCount=" << suspend_count_
Elliott Hughes234ab152011-10-26 14:02:26 -0700426 << " dsCount=" << debug_suspend_count_
Elliott Hughesdcc24742011-09-07 14:02:44 -0700427 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700428 << " self=" << reinterpret_cast<const void*>(this) << "\n";
429 os << " | sysTid=" << GetTid()
430 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
431 << " sched=" << policy << "/" << sp.sched_priority
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700432 << " cgrp=" << scheduler_group_name
Elliott Hughes3147a232011-10-12 15:55:07 -0700433 << " handle=" << pthread_self() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700434
435 // Grab the scheduler stats for this thread.
436 std::string scheduler_stats;
437 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
438 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
439 } else {
440 scheduler_stats = "0 0 0";
441 }
442
443 int utime = 0;
444 int stime = 0;
445 int task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700446 GetTaskStats(GetTid(), utime, stime, task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700447
448 os << " | schedstat=( " << scheduler_stats << " )"
449 << " utm=" << utime
450 << " stm=" << stime
451 << " core=" << task_cpu
452 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
453}
454
TDYa127ee0d3fb2012-04-01 14:55:33 -0700455#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersb04f69f2011-10-17 00:40:54 -0700456void Thread::PushNativeToManagedRecord(NativeToManagedRecord* record) {
457 Method **sp = top_of_managed_stack_.GetSP();
458#ifndef NDEBUG
459 if (sp != NULL) {
460 Method* m = *sp;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800461 Runtime::Current()->GetHeap()->VerifyObject(m);
Ian Rogersb04f69f2011-10-17 00:40:54 -0700462 DCHECK((m == NULL) || m->IsMethod());
463 }
464#endif
465 record->last_top_of_managed_stack_ = reinterpret_cast<void*>(sp);
466 record->last_top_of_managed_stack_pc_ = top_of_managed_stack_pc_;
467 record->link_ = native_to_managed_record_;
468 native_to_managed_record_ = record;
469 top_of_managed_stack_.SetSP(NULL);
470}
TDYa127ee0d3fb2012-04-01 14:55:33 -0700471#else
472void Thread::PushNativeToManagedRecord(NativeToManagedRecord*) {
473 LOG(FATAL) << "Called non-LLVM method with LLVM";
474}
475#endif
Ian Rogersb04f69f2011-10-17 00:40:54 -0700476
TDYa127ee0d3fb2012-04-01 14:55:33 -0700477#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersb04f69f2011-10-17 00:40:54 -0700478void Thread::PopNativeToManagedRecord(const NativeToManagedRecord& record) {
479 native_to_managed_record_ = record.link_;
480 top_of_managed_stack_.SetSP(reinterpret_cast<Method**>(record.last_top_of_managed_stack_));
481 top_of_managed_stack_pc_ = record.last_top_of_managed_stack_pc_;
482}
TDYa127ee0d3fb2012-04-01 14:55:33 -0700483#else
484void Thread::PopNativeToManagedRecord(const NativeToManagedRecord&) {
485 LOG(FATAL) << "Called non-LLVM method with LLVM";
486}
487#endif
Ian Rogersb04f69f2011-10-17 00:40:54 -0700488
Elliott Hughesd369bb72011-09-12 14:41:14 -0700489struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700490 StackDumpVisitor(std::ostream& os, const Thread* thread)
Ian Rogers28ad40d2011-10-27 15:19:26 -0700491 : last_method(NULL), last_line_number(0), repetition_count(0), os(os), thread(thread),
492 frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700493 }
494
Ian Rogersbdb03912011-09-14 00:55:44 -0700495 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700496 }
497
Elliott Hughes530fa002012-03-12 11:44:49 -0700498 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700499 if (!frame.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700500 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700501 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700502 const int kMaxRepetition = 3;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700503 Method* m = frame.GetMethod();
TDYa127540a5b72012-04-03 18:56:08 -0700504#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700505 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700506 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersb861dc02011-11-14 17:00:05 -0800507 const DexCache* dex_cache = c->GetDexCache();
508 int line_number = -1;
509 if (dex_cache != NULL) { // be tolerant of bad input
510 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
511 line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
512 }
TDYa127540a5b72012-04-03 18:56:08 -0700513#else
514 // Compiler_LLVM stores line_number in the ShadowFrame, and passes it to visitor.
515 int line_number = static_cast<int>(pc);
516#endif
Ian Rogers28ad40d2011-10-27 15:19:26 -0700517 if (line_number == last_line_number && last_method == m) {
518 repetition_count++;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700519 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700520 if (repetition_count >= kMaxRepetition) {
521 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
522 }
523 repetition_count = 0;
524 last_line_number = line_number;
525 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700526 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700527 if (repetition_count < kMaxRepetition) {
528 os << " at " << PrettyMethod(m, false);
529 if (m->IsNative()) {
530 os << "(Native method)";
531 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800532 mh.ChangeMethod(m);
533 const char* source_file(mh.GetDeclaringClassSourceFile());
534 os << "(" << (source_file != NULL ? source_file : "unavailable")
Ian Rogers28ad40d2011-10-27 15:19:26 -0700535 << ":" << line_number << ")";
536 }
537 os << "\n";
538 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700539
540 if (frame_count++ == 0) {
541 Monitor::DescribeWait(os, thread);
542 }
Elliott Hughes530fa002012-03-12 11:44:49 -0700543 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700544 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800545 MethodHelper mh;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700546 Method* last_method;
547 int last_line_number;
548 int repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700549 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700550 const Thread* thread;
551 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700552};
553
Elliott Hughesd92bec42011-09-02 17:04:36 -0700554void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800555 // If we're currently in native code, dump that stack before dumping the managed stack.
Elliott Hughes34e06962012-04-09 13:55:55 -0700556 if (GetState() == kNative || GetState() == kVmWait) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800557 DumpNativeStack(os);
558 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700559 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700560 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700561}
562
Elliott Hughes34e06962012-04-09 13:55:55 -0700563void Thread::SetStateWithoutSuspendCheck(ThreadState new_state) {
Elliott Hughesa4060e52012-03-02 16:51:35 -0800564 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
565 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
566 android_atomic_release_store(new_state, addr);
567}
568
Elliott Hughes34e06962012-04-09 13:55:55 -0700569ThreadState Thread::SetState(ThreadState new_state) {
570 ThreadState old_state = state_;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700571 if (old_state == new_state) {
572 return old_state;
573 }
574
575 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
576 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
577
Elliott Hughes34e06962012-04-09 13:55:55 -0700578 if (new_state == kRunnable) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700579 /*
Elliott Hughes34e06962012-04-09 13:55:55 -0700580 * Change our status to kRunnable. The transition requires
Elliott Hughes81ff3182012-03-23 20:35:56 -0700581 * that we check for pending suspension, because the runtime considers
Elliott Hughes8d768a92011-09-14 16:35:25 -0700582 * us to be "asleep" in all other states, and another thread could
583 * be performing a GC now.
584 *
585 * The order of operations is very significant here. One way to
586 * do this wrong is:
587 *
588 * GCing thread Our thread (in kNative)
589 * ------------ ----------------------
590 * check suspend count (== 0)
591 * SuspendAllThreads()
592 * grab suspend-count lock
593 * increment all suspend counts
594 * release suspend-count lock
595 * check thread state (== kNative)
596 * all are suspended, begin GC
597 * set state to kRunnable
598 * (continue executing)
599 *
600 * We can correct this by grabbing the suspend-count lock and
601 * performing both of our operations (check suspend count, set
602 * state) while holding it, now we need to grab a mutex on every
603 * transition to kRunnable.
604 *
605 * What we do instead is change the order of operations so that
606 * the transition to kRunnable happens first. If we then detect
607 * that the suspend count is nonzero, we switch to kSuspended.
608 *
609 * Appropriate compiler and memory barriers are required to ensure
610 * that the operations are observed in the expected order.
611 *
612 * This does create a small window of opportunity where a GC in
613 * progress could observe what appears to be a running thread (if
614 * it happens to look between when we set to kRunnable and when we
615 * switch to kSuspended). At worst this only affects assertions
616 * and thread logging. (We could work around it with some sort
617 * of intermediate "pre-running" state that is generally treated
618 * as equivalent to running, but that doesn't seem worthwhile.)
619 *
620 * We can also solve this by combining the "status" and "suspend
621 * count" fields into a single 32-bit value. This trades the
622 * store/load barrier on transition to kRunnable for an atomic RMW
623 * op on all transitions and all suspend count updates (also, all
624 * accesses to status or the thread count require bit-fiddling).
625 * It also eliminates the brief transition through kRunnable when
626 * the thread is supposed to be suspended. This is possibly faster
627 * on SMP and slightly more correct, but less convenient.
628 */
629 android_atomic_acquire_store(new_state, addr);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800630 ANNOTATE_IGNORE_READS_BEGIN();
631 int suspend_count = suspend_count_;
632 ANNOTATE_IGNORE_READS_END();
633 if (suspend_count != 0) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700634 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
635 }
636 } else {
637 /*
Elliott Hughes34e06962012-04-09 13:55:55 -0700638 * Not changing to kRunnable. No additional work required.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700639 *
640 * We use a releasing store to ensure that, if we were runnable,
641 * any updates we previously made to objects on the managed heap
642 * will be observed before the state change.
643 */
644 android_atomic_release_store(new_state, addr);
645 }
646
647 return old_state;
648}
649
Elliott Hughes761928d2011-11-16 18:33:03 -0800650bool Thread::IsSuspended() {
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800651 ANNOTATE_IGNORE_READS_BEGIN();
652 int suspend_count = suspend_count_;
653 ANNOTATE_IGNORE_READS_END();
Elliott Hughes34e06962012-04-09 13:55:55 -0700654 return suspend_count != 0 && GetState() != kRunnable;
Elliott Hughes761928d2011-11-16 18:33:03 -0800655}
656
Elliott Hughesff738062012-02-03 15:00:42 -0800657static void ReportThreadSuspendTimeout(Thread* waiting_thread) {
658 Runtime* runtime = Runtime::Current();
659 std::ostringstream ss;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800660 ss << "Thread suspend timeout waiting for thread " << *waiting_thread << "\n";
Elliott Hughesff738062012-02-03 15:00:42 -0800661 runtime->DumpLockHolders(ss);
662 ss << "\n";
663 runtime->GetThreadList()->DumpLocked(ss);
664 LOG(FATAL) << ss.str();
665}
666
Elliott Hughes8d768a92011-09-14 16:35:25 -0700667void Thread::WaitUntilSuspended() {
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800668 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
669
670 useconds_t total_delay = 0;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700671 useconds_t delay = 0;
Elliott Hughes34e06962012-04-09 13:55:55 -0700672 while (GetState() == kRunnable) {
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800673 if (total_delay >= kTimeoutUs) {
Elliott Hughesff738062012-02-03 15:00:42 -0800674 ReportThreadSuspendTimeout(this);
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800675 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700676 useconds_t new_delay = delay * 2;
677 CHECK_GE(new_delay, delay);
678 delay = new_delay;
679 if (delay == 0) {
680 sched_yield();
681 delay = 10000;
682 } else {
683 usleep(delay);
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800684 total_delay += delay;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700685 }
686 }
687}
688
Elliott Hughesbe759c62011-09-08 19:38:21 -0700689void Thread::ThreadExitCallback(void* arg) {
690 Thread* self = reinterpret_cast<Thread*>(arg);
691 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700692}
693
Elliott Hughesbe759c62011-09-08 19:38:21 -0700694void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700695 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700696 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700697
698 // Double-check the TLS slot allocation.
699 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800700 LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700701 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700702}
Carl Shapirob5573532011-07-12 18:22:59 -0700703
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700704// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700705static Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700706 Class* c = class_linker->FindSystemClass(descriptor);
707 CHECK(c != NULL) << descriptor;
708 return c;
709}
710
711// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700712static Field* FindFieldOrDie(Class* c, const char* name, const char* descriptor) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700713 Field* f = c->FindDeclaredInstanceField(name, descriptor);
714 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700715 return f;
716}
717
718// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700719static Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700720 Method* m = c->FindVirtualMethod(name, signature);
721 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
722 return m;
723}
724
Elliott Hughes462c9442012-03-23 18:47:50 -0700725// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700726static Field* FindStaticFieldOrDie(Class* c, const char* name, const char* descriptor) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700727 Field* f = c->FindDeclaredStaticField(name, descriptor);
728 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
729 return f;
730}
731
Elliott Hughes038a8062011-09-18 14:12:41 -0700732void Thread::FinishStartup() {
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500733 CHECK(Runtime::Current()->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700734 Thread* self = Thread::Current();
735
736 // Need to be kRunnable for FindClass
Elliott Hughes34e06962012-04-09 13:55:55 -0700737 ScopedThreadStateChange tsc(self, kRunnable);
Brian Carlstromb82b6872011-10-26 17:18:07 -0700738
Elliott Hughes038a8062011-09-18 14:12:41 -0700739 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
740 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700741
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700742 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700743 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
Elliott Hughes462c9442012-03-23 18:47:50 -0700744 gThreadGroup = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700745 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700746
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700747 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", "Z");
748 gThread_group = FindFieldOrDie(Thread_class, "group", "Ljava/lang/ThreadGroup;");
749 gThread_lock = FindFieldOrDie(Thread_class, "lock", "Ljava/lang/ThreadLock;");
750 gThread_name = FindFieldOrDie(Thread_class, "name", "Ljava/lang/String;");
751 gThread_priority = FindFieldOrDie(Thread_class, "priority", "I");
752 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
753 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", "I");
Elliott Hughes462c9442012-03-23 18:47:50 -0700754 gThreadGroup_name = FindFieldOrDie(gThreadGroup, "name", "Ljava/lang/String;");
755 gThreadGroup_mMain = FindStaticFieldOrDie(gThreadGroup, "mMain", "Ljava/lang/ThreadGroup;");
756 gThreadGroup_mSystem = FindStaticFieldOrDie(gThreadGroup, "mSystem", "Ljava/lang/ThreadGroup;");
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700757 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", "Ljava/lang/Thread;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700758
759 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
Elliott Hughes462c9442012-03-23 18:47:50 -0700760 gThreadGroup_removeThread = FindMethodOrDie(gThreadGroup, "removeThread", "(Ljava/lang/Thread;)V");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700761 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
762 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700763
764 // Finish attaching the main thread.
Elliott Hughes462c9442012-03-23 18:47:50 -0700765 Thread::Current()->CreatePeer("main", false, Thread::GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500766
767 InitBoxingMethods();
768 class_linker->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700769}
770
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700771void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700772 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700773}
774
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700775uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
776 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
777 return ThreadList::kInvalidId;
778 }
779 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
780 if (managed_thread == NULL) {
781 return ThreadList::kInvalidId;
782 }
783 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
784 Thread* thread = reinterpret_cast<Thread*>(vmData);
785 if (thread == NULL) {
786 return ThreadList::kInvalidId;
787 }
788 return thread->GetThinLockId();
789}
790
Elliott Hughesdcc24742011-09-07 14:02:44 -0700791Thread::Thread()
Elliott Hughes47179f72011-10-27 16:44:39 -0700792 : thin_lock_id_(0),
793 tid_(0),
794 peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700795 top_of_managed_stack_(),
796 top_of_managed_stack_pc_(0),
Elliott Hughese62934d2012-04-09 11:24:29 -0700797 wait_mutex_(new Mutex("a thread wait mutex")),
798 wait_cond_(new ConditionVariable("a thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700799 wait_monitor_(NULL),
800 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700801 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700802 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700803 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700804 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700805 native_to_managed_record_(NULL),
806 top_sirt_(NULL),
Logan Chienf7ad17e2012-03-15 03:10:03 +0800807 top_shadow_frame_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700808 jni_env_(NULL),
Elliott Hughes34e06962012-04-09 13:55:55 -0700809 state_(kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700810 self_(NULL),
811 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700812 exception_(NULL),
813 suspend_count_(0),
Elliott Hughes234ab152011-10-26 14:02:26 -0700814 debug_suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700815 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700816 long_jump_context_(NULL),
Elliott Hughes726079d2011-10-07 18:43:44 -0700817 throwing_OutOfMemoryError_(false),
Elliott Hughes475fc232011-10-25 15:00:35 -0700818 pre_allocated_OutOfMemoryError_(NULL),
jeffhaoe343b762011-12-05 16:36:44 -0800819 debug_invoke_req_(new DebugInvokeReq),
Elliott Hughes899e7892012-01-24 14:57:32 -0800820 trace_stack_(new std::vector<TraceStackFrame>),
821 name_(new std::string("<native thread without managed peer>")) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700822 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800823 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700824}
825
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700826static void MonitorExitVisitor(const Object* object, void*) {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700827 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700828 LOG(WARNING) << "Calling MonitorExit on object " << object << " (" << PrettyTypeOf(object) << ")"
829 << " left locked by native thread " << *Thread::Current() << " which is detaching";
Elliott Hughes5f791332011-09-15 17:45:30 -0700830 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700831}
832
Elliott Hughesc0f09332012-03-26 13:27:06 -0700833void Thread::Destroy() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700834 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700835 if (jni_env_ != NULL) {
836 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
837 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700838
Elliott Hughes93e74e82011-09-13 11:07:03 -0700839 if (peer_ != NULL) {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700840 Thread* self = this;
Elliott Hughes29f27422011-09-18 16:02:18 -0700841
Elliott Hughes534da072012-03-27 15:17:42 -0700842 // We may need to call user-supplied managed code.
Elliott Hughes34e06962012-04-09 13:55:55 -0700843 SetState(kRunnable);
Elliott Hughes534da072012-03-27 15:17:42 -0700844
845 HandleUncaughtExceptions();
846 RemoveFromThreadGroup();
847
Elliott Hughes29f27422011-09-18 16:02:18 -0700848 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700849 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700850
Elliott Hughesc0f09332012-03-26 13:27:06 -0700851 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700852
Elliott Hughes29f27422011-09-18 16:02:18 -0700853 // Thread.join() is implemented as an Object.wait() on the Thread.lock
854 // object. Signal anyone who is waiting.
Elliott Hughes038a8062011-09-18 14:12:41 -0700855 Object* lock = gThread_lock->GetObject(peer_);
856 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700857 if (lock != NULL) {
858 lock->MonitorEnter(self);
859 lock->NotifyAll();
860 lock->MonitorExit(self);
861 }
862 }
Elliott Hughesc0f09332012-03-26 13:27:06 -0700863}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700864
Elliott Hughesc0f09332012-03-26 13:27:06 -0700865Thread::~Thread() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700866 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700867 jni_env_ = NULL;
868
Elliott Hughes34e06962012-04-09 13:55:55 -0700869 SetState(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700870
871 delete wait_cond_;
872 delete wait_mutex_;
873
Ian Rogers776ac1f2012-04-13 23:36:36 -0700874#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes85d15452011-09-16 17:33:01 -0700875 delete long_jump_context_;
Ian Rogers776ac1f2012-04-13 23:36:36 -0700876#endif
Elliott Hughes475fc232011-10-25 15:00:35 -0700877
878 delete debug_invoke_req_;
jeffhaoe343b762011-12-05 16:36:44 -0800879 delete trace_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -0800880 delete name_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700881}
882
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700883void Thread::HandleUncaughtExceptions() {
884 if (!IsExceptionPending()) {
885 return;
886 }
887
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700888 // Get and clear the exception.
889 Object* exception = GetException();
890 ClearException();
891
892 // If the thread has its own handler, use that.
893 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
894 if (handler == NULL) {
895 // Otherwise use the thread group's default handler.
Elliott Hughesa2155262011-11-16 16:26:58 -0800896 handler = GetThreadGroup();
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700897 }
898
899 // Call the handler.
900 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
Elliott Hughes77405792012-03-15 15:22:12 -0700901 JValue args[2];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700902 args[0].SetL(peer_);
903 args[1].SetL(exception);
Elliott Hughes77405792012-03-15 15:22:12 -0700904 m->Invoke(this, handler, args, NULL);
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700905
906 // If the handler threw, clear that exception too.
907 ClearException();
908}
909
Elliott Hughesa2155262011-11-16 16:26:58 -0800910Object* Thread::GetThreadGroup() const {
911 return gThread_group->GetObject(peer_);
912}
913
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700914void Thread::RemoveFromThreadGroup() {
915 // this.group.removeThread(this);
916 // group can be null if we're in the compiler or a test.
Elliott Hughesa2155262011-11-16 16:26:58 -0800917 Object* group = GetThreadGroup();
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700918 if (group != NULL) {
919 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
Elliott Hughes77405792012-03-15 15:22:12 -0700920 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700921 args[0].SetL(peer_);
Elliott Hughes77405792012-03-15 15:22:12 -0700922 m->Invoke(this, group, args, NULL);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700923 }
924}
925
Ian Rogers408f79a2011-08-23 18:22:33 -0700926size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700927 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700928 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700929 count += cur->NumberOfReferences();
930 }
931 return count;
932}
933
TDYa12728f1a142012-03-15 21:51:52 -0700934size_t Thread::NumShadowFrameReferences() {
935 size_t count = 0;
936 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
937 count += cur->NumberOfReferences();
938 }
939 return count;
940}
941
Ian Rogers408f79a2011-08-23 18:22:33 -0700942bool Thread::SirtContains(jobject obj) {
943 Object** sirt_entry = reinterpret_cast<Object**>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700944 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
945 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700946 return true;
947 }
948 }
949 return false;
950}
951
TDYa12728f1a142012-03-15 21:51:52 -0700952bool Thread::ShadowFrameContains(jobject obj) {
953 Object** shadow_frame_entry = reinterpret_cast<Object**>(obj);
954 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
955 if (cur->Contains(shadow_frame_entry)) {
956 return true;
957 }
958 }
959 return false;
960}
961
962bool Thread::StackReferencesContain(jobject obj) {
963 return SirtContains(obj) || ShadowFrameContains(obj);
964}
965
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700966void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700967 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700968 size_t num_refs = cur->NumberOfReferences();
969 for (size_t j = 0; j < num_refs; j++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700970 Object* object = cur->GetReference(j);
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -0700971 if (object != NULL) {
972 visitor(object, arg);
973 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700974 }
975 }
976}
977
Logan Chienf7ad17e2012-03-15 03:10:03 +0800978void Thread::ShadowFrameVisitRoots(Heap::RootVisitor* visitor, void* arg) {
979 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
980 size_t num_refs = cur->NumberOfReferences();
981 for (size_t j = 0; j < num_refs; j++) {
982 Object* object = cur->GetReference(j);
983 if (object != NULL) {
984 visitor(object, arg);
985 }
986 }
987 }
988}
989
Ian Rogers408f79a2011-08-23 18:22:33 -0700990Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700991 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700992 if (obj == NULL) {
993 return NULL;
994 }
995 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
996 IndirectRefKind kind = GetIndirectRefKind(ref);
997 Object* result;
998 switch (kind) {
999 case kLocal:
1000 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001001 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001002 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001003 break;
1004 }
1005 case kGlobal:
1006 {
1007 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1008 IndirectReferenceTable& globals = vm->globals;
1009 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001010 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001011 break;
1012 }
1013 case kWeakGlobal:
1014 {
1015 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1016 IndirectReferenceTable& weak_globals = vm->weak_globals;
1017 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001018 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001019 if (result == kClearedJniWeakGlobal) {
1020 // This is a special case where it's okay to return NULL.
1021 return NULL;
1022 }
1023 break;
1024 }
1025 case kSirtOrInvalid:
1026 default:
1027 // TODO: make stack indirect reference table lookup more efficient
1028 // Check if this is a local reference in the SIRT
TDYa12728f1a142012-03-15 21:51:52 -07001029 if (StackReferencesContain(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001030 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc2dc62d2012-01-17 20:06:12 -08001031 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001032 // Assume an invalid local reference is actually a direct pointer.
1033 result = reinterpret_cast<Object*>(obj);
1034 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001035 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001036 }
1037 }
1038
1039 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001040 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1041 JniAbort(NULL);
1042 } else {
1043 if (result != kInvalidIndirectRefObject) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001044 Runtime::Current()->GetHeap()->VerifyObject(result);
Elliott Hughesa2501992011-08-26 19:39:54 -07001045 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001046 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001047 return result;
1048}
1049
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001050class CountStackDepthVisitor : public Thread::StackVisitor {
1051 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001052 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001053
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001054 bool VisitFrame(const Frame& frame, uintptr_t /*pc*/) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001055 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001056 // Note we also skip the frame if it doesn't have a method (namely the callee
1057 // save frame)
Ian Rogers5167c972012-02-03 10:41:20 -08001058 if (skipping_ && frame.HasMethod() &&
1059 !Throwable::GetJavaLangThrowable()->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001060 skipping_ = false;
1061 }
1062 if (!skipping_) {
Ian Rogers6b0870d2011-12-15 19:38:12 -08001063 if (frame.HasMethod()) { // ignore callee save frames
1064 ++depth_;
1065 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001066 } else {
1067 ++skip_depth_;
1068 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001069 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001070 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001071
1072 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001073 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001074 }
1075
Elliott Hughes29f27422011-09-18 16:02:18 -07001076 int GetSkipDepth() const {
1077 return skip_depth_;
1078 }
1079
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001080 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001081 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001082 uint32_t skip_depth_;
1083 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001084};
1085
Ian Rogersaaa20802011-09-11 21:47:37 -07001086class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001087 public:
Ian Rogers283ed0d2012-02-16 15:25:09 -08001088 explicit BuildInternalStackTraceVisitor(int skip_depth)
Elliott Hughes726079d2011-10-07 18:43:44 -07001089 : skip_depth_(skip_depth), count_(0), pc_trace_(NULL), method_trace_(NULL), local_ref_(NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001090 }
1091
1092 bool Init(int depth, ScopedJniThreadState& ts) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001093 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001094 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Elliott Hughes726079d2011-10-07 18:43:44 -07001095 if (method_trace_ == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001096 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001097 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001098 // Register a local reference as IntArray::Alloc may trigger GC
1099 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1100 pc_trace_ = IntArray::Alloc(depth);
Elliott Hughes726079d2011-10-07 18:43:44 -07001101 if (pc_trace_ == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001102 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001103 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001104#ifdef MOVING_GARBAGE_COLLECTOR
1105 // Re-read after potential GC
Brian Carlstrom26736442012-02-16 18:24:26 -08001106 method_trace_ = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
Ian Rogersaaa20802011-09-11 21:47:37 -07001107#endif
1108 // Save PC trace in last element of method trace, also places it into the
1109 // object graph.
1110 method_trace_->Set(depth, pc_trace_);
Ian Rogers283ed0d2012-02-16 15:25:09 -08001111 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001112 }
1113
Ian Rogersaaa20802011-09-11 21:47:37 -07001114 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001115
Elliott Hughes530fa002012-03-12 11:44:49 -07001116 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes726079d2011-10-07 18:43:44 -07001117 if (method_trace_ == NULL || pc_trace_ == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001118 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001119 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001120 if (skip_depth_ > 0) {
1121 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001122 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001123 }
Ian Rogers6b0870d2011-12-15 19:38:12 -08001124 if (!frame.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001125 return true; // ignore callee save frames
Ian Rogers6b0870d2011-12-15 19:38:12 -08001126 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001127 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001128 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001129 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001130 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001131 }
1132
Ian Rogersaaa20802011-09-11 21:47:37 -07001133 jobject GetInternalStackTrace() const {
1134 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001135 }
1136
1137 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001138 // How many more frames to skip.
1139 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001140 // Current position down stack trace
1141 uint32_t count_;
1142 // Array of return PC values
1143 IntArray* pc_trace_;
1144 // An array of the methods on the stack, the last entry is a reference to the
1145 // PC trace
1146 ObjectArray<Object>* method_trace_;
1147 // Local indirect reference table entry for method trace
1148 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001149};
1150
Ian Rogers776ac1f2012-04-13 23:36:36 -07001151#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001152// TODO: remove this.
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001153static uintptr_t ManglePc(uintptr_t pc) {
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001154 // Move the PC back 2 bytes as a call will frequently terminate the
1155 // decoding of a particular instruction and we want to make sure we
1156 // get the Dex PC of the instruction with the call and not the
1157 // instruction following.
1158 if (pc > 0) { pc -= 2; }
1159 return pc;
1160}
Ian Rogers776ac1f2012-04-13 23:36:36 -07001161#endif
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001162
1163// TODO: remove this.
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001164static uintptr_t DemanglePc(uintptr_t pc) {
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001165 // Revert mangling for the case where we need the PC to return to the upcall
Ian Rogers9a8a8882012-03-08 02:30:55 -08001166 if (pc > 0) { pc += 2; }
1167 return pc;
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001168}
Ian Rogersf57c47c2011-10-06 00:06:17 -07001169
Logan Chienf7ad17e2012-03-15 03:10:03 +08001170void Thread::PushShadowFrame(ShadowFrame* frame) {
1171 frame->SetLink(top_shadow_frame_);
1172 top_shadow_frame_ = frame;
1173}
1174
1175ShadowFrame* Thread::PopShadowFrame() {
1176 CHECK(top_shadow_frame_ != NULL);
1177 ShadowFrame* frame = top_shadow_frame_;
1178 top_shadow_frame_ = frame->GetLink();
1179 return frame;
1180}
1181
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001182void Thread::PushSirt(StackIndirectReferenceTable* sirt) {
1183 sirt->SetLink(top_sirt_);
1184 top_sirt_ = sirt;
1185}
1186
1187StackIndirectReferenceTable* Thread::PopSirt() {
1188 CHECK(top_sirt_ != NULL);
1189 StackIndirectReferenceTable* sirt = top_sirt_;
1190 top_sirt_ = top_sirt_->GetLink();
1191 return sirt;
1192}
1193
TDYa1279b2ba2e2012-03-19 10:12:32 -07001194#if !defined(ART_USE_LLVM_COMPILER) // LLVM use ShadowFrame
1195
Elliott Hughes530fa002012-03-12 11:44:49 -07001196void Thread::WalkStack(StackVisitor* visitor, bool include_upcalls) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001197 Frame frame = GetTopOfStack();
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001198 uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001199 uint32_t trace_stack_depth = 0;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001200 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1201 // CHECK(native_to_managed_record_ != NULL);
1202 NativeToManagedRecord* record = native_to_managed_record_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001203 bool method_tracing_active = Runtime::Current()->IsMethodTracingActive();
Elliott Hughes530fa002012-03-12 11:44:49 -07001204 while (frame.GetSP() != NULL) {
1205 for ( ; frame.GetMethod() != NULL; frame.Next()) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07001206 frame.GetMethod()->AssertPcIsWithinCode(pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001207 bool should_continue = visitor->VisitFrame(frame, pc);
Ian Rogers57b86d42012-03-27 16:05:41 -07001208 if (UNLIKELY(!should_continue)) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001209 return;
1210 }
Ian Rogers57b86d42012-03-27 16:05:41 -07001211 uintptr_t return_pc = frame.GetReturnPC();
1212 if (LIKELY(!method_tracing_active)) {
1213 pc = ManglePc(return_pc);
1214 } else {
jeffhao0791adc2012-04-04 11:14:32 -07001215 // While profiling, the return pc is restored from the side stack, except when walking
1216 // the stack for an exception where the side stack will be unwound in VisitFrame.
1217 if (IsTraceExitPc(return_pc) && !include_upcalls) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001218 TraceStackFrame trace_frame = GetTraceStackFrame(trace_stack_depth++);
jeffhao26c0a1a2012-01-17 16:28:33 -08001219 CHECK(trace_frame.method_ == frame.GetMethod());
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001220 pc = ManglePc(trace_frame.return_pc_);
Ian Rogers57b86d42012-03-27 16:05:41 -07001221 } else {
1222 pc = ManglePc(return_pc);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001223 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001224 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001225 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001226 if (include_upcalls) {
1227 bool should_continue = visitor->VisitFrame(frame, pc);
1228 if (!should_continue) {
1229 return;
1230 }
1231 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001232 if (record == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001233 return;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001234 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001235 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001236 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001237 pc = ManglePc(record->last_top_of_managed_stack_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001238 record = record->link_;
1239 }
1240}
1241
TDYa1279b2ba2e2012-03-19 10:12:32 -07001242#else // defined(ART_USE_LLVM_COMPILER) // LLVM uses ShadowFrame
1243
1244void Thread::WalkStack(StackVisitor* visitor, bool /*include_upcalls*/) const {
1245 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
1246 Frame frame;
1247 frame.SetSP(reinterpret_cast<Method**>(reinterpret_cast<byte*>(cur) +
1248 ShadowFrame::MethodOffset()));
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001249 bool should_continue = visitor->VisitFrame(frame, cur->GetLineNumber());
TDYa1279b2ba2e2012-03-19 10:12:32 -07001250 if (!should_continue) {
1251 return;
1252 }
1253 }
1254}
1255
1256/*
1257 * | |
1258 * | |
1259 * | |
1260 * | . |
1261 * | . |
1262 * | . |
1263 * | . |
1264 * | Method* |
1265 * | . |
1266 * | . | <-- top_shadow_frame_ (ShadowFrame*)
1267 * / +------------------------+
1268 * ->| . |
1269 * . | . |
1270 * . | . |
1271 * /+------------------------+
1272 * / | . |
1273 * / | . |
1274 * --- | | . |
1275 * | | | . |
1276 * | | Method* | <-- frame.GetSP() (Method**)
1277 * ShadowFrame \ | . |
1278 * | ->| . | <-- cur (ShadowFrame*)
1279 * --- /+------------------------+
1280 * / | . |
1281 * / | . |
1282 * --- | | . |
1283 * | cur->GetLink() | | . |
1284 * | | Method* |
1285 * ShadowFrame \ | . |
1286 * | ->| . |
1287 * --- +------------------------+
1288 * | . |
1289 * | . |
1290 * | . |
1291 * +========================+
1292 */
1293
1294#endif
1295
Elliott Hughes01158d72011-09-19 19:47:10 -07001296jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001297 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001298 CountStackDepthVisitor count_visitor;
1299 WalkStack(&count_visitor);
1300 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001301 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001302
Ian Rogersaaa20802011-09-11 21:47:37 -07001303 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001304 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001305
1306 // Build internal stack trace
Ian Rogers77f74c12012-02-16 22:35:30 -08001307 BuildInternalStackTraceVisitor build_trace_visitor(skip_depth);
1308 if (!build_trace_visitor.Init(depth, ts)) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001309 return NULL; // Allocation failed
Ian Rogers283ed0d2012-02-16 15:25:09 -08001310 }
Brian Carlstrom26736442012-02-16 18:24:26 -08001311 WalkStack(&build_trace_visitor);
1312 return build_trace_visitor.GetInternalStackTrace();
Ian Rogersaaa20802011-09-11 21:47:37 -07001313}
1314
Elliott Hughes01158d72011-09-19 19:47:10 -07001315jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1316 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001317 // Transition into runnable state to work on Object*/Array*
1318 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001319 // Decode the internal stack trace into the depth, method trace and PC trace
1320 ObjectArray<Object>* method_trace =
1321 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
Ian Rogers9074b992011-10-26 17:41:55 -07001322 int32_t depth = method_trace->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001323 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1324
1325 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1326
Elliott Hughes01158d72011-09-19 19:47:10 -07001327 jobjectArray result;
1328 ObjectArray<StackTraceElement>* java_traces;
1329 if (output_array != NULL) {
1330 // Reuse the array we were given.
1331 result = output_array;
1332 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1333 output_array));
1334 // ...adjusting the number of frames we'll write to not exceed the array length.
1335 depth = std::min(depth, java_traces->GetLength());
1336 } else {
1337 // Create java_trace array and place in local reference table
1338 java_traces = class_linker->AllocStackTraceElementArray(depth);
Elliott Hughes30646832011-10-13 16:59:46 -07001339 if (java_traces == NULL) {
1340 return NULL;
1341 }
Elliott Hughes01158d72011-09-19 19:47:10 -07001342 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1343 }
1344
1345 if (stack_depth != NULL) {
1346 *stack_depth = depth;
1347 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001348
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001349 MethodHelper mh;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001350 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001351 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1352 Method* method = down_cast<Method*>(method_trace->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001353 mh.ChangeMethod(method);
Ian Rogersaaa20802011-09-11 21:47:37 -07001354 uint32_t native_pc = pc_trace->Get(i);
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001355#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001356 int32_t line_number = mh.GetLineNumFromNativePC(native_pc);
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001357#else
1358 int32_t line_number = native_pc; // LLVM stored line_number in the ShadowFrame
1359#endif
Ian Rogersaaa20802011-09-11 21:47:37 -07001360 // Allocate element, potentially triggering GC
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001361 // TODO: reuse class_name_object via Class::name_?
Ian Rogers48601312011-12-07 16:45:19 -08001362 const char* descriptor = mh.GetDeclaringClassDescriptor();
1363 CHECK(descriptor != NULL);
1364 std::string class_name(PrettyDescriptor(descriptor));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001365 SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
1366 if (class_name_object.get() == NULL) {
1367 return NULL;
1368 }
Ian Rogers48601312011-12-07 16:45:19 -08001369 const char* method_name = mh.GetName();
1370 CHECK(method_name != NULL);
1371 SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001372 if (method_name_object.get() == NULL) {
1373 return NULL;
1374 }
Ian Rogers48601312011-12-07 16:45:19 -08001375 const char* source_file = mh.GetDeclaringClassSourceFile();
1376 SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001377 StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001378 method_name_object.get(),
1379 source_name_object.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001380 line_number);
Elliott Hughes30646832011-10-13 16:59:46 -07001381 if (obj == NULL) {
1382 return NULL;
1383 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001384#ifdef MOVING_GARBAGE_COLLECTOR
1385 // Re-read after potential GC
1386 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1387 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1388 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1389#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001390 java_traces->Set(i, obj);
1391 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001392 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001393}
1394
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001395void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001396 va_list args;
1397 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001398 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001399 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001400}
1401
1402void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1403 std::string msg;
1404 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001405 ThrowNewException(exception_class_descriptor, msg.c_str());
1406}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001407
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001408void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001409 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001410 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001411 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001412 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001413 descriptor.erase(descriptor.length() - 1);
1414
1415 JNIEnv* env = GetJniEnv();
Elliott Hughes726079d2011-10-07 18:43:44 -07001416 ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001417 if (exception_class.get() == NULL) {
1418 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1419 << PrettyTypeOf(GetException());
1420 CHECK(IsExceptionPending());
1421 return;
1422 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001423 if (!Runtime::Current()->IsStarted()) {
1424 // Something is trying to throw an exception without a started
1425 // runtime, which is the common case in the compiler. We won't be
1426 // able to invoke the constructor of the exception, so use
1427 // AllocObject which will not invoke a constructor.
1428 ScopedLocalRef<jthrowable> exception(
1429 env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1430 if (exception.get() != NULL) {
1431 ScopedJniThreadState ts(env);
1432 Throwable* t = reinterpret_cast<Throwable*>(ts.Self()->DecodeJObject(exception.get()));
Ian Rogers02fbef02012-01-31 22:15:33 -08001433 t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001434 ts.Self()->SetException(t);
1435 } else {
1436 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1437 << PrettyTypeOf(GetException());
1438 CHECK(IsExceptionPending());
1439 }
1440 return;
1441 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001442 int rc = env->ThrowNew(exception_class.get(), msg);
Elliott Hughes30646832011-10-13 16:59:46 -07001443 if (rc != JNI_OK) {
1444 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1445 << PrettyTypeOf(GetException());
1446 CHECK(IsExceptionPending());
Elliott Hughes30646832011-10-13 16:59:46 -07001447 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001448}
1449
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001450void Thread::ThrowOutOfMemoryError(const char* msg) {
1451 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1452 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Elliott Hughes726079d2011-10-07 18:43:44 -07001453 if (!throwing_OutOfMemoryError_) {
1454 throwing_OutOfMemoryError_ = true;
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001455 ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001456 } else {
Elliott Hughes726079d2011-10-07 18:43:44 -07001457 SetException(pre_allocated_OutOfMemoryError_);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001458 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001459 throwing_OutOfMemoryError_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001460}
1461
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001462
Elliott Hughes498508c2011-10-17 14:58:22 -07001463Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001464 return Thread::Current();
1465}
1466
1467void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001468 std::ostringstream ss;
1469 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001470 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001471 // log to stderr for debugging command line processes
1472 std::cerr << str;
1473#ifdef HAVE_ANDROID_OS
1474 // log to logcat for debugging frameworks processes
1475 LOG(INFO) << str;
1476#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001477}
1478
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001479void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset, size_t size_of_pointers) {
1480 CHECK_EQ(size_of_pointers, 4U); // TODO: support 64-bit targets.
Elliott Hughes3d71d072012-04-10 18:28:35 -07001481#define DO_THREAD_OFFSET(x) if (offset == static_cast<uint32_t>(OFFSETOF_VOLATILE_MEMBER(Thread, x))) { os << # x; } else
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001482#define DO_THREAD_ENTRY_POINT_OFFSET(x) if (offset == ENTRYPOINT_OFFSET(x)) { os << # x; } else
1483 DO_THREAD_OFFSET(card_table_)
1484 DO_THREAD_OFFSET(exception_)
1485 DO_THREAD_OFFSET(jni_env_)
1486 DO_THREAD_OFFSET(self_)
1487 DO_THREAD_OFFSET(stack_end_)
Elliott Hughes3d71d072012-04-10 18:28:35 -07001488 DO_THREAD_OFFSET(state_)
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001489 DO_THREAD_OFFSET(suspend_count_)
1490 DO_THREAD_OFFSET(thin_lock_id_)
1491 DO_THREAD_OFFSET(top_of_managed_stack_)
1492 DO_THREAD_OFFSET(top_of_managed_stack_pc_)
1493 DO_THREAD_OFFSET(top_sirt_)
1494 DO_THREAD_ENTRY_POINT_OFFSET(pAllocArrayFromCode)
1495 DO_THREAD_ENTRY_POINT_OFFSET(pAllocArrayFromCodeWithAccessCheck)
1496 DO_THREAD_ENTRY_POINT_OFFSET(pAllocObjectFromCode)
1497 DO_THREAD_ENTRY_POINT_OFFSET(pAllocObjectFromCodeWithAccessCheck)
1498 DO_THREAD_ENTRY_POINT_OFFSET(pCheckAndAllocArrayFromCode)
1499 DO_THREAD_ENTRY_POINT_OFFSET(pCheckAndAllocArrayFromCodeWithAccessCheck)
1500 DO_THREAD_ENTRY_POINT_OFFSET(pInstanceofNonTrivialFromCode)
1501 DO_THREAD_ENTRY_POINT_OFFSET(pCanPutArrayElementFromCode)
1502 DO_THREAD_ENTRY_POINT_OFFSET(pCheckCastFromCode)
1503 DO_THREAD_ENTRY_POINT_OFFSET(pDebugMe)
1504 DO_THREAD_ENTRY_POINT_OFFSET(pUpdateDebuggerFromCode)
1505 DO_THREAD_ENTRY_POINT_OFFSET(pInitializeStaticStorage)
1506 DO_THREAD_ENTRY_POINT_OFFSET(pInitializeTypeAndVerifyAccessFromCode)
1507 DO_THREAD_ENTRY_POINT_OFFSET(pInitializeTypeFromCode)
1508 DO_THREAD_ENTRY_POINT_OFFSET(pResolveStringFromCode)
1509 DO_THREAD_ENTRY_POINT_OFFSET(pSet32Instance)
1510 DO_THREAD_ENTRY_POINT_OFFSET(pSet32Static)
1511 DO_THREAD_ENTRY_POINT_OFFSET(pSet64Instance)
1512 DO_THREAD_ENTRY_POINT_OFFSET(pSet64Static)
1513 DO_THREAD_ENTRY_POINT_OFFSET(pSetObjInstance)
1514 DO_THREAD_ENTRY_POINT_OFFSET(pSetObjStatic)
1515 DO_THREAD_ENTRY_POINT_OFFSET(pGet32Instance)
1516 DO_THREAD_ENTRY_POINT_OFFSET(pGet32Static)
1517 DO_THREAD_ENTRY_POINT_OFFSET(pGet64Instance)
1518 DO_THREAD_ENTRY_POINT_OFFSET(pGet64Static)
1519 DO_THREAD_ENTRY_POINT_OFFSET(pGetObjInstance)
1520 DO_THREAD_ENTRY_POINT_OFFSET(pGetObjStatic)
1521 DO_THREAD_ENTRY_POINT_OFFSET(pHandleFillArrayDataFromCode)
1522 DO_THREAD_ENTRY_POINT_OFFSET(pDecodeJObjectInThread)
1523 DO_THREAD_ENTRY_POINT_OFFSET(pFindNativeMethod)
1524 DO_THREAD_ENTRY_POINT_OFFSET(pLockObjectFromCode)
1525 DO_THREAD_ENTRY_POINT_OFFSET(pUnlockObjectFromCode)
1526 DO_THREAD_ENTRY_POINT_OFFSET(pCmpgDouble)
1527 DO_THREAD_ENTRY_POINT_OFFSET(pCmpgFloat)
1528 DO_THREAD_ENTRY_POINT_OFFSET(pCmplDouble)
1529 DO_THREAD_ENTRY_POINT_OFFSET(pCmplFloat)
1530 DO_THREAD_ENTRY_POINT_OFFSET(pDadd)
1531 DO_THREAD_ENTRY_POINT_OFFSET(pDdiv)
1532 DO_THREAD_ENTRY_POINT_OFFSET(pDmul)
1533 DO_THREAD_ENTRY_POINT_OFFSET(pDsub)
1534 DO_THREAD_ENTRY_POINT_OFFSET(pF2d)
1535 DO_THREAD_ENTRY_POINT_OFFSET(pFmod)
1536 DO_THREAD_ENTRY_POINT_OFFSET(pI2d)
1537 DO_THREAD_ENTRY_POINT_OFFSET(pL2d)
1538 DO_THREAD_ENTRY_POINT_OFFSET(pD2f)
1539 DO_THREAD_ENTRY_POINT_OFFSET(pFadd)
1540 DO_THREAD_ENTRY_POINT_OFFSET(pFdiv)
1541 DO_THREAD_ENTRY_POINT_OFFSET(pFmodf)
1542 DO_THREAD_ENTRY_POINT_OFFSET(pFmul)
1543 DO_THREAD_ENTRY_POINT_OFFSET(pFsub)
1544 DO_THREAD_ENTRY_POINT_OFFSET(pI2f)
1545 DO_THREAD_ENTRY_POINT_OFFSET(pL2f)
1546 DO_THREAD_ENTRY_POINT_OFFSET(pD2iz)
1547 DO_THREAD_ENTRY_POINT_OFFSET(pF2iz)
1548 DO_THREAD_ENTRY_POINT_OFFSET(pIdiv)
1549 DO_THREAD_ENTRY_POINT_OFFSET(pIdivmod)
1550 DO_THREAD_ENTRY_POINT_OFFSET(pD2l)
1551 DO_THREAD_ENTRY_POINT_OFFSET(pF2l)
1552 DO_THREAD_ENTRY_POINT_OFFSET(pLdiv)
1553 DO_THREAD_ENTRY_POINT_OFFSET(pLdivmod)
1554 DO_THREAD_ENTRY_POINT_OFFSET(pLmul)
1555 DO_THREAD_ENTRY_POINT_OFFSET(pShlLong)
1556 DO_THREAD_ENTRY_POINT_OFFSET(pShrLong)
1557 DO_THREAD_ENTRY_POINT_OFFSET(pUshrLong)
1558 DO_THREAD_ENTRY_POINT_OFFSET(pIndexOf)
1559 DO_THREAD_ENTRY_POINT_OFFSET(pMemcmp16)
1560 DO_THREAD_ENTRY_POINT_OFFSET(pStringCompareTo)
1561 DO_THREAD_ENTRY_POINT_OFFSET(pMemcpy)
1562 DO_THREAD_ENTRY_POINT_OFFSET(pFindInterfaceMethodInCache)
1563 DO_THREAD_ENTRY_POINT_OFFSET(pUnresolvedDirectMethodTrampolineFromCode)
1564 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeDirectTrampolineWithAccessCheck)
1565 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeInterfaceTrampoline)
1566 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeInterfaceTrampolineWithAccessCheck)
1567 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeStaticTrampolineWithAccessCheck)
1568 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeSuperTrampolineWithAccessCheck)
1569 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeVirtualTrampolineWithAccessCheck)
1570 DO_THREAD_ENTRY_POINT_OFFSET(pCheckSuspendFromCode)
1571 DO_THREAD_ENTRY_POINT_OFFSET(pTestSuspendFromCode)
1572 DO_THREAD_ENTRY_POINT_OFFSET(pDeliverException)
1573 DO_THREAD_ENTRY_POINT_OFFSET(pThrowAbstractMethodErrorFromCode)
1574 DO_THREAD_ENTRY_POINT_OFFSET(pThrowArrayBoundsFromCode)
1575 DO_THREAD_ENTRY_POINT_OFFSET(pThrowDivZeroFromCode)
1576 DO_THREAD_ENTRY_POINT_OFFSET(pThrowNoSuchMethodFromCode)
1577 DO_THREAD_ENTRY_POINT_OFFSET(pThrowNullPointerFromCode)
1578 DO_THREAD_ENTRY_POINT_OFFSET(pThrowStackOverflowFromCode)
1579 DO_THREAD_ENTRY_POINT_OFFSET(pThrowVerificationErrorFromCode)
1580 {
1581 os << offset;
1582 }
1583#undef DO_THREAD_OFFSET
1584#undef DO_THREAD_ENTRY_POINT_OFFSET
1585}
1586
Ian Rogersbdb03912011-09-14 00:55:44 -07001587class CatchBlockStackVisitor : public Thread::StackVisitor {
1588 public:
1589 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers57b86d42012-03-27 16:05:41 -07001590 : to_find_(to_find), long_jump_context_(ljc), native_method_count_(0),
1591 method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001592#ifndef NDEBUG
1593 handler_pc_ = 0xEBADC0DE;
1594 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1595#endif
1596 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001597
Elliott Hughes530fa002012-03-12 11:44:49 -07001598 bool VisitFrame(const Frame& fr, uintptr_t pc) {
1599 Method* method = fr.GetMethod();
1600 if (method == NULL) {
1601 // This is the upcall, we remember the frame and last_pc so that we may
1602 // long jump to them
1603 handler_pc_ = DemanglePc(pc);
1604 handler_frame_ = fr;
Ian Rogers57b86d42012-03-27 16:05:41 -07001605 return false; // End stack walk.
Elliott Hughes530fa002012-03-12 11:44:49 -07001606 }
1607 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers57b86d42012-03-27 16:05:41 -07001608 if (method->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001609 // ignore callee save method
Ian Rogers57b86d42012-03-27 16:05:41 -07001610 DCHECK(method->IsCalleeSaveMethod());
Elliott Hughes530fa002012-03-12 11:44:49 -07001611 } else if (method->IsNative()) {
1612 native_method_count_++;
1613 } else {
jeffhao0791adc2012-04-04 11:14:32 -07001614 // Unwind stack when an exception occurs during method tracing
Ian Rogers57b86d42012-03-27 16:05:41 -07001615 if (UNLIKELY(method_tracing_active_)) {
Ian Rogers776ac1f2012-04-13 23:36:36 -07001616#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers57b86d42012-03-27 16:05:41 -07001617 if (IsTraceExitPc(DemanglePc(pc))) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001618 pc = ManglePc(TraceMethodUnwindFromCode(Thread::Current()));
1619 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001620#else
1621 UNIMPLEMENTED(FATAL);
1622#endif
Ian Rogers67375ac2011-09-14 00:55:44 -07001623 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001624 dex_pc = method->ToDexPC(pc);
1625 }
1626 if (dex_pc != DexFile::kDexNoIndex) {
1627 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1628 if (found_dex_pc != DexFile::kDexNoIndex) {
1629 handler_pc_ = method->ToNativePC(found_dex_pc);
1630 handler_frame_ = fr;
Ian Rogers57b86d42012-03-27 16:05:41 -07001631 return false; // End stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001632 }
1633 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001634#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes530fa002012-03-12 11:44:49 -07001635 // Caller may be handler, fill in callee saves in context
1636 long_jump_context_->FillCalleeSaves(fr);
Ian Rogers776ac1f2012-04-13 23:36:36 -07001637#endif
Ian Rogers57b86d42012-03-27 16:05:41 -07001638 return true; // Continue stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001639 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001640
Ian Rogersbdb03912011-09-14 00:55:44 -07001641 // The type of the exception catch block to find
1642 Class* to_find_;
1643 // Frame with found handler or last frame if no handler found
1644 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001645 // PC to branch to for the handler
1646 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001647 // Context that will be the target of the long jump
1648 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001649 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1650 uint32_t native_method_count_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001651 // Is method tracing active?
1652 const bool method_tracing_active_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001653};
1654
Ian Rogersff1ed472011-09-20 13:46:24 -07001655void Thread::DeliverException() {
Ian Rogers776ac1f2012-04-13 23:36:36 -07001656#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers28ad40d2011-10-27 15:19:26 -07001657 const bool kDebugExceptionDelivery = false;
Elliott Hughesd07986f2011-12-06 18:27:45 -08001658 Throwable* exception = GetException(); // Get exception from thread
Ian Rogersff1ed472011-09-20 13:46:24 -07001659 CHECK(exception != NULL);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001660 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001661 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001662 ClearException();
1663 if (kDebugExceptionDelivery) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001664 String* msg = exception->GetDetailMessage();
1665 std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1666 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
1667 << ": " << str_msg << std::endl);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001668 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001669
1670 Context* long_jump_context = GetLongJumpContext();
1671 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Elliott Hughes530fa002012-03-12 11:44:49 -07001672 WalkStack(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001673
Elliott Hughesd07986f2011-12-06 18:27:45 -08001674 Method** sp;
1675 uintptr_t throw_native_pc;
1676 Method* throw_method = GetCurrentMethod(&throw_native_pc, &sp);
1677 uintptr_t catch_native_pc = catch_finder.handler_pc_;
1678 Method* catch_method = catch_finder.handler_frame_.GetMethod();
1679 Dbg::PostException(sp, throw_method, throw_native_pc, catch_method, catch_native_pc, exception);
1680
Ian Rogers28ad40d2011-10-27 15:19:26 -07001681 if (kDebugExceptionDelivery) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001682 if (catch_method == NULL) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001683 LOG(INFO) << "Handler is upcall";
1684 } else {
1685 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1686 const DexFile& dex_file =
Elliott Hughesd07986f2011-12-06 18:27:45 -08001687 class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1688 int line_number = dex_file.GetLineNumFromPC(catch_method,
1689 catch_method->ToDexPC(catch_finder.handler_pc_));
1690 LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
Ian Rogers28ad40d2011-10-27 15:19:26 -07001691 }
1692 }
1693 SetException(exception);
Ian Rogers9a8a8882012-03-08 02:30:55 -08001694 CHECK_NE(catch_native_pc, 0u);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001695 long_jump_context->SetSP(reinterpret_cast<uintptr_t>(catch_finder.handler_frame_.GetSP()));
Ian Rogers9a8a8882012-03-08 02:30:55 -08001696 long_jump_context->SetPC(catch_native_pc);
Elliott Hughes9c750f92012-04-05 12:07:59 -07001697 long_jump_context->SmashCallerSaves();
Ian Rogersbdb03912011-09-14 00:55:44 -07001698 long_jump_context->DoLongJump();
Ian Rogers776ac1f2012-04-13 23:36:36 -07001699#endif
Ian Rogers9a8a8882012-03-08 02:30:55 -08001700 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001701}
1702
Ian Rogersbdb03912011-09-14 00:55:44 -07001703Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001704 Context* result = long_jump_context_;
Ian Rogers776ac1f2012-04-13 23:36:36 -07001705#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersbdb03912011-09-14 00:55:44 -07001706 if (result == NULL) {
1707 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001708 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001709 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001710#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001711 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001712}
1713
TDYa127ee0d3fb2012-04-01 14:55:33 -07001714#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughesd07986f2011-12-06 18:27:45 -08001715Method* Thread::GetCurrentMethod(uintptr_t* pc, Method*** sp) const {
1716 Frame f = top_of_managed_stack_;
1717 Method* m = f.GetMethod();
Elliott Hughes8be2d402012-02-23 14:22:41 -08001718 uintptr_t native_pc = top_of_managed_stack_pc_;
1719
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001720 // We use JNI internally for exception throwing, so it's possible to arrive
1721 // here via a "FromCode" function, in which case there's a synthetic
1722 // callee-save method at the top of the stack. These shouldn't be user-visible,
1723 // so if we find one, skip it and return the compiled method underneath.
jeffhao33dc7712011-11-09 17:54:24 -08001724 if (m != NULL && m->IsCalleeSaveMethod()) {
Elliott Hughes8be2d402012-02-23 14:22:41 -08001725 native_pc = f.GetReturnPC();
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001726 f.Next();
1727 m = f.GetMethod();
1728 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001729 if (pc != NULL) {
Elliott Hughes8be2d402012-02-23 14:22:41 -08001730 *pc = (m != NULL) ? ManglePc(native_pc) : 0;
jeffhao33dc7712011-11-09 17:54:24 -08001731 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001732 if (sp != NULL) {
1733 *sp = f.GetSP();
1734 }
1735 return m;
jeffhao33dc7712011-11-09 17:54:24 -08001736}
TDYa127ee0d3fb2012-04-01 14:55:33 -07001737#else
1738Method* Thread::GetCurrentMethod(uintptr_t*, Method***) const {
1739 ShadowFrame* frame = top_shadow_frame_;
TDYa12720efe542012-04-03 17:40:49 -07001740 if (frame == NULL) {
1741 return NULL;
TDYa127ee0d3fb2012-04-01 14:55:33 -07001742 }
1743 return frame->GetMethod();
1744}
1745#endif
jeffhao33dc7712011-11-09 17:54:24 -08001746
Elliott Hughes5f791332011-09-15 17:45:30 -07001747bool Thread::HoldsLock(Object* object) {
1748 if (object == NULL) {
1749 return false;
1750 }
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07001751 return object->GetThinLockId() == thin_lock_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001752}
1753
Elliott Hughes038a8062011-09-18 14:12:41 -07001754bool Thread::IsDaemon() {
1755 return gThread_daemon->GetBoolean(peer_);
1756}
1757
Ian Rogers776ac1f2012-04-13 23:36:36 -07001758#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersd6b1f612011-09-27 13:38:14 -07001759class ReferenceMapVisitor : public Thread::StackVisitor {
1760 public:
1761 ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1762 context_(context), root_visitor_(root_visitor), arg_(arg) {
1763 }
1764
Elliott Hughes530fa002012-03-12 11:44:49 -07001765 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001766 Method* m = frame.GetMethod();
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001767 if (false) {
jeffhao25045522012-03-13 19:34:37 -07001768 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m)
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001769 << StringPrintf("@ PC:%04x", m->ToDexPC(pc));
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001770 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001771 // Process register map (which native and callee save methods don't have)
Ian Rogers3891c772011-12-06 15:38:28 -08001772 if (!m->IsNative() && !m->IsCalleeSaveMethod() && !m->IsProxyMethod()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001773 CHECK(m->GetGcMap() != NULL) << PrettyMethod(m);
1774 CHECK_NE(0U, m->GetGcMapLength()) << PrettyMethod(m);
1775 verifier::PcToReferenceMap map(m->GetGcMap(), m->GetGcMapLength());
Ian Rogersd81871c2011-10-03 13:57:23 -07001776 const uint8_t* reg_bitmap = map.FindBitMap(m->ToDexPC(pc));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001777 CHECK(reg_bitmap != NULL);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001778 const VmapTable vmap_table(m->GetVmapTableRaw());
Elliott Hughes11d1b0c2012-01-23 16:57:47 -08001779 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001780 DCHECK(code_item != NULL); // can't be NULL or how would we compile its instructions?
1781 uint32_t core_spills = m->GetCoreSpillMask();
1782 uint32_t fp_spills = m->GetFpSpillMask();
1783 size_t frame_size = m->GetFrameSizeInBytes();
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001784 // For all dex registers in the bitmap
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001785 size_t num_regs = std::min(map.RegWidth() * 8,
1786 static_cast<size_t>(code_item->registers_size_));
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001787 for (size_t reg = 0; reg < num_regs; ++reg) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001788 // Does this register hold a reference?
1789 if (TestBitmap(reg, reg_bitmap)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001790 uint32_t vmap_offset;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001791 Object* ref;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001792 if (vmap_table.IsInContext(reg, vmap_offset)) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001793 // Compute the register we need to load from the context
1794 uint32_t spill_mask = m->GetCoreSpillMask();
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001795 CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
Ian Rogersf57c47c2011-10-06 00:06:17 -07001796 uint32_t matches = 0;
1797 uint32_t spill_shifts = 0;
1798 while (matches != (vmap_offset + 1)) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001799 DCHECK_NE(spill_mask, 0u);
Ian Rogersf57c47c2011-10-06 00:06:17 -07001800 matches += spill_mask & 1; // Add 1 if the low bit is set
1801 spill_mask >>= 1;
1802 spill_shifts++;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001803 }
Ian Rogersf57c47c2011-10-06 00:06:17 -07001804 spill_shifts--; // wind back one as we want the last match
1805 ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001806 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001807 ref = reinterpret_cast<Object*>(frame.GetVReg(code_item, core_spills, fp_spills,
1808 frame_size, reg));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001809 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001810 if (ref != NULL) {
1811 root_visitor_(ref, arg_);
1812 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001813 }
1814 }
1815 }
1816 context_->FillCalleeSaves(frame);
Elliott Hughes530fa002012-03-12 11:44:49 -07001817 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001818 }
1819
1820 private:
1821 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1822 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1823 }
1824
1825 // Context used to build up picture of callee saves
1826 Context* context_;
1827 // Call-back when we visit a root
1828 Heap::RootVisitor* root_visitor_;
1829 // Argument to call-back
1830 void* arg_;
1831};
Ian Rogers776ac1f2012-04-13 23:36:36 -07001832#endif
Ian Rogersd6b1f612011-09-27 13:38:14 -07001833
1834void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001835 if (exception_ != NULL) {
1836 visitor(exception_, arg);
1837 }
1838 if (peer_ != NULL) {
1839 visitor(peer_, arg);
1840 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001841 if (pre_allocated_OutOfMemoryError_ != NULL) {
1842 visitor(pre_allocated_OutOfMemoryError_, arg);
1843 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001844 if (class_loader_override_ != NULL) {
1845 visitor(class_loader_override_, arg);
1846 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001847 jni_env_->locals.VisitRoots(visitor, arg);
1848 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001849
1850 SirtVisitRoots(visitor, arg);
Logan Chienf7ad17e2012-03-15 03:10:03 +08001851 ShadowFrameVisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001852
TDYa127540a5b72012-04-03 18:56:08 -07001853#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersd6b1f612011-09-27 13:38:14 -07001854 // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1855 // delivery.
1856 Context* context = GetLongJumpContext();
1857 // Visit roots on this thread's stack
1858 ReferenceMapVisitor mapper(context, visitor, arg);
1859 WalkStack(&mapper);
TDYa127540a5b72012-04-03 18:56:08 -07001860#endif
Elliott Hughes410c0c82011-09-01 17:58:25 -07001861}
1862
jeffhao25045522012-03-13 19:34:37 -07001863#if VERIFY_OBJECT_ENABLED
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001864static void VerifyObject(const Object* obj, void*) {
jeffhao25045522012-03-13 19:34:37 -07001865 Runtime::Current()->GetHeap()->VerifyObject(obj);
1866}
1867
1868void Thread::VerifyStack() {
TDYa127540a5b72012-04-03 18:56:08 -07001869#if !defined(ART_USE_LLVM_COMPILER)
jeffhaoe66ac792012-03-19 16:08:46 -07001870 UniquePtr<Context> context(Context::Create());
1871 ReferenceMapVisitor mapper(context.get(), VerifyObject, NULL);
jeffhao25045522012-03-13 19:34:37 -07001872 WalkStack(&mapper);
TDYa127540a5b72012-04-03 18:56:08 -07001873#endif
jeffhao25045522012-03-13 19:34:37 -07001874}
1875#endif
1876
Elliott Hughes330304d2011-08-12 14:28:05 -07001877std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Elliott Hughes899e7892012-01-24 14:57:32 -08001878 thread.Dump(os, false);
Elliott Hughes330304d2011-08-12 14:28:05 -07001879 return os;
1880}
1881
Elliott Hughesa4060e52012-03-02 16:51:35 -08001882void Thread::CheckSafeToLockOrUnlock(MutexRank rank, bool is_locking) {
Elliott Hughes17057b12012-04-03 10:22:39 -07001883 if (this == NULL) {
1884 CHECK(Runtime::Current()->IsShuttingDown());
1885 return;
1886 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001887 if (is_locking) {
1888 if (held_mutexes_[rank] == 0) {
1889 bool bad_mutexes_held = false;
1890 for (int i = kMaxMutexRank; i > rank; --i) {
1891 if (held_mutexes_[i] != 0) {
1892 LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while " << (is_locking ? "locking" : "unlocking") << " " << rank;
1893 bad_mutexes_held = true;
1894 }
1895 }
Elliott Hughesb5db3bb2012-03-29 20:00:31 -07001896 CHECK(!bad_mutexes_held) << rank;
Elliott Hughesffb465f2012-03-01 18:46:05 -08001897 }
1898 ++held_mutexes_[rank];
1899 } else {
Elliott Hughesb5db3bb2012-03-29 20:00:31 -07001900 CHECK_GT(held_mutexes_[rank], 0U) << rank;
Elliott Hughesffb465f2012-03-01 18:46:05 -08001901 --held_mutexes_[rank];
1902 }
1903}
1904
Elliott Hughesa4060e52012-03-02 16:51:35 -08001905void Thread::CheckSafeToWait(MutexRank rank) {
Elliott Hughes17057b12012-04-03 10:22:39 -07001906 if (this == NULL) {
1907 CHECK(Runtime::Current()->IsShuttingDown());
1908 return;
1909 }
Elliott Hughesa4060e52012-03-02 16:51:35 -08001910 bool bad_mutexes_held = false;
1911 for (int i = kMaxMutexRank; i >= 0; --i) {
1912 if (i != rank && held_mutexes_[i] != 0) {
1913 LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while doing condition variable wait on " << rank;
1914 bad_mutexes_held = true;
1915 }
1916 }
1917 if (held_mutexes_[rank] == 0) {
1918 LOG(ERROR) << "*not* holding " << rank << " while doing condition variable wait on it";
1919 bad_mutexes_held = true;
1920 }
1921 CHECK(!bad_mutexes_held);
1922}
1923
Elliott Hughes8daa0922011-09-11 13:46:25 -07001924} // namespace art