blob: dc663190f17facfa9367242333f133aa140e233c [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 Rogers776ac1f2012-04-13 23:36:36 -070037#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers57b86d42012-03-27 16:05:41 -070038#include "oat/runtime/context.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070039#endif
Elliott Hughesa5b897e2011-08-16 11:33:06 -070040#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080041#include "object_utils.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -050042#include "reflection.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070043#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070044#include "runtime_support.h"
Elliott Hughes726079d2011-10-07 18:43:44 -070045#include "ScopedLocalRef.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070046#include "scoped_jni_thread_state.h"
Logan Chienf7ad17e2012-03-15 03:10:03 +080047#include "shadow_frame.h"
Ian Rogers30fab402012-01-23 15:43:46 -080048#include "space.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070049#include "stack.h"
50#include "stack_indirect_reference_table.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070051#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070052#include "utils.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070053#include "verifier/gc_map.h"
Carl Shapirob5573532011-07-12 18:22:59 -070054
55namespace art {
56
57pthread_key_t Thread::pthread_key_self_;
58
Elliott Hughes462c9442012-03-23 18:47:50 -070059static Class* gThreadGroup = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -070060static Class* gThreadLock = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070061static Field* gThread_daemon = NULL;
62static Field* gThread_group = NULL;
63static Field* gThread_lock = NULL;
64static Field* gThread_name = NULL;
65static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070066static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070067static Field* gThread_vmData = NULL;
Elliott Hughes462c9442012-03-23 18:47:50 -070068static Field* gThreadGroup_mMain = NULL;
69static Field* gThreadGroup_mSystem = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070070static Field* gThreadGroup_name = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -070071static Field* gThreadLock_thread = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070072static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070073static Method* gThreadGroup_removeThread = NULL;
74static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070075
Ian Rogers5d76c432011-10-31 21:42:49 -070076void Thread::InitCardTable() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080077 card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -070078}
79
buzbee3ea4ec52011-08-22 17:37:19 -070080void Thread::InitFunctionPointers() {
Ian Rogers776ac1f2012-04-13 23:36:36 -070081#if defined(ART_USE_LLVM_COMPILER)
82 memset(&entrypoints_, 0, sizeof(entrypoints_));
83#else
Ian Rogers57b86d42012-03-27 16:05:41 -070084 InitEntryPoints(&entrypoints_);
Ian Rogers776ac1f2012-04-13 23:36:36 -070085#endif
Elliott Hughesc0f09332012-03-26 13:27:06 -070086}
87
88void Thread::SetDebuggerUpdatesEnabled(bool enabled) {
89 LOG(INFO) << "Turning debugger updates " << (enabled ? "on" : "off") << " for " << *this;
Ian Rogers776ac1f2012-04-13 23:36:36 -070090#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers57b86d42012-03-27 16:05:41 -070091 ChangeDebuggerEntryPoint(&entrypoints_, enabled);
Ian Rogers776ac1f2012-04-13 23:36:36 -070092#else
93 UNIMPLEMENTED(FATAL);
94#endif
buzbee3ea4ec52011-08-22 17:37:19 -070095}
96
Brian Carlstromcaabb1b2011-10-11 18:09:13 -070097void Thread::InitTid() {
98 tid_ = ::art::GetTid();
99}
100
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700101void Thread::InitAfterFork() {
102 InitTid();
Elliott Hughes3147a232011-10-12 15:55:07 -0700103#if defined(__BIONIC__)
104 // Work around a bionic bug.
105 struct bionic_pthread_internal_t {
106 void* next;
107 void** pref;
108 pthread_attr_t attr;
109 pid_t kernel_id;
110 // et cetera. we just need 'kernel_id' so we can stop here.
111 };
112 reinterpret_cast<bionic_pthread_internal_t*>(pthread_self())->kernel_id = tid_;
113#endif
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700114}
115
Brian Carlstrom78128a62011-09-15 17:21:19 -0700116void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700117 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes462c9442012-03-23 18:47:50 -0700118 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700119
Elliott Hughes93e74e82011-09-13 11:07:03 -0700120 // Wait until it's safe to start running code. (There may have been a suspend-all
121 // in progress while we were starting up.)
Elliott Hughes462c9442012-03-23 18:47:50 -0700122 Runtime* runtime = Runtime::Current();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700123 runtime->GetThreadList()->WaitForGo();
124
Elliott Hughes47179f72011-10-27 16:44:39 -0700125 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700126 CHECK_EQ(self->GetState(), kRunnable);
Elliott Hughes899e7892012-01-24 14:57:32 -0800127 SirtRef<String> thread_name(self->GetThreadName());
128 self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
Elliott Hughes47179f72011-10-27 16:44:39 -0700129 }
130
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700131 Dbg::PostThreadStart(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700132
133 // Invoke the 'run' method of our java.lang.Thread.
134 CHECK(self->peer_ != NULL);
135 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700136 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700137 m->Invoke(self, receiver, NULL, NULL);
138
139 // Detach.
140 runtime->GetThreadList()->Unregister();
141
Carl Shapirob5573532011-07-12 18:22:59 -0700142 return NULL;
143}
144
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700145static void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700146 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700147}
148
Elliott Hughes761928d2011-11-16 18:33:03 -0800149Thread* Thread::FromManagedThread(Object* thread_peer) {
150 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread_peer)));
151}
152
Elliott Hughes01158d72011-09-19 19:47:10 -0700153Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
Elliott Hughes761928d2011-11-16 18:33:03 -0800154 return FromManagedThread(Decode<Object*>(env, java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700155}
156
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700157static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700158 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700159 if (stack_size == 0) {
160 stack_size = Runtime::Current()->GetDefaultStackSize();
161 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700162
Brian Carlstrom6414a972012-04-14 14:20:04 -0700163 // Dalvik used the bionic pthread default stack size for native threads,
164 // so include that here to support apps that expect large native stacks.
165 stack_size += 1 * MB;
166
167
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700168 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
169 if (stack_size < PTHREAD_STACK_MIN) {
170 stack_size = PTHREAD_STACK_MIN;
171 }
172
173 // It's likely that callers are trying to ensure they have at least a certain amount of
174 // stack space, so we should add our reserved space on top of what they requested, rather
175 // than implicitly take it away from them.
176 stack_size += Thread::kStackOverflowReservedBytes;
177
178 // Some systems require the stack size to be a multiple of the system page size, so round up.
179 stack_size = RoundUp(stack_size, kPageSize);
180
181 return stack_size;
182}
183
184void Thread::Create(Object* peer, size_t stack_size) {
185 CHECK(peer != NULL);
186
187 stack_size = FixStackSize(stack_size);
188
Elliott Hughes93e74e82011-09-13 11:07:03 -0700189 Thread* native_thread = new Thread;
190 native_thread->peer_ = peer;
191
192 // Thread.start is synchronized, so we know that vmData is 0,
193 // and know that we're not racing to assign it.
194 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700195
Elliott Hughes47179f72011-10-27 16:44:39 -0700196 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700197 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Elliott Hughes47179f72011-10-27 16:44:39 -0700198 pthread_t new_pthread;
199 pthread_attr_t attr;
200 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
201 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
202 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
203 CHECK_PTHREAD_CALL(pthread_create, (&new_pthread, &attr, Thread::CreateCallback, native_thread), "new thread");
204 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
205 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700206
207 // Let the child know when it's safe to start running.
208 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700209}
210
Elliott Hughes462c9442012-03-23 18:47:50 -0700211void Thread::Init() {
212 // This function does all the initialization that must be run by the native thread it applies to.
213 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
214 // we can handshake with the corresponding native thread when it's ready.) Check this native
215 // thread hasn't been through here already...
Elliott Hughescac6cc72011-11-03 20:31:21 -0700216 CHECK(Thread::Current() == NULL);
217
Elliott Hughes93e74e82011-09-13 11:07:03 -0700218 InitCpu();
219 InitFunctionPointers();
Ian Rogers5d76c432011-10-31 21:42:49 -0700220 InitCardTable();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700221
Elliott Hughes462c9442012-03-23 18:47:50 -0700222 Runtime* runtime = Runtime::Current();
223 CHECK(runtime != NULL);
224
225 thin_lock_id_ = runtime->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700226
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700227 InitTid();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700228 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700229
Elliott Hughes3147a232011-10-12 15:55:07 -0700230 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700231
Elliott Hughes93e74e82011-09-13 11:07:03 -0700232 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700233
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700234 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700235}
236
Elliott Hughes462c9442012-03-23 18:47:50 -0700237Thread* Thread::Attach(const char* thread_name, bool as_daemon, Object* thread_group) {
Elliott Hughescac6cc72011-11-03 20:31:21 -0700238 Thread* self = new Thread;
Elliott Hughes462c9442012-03-23 18:47:50 -0700239 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700240
Elliott Hughes34e06962012-04-09 13:55:55 -0700241 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700242
Elliott Hughescac6cc72011-11-03 20:31:21 -0700243 // If we're the main thread, ClassLinker won't be created until after we're attached,
244 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800245 // In the compiler, all threads need this hack, because no-one's going to be getting
246 // a native peer!
247 if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700248 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800249 } else {
250 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Elliott Hughes22869a92012-03-27 14:08:24 -0700251 if (thread_name != NULL) {
252 self->name_->assign(thread_name);
253 ::art::SetThreadName(thread_name);
254 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700255 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700256
257 self->GetJniEnv()->locals.AssertEmpty();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700258 return self;
259}
260
Elliott Hughes462c9442012-03-23 18:47:50 -0700261Object* Thread::GetMainThreadGroup() {
Ian Rogers0045a292012-03-31 21:08:41 -0700262 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(gThreadGroup, true, true)) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700263 return NULL;
264 }
265 return gThreadGroup_mMain->GetObject(NULL);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700266}
267
Elliott Hughes462c9442012-03-23 18:47:50 -0700268Object* Thread::GetSystemThreadGroup() {
Ian Rogers0045a292012-03-31 21:08:41 -0700269 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(gThreadGroup, true, true)) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700270 return NULL;
271 }
272 return gThreadGroup_mSystem->GetObject(NULL);
273}
274
275void Thread::CreatePeer(const char* name, bool as_daemon, Object* thread_group) {
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500276 CHECK(Runtime::Current()->IsStarted());
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700277 JNIEnv* env = jni_env_;
278
Elliott Hughes462c9442012-03-23 18:47:50 -0700279 if (thread_group == NULL) {
280 thread_group = Thread::GetMainThreadGroup();
281 }
282 ScopedLocalRef<jobject> java_thread_group(env, AddLocalReference<jobject>(env, thread_group));
Elliott Hughes726079d2011-10-07 18:43:44 -0700283 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Elliott Hughes8daa0922011-09-11 13:46:25 -0700284 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700285 jboolean thread_is_daemon = as_daemon;
286
Elliott Hughes726079d2011-10-07 18:43:44 -0700287 ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/Thread"));
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700288 ScopedLocalRef<jobject> peer(env, env->AllocObject(c.get()));
Elliott Hughes726079d2011-10-07 18:43:44 -0700289 peer_ = DecodeJObject(peer.get());
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700290 if (peer_ == NULL) {
291 CHECK(IsExceptionPending());
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700292 return;
293 }
294 jmethodID mid = env->GetMethodID(c.get(), "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes462c9442012-03-23 18:47:50 -0700295 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 -0500296 CHECK(!IsExceptionPending()) << " " << PrettyTypeOf(GetException());
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700297 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700298
Elliott Hughes899e7892012-01-24 14:57:32 -0800299 SirtRef<String> peer_thread_name(GetThreadName());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700300 if (peer_thread_name.get() == NULL) {
301 // The Thread constructor should have set the Thread.name to a
302 // non-null value. However, because we can run without code
303 // available (in the compiler, in tests), we manually assign the
304 // fields the constructor should have set.
305 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
Elliott Hughes462c9442012-03-23 18:47:50 -0700306 gThread_group->SetObject(peer_, thread_group);
Brian Carlstrom00fae582011-10-28 01:16:28 -0700307 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name.get()));
308 gThread_priority->SetInt(peer_, thread_priority);
Elliott Hughes899e7892012-01-24 14:57:32 -0800309 peer_thread_name.reset(GetThreadName());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700310 }
311 // thread_name may have been null, so don't trust this to be non-null
312 if (peer_thread_name.get() != NULL) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800313 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700314 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700315
316 // Pre-allocate an OutOfMemoryError for the double-OOME case.
317 ThrowNewException("Ljava/lang/OutOfMemoryError;",
318 "OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available");
319 ScopedLocalRef<jthrowable> exception(env, env->ExceptionOccurred());
320 env->ExceptionClear();
321 pre_allocated_OutOfMemoryError_ = Decode<Throwable*>(env, exception.get());
Carl Shapiro61e019d2011-07-14 16:53:09 -0700322}
323
Elliott Hughes899e7892012-01-24 14:57:32 -0800324void Thread::SetThreadName(const char* name) {
325 name_->assign(name);
326 ::art::SetThreadName(name);
327 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
328}
329
Elliott Hughesbe759c62011-09-08 19:38:21 -0700330void Thread::InitStackHwm() {
Elliott Hughes215f3142012-01-19 00:22:47 -0800331#if defined(__APPLE__)
Elliott Hughes6cc332e2012-01-20 22:59:20 -0800332 // Only needed to run code. Try implementing this with pthread_get_stacksize_np and pthread_get_stackaddr_np.
333 UNIMPLEMENTED(WARNING);
Elliott Hughes215f3142012-01-19 00:22:47 -0800334#else
Elliott Hughesbe759c62011-09-08 19:38:21 -0700335 pthread_attr_t attributes;
Elliott Hughes3147a232011-10-12 15:55:07 -0700336 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700337
Ian Rogers932746a2011-09-22 18:57:50 -0700338 void* temp_stack_base;
339 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
340 __FUNCTION__);
Ian Rogers30fab402012-01-23 15:43:46 -0800341 stack_begin_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700342
Ian Rogers932746a2011-09-22 18:57:50 -0700343 if (stack_size_ <= kStackOverflowReservedBytes) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800344 LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700345 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700346
Ian Rogers932746a2011-09-22 18:57:50 -0700347 // Set stack_end_ to the bottom of the stack saving space of stack overflows
348 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700349
350 // Sanity check.
351 int stack_variable;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700352 CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
Elliott Hughesbe759c62011-09-08 19:38:21 -0700353
Elliott Hughes8d768a92011-09-14 16:35:25 -0700354 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes215f3142012-01-19 00:22:47 -0800355#endif
Elliott Hughesbe759c62011-09-08 19:38:21 -0700356}
357
Elliott Hughes899e7892012-01-24 14:57:32 -0800358void Thread::Dump(std::ostream& os, bool full) const {
359 if (full) {
360 DumpState(os);
361 DumpStack(os);
362 } else {
363 os << "Thread[";
364 if (GetThinLockId() != 0) {
365 // If we're in kStarting, we won't have a thin lock id or tid yet.
366 os << GetThinLockId()
367 << ",tid=" << GetTid() << ',';
368 }
369 os << GetState()
370 << ",Thread*=" << this
Elliott Hughesffb465f2012-03-01 18:46:05 -0800371 << ",peer=" << peer_
Elliott Hughes899e7892012-01-24 14:57:32 -0800372 << ",\"" << *name_ << "\""
373 << "]";
Elliott Hughese0918552011-10-28 17:18:29 -0700374 }
Elliott Hughesa0957642011-09-02 14:27:33 -0700375}
376
Elliott Hughes899e7892012-01-24 14:57:32 -0800377String* Thread::GetThreadName() const {
Elliott Hughesfc861622011-10-17 17:57:47 -0700378 return (peer_ != NULL) ? reinterpret_cast<String*>(gThread_name->GetObject(peer_)) : NULL;
379}
380
Elliott Hughesffb465f2012-03-01 18:46:05 -0800381void Thread::GetThreadName(std::string& name) const {
382 name.assign(*name_);
383}
384
Elliott Hughesd92bec42011-09-02 17:04:36 -0700385void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700386 std::string group_name;
387 int priority;
388 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700389
Elliott Hughesd369bb72011-09-12 14:41:14 -0700390 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700391 priority = gThread_priority->GetInt(peer_);
392 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700393
Elliott Hughesa2155262011-11-16 16:26:58 -0800394 Object* thread_group = GetThreadGroup();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700395 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700396 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700397 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
398 }
399 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700400 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700401 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700402
403 int policy;
404 sched_param sp;
Elliott Hughes3147a232011-10-12 15:55:07 -0700405 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_self(), &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700406
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700407 std::string scheduler_group_name(GetSchedulerGroupName(GetTid()));
408 if (scheduler_group_name.empty()) {
409 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700410 }
411
Elliott Hughes899e7892012-01-24 14:57:32 -0800412 os << '"' << *name_ << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700413 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700414 os << " daemon";
415 }
416 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700417 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700418 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700419
Elliott Hughesd92bec42011-09-02 17:04:36 -0700420 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700421 << " sCount=" << suspend_count_
Elliott Hughes234ab152011-10-26 14:02:26 -0700422 << " dsCount=" << debug_suspend_count_
Elliott Hughesdcc24742011-09-07 14:02:44 -0700423 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700424 << " self=" << reinterpret_cast<const void*>(this) << "\n";
425 os << " | sysTid=" << GetTid()
426 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
427 << " sched=" << policy << "/" << sp.sched_priority
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700428 << " cgrp=" << scheduler_group_name
Elliott Hughes3147a232011-10-12 15:55:07 -0700429 << " handle=" << pthread_self() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700430
431 // Grab the scheduler stats for this thread.
432 std::string scheduler_stats;
433 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
434 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
435 } else {
436 scheduler_stats = "0 0 0";
437 }
438
439 int utime = 0;
440 int stime = 0;
441 int task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700442 GetTaskStats(GetTid(), utime, stime, task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700443
444 os << " | schedstat=( " << scheduler_stats << " )"
445 << " utm=" << utime
446 << " stm=" << stime
447 << " core=" << task_cpu
448 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
449}
450
TDYa127ee0d3fb2012-04-01 14:55:33 -0700451#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersb04f69f2011-10-17 00:40:54 -0700452void Thread::PushNativeToManagedRecord(NativeToManagedRecord* record) {
453 Method **sp = top_of_managed_stack_.GetSP();
454#ifndef NDEBUG
455 if (sp != NULL) {
456 Method* m = *sp;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800457 Runtime::Current()->GetHeap()->VerifyObject(m);
Ian Rogersb04f69f2011-10-17 00:40:54 -0700458 DCHECK((m == NULL) || m->IsMethod());
459 }
460#endif
461 record->last_top_of_managed_stack_ = reinterpret_cast<void*>(sp);
462 record->last_top_of_managed_stack_pc_ = top_of_managed_stack_pc_;
463 record->link_ = native_to_managed_record_;
464 native_to_managed_record_ = record;
465 top_of_managed_stack_.SetSP(NULL);
466}
TDYa127ee0d3fb2012-04-01 14:55:33 -0700467#else
468void Thread::PushNativeToManagedRecord(NativeToManagedRecord*) {
469 LOG(FATAL) << "Called non-LLVM method with LLVM";
470}
471#endif
Ian Rogersb04f69f2011-10-17 00:40:54 -0700472
TDYa127ee0d3fb2012-04-01 14:55:33 -0700473#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersb04f69f2011-10-17 00:40:54 -0700474void Thread::PopNativeToManagedRecord(const NativeToManagedRecord& record) {
475 native_to_managed_record_ = record.link_;
476 top_of_managed_stack_.SetSP(reinterpret_cast<Method**>(record.last_top_of_managed_stack_));
477 top_of_managed_stack_pc_ = record.last_top_of_managed_stack_pc_;
478}
TDYa127ee0d3fb2012-04-01 14:55:33 -0700479#else
480void Thread::PopNativeToManagedRecord(const NativeToManagedRecord&) {
481 LOG(FATAL) << "Called non-LLVM method with LLVM";
482}
483#endif
Ian Rogersb04f69f2011-10-17 00:40:54 -0700484
Elliott Hughesd369bb72011-09-12 14:41:14 -0700485struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700486 StackDumpVisitor(std::ostream& os, const Thread* thread)
Ian Rogers28ad40d2011-10-27 15:19:26 -0700487 : last_method(NULL), last_line_number(0), repetition_count(0), os(os), thread(thread),
488 frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700489 }
490
Ian Rogersbdb03912011-09-14 00:55:44 -0700491 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700492 }
493
Elliott Hughes530fa002012-03-12 11:44:49 -0700494 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700495 if (!frame.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700496 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700497 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700498 const int kMaxRepetition = 3;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700499 Method* m = frame.GetMethod();
TDYa127540a5b72012-04-03 18:56:08 -0700500#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700501 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700502 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersb861dc02011-11-14 17:00:05 -0800503 const DexCache* dex_cache = c->GetDexCache();
504 int line_number = -1;
505 if (dex_cache != NULL) { // be tolerant of bad input
506 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
507 line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
508 }
TDYa127540a5b72012-04-03 18:56:08 -0700509#else
510 // Compiler_LLVM stores line_number in the ShadowFrame, and passes it to visitor.
511 int line_number = static_cast<int>(pc);
512#endif
Ian Rogers28ad40d2011-10-27 15:19:26 -0700513 if (line_number == last_line_number && last_method == m) {
514 repetition_count++;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700515 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700516 if (repetition_count >= kMaxRepetition) {
517 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
518 }
519 repetition_count = 0;
520 last_line_number = line_number;
521 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700522 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700523 if (repetition_count < kMaxRepetition) {
524 os << " at " << PrettyMethod(m, false);
525 if (m->IsNative()) {
526 os << "(Native method)";
527 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800528 mh.ChangeMethod(m);
529 const char* source_file(mh.GetDeclaringClassSourceFile());
530 os << "(" << (source_file != NULL ? source_file : "unavailable")
Ian Rogers28ad40d2011-10-27 15:19:26 -0700531 << ":" << line_number << ")";
532 }
533 os << "\n";
534 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700535
536 if (frame_count++ == 0) {
537 Monitor::DescribeWait(os, thread);
538 }
Elliott Hughes530fa002012-03-12 11:44:49 -0700539 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700540 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800541 MethodHelper mh;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700542 Method* last_method;
543 int last_line_number;
544 int repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700545 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700546 const Thread* thread;
547 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700548};
549
Elliott Hughesd92bec42011-09-02 17:04:36 -0700550void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800551 // If we're currently in native code, dump that stack before dumping the managed stack.
Elliott Hughes34e06962012-04-09 13:55:55 -0700552 if (GetState() == kNative || GetState() == kVmWait) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800553 DumpNativeStack(os);
554 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700555 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700556 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700557}
558
Elliott Hughes34e06962012-04-09 13:55:55 -0700559void Thread::SetStateWithoutSuspendCheck(ThreadState new_state) {
Elliott Hughesa4060e52012-03-02 16:51:35 -0800560 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
561 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
562 android_atomic_release_store(new_state, addr);
563}
564
Elliott Hughes34e06962012-04-09 13:55:55 -0700565ThreadState Thread::SetState(ThreadState new_state) {
566 ThreadState old_state = state_;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700567 if (old_state == new_state) {
568 return old_state;
569 }
570
571 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
572 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
573
Elliott Hughes34e06962012-04-09 13:55:55 -0700574 if (new_state == kRunnable) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700575 /*
Elliott Hughes34e06962012-04-09 13:55:55 -0700576 * Change our status to kRunnable. The transition requires
Elliott Hughes81ff3182012-03-23 20:35:56 -0700577 * that we check for pending suspension, because the runtime considers
Elliott Hughes8d768a92011-09-14 16:35:25 -0700578 * us to be "asleep" in all other states, and another thread could
579 * be performing a GC now.
580 *
581 * The order of operations is very significant here. One way to
582 * do this wrong is:
583 *
584 * GCing thread Our thread (in kNative)
585 * ------------ ----------------------
586 * check suspend count (== 0)
587 * SuspendAllThreads()
588 * grab suspend-count lock
589 * increment all suspend counts
590 * release suspend-count lock
591 * check thread state (== kNative)
592 * all are suspended, begin GC
593 * set state to kRunnable
594 * (continue executing)
595 *
596 * We can correct this by grabbing the suspend-count lock and
597 * performing both of our operations (check suspend count, set
598 * state) while holding it, now we need to grab a mutex on every
599 * transition to kRunnable.
600 *
601 * What we do instead is change the order of operations so that
602 * the transition to kRunnable happens first. If we then detect
603 * that the suspend count is nonzero, we switch to kSuspended.
604 *
605 * Appropriate compiler and memory barriers are required to ensure
606 * that the operations are observed in the expected order.
607 *
608 * This does create a small window of opportunity where a GC in
609 * progress could observe what appears to be a running thread (if
610 * it happens to look between when we set to kRunnable and when we
611 * switch to kSuspended). At worst this only affects assertions
612 * and thread logging. (We could work around it with some sort
613 * of intermediate "pre-running" state that is generally treated
614 * as equivalent to running, but that doesn't seem worthwhile.)
615 *
616 * We can also solve this by combining the "status" and "suspend
617 * count" fields into a single 32-bit value. This trades the
618 * store/load barrier on transition to kRunnable for an atomic RMW
619 * op on all transitions and all suspend count updates (also, all
620 * accesses to status or the thread count require bit-fiddling).
621 * It also eliminates the brief transition through kRunnable when
622 * the thread is supposed to be suspended. This is possibly faster
623 * on SMP and slightly more correct, but less convenient.
624 */
625 android_atomic_acquire_store(new_state, addr);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800626 ANNOTATE_IGNORE_READS_BEGIN();
627 int suspend_count = suspend_count_;
628 ANNOTATE_IGNORE_READS_END();
629 if (suspend_count != 0) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700630 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
631 }
632 } else {
633 /*
Elliott Hughes34e06962012-04-09 13:55:55 -0700634 * Not changing to kRunnable. No additional work required.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700635 *
636 * We use a releasing store to ensure that, if we were runnable,
637 * any updates we previously made to objects on the managed heap
638 * will be observed before the state change.
639 */
640 android_atomic_release_store(new_state, addr);
641 }
642
643 return old_state;
644}
645
Elliott Hughes761928d2011-11-16 18:33:03 -0800646bool Thread::IsSuspended() {
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800647 ANNOTATE_IGNORE_READS_BEGIN();
648 int suspend_count = suspend_count_;
649 ANNOTATE_IGNORE_READS_END();
Elliott Hughes34e06962012-04-09 13:55:55 -0700650 return suspend_count != 0 && GetState() != kRunnable;
Elliott Hughes761928d2011-11-16 18:33:03 -0800651}
652
Elliott Hughesff738062012-02-03 15:00:42 -0800653static void ReportThreadSuspendTimeout(Thread* waiting_thread) {
654 Runtime* runtime = Runtime::Current();
655 std::ostringstream ss;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800656 ss << "Thread suspend timeout waiting for thread " << *waiting_thread << "\n";
Elliott Hughesff738062012-02-03 15:00:42 -0800657 runtime->DumpLockHolders(ss);
658 ss << "\n";
659 runtime->GetThreadList()->DumpLocked(ss);
660 LOG(FATAL) << ss.str();
661}
662
Elliott Hughes8d768a92011-09-14 16:35:25 -0700663void Thread::WaitUntilSuspended() {
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800664 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
665
666 useconds_t total_delay = 0;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700667 useconds_t delay = 0;
Elliott Hughes34e06962012-04-09 13:55:55 -0700668 while (GetState() == kRunnable) {
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800669 if (total_delay >= kTimeoutUs) {
Elliott Hughesff738062012-02-03 15:00:42 -0800670 ReportThreadSuspendTimeout(this);
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800671 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700672 useconds_t new_delay = delay * 2;
673 CHECK_GE(new_delay, delay);
674 delay = new_delay;
675 if (delay == 0) {
676 sched_yield();
677 delay = 10000;
678 } else {
679 usleep(delay);
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800680 total_delay += delay;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700681 }
682 }
683}
684
Elliott Hughesbe759c62011-09-08 19:38:21 -0700685void Thread::ThreadExitCallback(void* arg) {
686 Thread* self = reinterpret_cast<Thread*>(arg);
687 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700688}
689
Elliott Hughesbe759c62011-09-08 19:38:21 -0700690void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700691 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700692 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700693
694 // Double-check the TLS slot allocation.
695 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800696 LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700697 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700698}
Carl Shapirob5573532011-07-12 18:22:59 -0700699
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700700// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700701static Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700702 Class* c = class_linker->FindSystemClass(descriptor);
703 CHECK(c != NULL) << descriptor;
704 return c;
705}
706
707// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700708static Field* FindFieldOrDie(Class* c, const char* name, const char* descriptor) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700709 Field* f = c->FindDeclaredInstanceField(name, descriptor);
710 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700711 return f;
712}
713
714// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700715static Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700716 Method* m = c->FindVirtualMethod(name, signature);
717 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
718 return m;
719}
720
Elliott Hughes462c9442012-03-23 18:47:50 -0700721// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700722static Field* FindStaticFieldOrDie(Class* c, const char* name, const char* descriptor) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700723 Field* f = c->FindDeclaredStaticField(name, descriptor);
724 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
725 return f;
726}
727
Elliott Hughes038a8062011-09-18 14:12:41 -0700728void Thread::FinishStartup() {
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500729 CHECK(Runtime::Current()->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700730 Thread* self = Thread::Current();
731
732 // Need to be kRunnable for FindClass
Elliott Hughes34e06962012-04-09 13:55:55 -0700733 ScopedThreadStateChange tsc(self, kRunnable);
Brian Carlstromb82b6872011-10-26 17:18:07 -0700734
Elliott Hughes038a8062011-09-18 14:12:41 -0700735 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
736 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700737
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700738 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700739 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
Elliott Hughes462c9442012-03-23 18:47:50 -0700740 gThreadGroup = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700741 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700742
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700743 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", "Z");
744 gThread_group = FindFieldOrDie(Thread_class, "group", "Ljava/lang/ThreadGroup;");
745 gThread_lock = FindFieldOrDie(Thread_class, "lock", "Ljava/lang/ThreadLock;");
746 gThread_name = FindFieldOrDie(Thread_class, "name", "Ljava/lang/String;");
747 gThread_priority = FindFieldOrDie(Thread_class, "priority", "I");
748 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
749 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", "I");
Elliott Hughes462c9442012-03-23 18:47:50 -0700750 gThreadGroup_name = FindFieldOrDie(gThreadGroup, "name", "Ljava/lang/String;");
751 gThreadGroup_mMain = FindStaticFieldOrDie(gThreadGroup, "mMain", "Ljava/lang/ThreadGroup;");
752 gThreadGroup_mSystem = FindStaticFieldOrDie(gThreadGroup, "mSystem", "Ljava/lang/ThreadGroup;");
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700753 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", "Ljava/lang/Thread;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700754
755 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
Elliott Hughes462c9442012-03-23 18:47:50 -0700756 gThreadGroup_removeThread = FindMethodOrDie(gThreadGroup, "removeThread", "(Ljava/lang/Thread;)V");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700757 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
758 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700759
760 // Finish attaching the main thread.
Elliott Hughes462c9442012-03-23 18:47:50 -0700761 Thread::Current()->CreatePeer("main", false, Thread::GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500762
763 InitBoxingMethods();
764 class_linker->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700765}
766
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700767void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700768 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700769}
770
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700771uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
772 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
773 return ThreadList::kInvalidId;
774 }
775 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
776 if (managed_thread == NULL) {
777 return ThreadList::kInvalidId;
778 }
779 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
780 Thread* thread = reinterpret_cast<Thread*>(vmData);
781 if (thread == NULL) {
782 return ThreadList::kInvalidId;
783 }
784 return thread->GetThinLockId();
785}
786
Elliott Hughesdcc24742011-09-07 14:02:44 -0700787Thread::Thread()
Elliott Hughes47179f72011-10-27 16:44:39 -0700788 : thin_lock_id_(0),
789 tid_(0),
790 peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700791 top_of_managed_stack_(),
792 top_of_managed_stack_pc_(0),
Elliott Hughese62934d2012-04-09 11:24:29 -0700793 wait_mutex_(new Mutex("a thread wait mutex")),
794 wait_cond_(new ConditionVariable("a thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700795 wait_monitor_(NULL),
796 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700797 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700798 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700799 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700800 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700801 native_to_managed_record_(NULL),
802 top_sirt_(NULL),
Logan Chienf7ad17e2012-03-15 03:10:03 +0800803 top_shadow_frame_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700804 jni_env_(NULL),
Elliott Hughes34e06962012-04-09 13:55:55 -0700805 state_(kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700806 self_(NULL),
807 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700808 exception_(NULL),
809 suspend_count_(0),
Elliott Hughes234ab152011-10-26 14:02:26 -0700810 debug_suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700811 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700812 long_jump_context_(NULL),
Elliott Hughes726079d2011-10-07 18:43:44 -0700813 throwing_OutOfMemoryError_(false),
Elliott Hughes475fc232011-10-25 15:00:35 -0700814 pre_allocated_OutOfMemoryError_(NULL),
jeffhaoe343b762011-12-05 16:36:44 -0800815 debug_invoke_req_(new DebugInvokeReq),
Elliott Hughes899e7892012-01-24 14:57:32 -0800816 trace_stack_(new std::vector<TraceStackFrame>),
817 name_(new std::string("<native thread without managed peer>")) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700818 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800819 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700820}
821
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700822static void MonitorExitVisitor(const Object* object, void*) {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700823 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700824 LOG(WARNING) << "Calling MonitorExit on object " << object << " (" << PrettyTypeOf(object) << ")"
825 << " left locked by native thread " << *Thread::Current() << " which is detaching";
Elliott Hughes5f791332011-09-15 17:45:30 -0700826 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700827}
828
Elliott Hughesc0f09332012-03-26 13:27:06 -0700829void Thread::Destroy() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700830 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700831 if (jni_env_ != NULL) {
832 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
833 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700834
Elliott Hughes93e74e82011-09-13 11:07:03 -0700835 if (peer_ != NULL) {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700836 Thread* self = this;
Elliott Hughes29f27422011-09-18 16:02:18 -0700837
Elliott Hughes534da072012-03-27 15:17:42 -0700838 // We may need to call user-supplied managed code.
Elliott Hughes34e06962012-04-09 13:55:55 -0700839 SetState(kRunnable);
Elliott Hughes534da072012-03-27 15:17:42 -0700840
841 HandleUncaughtExceptions();
842 RemoveFromThreadGroup();
843
Elliott Hughes29f27422011-09-18 16:02:18 -0700844 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700845 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700846
Elliott Hughesc0f09332012-03-26 13:27:06 -0700847 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700848
Elliott Hughes29f27422011-09-18 16:02:18 -0700849 // Thread.join() is implemented as an Object.wait() on the Thread.lock
850 // object. Signal anyone who is waiting.
Elliott Hughes038a8062011-09-18 14:12:41 -0700851 Object* lock = gThread_lock->GetObject(peer_);
852 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700853 if (lock != NULL) {
854 lock->MonitorEnter(self);
855 lock->NotifyAll();
856 lock->MonitorExit(self);
857 }
858 }
Elliott Hughesc0f09332012-03-26 13:27:06 -0700859}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700860
Elliott Hughesc0f09332012-03-26 13:27:06 -0700861Thread::~Thread() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700862 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700863 jni_env_ = NULL;
864
Elliott Hughes34e06962012-04-09 13:55:55 -0700865 SetState(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700866
867 delete wait_cond_;
868 delete wait_mutex_;
869
Ian Rogers776ac1f2012-04-13 23:36:36 -0700870#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes85d15452011-09-16 17:33:01 -0700871 delete long_jump_context_;
Ian Rogers776ac1f2012-04-13 23:36:36 -0700872#endif
Elliott Hughes475fc232011-10-25 15:00:35 -0700873
874 delete debug_invoke_req_;
jeffhaoe343b762011-12-05 16:36:44 -0800875 delete trace_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -0800876 delete name_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700877}
878
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700879void Thread::HandleUncaughtExceptions() {
880 if (!IsExceptionPending()) {
881 return;
882 }
883
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700884 // Get and clear the exception.
885 Object* exception = GetException();
886 ClearException();
887
888 // If the thread has its own handler, use that.
889 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
890 if (handler == NULL) {
891 // Otherwise use the thread group's default handler.
Elliott Hughesa2155262011-11-16 16:26:58 -0800892 handler = GetThreadGroup();
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700893 }
894
895 // Call the handler.
896 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
Elliott Hughes77405792012-03-15 15:22:12 -0700897 JValue args[2];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700898 args[0].SetL(peer_);
899 args[1].SetL(exception);
Elliott Hughes77405792012-03-15 15:22:12 -0700900 m->Invoke(this, handler, args, NULL);
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700901
902 // If the handler threw, clear that exception too.
903 ClearException();
904}
905
Elliott Hughesa2155262011-11-16 16:26:58 -0800906Object* Thread::GetThreadGroup() const {
907 return gThread_group->GetObject(peer_);
908}
909
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700910void Thread::RemoveFromThreadGroup() {
911 // this.group.removeThread(this);
912 // group can be null if we're in the compiler or a test.
Elliott Hughesa2155262011-11-16 16:26:58 -0800913 Object* group = GetThreadGroup();
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700914 if (group != NULL) {
915 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
Elliott Hughes77405792012-03-15 15:22:12 -0700916 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700917 args[0].SetL(peer_);
Elliott Hughes77405792012-03-15 15:22:12 -0700918 m->Invoke(this, group, args, NULL);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -0700919 }
920}
921
Ian Rogers408f79a2011-08-23 18:22:33 -0700922size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700923 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700924 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700925 count += cur->NumberOfReferences();
926 }
927 return count;
928}
929
TDYa12728f1a142012-03-15 21:51:52 -0700930size_t Thread::NumShadowFrameReferences() {
931 size_t count = 0;
932 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
933 count += cur->NumberOfReferences();
934 }
935 return count;
936}
937
Ian Rogers408f79a2011-08-23 18:22:33 -0700938bool Thread::SirtContains(jobject obj) {
939 Object** sirt_entry = reinterpret_cast<Object**>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700940 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
941 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700942 return true;
943 }
944 }
945 return false;
946}
947
TDYa12728f1a142012-03-15 21:51:52 -0700948bool Thread::ShadowFrameContains(jobject obj) {
949 Object** shadow_frame_entry = reinterpret_cast<Object**>(obj);
950 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
951 if (cur->Contains(shadow_frame_entry)) {
952 return true;
953 }
954 }
955 return false;
956}
957
958bool Thread::StackReferencesContain(jobject obj) {
959 return SirtContains(obj) || ShadowFrameContains(obj);
960}
961
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700962void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700963 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700964 size_t num_refs = cur->NumberOfReferences();
965 for (size_t j = 0; j < num_refs; j++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700966 Object* object = cur->GetReference(j);
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -0700967 if (object != NULL) {
968 visitor(object, arg);
969 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700970 }
971 }
972}
973
Logan Chienf7ad17e2012-03-15 03:10:03 +0800974void Thread::ShadowFrameVisitRoots(Heap::RootVisitor* visitor, void* arg) {
975 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
976 size_t num_refs = cur->NumberOfReferences();
977 for (size_t j = 0; j < num_refs; j++) {
978 Object* object = cur->GetReference(j);
979 if (object != NULL) {
980 visitor(object, arg);
981 }
982 }
983 }
984}
985
Ian Rogers408f79a2011-08-23 18:22:33 -0700986Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700987 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700988 if (obj == NULL) {
989 return NULL;
990 }
991 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
992 IndirectRefKind kind = GetIndirectRefKind(ref);
993 Object* result;
994 switch (kind) {
995 case kLocal:
996 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700997 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700998 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700999 break;
1000 }
1001 case kGlobal:
1002 {
1003 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1004 IndirectReferenceTable& globals = vm->globals;
1005 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001006 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001007 break;
1008 }
1009 case kWeakGlobal:
1010 {
1011 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1012 IndirectReferenceTable& weak_globals = vm->weak_globals;
1013 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001014 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001015 if (result == kClearedJniWeakGlobal) {
1016 // This is a special case where it's okay to return NULL.
1017 return NULL;
1018 }
1019 break;
1020 }
1021 case kSirtOrInvalid:
1022 default:
1023 // TODO: make stack indirect reference table lookup more efficient
1024 // Check if this is a local reference in the SIRT
TDYa12728f1a142012-03-15 21:51:52 -07001025 if (StackReferencesContain(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001026 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc2dc62d2012-01-17 20:06:12 -08001027 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001028 // Assume an invalid local reference is actually a direct pointer.
1029 result = reinterpret_cast<Object*>(obj);
1030 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001031 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001032 }
1033 }
1034
1035 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001036 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1037 JniAbort(NULL);
1038 } else {
1039 if (result != kInvalidIndirectRefObject) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001040 Runtime::Current()->GetHeap()->VerifyObject(result);
Elliott Hughesa2501992011-08-26 19:39:54 -07001041 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001042 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001043 return result;
1044}
1045
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001046class CountStackDepthVisitor : public Thread::StackVisitor {
1047 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001048 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001049
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001050 bool VisitFrame(const Frame& frame, uintptr_t /*pc*/) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001051 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001052 // Note we also skip the frame if it doesn't have a method (namely the callee
1053 // save frame)
Ian Rogers5167c972012-02-03 10:41:20 -08001054 if (skipping_ && frame.HasMethod() &&
1055 !Throwable::GetJavaLangThrowable()->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001056 skipping_ = false;
1057 }
1058 if (!skipping_) {
Ian Rogers6b0870d2011-12-15 19:38:12 -08001059 if (frame.HasMethod()) { // ignore callee save frames
1060 ++depth_;
1061 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001062 } else {
1063 ++skip_depth_;
1064 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001065 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001066 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001067
1068 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001069 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001070 }
1071
Elliott Hughes29f27422011-09-18 16:02:18 -07001072 int GetSkipDepth() const {
1073 return skip_depth_;
1074 }
1075
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001076 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001077 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001078 uint32_t skip_depth_;
1079 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001080};
1081
Ian Rogersaaa20802011-09-11 21:47:37 -07001082class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001083 public:
Ian Rogers283ed0d2012-02-16 15:25:09 -08001084 explicit BuildInternalStackTraceVisitor(int skip_depth)
Elliott Hughes726079d2011-10-07 18:43:44 -07001085 : skip_depth_(skip_depth), count_(0), pc_trace_(NULL), method_trace_(NULL), local_ref_(NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001086 }
1087
1088 bool Init(int depth, ScopedJniThreadState& ts) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001089 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001090 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Elliott Hughes726079d2011-10-07 18:43:44 -07001091 if (method_trace_ == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001092 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001093 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001094 // Register a local reference as IntArray::Alloc may trigger GC
1095 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1096 pc_trace_ = IntArray::Alloc(depth);
Elliott Hughes726079d2011-10-07 18:43:44 -07001097 if (pc_trace_ == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001098 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001099 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001100#ifdef MOVING_GARBAGE_COLLECTOR
1101 // Re-read after potential GC
Brian Carlstrom26736442012-02-16 18:24:26 -08001102 method_trace_ = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
Ian Rogersaaa20802011-09-11 21:47:37 -07001103#endif
1104 // Save PC trace in last element of method trace, also places it into the
1105 // object graph.
1106 method_trace_->Set(depth, pc_trace_);
Ian Rogers283ed0d2012-02-16 15:25:09 -08001107 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001108 }
1109
Ian Rogersaaa20802011-09-11 21:47:37 -07001110 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001111
Elliott Hughes530fa002012-03-12 11:44:49 -07001112 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes726079d2011-10-07 18:43:44 -07001113 if (method_trace_ == NULL || pc_trace_ == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001114 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001115 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001116 if (skip_depth_ > 0) {
1117 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001118 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001119 }
Ian Rogers6b0870d2011-12-15 19:38:12 -08001120 if (!frame.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001121 return true; // ignore callee save frames
Ian Rogers6b0870d2011-12-15 19:38:12 -08001122 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001123 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001124 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001125 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001126 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001127 }
1128
Ian Rogersaaa20802011-09-11 21:47:37 -07001129 jobject GetInternalStackTrace() const {
1130 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001131 }
1132
1133 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001134 // How many more frames to skip.
1135 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001136 // Current position down stack trace
1137 uint32_t count_;
1138 // Array of return PC values
1139 IntArray* pc_trace_;
1140 // An array of the methods on the stack, the last entry is a reference to the
1141 // PC trace
1142 ObjectArray<Object>* method_trace_;
1143 // Local indirect reference table entry for method trace
1144 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001145};
1146
Ian Rogers776ac1f2012-04-13 23:36:36 -07001147#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001148// TODO: remove this.
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001149static uintptr_t ManglePc(uintptr_t pc) {
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001150 // Move the PC back 2 bytes as a call will frequently terminate the
1151 // decoding of a particular instruction and we want to make sure we
1152 // get the Dex PC of the instruction with the call and not the
1153 // instruction following.
1154 if (pc > 0) { pc -= 2; }
1155 return pc;
1156}
Ian Rogers776ac1f2012-04-13 23:36:36 -07001157#endif
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001158
1159// TODO: remove this.
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001160static uintptr_t DemanglePc(uintptr_t pc) {
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001161 // Revert mangling for the case where we need the PC to return to the upcall
Ian Rogers9a8a8882012-03-08 02:30:55 -08001162 if (pc > 0) { pc += 2; }
1163 return pc;
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001164}
Ian Rogersf57c47c2011-10-06 00:06:17 -07001165
Logan Chienf7ad17e2012-03-15 03:10:03 +08001166void Thread::PushShadowFrame(ShadowFrame* frame) {
1167 frame->SetLink(top_shadow_frame_);
1168 top_shadow_frame_ = frame;
1169}
1170
1171ShadowFrame* Thread::PopShadowFrame() {
1172 CHECK(top_shadow_frame_ != NULL);
1173 ShadowFrame* frame = top_shadow_frame_;
1174 top_shadow_frame_ = frame->GetLink();
1175 return frame;
1176}
1177
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001178void Thread::PushSirt(StackIndirectReferenceTable* sirt) {
1179 sirt->SetLink(top_sirt_);
1180 top_sirt_ = sirt;
1181}
1182
1183StackIndirectReferenceTable* Thread::PopSirt() {
1184 CHECK(top_sirt_ != NULL);
1185 StackIndirectReferenceTable* sirt = top_sirt_;
1186 top_sirt_ = top_sirt_->GetLink();
1187 return sirt;
1188}
1189
TDYa1279b2ba2e2012-03-19 10:12:32 -07001190#if !defined(ART_USE_LLVM_COMPILER) // LLVM use ShadowFrame
1191
Elliott Hughes530fa002012-03-12 11:44:49 -07001192void Thread::WalkStack(StackVisitor* visitor, bool include_upcalls) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001193 Frame frame = GetTopOfStack();
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001194 uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001195 uint32_t trace_stack_depth = 0;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001196 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1197 // CHECK(native_to_managed_record_ != NULL);
1198 NativeToManagedRecord* record = native_to_managed_record_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001199 bool method_tracing_active = Runtime::Current()->IsMethodTracingActive();
Elliott Hughes530fa002012-03-12 11:44:49 -07001200 while (frame.GetSP() != NULL) {
1201 for ( ; frame.GetMethod() != NULL; frame.Next()) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07001202 frame.GetMethod()->AssertPcIsWithinCode(pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001203 bool should_continue = visitor->VisitFrame(frame, pc);
Ian Rogers57b86d42012-03-27 16:05:41 -07001204 if (UNLIKELY(!should_continue)) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001205 return;
1206 }
Ian Rogers57b86d42012-03-27 16:05:41 -07001207 uintptr_t return_pc = frame.GetReturnPC();
1208 if (LIKELY(!method_tracing_active)) {
1209 pc = ManglePc(return_pc);
1210 } else {
jeffhao0791adc2012-04-04 11:14:32 -07001211 // While profiling, the return pc is restored from the side stack, except when walking
1212 // the stack for an exception where the side stack will be unwound in VisitFrame.
1213 if (IsTraceExitPc(return_pc) && !include_upcalls) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001214 TraceStackFrame trace_frame = GetTraceStackFrame(trace_stack_depth++);
jeffhao26c0a1a2012-01-17 16:28:33 -08001215 CHECK(trace_frame.method_ == frame.GetMethod());
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001216 pc = ManglePc(trace_frame.return_pc_);
Ian Rogers57b86d42012-03-27 16:05:41 -07001217 } else {
1218 pc = ManglePc(return_pc);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001219 }
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001220 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001221 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001222 if (include_upcalls) {
1223 bool should_continue = visitor->VisitFrame(frame, pc);
1224 if (!should_continue) {
1225 return;
1226 }
1227 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001228 if (record == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001229 return;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001230 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001231 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001232 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001233 pc = ManglePc(record->last_top_of_managed_stack_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001234 record = record->link_;
1235 }
1236}
1237
TDYa1279b2ba2e2012-03-19 10:12:32 -07001238#else // defined(ART_USE_LLVM_COMPILER) // LLVM uses ShadowFrame
1239
1240void Thread::WalkStack(StackVisitor* visitor, bool /*include_upcalls*/) const {
1241 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
1242 Frame frame;
1243 frame.SetSP(reinterpret_cast<Method**>(reinterpret_cast<byte*>(cur) +
1244 ShadowFrame::MethodOffset()));
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001245 bool should_continue = visitor->VisitFrame(frame, cur->GetLineNumber());
TDYa1279b2ba2e2012-03-19 10:12:32 -07001246 if (!should_continue) {
1247 return;
1248 }
1249 }
1250}
1251
1252/*
1253 * | |
1254 * | |
1255 * | |
1256 * | . |
1257 * | . |
1258 * | . |
1259 * | . |
1260 * | Method* |
1261 * | . |
1262 * | . | <-- top_shadow_frame_ (ShadowFrame*)
1263 * / +------------------------+
1264 * ->| . |
1265 * . | . |
1266 * . | . |
1267 * /+------------------------+
1268 * / | . |
1269 * / | . |
1270 * --- | | . |
1271 * | | | . |
1272 * | | Method* | <-- frame.GetSP() (Method**)
1273 * ShadowFrame \ | . |
1274 * | ->| . | <-- cur (ShadowFrame*)
1275 * --- /+------------------------+
1276 * / | . |
1277 * / | . |
1278 * --- | | . |
1279 * | cur->GetLink() | | . |
1280 * | | Method* |
1281 * ShadowFrame \ | . |
1282 * | ->| . |
1283 * --- +------------------------+
1284 * | . |
1285 * | . |
1286 * | . |
1287 * +========================+
1288 */
1289
1290#endif
1291
Elliott Hughes01158d72011-09-19 19:47:10 -07001292jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001293 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001294 CountStackDepthVisitor count_visitor;
1295 WalkStack(&count_visitor);
1296 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001297 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001298
Ian Rogersaaa20802011-09-11 21:47:37 -07001299 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001300 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001301
1302 // Build internal stack trace
Ian Rogers77f74c12012-02-16 22:35:30 -08001303 BuildInternalStackTraceVisitor build_trace_visitor(skip_depth);
1304 if (!build_trace_visitor.Init(depth, ts)) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001305 return NULL; // Allocation failed
Ian Rogers283ed0d2012-02-16 15:25:09 -08001306 }
Brian Carlstrom26736442012-02-16 18:24:26 -08001307 WalkStack(&build_trace_visitor);
1308 return build_trace_visitor.GetInternalStackTrace();
Ian Rogersaaa20802011-09-11 21:47:37 -07001309}
1310
Elliott Hughes01158d72011-09-19 19:47:10 -07001311jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1312 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001313 // Transition into runnable state to work on Object*/Array*
1314 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001315 // Decode the internal stack trace into the depth, method trace and PC trace
1316 ObjectArray<Object>* method_trace =
1317 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
Ian Rogers9074b992011-10-26 17:41:55 -07001318 int32_t depth = method_trace->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001319 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1320
1321 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1322
Elliott Hughes01158d72011-09-19 19:47:10 -07001323 jobjectArray result;
1324 ObjectArray<StackTraceElement>* java_traces;
1325 if (output_array != NULL) {
1326 // Reuse the array we were given.
1327 result = output_array;
1328 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1329 output_array));
1330 // ...adjusting the number of frames we'll write to not exceed the array length.
1331 depth = std::min(depth, java_traces->GetLength());
1332 } else {
1333 // Create java_trace array and place in local reference table
1334 java_traces = class_linker->AllocStackTraceElementArray(depth);
Elliott Hughes30646832011-10-13 16:59:46 -07001335 if (java_traces == NULL) {
1336 return NULL;
1337 }
Elliott Hughes01158d72011-09-19 19:47:10 -07001338 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1339 }
1340
1341 if (stack_depth != NULL) {
1342 *stack_depth = depth;
1343 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001344
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001345 MethodHelper mh;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001346 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001347 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1348 Method* method = down_cast<Method*>(method_trace->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001349 mh.ChangeMethod(method);
Ian Rogersaaa20802011-09-11 21:47:37 -07001350 uint32_t native_pc = pc_trace->Get(i);
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001351#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001352 int32_t line_number = mh.GetLineNumFromNativePC(native_pc);
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001353#else
1354 int32_t line_number = native_pc; // LLVM stored line_number in the ShadowFrame
1355#endif
Ian Rogersaaa20802011-09-11 21:47:37 -07001356 // Allocate element, potentially triggering GC
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001357 // TODO: reuse class_name_object via Class::name_?
Ian Rogers48601312011-12-07 16:45:19 -08001358 const char* descriptor = mh.GetDeclaringClassDescriptor();
1359 CHECK(descriptor != NULL);
1360 std::string class_name(PrettyDescriptor(descriptor));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001361 SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
1362 if (class_name_object.get() == NULL) {
1363 return NULL;
1364 }
Ian Rogers48601312011-12-07 16:45:19 -08001365 const char* method_name = mh.GetName();
1366 CHECK(method_name != NULL);
1367 SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001368 if (method_name_object.get() == NULL) {
1369 return NULL;
1370 }
Ian Rogers48601312011-12-07 16:45:19 -08001371 const char* source_file = mh.GetDeclaringClassSourceFile();
1372 SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001373 StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001374 method_name_object.get(),
1375 source_name_object.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001376 line_number);
Elliott Hughes30646832011-10-13 16:59:46 -07001377 if (obj == NULL) {
1378 return NULL;
1379 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001380#ifdef MOVING_GARBAGE_COLLECTOR
1381 // Re-read after potential GC
1382 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1383 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1384 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1385#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001386 java_traces->Set(i, obj);
1387 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001388 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001389}
1390
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001391void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001392 va_list args;
1393 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001394 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001395 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001396}
1397
1398void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1399 std::string msg;
1400 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001401 ThrowNewException(exception_class_descriptor, msg.c_str());
1402}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001403
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001404void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001405 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001406 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001407 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001408 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001409 descriptor.erase(descriptor.length() - 1);
1410
1411 JNIEnv* env = GetJniEnv();
Elliott Hughes726079d2011-10-07 18:43:44 -07001412 ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001413 if (exception_class.get() == NULL) {
1414 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1415 << PrettyTypeOf(GetException());
1416 CHECK(IsExceptionPending());
1417 return;
1418 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001419 if (!Runtime::Current()->IsStarted()) {
1420 // Something is trying to throw an exception without a started
1421 // runtime, which is the common case in the compiler. We won't be
1422 // able to invoke the constructor of the exception, so use
1423 // AllocObject which will not invoke a constructor.
1424 ScopedLocalRef<jthrowable> exception(
1425 env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1426 if (exception.get() != NULL) {
1427 ScopedJniThreadState ts(env);
1428 Throwable* t = reinterpret_cast<Throwable*>(ts.Self()->DecodeJObject(exception.get()));
Ian Rogers02fbef02012-01-31 22:15:33 -08001429 t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001430 ts.Self()->SetException(t);
1431 } else {
1432 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1433 << PrettyTypeOf(GetException());
1434 CHECK(IsExceptionPending());
1435 }
1436 return;
1437 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001438 int rc = env->ThrowNew(exception_class.get(), msg);
Elliott Hughes30646832011-10-13 16:59:46 -07001439 if (rc != JNI_OK) {
1440 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1441 << PrettyTypeOf(GetException());
1442 CHECK(IsExceptionPending());
Elliott Hughes30646832011-10-13 16:59:46 -07001443 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001444}
1445
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001446void Thread::ThrowOutOfMemoryError(const char* msg) {
1447 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1448 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Elliott Hughes726079d2011-10-07 18:43:44 -07001449 if (!throwing_OutOfMemoryError_) {
1450 throwing_OutOfMemoryError_ = true;
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001451 ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001452 } else {
Elliott Hughes726079d2011-10-07 18:43:44 -07001453 SetException(pre_allocated_OutOfMemoryError_);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001454 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001455 throwing_OutOfMemoryError_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001456}
1457
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001458
Elliott Hughes498508c2011-10-17 14:58:22 -07001459Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001460 return Thread::Current();
1461}
1462
1463void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001464 std::ostringstream ss;
1465 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001466 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001467 // log to stderr for debugging command line processes
1468 std::cerr << str;
1469#ifdef HAVE_ANDROID_OS
1470 // log to logcat for debugging frameworks processes
1471 LOG(INFO) << str;
1472#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001473}
1474
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001475void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset, size_t size_of_pointers) {
1476 CHECK_EQ(size_of_pointers, 4U); // TODO: support 64-bit targets.
Elliott Hughes3d71d072012-04-10 18:28:35 -07001477#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 -07001478#define DO_THREAD_ENTRY_POINT_OFFSET(x) if (offset == ENTRYPOINT_OFFSET(x)) { os << # x; } else
1479 DO_THREAD_OFFSET(card_table_)
1480 DO_THREAD_OFFSET(exception_)
1481 DO_THREAD_OFFSET(jni_env_)
1482 DO_THREAD_OFFSET(self_)
1483 DO_THREAD_OFFSET(stack_end_)
Elliott Hughes3d71d072012-04-10 18:28:35 -07001484 DO_THREAD_OFFSET(state_)
Elliott Hughes28fa76d2012-04-09 17:31:46 -07001485 DO_THREAD_OFFSET(suspend_count_)
1486 DO_THREAD_OFFSET(thin_lock_id_)
1487 DO_THREAD_OFFSET(top_of_managed_stack_)
1488 DO_THREAD_OFFSET(top_of_managed_stack_pc_)
1489 DO_THREAD_OFFSET(top_sirt_)
1490 DO_THREAD_ENTRY_POINT_OFFSET(pAllocArrayFromCode)
1491 DO_THREAD_ENTRY_POINT_OFFSET(pAllocArrayFromCodeWithAccessCheck)
1492 DO_THREAD_ENTRY_POINT_OFFSET(pAllocObjectFromCode)
1493 DO_THREAD_ENTRY_POINT_OFFSET(pAllocObjectFromCodeWithAccessCheck)
1494 DO_THREAD_ENTRY_POINT_OFFSET(pCheckAndAllocArrayFromCode)
1495 DO_THREAD_ENTRY_POINT_OFFSET(pCheckAndAllocArrayFromCodeWithAccessCheck)
1496 DO_THREAD_ENTRY_POINT_OFFSET(pInstanceofNonTrivialFromCode)
1497 DO_THREAD_ENTRY_POINT_OFFSET(pCanPutArrayElementFromCode)
1498 DO_THREAD_ENTRY_POINT_OFFSET(pCheckCastFromCode)
1499 DO_THREAD_ENTRY_POINT_OFFSET(pDebugMe)
1500 DO_THREAD_ENTRY_POINT_OFFSET(pUpdateDebuggerFromCode)
1501 DO_THREAD_ENTRY_POINT_OFFSET(pInitializeStaticStorage)
1502 DO_THREAD_ENTRY_POINT_OFFSET(pInitializeTypeAndVerifyAccessFromCode)
1503 DO_THREAD_ENTRY_POINT_OFFSET(pInitializeTypeFromCode)
1504 DO_THREAD_ENTRY_POINT_OFFSET(pResolveStringFromCode)
1505 DO_THREAD_ENTRY_POINT_OFFSET(pSet32Instance)
1506 DO_THREAD_ENTRY_POINT_OFFSET(pSet32Static)
1507 DO_THREAD_ENTRY_POINT_OFFSET(pSet64Instance)
1508 DO_THREAD_ENTRY_POINT_OFFSET(pSet64Static)
1509 DO_THREAD_ENTRY_POINT_OFFSET(pSetObjInstance)
1510 DO_THREAD_ENTRY_POINT_OFFSET(pSetObjStatic)
1511 DO_THREAD_ENTRY_POINT_OFFSET(pGet32Instance)
1512 DO_THREAD_ENTRY_POINT_OFFSET(pGet32Static)
1513 DO_THREAD_ENTRY_POINT_OFFSET(pGet64Instance)
1514 DO_THREAD_ENTRY_POINT_OFFSET(pGet64Static)
1515 DO_THREAD_ENTRY_POINT_OFFSET(pGetObjInstance)
1516 DO_THREAD_ENTRY_POINT_OFFSET(pGetObjStatic)
1517 DO_THREAD_ENTRY_POINT_OFFSET(pHandleFillArrayDataFromCode)
1518 DO_THREAD_ENTRY_POINT_OFFSET(pDecodeJObjectInThread)
1519 DO_THREAD_ENTRY_POINT_OFFSET(pFindNativeMethod)
1520 DO_THREAD_ENTRY_POINT_OFFSET(pLockObjectFromCode)
1521 DO_THREAD_ENTRY_POINT_OFFSET(pUnlockObjectFromCode)
1522 DO_THREAD_ENTRY_POINT_OFFSET(pCmpgDouble)
1523 DO_THREAD_ENTRY_POINT_OFFSET(pCmpgFloat)
1524 DO_THREAD_ENTRY_POINT_OFFSET(pCmplDouble)
1525 DO_THREAD_ENTRY_POINT_OFFSET(pCmplFloat)
1526 DO_THREAD_ENTRY_POINT_OFFSET(pDadd)
1527 DO_THREAD_ENTRY_POINT_OFFSET(pDdiv)
1528 DO_THREAD_ENTRY_POINT_OFFSET(pDmul)
1529 DO_THREAD_ENTRY_POINT_OFFSET(pDsub)
1530 DO_THREAD_ENTRY_POINT_OFFSET(pF2d)
1531 DO_THREAD_ENTRY_POINT_OFFSET(pFmod)
1532 DO_THREAD_ENTRY_POINT_OFFSET(pI2d)
1533 DO_THREAD_ENTRY_POINT_OFFSET(pL2d)
1534 DO_THREAD_ENTRY_POINT_OFFSET(pD2f)
1535 DO_THREAD_ENTRY_POINT_OFFSET(pFadd)
1536 DO_THREAD_ENTRY_POINT_OFFSET(pFdiv)
1537 DO_THREAD_ENTRY_POINT_OFFSET(pFmodf)
1538 DO_THREAD_ENTRY_POINT_OFFSET(pFmul)
1539 DO_THREAD_ENTRY_POINT_OFFSET(pFsub)
1540 DO_THREAD_ENTRY_POINT_OFFSET(pI2f)
1541 DO_THREAD_ENTRY_POINT_OFFSET(pL2f)
1542 DO_THREAD_ENTRY_POINT_OFFSET(pD2iz)
1543 DO_THREAD_ENTRY_POINT_OFFSET(pF2iz)
1544 DO_THREAD_ENTRY_POINT_OFFSET(pIdiv)
1545 DO_THREAD_ENTRY_POINT_OFFSET(pIdivmod)
1546 DO_THREAD_ENTRY_POINT_OFFSET(pD2l)
1547 DO_THREAD_ENTRY_POINT_OFFSET(pF2l)
1548 DO_THREAD_ENTRY_POINT_OFFSET(pLdiv)
1549 DO_THREAD_ENTRY_POINT_OFFSET(pLdivmod)
1550 DO_THREAD_ENTRY_POINT_OFFSET(pLmul)
1551 DO_THREAD_ENTRY_POINT_OFFSET(pShlLong)
1552 DO_THREAD_ENTRY_POINT_OFFSET(pShrLong)
1553 DO_THREAD_ENTRY_POINT_OFFSET(pUshrLong)
1554 DO_THREAD_ENTRY_POINT_OFFSET(pIndexOf)
1555 DO_THREAD_ENTRY_POINT_OFFSET(pMemcmp16)
1556 DO_THREAD_ENTRY_POINT_OFFSET(pStringCompareTo)
1557 DO_THREAD_ENTRY_POINT_OFFSET(pMemcpy)
1558 DO_THREAD_ENTRY_POINT_OFFSET(pFindInterfaceMethodInCache)
1559 DO_THREAD_ENTRY_POINT_OFFSET(pUnresolvedDirectMethodTrampolineFromCode)
1560 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeDirectTrampolineWithAccessCheck)
1561 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeInterfaceTrampoline)
1562 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeInterfaceTrampolineWithAccessCheck)
1563 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeStaticTrampolineWithAccessCheck)
1564 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeSuperTrampolineWithAccessCheck)
1565 DO_THREAD_ENTRY_POINT_OFFSET(pInvokeVirtualTrampolineWithAccessCheck)
1566 DO_THREAD_ENTRY_POINT_OFFSET(pCheckSuspendFromCode)
1567 DO_THREAD_ENTRY_POINT_OFFSET(pTestSuspendFromCode)
1568 DO_THREAD_ENTRY_POINT_OFFSET(pDeliverException)
1569 DO_THREAD_ENTRY_POINT_OFFSET(pThrowAbstractMethodErrorFromCode)
1570 DO_THREAD_ENTRY_POINT_OFFSET(pThrowArrayBoundsFromCode)
1571 DO_THREAD_ENTRY_POINT_OFFSET(pThrowDivZeroFromCode)
1572 DO_THREAD_ENTRY_POINT_OFFSET(pThrowNoSuchMethodFromCode)
1573 DO_THREAD_ENTRY_POINT_OFFSET(pThrowNullPointerFromCode)
1574 DO_THREAD_ENTRY_POINT_OFFSET(pThrowStackOverflowFromCode)
1575 DO_THREAD_ENTRY_POINT_OFFSET(pThrowVerificationErrorFromCode)
1576 {
1577 os << offset;
1578 }
1579#undef DO_THREAD_OFFSET
1580#undef DO_THREAD_ENTRY_POINT_OFFSET
1581}
1582
Ian Rogersbdb03912011-09-14 00:55:44 -07001583class CatchBlockStackVisitor : public Thread::StackVisitor {
1584 public:
1585 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers57b86d42012-03-27 16:05:41 -07001586 : to_find_(to_find), long_jump_context_(ljc), native_method_count_(0),
1587 method_tracing_active_(Runtime::Current()->IsMethodTracingActive()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001588#ifndef NDEBUG
1589 handler_pc_ = 0xEBADC0DE;
1590 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1591#endif
1592 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001593
Elliott Hughes530fa002012-03-12 11:44:49 -07001594 bool VisitFrame(const Frame& fr, uintptr_t pc) {
1595 Method* method = fr.GetMethod();
1596 if (method == NULL) {
1597 // This is the upcall, we remember the frame and last_pc so that we may
1598 // long jump to them
1599 handler_pc_ = DemanglePc(pc);
1600 handler_frame_ = fr;
Ian Rogers57b86d42012-03-27 16:05:41 -07001601 return false; // End stack walk.
Elliott Hughes530fa002012-03-12 11:44:49 -07001602 }
1603 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers57b86d42012-03-27 16:05:41 -07001604 if (method->IsRuntimeMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001605 // ignore callee save method
Ian Rogers57b86d42012-03-27 16:05:41 -07001606 DCHECK(method->IsCalleeSaveMethod());
Elliott Hughes530fa002012-03-12 11:44:49 -07001607 } else if (method->IsNative()) {
1608 native_method_count_++;
1609 } else {
jeffhao0791adc2012-04-04 11:14:32 -07001610 // Unwind stack when an exception occurs during method tracing
Ian Rogers57b86d42012-03-27 16:05:41 -07001611 if (UNLIKELY(method_tracing_active_)) {
Ian Rogers776ac1f2012-04-13 23:36:36 -07001612#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers57b86d42012-03-27 16:05:41 -07001613 if (IsTraceExitPc(DemanglePc(pc))) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001614 pc = ManglePc(TraceMethodUnwindFromCode(Thread::Current()));
1615 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001616#else
1617 UNIMPLEMENTED(FATAL);
1618#endif
Ian Rogers67375ac2011-09-14 00:55:44 -07001619 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001620 dex_pc = method->ToDexPC(pc);
1621 }
1622 if (dex_pc != DexFile::kDexNoIndex) {
1623 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1624 if (found_dex_pc != DexFile::kDexNoIndex) {
1625 handler_pc_ = method->ToNativePC(found_dex_pc);
1626 handler_frame_ = fr;
Ian Rogers57b86d42012-03-27 16:05:41 -07001627 return false; // End stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001628 }
1629 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001630#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes530fa002012-03-12 11:44:49 -07001631 // Caller may be handler, fill in callee saves in context
1632 long_jump_context_->FillCalleeSaves(fr);
Ian Rogers776ac1f2012-04-13 23:36:36 -07001633#endif
Ian Rogers57b86d42012-03-27 16:05:41 -07001634 return true; // Continue stack walk.
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001635 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001636
Ian Rogersbdb03912011-09-14 00:55:44 -07001637 // The type of the exception catch block to find
1638 Class* to_find_;
1639 // Frame with found handler or last frame if no handler found
1640 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001641 // PC to branch to for the handler
1642 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001643 // Context that will be the target of the long jump
1644 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001645 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1646 uint32_t native_method_count_;
Ian Rogers57b86d42012-03-27 16:05:41 -07001647 // Is method tracing active?
1648 const bool method_tracing_active_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001649};
1650
Ian Rogersff1ed472011-09-20 13:46:24 -07001651void Thread::DeliverException() {
Ian Rogers776ac1f2012-04-13 23:36:36 -07001652#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers28ad40d2011-10-27 15:19:26 -07001653 const bool kDebugExceptionDelivery = false;
Elliott Hughesd07986f2011-12-06 18:27:45 -08001654 Throwable* exception = GetException(); // Get exception from thread
Ian Rogersff1ed472011-09-20 13:46:24 -07001655 CHECK(exception != NULL);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001656 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001657 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001658 ClearException();
1659 if (kDebugExceptionDelivery) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001660 String* msg = exception->GetDetailMessage();
1661 std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1662 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
1663 << ": " << str_msg << std::endl);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001664 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001665
1666 Context* long_jump_context = GetLongJumpContext();
1667 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Elliott Hughes530fa002012-03-12 11:44:49 -07001668 WalkStack(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001669
Elliott Hughesd07986f2011-12-06 18:27:45 -08001670 Method** sp;
1671 uintptr_t throw_native_pc;
1672 Method* throw_method = GetCurrentMethod(&throw_native_pc, &sp);
1673 uintptr_t catch_native_pc = catch_finder.handler_pc_;
1674 Method* catch_method = catch_finder.handler_frame_.GetMethod();
1675 Dbg::PostException(sp, throw_method, throw_native_pc, catch_method, catch_native_pc, exception);
1676
Ian Rogers28ad40d2011-10-27 15:19:26 -07001677 if (kDebugExceptionDelivery) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001678 if (catch_method == NULL) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001679 LOG(INFO) << "Handler is upcall";
1680 } else {
1681 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1682 const DexFile& dex_file =
Elliott Hughesd07986f2011-12-06 18:27:45 -08001683 class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1684 int line_number = dex_file.GetLineNumFromPC(catch_method,
1685 catch_method->ToDexPC(catch_finder.handler_pc_));
1686 LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
Ian Rogers28ad40d2011-10-27 15:19:26 -07001687 }
1688 }
1689 SetException(exception);
Ian Rogers9a8a8882012-03-08 02:30:55 -08001690 CHECK_NE(catch_native_pc, 0u);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001691 long_jump_context->SetSP(reinterpret_cast<uintptr_t>(catch_finder.handler_frame_.GetSP()));
Ian Rogers9a8a8882012-03-08 02:30:55 -08001692 long_jump_context->SetPC(catch_native_pc);
Elliott Hughes9c750f92012-04-05 12:07:59 -07001693 long_jump_context->SmashCallerSaves();
Ian Rogersbdb03912011-09-14 00:55:44 -07001694 long_jump_context->DoLongJump();
Ian Rogers776ac1f2012-04-13 23:36:36 -07001695#endif
Ian Rogers9a8a8882012-03-08 02:30:55 -08001696 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001697}
1698
Ian Rogersbdb03912011-09-14 00:55:44 -07001699Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001700 Context* result = long_jump_context_;
Ian Rogers776ac1f2012-04-13 23:36:36 -07001701#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersbdb03912011-09-14 00:55:44 -07001702 if (result == NULL) {
1703 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001704 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001705 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001706#endif
Ian Rogersbdb03912011-09-14 00:55:44 -07001707 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001708}
1709
TDYa127ee0d3fb2012-04-01 14:55:33 -07001710#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughesd07986f2011-12-06 18:27:45 -08001711Method* Thread::GetCurrentMethod(uintptr_t* pc, Method*** sp) const {
1712 Frame f = top_of_managed_stack_;
1713 Method* m = f.GetMethod();
Elliott Hughes8be2d402012-02-23 14:22:41 -08001714 uintptr_t native_pc = top_of_managed_stack_pc_;
1715
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001716 // We use JNI internally for exception throwing, so it's possible to arrive
1717 // here via a "FromCode" function, in which case there's a synthetic
1718 // callee-save method at the top of the stack. These shouldn't be user-visible,
1719 // so if we find one, skip it and return the compiled method underneath.
jeffhao33dc7712011-11-09 17:54:24 -08001720 if (m != NULL && m->IsCalleeSaveMethod()) {
Elliott Hughes8be2d402012-02-23 14:22:41 -08001721 native_pc = f.GetReturnPC();
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001722 f.Next();
1723 m = f.GetMethod();
1724 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001725 if (pc != NULL) {
Elliott Hughes8be2d402012-02-23 14:22:41 -08001726 *pc = (m != NULL) ? ManglePc(native_pc) : 0;
jeffhao33dc7712011-11-09 17:54:24 -08001727 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001728 if (sp != NULL) {
1729 *sp = f.GetSP();
1730 }
1731 return m;
jeffhao33dc7712011-11-09 17:54:24 -08001732}
TDYa127ee0d3fb2012-04-01 14:55:33 -07001733#else
1734Method* Thread::GetCurrentMethod(uintptr_t*, Method***) const {
1735 ShadowFrame* frame = top_shadow_frame_;
TDYa12720efe542012-04-03 17:40:49 -07001736 if (frame == NULL) {
1737 return NULL;
TDYa127ee0d3fb2012-04-01 14:55:33 -07001738 }
1739 return frame->GetMethod();
1740}
1741#endif
jeffhao33dc7712011-11-09 17:54:24 -08001742
Elliott Hughes5f791332011-09-15 17:45:30 -07001743bool Thread::HoldsLock(Object* object) {
1744 if (object == NULL) {
1745 return false;
1746 }
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07001747 return object->GetThinLockId() == thin_lock_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001748}
1749
Elliott Hughes038a8062011-09-18 14:12:41 -07001750bool Thread::IsDaemon() {
1751 return gThread_daemon->GetBoolean(peer_);
1752}
1753
Ian Rogers776ac1f2012-04-13 23:36:36 -07001754#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersd6b1f612011-09-27 13:38:14 -07001755class ReferenceMapVisitor : public Thread::StackVisitor {
1756 public:
1757 ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1758 context_(context), root_visitor_(root_visitor), arg_(arg) {
1759 }
1760
Elliott Hughes530fa002012-03-12 11:44:49 -07001761 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001762 Method* m = frame.GetMethod();
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001763 if (false) {
jeffhao25045522012-03-13 19:34:37 -07001764 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m)
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001765 << StringPrintf("@ PC:%04x", m->ToDexPC(pc));
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001766 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001767 // Process register map (which native and callee save methods don't have)
Ian Rogers3891c772011-12-06 15:38:28 -08001768 if (!m->IsNative() && !m->IsCalleeSaveMethod() && !m->IsProxyMethod()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001769 CHECK(m->GetGcMap() != NULL) << PrettyMethod(m);
1770 CHECK_NE(0U, m->GetGcMapLength()) << PrettyMethod(m);
1771 verifier::PcToReferenceMap map(m->GetGcMap(), m->GetGcMapLength());
Ian Rogersd81871c2011-10-03 13:57:23 -07001772 const uint8_t* reg_bitmap = map.FindBitMap(m->ToDexPC(pc));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001773 CHECK(reg_bitmap != NULL);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001774 const VmapTable vmap_table(m->GetVmapTableRaw());
Elliott Hughes11d1b0c2012-01-23 16:57:47 -08001775 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001776 DCHECK(code_item != NULL); // can't be NULL or how would we compile its instructions?
1777 uint32_t core_spills = m->GetCoreSpillMask();
1778 uint32_t fp_spills = m->GetFpSpillMask();
1779 size_t frame_size = m->GetFrameSizeInBytes();
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001780 // For all dex registers in the bitmap
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001781 size_t num_regs = std::min(map.RegWidth() * 8,
1782 static_cast<size_t>(code_item->registers_size_));
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001783 for (size_t reg = 0; reg < num_regs; ++reg) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001784 // Does this register hold a reference?
1785 if (TestBitmap(reg, reg_bitmap)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001786 uint32_t vmap_offset;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001787 Object* ref;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001788 if (vmap_table.IsInContext(reg, vmap_offset)) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001789 // Compute the register we need to load from the context
1790 uint32_t spill_mask = m->GetCoreSpillMask();
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001791 CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
Ian Rogersf57c47c2011-10-06 00:06:17 -07001792 uint32_t matches = 0;
1793 uint32_t spill_shifts = 0;
1794 while (matches != (vmap_offset + 1)) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001795 DCHECK_NE(spill_mask, 0u);
Ian Rogersf57c47c2011-10-06 00:06:17 -07001796 matches += spill_mask & 1; // Add 1 if the low bit is set
1797 spill_mask >>= 1;
1798 spill_shifts++;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001799 }
Ian Rogersf57c47c2011-10-06 00:06:17 -07001800 spill_shifts--; // wind back one as we want the last match
1801 ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001802 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001803 ref = reinterpret_cast<Object*>(frame.GetVReg(code_item, core_spills, fp_spills,
1804 frame_size, reg));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001805 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001806 if (ref != NULL) {
1807 root_visitor_(ref, arg_);
1808 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001809 }
1810 }
1811 }
1812 context_->FillCalleeSaves(frame);
Elliott Hughes530fa002012-03-12 11:44:49 -07001813 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001814 }
1815
1816 private:
1817 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1818 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1819 }
1820
1821 // Context used to build up picture of callee saves
1822 Context* context_;
1823 // Call-back when we visit a root
1824 Heap::RootVisitor* root_visitor_;
1825 // Argument to call-back
1826 void* arg_;
1827};
Ian Rogers776ac1f2012-04-13 23:36:36 -07001828#endif
Ian Rogersd6b1f612011-09-27 13:38:14 -07001829
1830void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001831 if (exception_ != NULL) {
1832 visitor(exception_, arg);
1833 }
1834 if (peer_ != NULL) {
1835 visitor(peer_, arg);
1836 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001837 if (pre_allocated_OutOfMemoryError_ != NULL) {
1838 visitor(pre_allocated_OutOfMemoryError_, arg);
1839 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001840 if (class_loader_override_ != NULL) {
1841 visitor(class_loader_override_, arg);
1842 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001843 jni_env_->locals.VisitRoots(visitor, arg);
1844 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001845
1846 SirtVisitRoots(visitor, arg);
Logan Chienf7ad17e2012-03-15 03:10:03 +08001847 ShadowFrameVisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001848
TDYa127540a5b72012-04-03 18:56:08 -07001849#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogersd6b1f612011-09-27 13:38:14 -07001850 // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1851 // delivery.
1852 Context* context = GetLongJumpContext();
1853 // Visit roots on this thread's stack
1854 ReferenceMapVisitor mapper(context, visitor, arg);
1855 WalkStack(&mapper);
TDYa127540a5b72012-04-03 18:56:08 -07001856#endif
Elliott Hughes410c0c82011-09-01 17:58:25 -07001857}
1858
jeffhao25045522012-03-13 19:34:37 -07001859#if VERIFY_OBJECT_ENABLED
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001860static void VerifyObject(const Object* obj, void*) {
jeffhao25045522012-03-13 19:34:37 -07001861 Runtime::Current()->GetHeap()->VerifyObject(obj);
1862}
1863
1864void Thread::VerifyStack() {
TDYa127540a5b72012-04-03 18:56:08 -07001865#if !defined(ART_USE_LLVM_COMPILER)
jeffhaoe66ac792012-03-19 16:08:46 -07001866 UniquePtr<Context> context(Context::Create());
1867 ReferenceMapVisitor mapper(context.get(), VerifyObject, NULL);
jeffhao25045522012-03-13 19:34:37 -07001868 WalkStack(&mapper);
TDYa127540a5b72012-04-03 18:56:08 -07001869#endif
jeffhao25045522012-03-13 19:34:37 -07001870}
1871#endif
1872
Elliott Hughes330304d2011-08-12 14:28:05 -07001873std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Elliott Hughes899e7892012-01-24 14:57:32 -08001874 thread.Dump(os, false);
Elliott Hughes330304d2011-08-12 14:28:05 -07001875 return os;
1876}
1877
Elliott Hughesa4060e52012-03-02 16:51:35 -08001878void Thread::CheckSafeToLockOrUnlock(MutexRank rank, bool is_locking) {
Elliott Hughes17057b12012-04-03 10:22:39 -07001879 if (this == NULL) {
1880 CHECK(Runtime::Current()->IsShuttingDown());
1881 return;
1882 }
Elliott Hughesffb465f2012-03-01 18:46:05 -08001883 if (is_locking) {
1884 if (held_mutexes_[rank] == 0) {
1885 bool bad_mutexes_held = false;
1886 for (int i = kMaxMutexRank; i > rank; --i) {
1887 if (held_mutexes_[i] != 0) {
1888 LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while " << (is_locking ? "locking" : "unlocking") << " " << rank;
1889 bad_mutexes_held = true;
1890 }
1891 }
Elliott Hughesb5db3bb2012-03-29 20:00:31 -07001892 CHECK(!bad_mutexes_held) << rank;
Elliott Hughesffb465f2012-03-01 18:46:05 -08001893 }
1894 ++held_mutexes_[rank];
1895 } else {
Elliott Hughesb5db3bb2012-03-29 20:00:31 -07001896 CHECK_GT(held_mutexes_[rank], 0U) << rank;
Elliott Hughesffb465f2012-03-01 18:46:05 -08001897 --held_mutexes_[rank];
1898 }
1899}
1900
Elliott Hughesa4060e52012-03-02 16:51:35 -08001901void Thread::CheckSafeToWait(MutexRank rank) {
Elliott Hughes17057b12012-04-03 10:22:39 -07001902 if (this == NULL) {
1903 CHECK(Runtime::Current()->IsShuttingDown());
1904 return;
1905 }
Elliott Hughesa4060e52012-03-02 16:51:35 -08001906 bool bad_mutexes_held = false;
1907 for (int i = kMaxMutexRank; i >= 0; --i) {
1908 if (i != rank && held_mutexes_[i] != 0) {
1909 LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while doing condition variable wait on " << rank;
1910 bad_mutexes_held = true;
1911 }
1912 }
1913 if (held_mutexes_[rank] == 0) {
1914 LOG(ERROR) << "*not* holding " << rank << " while doing condition variable wait on it";
1915 bad_mutexes_held = true;
1916 }
1917 CHECK(!bad_mutexes_held);
1918}
1919
Elliott Hughes8daa0922011-09-11 13:46:25 -07001920} // namespace art