blob: cc5ded2ec1b51005315c539ba9f78488aae37039 [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>
Elliott Hughesa0957642011-09-02 14:27:33 -070022
Carl Shapirob5573532011-07-12 18:22:59 -070023#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070024#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070025#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070026#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070027#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070028
Elliott Hughesa5b897e2011-08-16 11:33:06 -070029#include "class_linker.h"
Ian Rogersd6b1f612011-09-27 13:38:14 -070030#include "compiler.h"
Ian Rogersbdb03912011-09-14 00:55:44 -070031#include "context.h"
Ian Rogersd6b1f612011-09-27 13:38:14 -070032#include "dex_verifier.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070033#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070034#include "jni_internal.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070035#include "monitor.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070036#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070037#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070038#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070039#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070040#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070041#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070042
43namespace art {
44
45pthread_key_t Thread::pthread_key_self_;
46
Elliott Hughes8e4aac52011-09-26 17:03:36 -070047static Class* gThreadLock = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070048static Class* gThrowable = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070049static Field* gThread_daemon = NULL;
50static Field* gThread_group = NULL;
51static Field* gThread_lock = NULL;
52static Field* gThread_name = NULL;
53static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070054static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070055static Field* gThread_vmData = NULL;
56static Field* gThreadGroup_name = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -070057static Field* gThreadLock_thread = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070058static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070059static Method* gThreadGroup_removeThread = NULL;
60static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070061
buzbeece302932011-10-04 14:32:18 -070062// TODO: flesh out and move to appropriate location
63String* ResolveStringFromCode(Method* method, int32_t string_idx) {
buzbee99f27232011-10-05 12:56:36 -070064 UNIMPLEMENTED(FATAL) << "Resolve string; handle OOM";
65 return NULL; // Must return valid string or if exception, doesn't return
66}
67
68// TODO: move to appropriate location
69static void ObjectInitFromCode(Object* o) {
70 Class* c = o->GetClass();
71 if (c->IsFinalizable()) {
72 o->AddFinalizerReference();
73 }
74 /*
75 * NOTE: once debugger/profiler support is added, we'll need to check
76 * here and branch to actual compiled object.<init> to handle any
77 * breakpoint/logging activites if either is active.
78 */
buzbeece302932011-10-04 14:32:18 -070079}
80
buzbee3ea4ec52011-08-22 17:37:19 -070081void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -070082#if defined(__arm__)
83 pShlLong = art_shl_long;
84 pShrLong = art_shr_long;
85 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -070086 pIdiv = __aeabi_idiv;
87 pIdivmod = __aeabi_idivmod;
88 pI2f = __aeabi_i2f;
89 pF2iz = __aeabi_f2iz;
90 pD2f = __aeabi_d2f;
91 pF2d = __aeabi_f2d;
92 pD2iz = __aeabi_d2iz;
93 pL2f = __aeabi_l2f;
94 pL2d = __aeabi_l2d;
95 pFadd = __aeabi_fadd;
96 pFsub = __aeabi_fsub;
97 pFdiv = __aeabi_fdiv;
98 pFmul = __aeabi_fmul;
99 pFmodf = fmodf;
100 pDadd = __aeabi_dadd;
101 pDsub = __aeabi_dsub;
102 pDdiv = __aeabi_ddiv;
103 pDmul = __aeabi_dmul;
104 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700105 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700106 pLmul = __aeabi_lmul;
Ian Rogers21d9e832011-09-23 17:05:09 -0700107 pAllocObjectFromCode = art_alloc_object_from_code;
Elliott Hughesb408de72011-10-04 14:35:05 -0700108 pAllocArrayFromCode = art_alloc_array_from_code;
Ian Rogerse51a5112011-09-23 14:16:35 -0700109 pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
Elliott Hughesb408de72011-10-04 14:35:05 -0700110 pCheckAndAllocArrayFromCode = art_check_and_alloc_array_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700111 pCheckCastFromCode = art_check_cast_from_code;
112 pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
Ian Rogerscbba6ac2011-09-22 16:28:37 -0700113 pInitializeStaticStorage = art_initialize_static_storage_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700114 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbeec1f45042011-09-21 16:03:19 -0700115 pTestSuspendFromCode = art_test_suspend;
Ian Rogersff1ed472011-09-20 13:46:24 -0700116 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
117 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700118 pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
119 pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700120 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
Ian Rogers932746a2011-09-22 18:57:50 -0700121 pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700122 pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700123 pUnlockObjectFromCode = art_unlock_object_from_code;
Ian Rogers67375ac2011-09-14 00:55:44 -0700124#endif
Ian Rogersff1ed472011-09-20 13:46:24 -0700125 pDeliverException = art_deliver_exception_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700126 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
buzbeec396efc2011-09-11 09:36:41 -0700127 pF2l = F2L;
128 pD2l = D2L;
buzbee3ea4ec52011-08-22 17:37:19 -0700129 pMemcpy = memcpy;
buzbeee1931742011-08-28 21:15:53 -0700130 pGet32Static = Field::Get32StaticFromCode;
131 pSet32Static = Field::Set32StaticFromCode;
132 pGet64Static = Field::Get64StaticFromCode;
133 pSet64Static = Field::Set64StaticFromCode;
134 pGetObjStatic = Field::GetObjStaticFromCode;
135 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700136 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700137 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee991e3ac2011-09-29 15:44:22 -0700138 pInstanceofNonTrivialFromCode = Class::IsAssignableFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700139 pLockObjectFromCode = LockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700140 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbeec1f45042011-09-21 16:03:19 -0700141 pCheckSuspendFromCode = artCheckSuspendFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700142 pFindNativeMethod = FindNativeMethod;
143 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbeece302932011-10-04 14:32:18 -0700144 pResolveStringFromCode = ResolveStringFromCode;
buzbee99f27232011-10-05 12:56:36 -0700145 pObjectInit = ObjectInitFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700146 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700147}
148
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700149void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700150 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
151 DCHECK_NE(frame_size, 0u);
152 DCHECK_LT(frame_size, 1024u);
Ian Rogersff1ed472011-09-20 13:46:24 -0700153 byte* next_sp = reinterpret_cast<byte*>(sp_) + frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700154 sp_ = reinterpret_cast<Method**>(next_sp);
Elliott Hughes80609252011-09-23 17:24:51 -0700155 if (*sp_ != NULL) {
156 DCHECK((*sp_)->GetClass() == Method::GetMethodClass() ||
157 (*sp_)->GetClass() == Method::GetConstructorClass());
Ian Rogersff1ed472011-09-20 13:46:24 -0700158 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700159}
160
Ian Rogers90865722011-09-19 11:11:44 -0700161bool Frame::HasMethod() const {
162 return GetMethod() != NULL && (!GetMethod()->IsPhony());
163}
164
Ian Rogersbdb03912011-09-14 00:55:44 -0700165uintptr_t Frame::GetReturnPC() const {
Ian Rogersff1ed472011-09-20 13:46:24 -0700166 byte* pc_addr = reinterpret_cast<byte*>(sp_) + GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700167 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700168}
169
Ian Rogersd6b1f612011-09-27 13:38:14 -0700170uintptr_t Frame::GetVReg(Method* method, int vreg) const {
171 DCHECK(method == GetMethod());
172 int offset = oatVRegOffsetFromMethod(method, vreg);
173 byte* vreg_addr = reinterpret_cast<byte*>(sp_) + offset;
174 return *reinterpret_cast<uintptr_t*>(vreg_addr);
175}
176
Ian Rogersbdb03912011-09-14 00:55:44 -0700177uintptr_t Frame::LoadCalleeSave(int num) const {
178 // Callee saves are held at the top of the frame
179 Method* method = GetMethod();
180 DCHECK(method != NULL);
181 size_t frame_size = method->GetFrameSizeInBytes();
Ian Rogersff1ed472011-09-20 13:46:24 -0700182 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size - ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700183#if defined(__i386__)
184 save_addr -= kPointerSize; // account for return address
185#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700186 return *reinterpret_cast<uintptr_t*>(save_addr);
187}
188
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700189Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700190 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700191 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700192 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700193}
194
Brian Carlstrom78128a62011-09-15 17:21:19 -0700195void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700196 Thread* self = reinterpret_cast<Thread*>(arg);
197 Runtime* runtime = Runtime::Current();
198
199 self->Attach(runtime);
200
Elliott Hughes038a8062011-09-18 14:12:41 -0700201 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700202 if (thread_name != NULL) {
203 SetThreadName(thread_name->ToModifiedUtf8().c_str());
204 }
205
206 // Wait until it's safe to start running code. (There may have been a suspend-all
207 // in progress while we were starting up.)
208 runtime->GetThreadList()->WaitForGo();
209
210 // TODO: say "hi" to the debugger.
211 //if (gDvm.debuggerConnected) {
212 // dvmDbgPostThreadStart(self);
213 //}
214
215 // Invoke the 'run' method of our java.lang.Thread.
216 CHECK(self->peer_ != NULL);
217 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700218 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700219 m->Invoke(self, receiver, NULL, NULL);
220
221 // Detach.
222 runtime->GetThreadList()->Unregister();
223
Carl Shapirob5573532011-07-12 18:22:59 -0700224 return NULL;
225}
226
Elliott Hughes93e74e82011-09-13 11:07:03 -0700227void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700228 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700229}
230
Elliott Hughes01158d72011-09-19 19:47:10 -0700231Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
232 Object* thread = Decode<Object*>(env, java_thread);
233 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
234}
235
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700236size_t FixStackSize(size_t stack_size) {
237 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700238 if (stack_size == 0) {
239 stack_size = Runtime::Current()->GetDefaultStackSize();
240 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700241
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700242 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
243 if (stack_size < PTHREAD_STACK_MIN) {
244 stack_size = PTHREAD_STACK_MIN;
245 }
246
247 // It's likely that callers are trying to ensure they have at least a certain amount of
248 // stack space, so we should add our reserved space on top of what they requested, rather
249 // than implicitly take it away from them.
250 stack_size += Thread::kStackOverflowReservedBytes;
251
252 // Some systems require the stack size to be a multiple of the system page size, so round up.
253 stack_size = RoundUp(stack_size, kPageSize);
254
255 return stack_size;
256}
257
258void Thread::Create(Object* peer, size_t stack_size) {
259 CHECK(peer != NULL);
260
261 stack_size = FixStackSize(stack_size);
262
Elliott Hughes93e74e82011-09-13 11:07:03 -0700263 Thread* native_thread = new Thread;
264 native_thread->peer_ = peer;
265
266 // Thread.start is synchronized, so we know that vmData is 0,
267 // and know that we're not racing to assign it.
268 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700269
270 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700271 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
272 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
273 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
274 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
275 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700276
277 // Let the child know when it's safe to start running.
278 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700279}
280
Elliott Hughes93e74e82011-09-13 11:07:03 -0700281void Thread::Attach(const Runtime* runtime) {
282 InitCpu();
283 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700284
Elliott Hughes93e74e82011-09-13 11:07:03 -0700285 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700286
Elliott Hughes93e74e82011-09-13 11:07:03 -0700287 tid_ = ::art::GetTid();
288 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700289
Elliott Hughes93e74e82011-09-13 11:07:03 -0700290 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700291
Elliott Hughes8d768a92011-09-14 16:35:25 -0700292 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700293
Elliott Hughes93e74e82011-09-13 11:07:03 -0700294 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700295
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700296 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700297}
298
299Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
300 Thread* self = new Thread;
301 self->Attach(runtime);
302
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700303 self->SetState(Thread::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700304
305 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700306
307 // If we're the main thread, ClassLinker won't be created until after we're attached,
308 // so that thread needs a two-stage attach. Regular threads don't need this hack.
309 if (self->thin_lock_id_ != ThreadList::kMainId) {
310 self->CreatePeer(name, as_daemon);
311 }
312
313 return self;
314}
315
Elliott Hughesd369bb72011-09-12 14:41:14 -0700316jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
317 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
318 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
319 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
320 // This will be null in the compiler (and tests), but never in a running system.
321 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
322 return thread_group;
323}
324
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700325void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700326 JNIEnv* env = jni_env_;
327
Elliott Hughesd369bb72011-09-12 14:41:14 -0700328 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
329 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700330 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700331 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700332 jboolean thread_is_daemon = as_daemon;
333
334 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700335 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700336
Elliott Hughes8daa0922011-09-11 13:46:25 -0700337 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700338 peer_ = DecodeJObject(peer);
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700339 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700340
341 // Because we mostly run without code available (in the compiler, in tests), we
342 // manually assign the fields the constructor should have set.
343 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700344 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
345 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
346 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
347 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700348}
349
Elliott Hughesbe759c62011-09-08 19:38:21 -0700350void Thread::InitStackHwm() {
351 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700352 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700353
Ian Rogers932746a2011-09-22 18:57:50 -0700354 void* temp_stack_base;
355 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
356 __FUNCTION__);
357 stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700358
Ian Rogers932746a2011-09-22 18:57:50 -0700359 if (stack_size_ <= kStackOverflowReservedBytes) {
360 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700361 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700362
Ian Rogers932746a2011-09-22 18:57:50 -0700363 // Set stack_end_ to the bottom of the stack saving space of stack overflows
364 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700365
366 // Sanity check.
367 int stack_variable;
368 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700369
Elliott Hughes8d768a92011-09-14 16:35:25 -0700370 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700371}
372
Elliott Hughesa0957642011-09-02 14:27:33 -0700373void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700374 DumpState(os);
375 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700376}
377
Elliott Hughesd92bec42011-09-02 17:04:36 -0700378std::string GetSchedulerGroup(pid_t tid) {
379 // /proc/<pid>/group looks like this:
380 // 2:devices:/
381 // 1:cpuacct,cpu:/
382 // We want the third field from the line whose second field contains the "cpu" token.
383 std::string cgroup_file;
384 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
385 return "";
386 }
387 std::vector<std::string> cgroup_lines;
388 Split(cgroup_file, '\n', cgroup_lines);
389 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
390 std::vector<std::string> cgroup_fields;
391 Split(cgroup_lines[i], ':', cgroup_fields);
392 std::vector<std::string> cgroups;
393 Split(cgroup_fields[1], ',', cgroups);
394 for (size_t i = 0; i < cgroups.size(); ++i) {
395 if (cgroups[i] == "cpu") {
396 return cgroup_fields[2].substr(1); // Skip the leading slash.
397 }
398 }
399 }
400 return "";
401}
402
403void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700404 std::string thread_name("<native thread without managed peer>");
405 std::string group_name;
406 int priority;
407 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700408
Elliott Hughesd369bb72011-09-12 14:41:14 -0700409 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700410 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700411 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700412 priority = gThread_priority->GetInt(peer_);
413 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700414
Elliott Hughes038a8062011-09-18 14:12:41 -0700415 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700416 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700417 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700418 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
419 }
420 } else {
421 // This name may be truncated, but it's the best we can do in the absence of a managed peer.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700422 std::string stats;
423 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
424 size_t start = stats.find('(') + 1;
425 size_t end = stats.find(')') - start;
426 thread_name = stats.substr(start, end);
427 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700428 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700429 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700430
431 int policy;
432 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700433 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700434
435 std::string scheduler_group(GetSchedulerGroup(GetTid()));
436 if (scheduler_group.empty()) {
437 scheduler_group = "default";
438 }
439
Elliott Hughesd92bec42011-09-02 17:04:36 -0700440 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700441 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700442 os << " daemon";
443 }
444 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700445 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700446 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700447
Elliott Hughesd92bec42011-09-02 17:04:36 -0700448 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700449 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700450 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700451 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700452 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700453 << " self=" << reinterpret_cast<const void*>(this) << "\n";
454 os << " | sysTid=" << GetTid()
455 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
456 << " sched=" << policy << "/" << sp.sched_priority
457 << " cgrp=" << scheduler_group
458 << " handle=" << GetImpl() << "\n";
459
460 // Grab the scheduler stats for this thread.
461 std::string scheduler_stats;
462 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
463 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
464 } else {
465 scheduler_stats = "0 0 0";
466 }
467
468 int utime = 0;
469 int stime = 0;
470 int task_cpu = 0;
471 std::string stats;
472 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
473 // Skip the command, which may contain spaces.
474 stats = stats.substr(stats.find(')') + 2);
475 // Extract the three fields we care about.
476 std::vector<std::string> fields;
477 Split(stats, ' ', fields);
478 utime = strtoull(fields[11].c_str(), NULL, 10);
479 stime = strtoull(fields[12].c_str(), NULL, 10);
480 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
481 }
482
483 os << " | schedstat=( " << scheduler_stats << " )"
484 << " utm=" << utime
485 << " stm=" << stime
486 << " core=" << task_cpu
487 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
488}
489
Elliott Hughesd369bb72011-09-12 14:41:14 -0700490struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700491 StackDumpVisitor(std::ostream& os, const Thread* thread)
492 : os(os), thread(thread), frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700493 }
494
Ian Rogersbdb03912011-09-14 00:55:44 -0700495 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700496 }
497
Ian Rogersbdb03912011-09-14 00:55:44 -0700498 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700499 if (!frame.HasMethod()) {
500 return;
501 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700502
503 Method* m = frame.GetMethod();
504 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700505 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700506 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
507
508 os << " at " << PrettyMethod(m, false);
509 if (m->IsNative()) {
510 os << "(Native method)";
511 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700512 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700513 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
514 }
515 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700516
517 if (frame_count++ == 0) {
518 Monitor::DescribeWait(os, thread);
519 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700520 }
521
522 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700523 const Thread* thread;
524 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700525};
526
Elliott Hughesd92bec42011-09-02 17:04:36 -0700527void Thread::DumpStack(std::ostream& os) const {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700528 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700529 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700530}
531
Elliott Hughes8d768a92011-09-14 16:35:25 -0700532Thread::State Thread::SetState(Thread::State new_state) {
533 Thread::State old_state = state_;
534 if (old_state == new_state) {
535 return old_state;
536 }
537
538 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
539 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
540
541 if (new_state == Thread::kRunnable) {
542 /*
543 * Change our status to Thread::kRunnable. The transition requires
544 * that we check for pending suspension, because the VM considers
545 * us to be "asleep" in all other states, and another thread could
546 * be performing a GC now.
547 *
548 * The order of operations is very significant here. One way to
549 * do this wrong is:
550 *
551 * GCing thread Our thread (in kNative)
552 * ------------ ----------------------
553 * check suspend count (== 0)
554 * SuspendAllThreads()
555 * grab suspend-count lock
556 * increment all suspend counts
557 * release suspend-count lock
558 * check thread state (== kNative)
559 * all are suspended, begin GC
560 * set state to kRunnable
561 * (continue executing)
562 *
563 * We can correct this by grabbing the suspend-count lock and
564 * performing both of our operations (check suspend count, set
565 * state) while holding it, now we need to grab a mutex on every
566 * transition to kRunnable.
567 *
568 * What we do instead is change the order of operations so that
569 * the transition to kRunnable happens first. If we then detect
570 * that the suspend count is nonzero, we switch to kSuspended.
571 *
572 * Appropriate compiler and memory barriers are required to ensure
573 * that the operations are observed in the expected order.
574 *
575 * This does create a small window of opportunity where a GC in
576 * progress could observe what appears to be a running thread (if
577 * it happens to look between when we set to kRunnable and when we
578 * switch to kSuspended). At worst this only affects assertions
579 * and thread logging. (We could work around it with some sort
580 * of intermediate "pre-running" state that is generally treated
581 * as equivalent to running, but that doesn't seem worthwhile.)
582 *
583 * We can also solve this by combining the "status" and "suspend
584 * count" fields into a single 32-bit value. This trades the
585 * store/load barrier on transition to kRunnable for an atomic RMW
586 * op on all transitions and all suspend count updates (also, all
587 * accesses to status or the thread count require bit-fiddling).
588 * It also eliminates the brief transition through kRunnable when
589 * the thread is supposed to be suspended. This is possibly faster
590 * on SMP and slightly more correct, but less convenient.
591 */
592 android_atomic_acquire_store(new_state, addr);
593 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
594 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
595 }
596 } else {
597 /*
598 * Not changing to Thread::kRunnable. No additional work required.
599 *
600 * We use a releasing store to ensure that, if we were runnable,
601 * any updates we previously made to objects on the managed heap
602 * will be observed before the state change.
603 */
604 android_atomic_release_store(new_state, addr);
605 }
606
607 return old_state;
608}
609
610void Thread::WaitUntilSuspended() {
611 // TODO: dalvik dropped the waiting thread's priority after a while.
612 // TODO: dalvik timed out and aborted.
613 useconds_t delay = 0;
614 while (GetState() == Thread::kRunnable) {
615 useconds_t new_delay = delay * 2;
616 CHECK_GE(new_delay, delay);
617 delay = new_delay;
618 if (delay == 0) {
619 sched_yield();
620 delay = 10000;
621 } else {
622 usleep(delay);
623 }
624 }
625}
626
Elliott Hughesbe759c62011-09-08 19:38:21 -0700627void Thread::ThreadExitCallback(void* arg) {
628 Thread* self = reinterpret_cast<Thread*>(arg);
629 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700630}
631
Elliott Hughesbe759c62011-09-08 19:38:21 -0700632void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700633 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700634 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700635
636 // Double-check the TLS slot allocation.
637 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700638 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700639 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700640}
Carl Shapirob5573532011-07-12 18:22:59 -0700641
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700642// TODO: make more accessible?
643Class* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
644 Class* c = class_linker->FindPrimitiveClass(descriptor);
645 CHECK(c != NULL) << descriptor;
646 return c;
647}
648
649// TODO: make more accessible?
650Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
651 Class* c = class_linker->FindSystemClass(descriptor);
652 CHECK(c != NULL) << descriptor;
653 return c;
654}
655
656// TODO: make more accessible?
657Field* FindFieldOrDie(Class* c, const char* name, Class* type) {
658 Field* f = c->FindDeclaredInstanceField(name, type);
659 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << PrettyClass(type);
660 return f;
661}
662
663// TODO: make more accessible?
664Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
665 Method* m = c->FindVirtualMethod(name, signature);
666 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
667 return m;
668}
669
Elliott Hughes038a8062011-09-18 14:12:41 -0700670void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -0700671 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
672 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700673
674 Class* boolean_class = FindPrimitiveClassOrDie(class_linker, 'Z');
675 Class* int_class = FindPrimitiveClassOrDie(class_linker, 'I');
676 Class* String_class = FindClassOrDie(class_linker, "Ljava/lang/String;");
677 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
678 Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
679 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
680 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
681 gThrowable = FindClassOrDie(class_linker, "Ljava/lang/Throwable;");
682
683 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", boolean_class);
684 gThread_group = FindFieldOrDie(Thread_class, "group", ThreadGroup_class);
685 gThread_lock = FindFieldOrDie(Thread_class, "lock", gThreadLock);
686 gThread_name = FindFieldOrDie(Thread_class, "name", String_class);
687 gThread_priority = FindFieldOrDie(Thread_class, "priority", int_class);
688 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", UncaughtExceptionHandler_class);
689 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", int_class);
690 gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", String_class);
691 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", Thread_class);
692
693 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
694 gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
695 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
696 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700697
698 // Finish attaching the main thread.
699 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -0700700}
701
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700702void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700703 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700704}
705
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700706uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
707 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
708 return ThreadList::kInvalidId;
709 }
710 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
711 if (managed_thread == NULL) {
712 return ThreadList::kInvalidId;
713 }
714 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
715 Thread* thread = reinterpret_cast<Thread*>(vmData);
716 if (thread == NULL) {
717 return ThreadList::kInvalidId;
718 }
719 return thread->GetThinLockId();
720}
721
Elliott Hughesdcc24742011-09-07 14:02:44 -0700722Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700723 : peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700724 top_of_managed_stack_(),
725 top_of_managed_stack_pc_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700726 wait_mutex_(new Mutex("Thread wait mutex")),
727 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700728 wait_monitor_(NULL),
729 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700730 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700731 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700732 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700733 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700734 native_to_managed_record_(NULL),
735 top_sirt_(NULL),
736 jni_env_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700737 state_(Thread::kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700738 self_(NULL),
739 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700740 exception_(NULL),
741 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700742 class_loader_override_(NULL),
743 long_jump_context_(NULL) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700744 CHECK((sizeof(Thread) % 4) == 0) << sizeof(Thread);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700745}
746
Elliott Hughes02b48d12011-09-07 17:15:51 -0700747void MonitorExitVisitor(const Object* object, void*) {
748 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700749 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700750}
751
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700752Thread::~Thread() {
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700753 SetState(Thread::kRunnable);
754
Elliott Hughes02b48d12011-09-07 17:15:51 -0700755 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700756 if (jni_env_ != NULL) {
757 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
758 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700759
Elliott Hughes93e74e82011-09-13 11:07:03 -0700760 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700761 Object* group = gThread_group->GetObject(peer_);
762
763 // Handle any pending exception.
764 if (IsExceptionPending()) {
765 // Get and clear the exception.
766 Object* exception = GetException();
767 ClearException();
768
769 // If the thread has its own handler, use that.
770 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
771 if (handler == NULL) {
772 // Otherwise use the thread group's default handler.
773 handler = group;
774 }
775
776 // Call the handler.
777 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
778 Object* args[2];
779 args[0] = peer_;
780 args[1] = exception;
781 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
782
783 // If the handler threw, clear that exception too.
784 ClearException();
785 }
786
787 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -0700788 // group can be null if we're in the compiler or a test.
789 if (group != NULL) {
790 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
791 Object* args = peer_;
792 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
793 }
Elliott Hughes29f27422011-09-18 16:02:18 -0700794
795 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700796 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700797
Elliott Hughes29f27422011-09-18 16:02:18 -0700798 // TODO: say "bye" to the debugger.
799 //if (gDvm.debuggerConnected) {
800 // dvmDbgPostThreadDeath(self);
801 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700802
Elliott Hughes29f27422011-09-18 16:02:18 -0700803 // Thread.join() is implemented as an Object.wait() on the Thread.lock
804 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700805 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -0700806 Object* lock = gThread_lock->GetObject(peer_);
807 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700808 if (lock != NULL) {
809 lock->MonitorEnter(self);
810 lock->NotifyAll();
811 lock->MonitorExit(self);
812 }
813 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700814
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700815 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700816 jni_env_ = NULL;
817
818 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700819
820 delete wait_cond_;
821 delete wait_mutex_;
822
823 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700824}
825
Ian Rogers408f79a2011-08-23 18:22:33 -0700826size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700827 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700828 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700829 count += cur->NumberOfReferences();
830 }
831 return count;
832}
833
Ian Rogers408f79a2011-08-23 18:22:33 -0700834bool Thread::SirtContains(jobject obj) {
835 Object** sirt_entry = reinterpret_cast<Object**>(obj);
836 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700837 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700838 // A SIRT should always have a jobject/jclass as a native method is passed
839 // in a this pointer or a class
840 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700841 if ((&cur->References()[0] <= sirt_entry) &&
842 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700843 return true;
844 }
845 }
846 return false;
847}
848
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -0700849void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
850 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
851 size_t num_refs = cur->NumberOfReferences();
852 for (size_t j = 0; j < num_refs; j++) {
853 visitor(cur->References()[j], arg);
854 }
855 }
856}
857
Ian Rogers67375ac2011-09-14 00:55:44 -0700858void Thread::PopSirt() {
859 CHECK(top_sirt_ != NULL);
860 top_sirt_ = top_sirt_->Link();
861}
862
Ian Rogers408f79a2011-08-23 18:22:33 -0700863Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700864 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700865 if (obj == NULL) {
866 return NULL;
867 }
868 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
869 IndirectRefKind kind = GetIndirectRefKind(ref);
870 Object* result;
871 switch (kind) {
872 case kLocal:
873 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700874 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700875 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700876 break;
877 }
878 case kGlobal:
879 {
880 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
881 IndirectReferenceTable& globals = vm->globals;
882 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700883 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700884 break;
885 }
886 case kWeakGlobal:
887 {
888 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
889 IndirectReferenceTable& weak_globals = vm->weak_globals;
890 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700891 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700892 if (result == kClearedJniWeakGlobal) {
893 // This is a special case where it's okay to return NULL.
894 return NULL;
895 }
896 break;
897 }
898 case kSirtOrInvalid:
899 default:
900 // TODO: make stack indirect reference table lookup more efficient
901 // Check if this is a local reference in the SIRT
902 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700903 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700904 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700905 // Assume an invalid local reference is actually a direct pointer.
906 result = reinterpret_cast<Object*>(obj);
907 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700908 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700909 }
910 }
911
912 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700913 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
914 JniAbort(NULL);
915 } else {
916 if (result != kInvalidIndirectRefObject) {
917 Heap::VerifyObject(result);
918 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700919 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700920 return result;
921}
922
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700923class CountStackDepthVisitor : public Thread::StackVisitor {
924 public:
Elliott Hughes29f27422011-09-18 16:02:18 -0700925 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -0700926
Elliott Hughes29f27422011-09-18 16:02:18 -0700927 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
928 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -0700929 // Note we also skip the frame if it doesn't have a method (namely the callee
930 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -0700931 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -0700932 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700933 skipping_ = false;
934 }
935 if (!skipping_) {
936 ++depth_;
937 } else {
938 ++skip_depth_;
939 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700940 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700941
942 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -0700943 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700944 }
945
Elliott Hughes29f27422011-09-18 16:02:18 -0700946 int GetSkipDepth() const {
947 return skip_depth_;
948 }
949
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700950 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700951 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -0700952 uint32_t skip_depth_;
953 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700954};
955
Ian Rogersaaa20802011-09-11 21:47:37 -0700956class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700957 public:
Elliott Hughes29f27422011-09-18 16:02:18 -0700958 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
959 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700960 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -0700961 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -0700962 // Register a local reference as IntArray::Alloc may trigger GC
963 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
964 pc_trace_ = IntArray::Alloc(depth);
965#ifdef MOVING_GARBAGE_COLLECTOR
966 // Re-read after potential GC
967 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
968#endif
969 // Save PC trace in last element of method trace, also places it into the
970 // object graph.
971 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700972 }
973
Ian Rogersaaa20802011-09-11 21:47:37 -0700974 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700975
Ian Rogersbdb03912011-09-14 00:55:44 -0700976 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700977 if (skip_depth_ > 0) {
978 skip_depth_--;
979 return;
980 }
Ian Rogersaaa20802011-09-11 21:47:37 -0700981 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -0700982 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -0700983 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700984 }
985
Ian Rogersaaa20802011-09-11 21:47:37 -0700986 jobject GetInternalStackTrace() const {
987 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700988 }
989
990 private:
Elliott Hughes29f27422011-09-18 16:02:18 -0700991 // How many more frames to skip.
992 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -0700993 // Current position down stack trace
994 uint32_t count_;
995 // Array of return PC values
996 IntArray* pc_trace_;
997 // An array of the methods on the stack, the last entry is a reference to the
998 // PC trace
999 ObjectArray<Object>* method_trace_;
1000 // Local indirect reference table entry for method trace
1001 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001002};
1003
Ian Rogersaaa20802011-09-11 21:47:37 -07001004void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001005 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001006 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001007 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1008 // CHECK(native_to_managed_record_ != NULL);
1009 NativeToManagedRecord* record = native_to_managed_record_;
1010
Ian Rogersbdb03912011-09-14 00:55:44 -07001011 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001012 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001013 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1014 visitor->VisitFrame(frame, pc);
1015 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001016 }
1017 if (record == NULL) {
1018 break;
1019 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001020 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001021 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Ian Rogersbdb03912011-09-14 00:55:44 -07001022 pc = record->last_top_of_managed_stack_pc_;
1023 record = record->link_;
1024 }
1025}
1026
Ian Rogers67375ac2011-09-14 00:55:44 -07001027void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001028 Frame frame = GetTopOfStack();
1029 uintptr_t pc = top_of_managed_stack_pc_;
1030
1031 if (frame.GetSP() != 0) {
1032 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001033 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001034 visitor->VisitFrame(frame, pc);
1035 pc = frame.GetReturnPC();
1036 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001037 if (include_upcall) {
1038 visitor->VisitFrame(frame, pc);
1039 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001040 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001041}
1042
Elliott Hughes01158d72011-09-19 19:47:10 -07001043jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001044 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001045 CountStackDepthVisitor count_visitor;
1046 WalkStack(&count_visitor);
1047 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001048 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001049
Ian Rogersaaa20802011-09-11 21:47:37 -07001050 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001051 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001052
1053 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001054 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001055 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001056
Ian Rogersaaa20802011-09-11 21:47:37 -07001057 return build_trace_visitor.GetInternalStackTrace();
1058}
1059
Elliott Hughes01158d72011-09-19 19:47:10 -07001060jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1061 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001062 // Transition into runnable state to work on Object*/Array*
1063 ScopedJniThreadState ts(env);
1064
1065 // Decode the internal stack trace into the depth, method trace and PC trace
1066 ObjectArray<Object>* method_trace =
1067 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1068 int32_t depth = method_trace->GetLength()-1;
1069 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1070
1071 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1072
Elliott Hughes01158d72011-09-19 19:47:10 -07001073 jobjectArray result;
1074 ObjectArray<StackTraceElement>* java_traces;
1075 if (output_array != NULL) {
1076 // Reuse the array we were given.
1077 result = output_array;
1078 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1079 output_array));
1080 // ...adjusting the number of frames we'll write to not exceed the array length.
1081 depth = std::min(depth, java_traces->GetLength());
1082 } else {
1083 // Create java_trace array and place in local reference table
1084 java_traces = class_linker->AllocStackTraceElementArray(depth);
1085 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1086 }
1087
1088 if (stack_depth != NULL) {
1089 *stack_depth = depth;
1090 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001091
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001092 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001093 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1094 Method* method = down_cast<Method*>(method_trace->Get(i));
1095 uint32_t native_pc = pc_trace->Get(i);
1096 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001097 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001098 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001099
Ian Rogersaaa20802011-09-11 21:47:37 -07001100 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001101 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001102 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001103 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001104 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001105 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001106 method->ToDexPC(native_pc)));
1107#ifdef MOVING_GARBAGE_COLLECTOR
1108 // Re-read after potential GC
1109 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1110 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1111 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1112#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001113 java_traces->Set(i, obj);
1114 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001115 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001116}
1117
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001118void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001119 va_list args;
1120 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001121 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001122 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001123}
1124
1125void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1126 std::string msg;
1127 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001128 ThrowNewException(exception_class_descriptor, msg.c_str());
1129}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001130
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001131void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001132 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001133 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001134 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001135 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001136 descriptor.erase(descriptor.length() - 1);
1137
1138 JNIEnv* env = GetJniEnv();
1139 jclass exception_class = env->FindClass(descriptor.c_str());
1140 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001141 int rc = env->ThrowNew(exception_class, msg);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001142 CHECK_EQ(rc, JNI_OK);
Brian Carlstrombc2f3e32011-09-22 17:16:54 -07001143 env->DeleteLocalRef(exception_class);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001144}
1145
Elliott Hughes79082e32011-08-25 12:07:32 -07001146void Thread::ThrowOutOfMemoryError() {
1147 UNIMPLEMENTED(FATAL);
1148}
1149
Ian Rogersbdb03912011-09-14 00:55:44 -07001150class CatchBlockStackVisitor : public Thread::StackVisitor {
1151 public:
1152 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001153 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1154#ifndef NDEBUG
1155 handler_pc_ = 0xEBADC0DE;
1156 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1157#endif
1158 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001159
Ian Rogersbdb03912011-09-14 00:55:44 -07001160 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1161 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001162 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001163 if (method == NULL) {
1164 // This is the upcall, we remember the frame and last_pc so that we may
1165 // long jump to them
1166 handler_pc_ = pc;
1167 handler_frame_ = fr;
1168 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001169 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001170 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001171 if (method->IsPhony()) {
1172 // ignore callee save method
1173 } else if (method->IsNative()) {
1174 native_method_count_++;
1175 } else {
1176 // Move the PC back 2 bytes as a call will frequently terminate the
1177 // decoding of a particular instruction and we want to make sure we
1178 // get the Dex PC of the instruction with the call and not the
1179 // instruction following.
1180 pc -= 2;
1181 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001182 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001183 if (dex_pc != DexFile::kDexNoIndex) {
1184 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1185 if (found_dex_pc != DexFile::kDexNoIndex) {
1186 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001187 handler_pc_ = method->ToNativePC(found_dex_pc);
1188 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001189 }
1190 }
1191 if (!found_) {
1192 // Caller may be handler, fill in callee saves in context
1193 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001194 }
1195 }
1196 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001197
1198 // Did we find a catch block yet?
1199 bool found_;
1200 // The type of the exception catch block to find
1201 Class* to_find_;
1202 // Frame with found handler or last frame if no handler found
1203 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001204 // PC to branch to for the handler
1205 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001206 // Context that will be the target of the long jump
1207 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001208 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1209 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001210};
1211
Ian Rogersff1ed472011-09-20 13:46:24 -07001212void Thread::DeliverException() {
1213 Throwable *exception = GetException(); // Set exception on thread
1214 CHECK(exception != NULL);
Ian Rogersbdb03912011-09-14 00:55:44 -07001215
1216 Context* long_jump_context = GetLongJumpContext();
1217 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001218 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001219
Ian Rogers67375ac2011-09-14 00:55:44 -07001220 // Pop any SIRT
1221 if (catch_finder.native_method_count_ == 1) {
1222 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001223 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001224 // We only expect the stack crawl to have passed 1 native method as it's terminated
1225 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001226 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001227 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001228 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1229 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001230 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001231}
1232
Ian Rogersbdb03912011-09-14 00:55:44 -07001233Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001234 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001235 if (result == NULL) {
1236 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001237 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001238 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001239 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001240}
1241
Elliott Hughes5f791332011-09-15 17:45:30 -07001242bool Thread::HoldsLock(Object* object) {
1243 if (object == NULL) {
1244 return false;
1245 }
1246 return object->GetLockOwner() == thin_lock_id_;
1247}
1248
Elliott Hughes038a8062011-09-18 14:12:41 -07001249bool Thread::IsDaemon() {
1250 return gThread_daemon->GetBoolean(peer_);
1251}
1252
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001253// blx is 2-byte in Thumb2. Need to offset PC back to a call site.
1254static const int kThumb2InstSize = 2;
1255
Ian Rogersd6b1f612011-09-27 13:38:14 -07001256class ReferenceMapVisitor : public Thread::StackVisitor {
1257 public:
1258 ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1259 context_(context), root_visitor_(root_visitor), arg_(arg) {
1260 }
1261
1262 void VisitFrame(const Frame& frame, uintptr_t pc) {
1263 Method* m = frame.GetMethod();
Ian Rogersd6b1f612011-09-27 13:38:14 -07001264
1265 // Process register map (which native and callee save methods don't have)
1266 if (!m->IsNative() && !m->IsPhony()) {
1267 UniquePtr<art::DexVerifier::RegisterMap> map(art::DexVerifier::GetExpandedRegisterMap(m));
1268
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001269 const uint8_t* reg_bitmap = art::DexVerifier::RegisterMapGetLine(
1270 map.get(),
1271 m->ToDexPC(pc -kThumb2InstSize));
1272
1273 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m, false)
1274 << "@ PC: " << m->ToDexPC(pc - kThumb2InstSize);
1275
Ian Rogersd6b1f612011-09-27 13:38:14 -07001276 CHECK(reg_bitmap != NULL);
1277 ShortArray* vmap = m->GetVMapTable();
1278 // For all dex registers
1279 for (int reg = 0; reg < m->NumRegisters(); ++reg) {
1280 // Does this register hold a reference?
1281 if (TestBitmap(reg, reg_bitmap)) {
1282 // Is the reference in the context or on the stack?
1283 bool in_context = false;
1284 int vmap_offset = -1;
1285 // TODO: take advantage of the registers being ordered
1286 for (int i = 0; i < vmap->GetLength(); i++) {
1287 if (vmap->Get(i) == reg) {
1288 in_context = true;
1289 vmap_offset = i;
1290 break;
1291 }
1292 }
1293 Object* ref;
1294 if (in_context) {
1295 // Compute the register we need to load from the context
1296 uint32_t spill_mask = m->GetCoreSpillMask();
1297 uint32_t reg = 0;
1298 for (int i = 0; i < vmap_offset; i++) {
1299 while ((spill_mask & 1) == 0) {
1300 CHECK_NE(spill_mask, 0u);
1301 spill_mask >>= 1;
1302 reg++;
1303 }
1304 }
1305 ref = reinterpret_cast<Object*>(context_->GetGPR(reg));
1306 } else {
1307 ref = reinterpret_cast<Object*>(frame.GetVReg(m ,reg));
1308 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001309 if (ref != NULL) {
1310 root_visitor_(ref, arg_);
1311 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001312 }
1313 }
1314 }
1315 context_->FillCalleeSaves(frame);
1316 }
1317
1318 private:
1319 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1320 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1321 }
1322
1323 // Context used to build up picture of callee saves
1324 Context* context_;
1325 // Call-back when we visit a root
1326 Heap::RootVisitor* root_visitor_;
1327 // Argument to call-back
1328 void* arg_;
1329};
1330
1331void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001332 if (exception_ != NULL) {
1333 visitor(exception_, arg);
1334 }
1335 if (peer_ != NULL) {
1336 visitor(peer_, arg);
1337 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001338 jni_env_->locals.VisitRoots(visitor, arg);
1339 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001340
1341 SirtVisitRoots(visitor, arg);
1342
Ian Rogersd6b1f612011-09-27 13:38:14 -07001343 // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1344 // delivery.
1345 Context* context = GetLongJumpContext();
1346 // Visit roots on this thread's stack
1347 ReferenceMapVisitor mapper(context, visitor, arg);
1348 WalkStack(&mapper);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001349}
1350
Ian Rogersb033c752011-07-20 12:22:35 -07001351static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001352 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001353 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001354 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001355 "Blocked",
1356 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001357 "Initializing",
1358 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001359 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001360 "VmWait",
1361 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001362};
1363std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001364 int32_t int_state = static_cast<int32_t>(state);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001365 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1366 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001367 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001368 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001369 }
1370 return os;
1371}
1372
Elliott Hughes330304d2011-08-12 14:28:05 -07001373std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1374 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001375 << ",pthread_t=" << thread.GetImpl()
1376 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001377 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001378 << ",state=" << thread.GetState()
1379 << ",peer=" << thread.GetPeer()
1380 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001381 return os;
1382}
1383
Elliott Hughes8daa0922011-09-11 13:46:25 -07001384} // namespace art