blob: 45ff6dd73ef0bf42abb99fb8adec9307f737a8e2 [file] [log] [blame]
Carl Shapirob5573532011-07-12 18:22:59 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -07004
Ian Rogersb033c752011-07-20 12:22:35 -07005#include <pthread.h>
6#include <sys/mman.h>
Elliott Hughesa0957642011-09-02 14:27:33 -07007
Carl Shapirob5573532011-07-12 18:22:59 -07008#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -07009#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070010#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070011#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070012#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070013
Elliott Hughesa5b897e2011-08-16 11:33:06 -070014#include "class_linker.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070015#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070016#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070017#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070018#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070019#include "runtime_support.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070020#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070021
22namespace art {
23
24pthread_key_t Thread::pthread_key_self_;
25
buzbee4a3164f2011-09-03 11:25:10 -070026// Temporary debugging hook for compiler.
27static void DebugMe(Method* method, uint32_t info) {
28 LOG(INFO) << "DebugMe";
29 if (method != NULL)
30 LOG(INFO) << PrettyMethod(method);
31 LOG(INFO) << "Info: " << info;
32}
33
34/*
35 * TODO: placeholder for a method that can be called by the
36 * invoke-interface trampoline to unwind and handle exception. The
37 * trampoline will arrange it so that the caller appears to be the
38 * callsite of the failed invoke-interface. See comments in
39 * compiler/runtime_support.S
40 */
41extern "C" void artFailedInvokeInterface()
42{
43 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
44}
45
46// TODO: placeholder. See comments in compiler/runtime_support.S
47extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
48 Object* this_object , Method* caller_method)
49{
50 /*
51 * Note: this_object has not yet been null-checked. To match
52 * the old-world state, nullcheck this_object and load
53 * Class* this_class = this_object->GetClass().
54 * See comments and possible thrown exceptions in old-world
55 * Interp.cpp:dvmInterpFindInterfaceMethod, and complete with
56 * new-world FindVirtualMethodForInterface.
57 */
58 UNIMPLEMENTED(FATAL) << "Unimplemented invoke interface";
59 return 0LL;
60}
61
buzbee1b4c8592011-08-31 10:43:51 -070062// TODO: placeholder. This is what generated code will call to throw
63static void ThrowException(Thread* thread, Throwable* exception) {
64 /*
65 * exception may be NULL, in which case this routine should
66 * throw NPE. NOTE: this is a convenience for generated code,
67 * which previuosly did the null check inline and constructed
68 * and threw a NPE if NULL. This routine responsible for setting
69 * exception_ in thread.
70 */
71 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
72}
73
74// TODO: placeholder. Helper function to type
75static Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
76 /*
77 * Should initialize & fix up method->dex_cache_resolved_types_[].
78 * Returns initialized type. Does not return normally if an exception
79 * is thrown, but instead initiates the catch. Should be similar to
80 * ClassLinker::InitializeStaticStorageFromCode.
81 */
82 UNIMPLEMENTED(FATAL);
83 return NULL;
84}
85
buzbee561227c2011-09-02 15:28:19 -070086// TODO: placeholder. Helper function to resolve virtual method
87static void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
88 /*
89 * Slow-path handler on invoke virtual method path in which
90 * base method is unresolved at compile-time. Doesn't need to
91 * return anything - just either ensure that
92 * method->dex_cache_resolved_methods_(method_idx) != NULL or
93 * throw and unwind. The caller will restart call sequence
94 * from the beginning.
95 */
96}
97
buzbee1da522d2011-09-04 11:22:20 -070098// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
99static Array* CheckAndAllocFromCode(uint32_t type_index, Method* method,
100 int32_t component_count)
101{
102 /*
103 * Just a wrapper around Array::AllocFromCode() that additionally
104 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
105 */
106 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
107 return Array::AllocFromCode(type_index, method, component_count);
108}
109
buzbee2a475e72011-09-07 17:19:17 -0700110// TODO: placeholder (throw on failure)
111static void CheckCastFromCode(const Class* a, const Class* b) {
112 if (a->IsAssignableFrom(b)) {
113 return;
114 }
115 UNIMPLEMENTED(FATAL);
116}
117
118// TODO: placeholder
119static void UnlockObjectFromCode(Thread* thread, Object* obj) {
120 // TODO: throw and unwind if lock not held
121 // TODO: throw and unwind on NPE
buzbee4ef76522011-09-08 10:00:32 -0700122 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700123}
124
125// TODO: placeholder
126static void LockObjectFromCode(Thread* thread, Object* obj) {
buzbee4ef76522011-09-08 10:00:32 -0700127 obj->MonitorEnter(thread);
buzbee2a475e72011-09-07 17:19:17 -0700128}
129
buzbee0d966cf2011-09-08 17:34:58 -0700130// TODO: placeholder
131static void CheckSuspendFromCode(Thread* thread) {
132 /*
133 * Code is at a safe point, suspend if needed.
134 * Also, this is where a pending safepoint callback
135 * would be fired.
136 */
137}
138
buzbeecefd1872011-09-09 09:59:52 -0700139// TODO: placeholder
140static void StackOverflowFromCode(Method* method) {
141 //NOTE: to save code space, this handler needs to look up its own Thread*
142 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
143}
144
buzbee3ea4ec52011-08-22 17:37:19 -0700145void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700146#if defined(__arm__)
147 pShlLong = art_shl_long;
148 pShrLong = art_shr_long;
149 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700150 pIdiv = __aeabi_idiv;
151 pIdivmod = __aeabi_idivmod;
152 pI2f = __aeabi_i2f;
153 pF2iz = __aeabi_f2iz;
154 pD2f = __aeabi_d2f;
155 pF2d = __aeabi_f2d;
156 pD2iz = __aeabi_d2iz;
157 pL2f = __aeabi_l2f;
158 pL2d = __aeabi_l2d;
159 pFadd = __aeabi_fadd;
160 pFsub = __aeabi_fsub;
161 pFdiv = __aeabi_fdiv;
162 pFmul = __aeabi_fmul;
163 pFmodf = fmodf;
164 pDadd = __aeabi_dadd;
165 pDsub = __aeabi_dsub;
166 pDdiv = __aeabi_ddiv;
167 pDmul = __aeabi_dmul;
168 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -0700169 pF2l = F2L;
170 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -0700171 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700172 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700173 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700174#endif
buzbeedfd3d702011-08-28 12:56:51 -0700175 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700176 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700177 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700178 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700179 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700180 pGet32Static = Field::Get32StaticFromCode;
181 pSet32Static = Field::Set32StaticFromCode;
182 pGet64Static = Field::Get64StaticFromCode;
183 pSet64Static = Field::Set64StaticFromCode;
184 pGetObjStatic = Field::GetObjStaticFromCode;
185 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700186 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
187 pThrowException = ThrowException;
188 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700189 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700190 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700191 pInstanceofNonTrivialFromCode = Object::InstanceOf;
192 pCheckCastFromCode = CheckCastFromCode;
193 pLockObjectFromCode = LockObjectFromCode;
194 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700195 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700196 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700197 pStackOverflowFromCode = StackOverflowFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700198 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700199}
200
Elliott Hughesbe759c62011-09-08 19:38:21 -0700201Mutex::~Mutex() {
202 errno = pthread_mutex_destroy(&mutex_);
203 if (errno != 0) {
204 PLOG(FATAL) << "pthread_mutex_destroy failed";
205 }
206}
207
Carl Shapirob5573532011-07-12 18:22:59 -0700208Mutex* Mutex::Create(const char* name) {
209 Mutex* mu = new Mutex(name);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700210#ifndef NDEBUG
211 pthread_mutexattr_t debug_attributes;
212 errno = pthread_mutexattr_init(&debug_attributes);
213 if (errno != 0) {
214 PLOG(FATAL) << "pthread_mutexattr_init failed";
215 }
216 errno = pthread_mutexattr_settype(&debug_attributes, PTHREAD_MUTEX_ERRORCHECK);
217 if (errno != 0) {
218 PLOG(FATAL) << "pthread_mutexattr_settype failed";
219 }
Elliott Hughesbe759c62011-09-08 19:38:21 -0700220 errno = pthread_mutex_init(&mu->mutex_, &debug_attributes);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700221 if (errno != 0) {
222 PLOG(FATAL) << "pthread_mutex_init failed";
223 }
224 errno = pthread_mutexattr_destroy(&debug_attributes);
225 if (errno != 0) {
226 PLOG(FATAL) << "pthread_mutexattr_destroy failed";
227 }
228#else
Elliott Hughesbe759c62011-09-08 19:38:21 -0700229 errno = pthread_mutex_init(&mu->mutex_, NULL);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700230 if (errno != 0) {
231 PLOG(FATAL) << "pthread_mutex_init failed";
232 }
233#endif
Carl Shapirob5573532011-07-12 18:22:59 -0700234 return mu;
235}
236
237void Mutex::Lock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700238 int result = pthread_mutex_lock(&mutex_);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700239 if (result != 0) {
240 errno = result;
241 PLOG(FATAL) << "pthread_mutex_lock failed";
242 }
Carl Shapirob5573532011-07-12 18:22:59 -0700243}
244
245bool Mutex::TryLock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700246 int result = pthread_mutex_trylock(&mutex_);
Carl Shapirob5573532011-07-12 18:22:59 -0700247 if (result == EBUSY) {
248 return false;
Carl Shapirob5573532011-07-12 18:22:59 -0700249 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700250 if (result != 0) {
251 errno = result;
252 PLOG(FATAL) << "pthread_mutex_trylock failed";
253 }
254 return true;
Carl Shapirob5573532011-07-12 18:22:59 -0700255}
256
257void Mutex::Unlock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700258 int result = pthread_mutex_unlock(&mutex_);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700259 if (result != 0) {
260 errno = result;
261 PLOG(FATAL) << "pthread_mutex_unlock failed";
262 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700263}
264
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700265void Frame::Next() {
266 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700267 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700268 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700269}
270
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700271uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700272 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700273 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700274 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700275}
276
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700277Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700278 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700279 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700280 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700281}
282
Carl Shapiro61e019d2011-07-14 16:53:09 -0700283void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700284 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700285 return NULL;
286}
287
Brian Carlstromb765be02011-08-17 23:54:10 -0700288Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700289 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
290
Elliott Hughesbe759c62011-09-08 19:38:21 -0700291 size_t stack_size = runtime->GetDefaultStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700292
293 Thread* new_thread = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700294
295 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700296 errno = pthread_attr_init(&attr);
297 if (errno != 0) {
298 PLOG(FATAL) << "pthread_attr_init failed";
299 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700300
Elliott Hughese27955c2011-08-26 15:21:24 -0700301 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
302 if (errno != 0) {
303 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
304 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700305
Elliott Hughese27955c2011-08-26 15:21:24 -0700306 errno = pthread_attr_setstacksize(&attr, stack_size);
307 if (errno != 0) {
308 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
309 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700310
Elliott Hughesbe759c62011-09-08 19:38:21 -0700311 errno = pthread_create(&new_thread->pthread_, &attr, ThreadStart, new_thread);
Elliott Hughese27955c2011-08-26 15:21:24 -0700312 if (errno != 0) {
313 PLOG(FATAL) << "pthread_create failed";
314 }
315
316 errno = pthread_attr_destroy(&attr);
317 if (errno != 0) {
318 PLOG(FATAL) << "pthread_attr_destroy failed";
319 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700320
Elliott Hughesdcc24742011-09-07 14:02:44 -0700321 // TODO: get the "daemon" field from the java.lang.Thread.
322 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
323
Carl Shapiro61e019d2011-07-14 16:53:09 -0700324 return new_thread;
325}
326
Elliott Hughesdcc24742011-09-07 14:02:44 -0700327Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700328 Thread* self = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700329
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700330 self->tid_ = ::art::GetTid();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700331 self->pthread_ = pthread_self();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700332 self->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700333
Elliott Hughesbe759c62011-09-08 19:38:21 -0700334 self->InitStackHwm();
335
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700336 self->state_ = kRunnable;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700337
Elliott Hughesdcc24742011-09-07 14:02:44 -0700338 SetThreadName(name);
339
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700340 errno = pthread_setspecific(Thread::pthread_key_self_, self);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700341 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700342 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700343 }
344
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700345 self->jni_env_ = new JNIEnvExt(self, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700346
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700347 runtime->GetThreadList()->Register(self);
348
349 // If we're the main thread, ClassLinker won't be created until after we're attached,
350 // so that thread needs a two-stage attach. Regular threads don't need this hack.
351 if (self->thin_lock_id_ != ThreadList::kMainId) {
352 self->CreatePeer(name, as_daemon);
353 }
354
355 return self;
356}
357
358void Thread::CreatePeer(const char* name, bool as_daemon) {
359 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
360
361 JNIEnv* env = jni_env_;
362
363 jobject thread_group = NULL;
364 jobject thread_name = env->NewStringUTF(name);
365 jint thread_priority = 123;
366 jboolean thread_is_daemon = as_daemon;
367
368 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700369 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700370 jobject o = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
371 LOG(INFO) << "Created new java.lang.Thread " << (void*) o << " decoded=" << (void*) DecodeJObject(o);
372
373 peer_ = DecodeJObject(o);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700374}
375
Elliott Hughesbe759c62011-09-08 19:38:21 -0700376void Thread::InitStackHwm() {
377 pthread_attr_t attributes;
378 errno = pthread_getattr_np(pthread_, &attributes);
379 if (errno != 0) {
380 PLOG(FATAL) << "pthread_getattr_np failed";
381 }
382
Elliott Hughesbe759c62011-09-08 19:38:21 -0700383 void* stack_base;
384 size_t stack_size;
385 errno = pthread_attr_getstack(&attributes, &stack_base, &stack_size);
386 if (errno != 0) {
387 PLOG(FATAL) << "pthread_attr_getstack failed";
388 }
389
Elliott Hughesbe759c62011-09-08 19:38:21 -0700390 if (stack_size <= kStackOverflowReservedBytes) {
391 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
392 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700393
394 // stack_base is the "lowest addressable byte" of the stack.
395 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
396 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700397 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700398
399 // Sanity check.
400 int stack_variable;
401 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700402
403 errno = pthread_attr_destroy(&attributes);
404 if (errno != 0) {
405 PLOG(FATAL) << "pthread_attr_destroy failed";
406 }
407}
408
Elliott Hughesa0957642011-09-02 14:27:33 -0700409void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700410 /*
411 * Get the java.lang.Thread object. This function gets called from
412 * some weird debug contexts, so it's possible that there's a GC in
413 * progress on some other thread. To decrease the chances of the
414 * thread object being moved out from under us, we add the reference
415 * to the tracked allocation list, which pins it in place.
416 *
417 * If threadObj is NULL, the thread is still in the process of being
418 * attached to the VM, and there's really nothing interesting to
419 * say about it yet.
420 */
421 os << "TODO: pin Thread before dumping\n";
422#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700423 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
424 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700425 LOGI("Can't dump thread %d: threadObj not set", threadId);
426 return;
427 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700428 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700429#endif
430
431 DumpState(os);
432 DumpStack(os);
433
434#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700435 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700436#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700437}
438
Elliott Hughesd92bec42011-09-02 17:04:36 -0700439std::string GetSchedulerGroup(pid_t tid) {
440 // /proc/<pid>/group looks like this:
441 // 2:devices:/
442 // 1:cpuacct,cpu:/
443 // We want the third field from the line whose second field contains the "cpu" token.
444 std::string cgroup_file;
445 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
446 return "";
447 }
448 std::vector<std::string> cgroup_lines;
449 Split(cgroup_file, '\n', cgroup_lines);
450 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
451 std::vector<std::string> cgroup_fields;
452 Split(cgroup_lines[i], ':', cgroup_fields);
453 std::vector<std::string> cgroups;
454 Split(cgroup_fields[1], ',', cgroups);
455 for (size_t i = 0; i < cgroups.size(); ++i) {
456 if (cgroups[i] == "cpu") {
457 return cgroup_fields[2].substr(1); // Skip the leading slash.
458 }
459 }
460 }
461 return "";
462}
463
464void Thread::DumpState(std::ostream& os) const {
465 std::string thread_name("unknown");
466 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700467
Elliott Hughesd92bec42011-09-02 17:04:36 -0700468#if 0 // TODO
469 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
470 threadName = dvmCreateCstrFromString(nameStr);
471 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700472#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700473 {
474 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
475 std::string stats;
476 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
477 size_t start = stats.find('(') + 1;
478 size_t end = stats.find(')') - start;
479 thread_name = stats.substr(start, end);
480 }
481 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700482 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700483#endif
484
485 int policy;
486 sched_param sp;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700487 errno = pthread_getschedparam(pthread_, &policy, &sp);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700488 if (errno != 0) {
489 PLOG(FATAL) << "pthread_getschedparam failed";
490 }
491
492 std::string scheduler_group(GetSchedulerGroup(GetTid()));
493 if (scheduler_group.empty()) {
494 scheduler_group = "default";
495 }
496
497 std::string group_name("(null; initializing?)");
498#if 0
499 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
500 if (groupObj != NULL) {
501 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
502 groupName = dvmCreateCstrFromString(nameStr);
503 }
504#else
505 group_name = "TODO";
506#endif
507
508 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700509 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700510 os << " daemon";
511 }
512 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700513 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700514 << " " << state_ << "\n";
515
516 int suspend_count = 0; // TODO
517 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700518 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700519 os << " | group=\"" << group_name << "\""
520 << " sCount=" << suspend_count
521 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700522 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700523 << " self=" << reinterpret_cast<const void*>(this) << "\n";
524 os << " | sysTid=" << GetTid()
525 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
526 << " sched=" << policy << "/" << sp.sched_priority
527 << " cgrp=" << scheduler_group
528 << " handle=" << GetImpl() << "\n";
529
530 // Grab the scheduler stats for this thread.
531 std::string scheduler_stats;
532 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
533 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
534 } else {
535 scheduler_stats = "0 0 0";
536 }
537
538 int utime = 0;
539 int stime = 0;
540 int task_cpu = 0;
541 std::string stats;
542 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
543 // Skip the command, which may contain spaces.
544 stats = stats.substr(stats.find(')') + 2);
545 // Extract the three fields we care about.
546 std::vector<std::string> fields;
547 Split(stats, ' ', fields);
548 utime = strtoull(fields[11].c_str(), NULL, 10);
549 stime = strtoull(fields[12].c_str(), NULL, 10);
550 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
551 }
552
553 os << " | schedstat=( " << scheduler_stats << " )"
554 << " utm=" << utime
555 << " stm=" << stime
556 << " core=" << task_cpu
557 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
558}
559
560void Thread::DumpStack(std::ostream& os) const {
561 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700562}
563
Elliott Hughesbe759c62011-09-08 19:38:21 -0700564void Thread::ThreadExitCallback(void* arg) {
565 Thread* self = reinterpret_cast<Thread*>(arg);
566 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700567}
568
Elliott Hughesbe759c62011-09-08 19:38:21 -0700569void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700570 // Allocate a TLS slot.
Elliott Hughesbe759c62011-09-08 19:38:21 -0700571 errno = pthread_key_create(&Thread::pthread_key_self_, Thread::ThreadExitCallback);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700572 if (errno != 0) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700573 PLOG(FATAL) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700574 }
575
576 // Double-check the TLS slot allocation.
577 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700578 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700579 }
580
581 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700582}
583
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700584void Thread::Shutdown() {
585 errno = pthread_key_delete(Thread::pthread_key_self_);
586 if (errno != 0) {
587 PLOG(WARNING) << "pthread_key_delete failed";
588 }
589}
590
Elliott Hughesdcc24742011-09-07 14:02:44 -0700591Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700592 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700593 top_of_managed_stack_(),
594 native_to_managed_record_(NULL),
595 top_sirt_(NULL),
596 jni_env_(NULL),
597 exception_(NULL),
598 suspend_count_(0),
599 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700600 InitCpu();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700601 {
602 ThreadListLock mu;
603 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
604 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700605 InitFunctionPointers();
606}
607
Elliott Hughes02b48d12011-09-07 17:15:51 -0700608void MonitorExitVisitor(const Object* object, void*) {
609 Object* entered_monitor = const_cast<Object*>(object);
610 entered_monitor->MonitorExit();;
611}
612
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700613Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700614 // TODO: check we're not calling the JNI DetachCurrentThread function from
615 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
616
617 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
618 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
619
620 if (IsExceptionPending()) {
621 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
622 }
623
624 // TODO: ThreadGroup.removeThread(this);
625
626 // TODO: this.vmData = 0;
627
628 // TODO: say "bye" to the debugger.
629 //if (gDvm.debuggerConnected) {
630 // dvmDbgPostThreadDeath(self);
631 //}
632
633 // Thread.join() is implemented as an Object.wait() on the Thread.lock
634 // object. Signal anyone who is waiting.
635 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
636 //dvmLockObject(self, lock);
637 //dvmObjectNotifyAll(self, lock);
638 //dvmUnlockObject(self, lock);
639 //lock = NULL;
640
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700641 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700642 jni_env_ = NULL;
643
644 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700645}
646
Ian Rogers408f79a2011-08-23 18:22:33 -0700647size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700648 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700649 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700650 count += cur->NumberOfReferences();
651 }
652 return count;
653}
654
Ian Rogers408f79a2011-08-23 18:22:33 -0700655bool Thread::SirtContains(jobject obj) {
656 Object** sirt_entry = reinterpret_cast<Object**>(obj);
657 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700658 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700659 // A SIRT should always have a jobject/jclass as a native method is passed
660 // in a this pointer or a class
661 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700662 if ((&cur->References()[0] <= sirt_entry) &&
663 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700664 return true;
665 }
666 }
667 return false;
668}
669
Ian Rogers408f79a2011-08-23 18:22:33 -0700670Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700671 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700672 if (obj == NULL) {
673 return NULL;
674 }
675 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
676 IndirectRefKind kind = GetIndirectRefKind(ref);
677 Object* result;
678 switch (kind) {
679 case kLocal:
680 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700681 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700682 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700683 break;
684 }
685 case kGlobal:
686 {
687 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
688 IndirectReferenceTable& globals = vm->globals;
689 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700690 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700691 break;
692 }
693 case kWeakGlobal:
694 {
695 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
696 IndirectReferenceTable& weak_globals = vm->weak_globals;
697 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700698 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700699 if (result == kClearedJniWeakGlobal) {
700 // This is a special case where it's okay to return NULL.
701 return NULL;
702 }
703 break;
704 }
705 case kSirtOrInvalid:
706 default:
707 // TODO: make stack indirect reference table lookup more efficient
708 // Check if this is a local reference in the SIRT
709 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700710 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700711 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700712 // Assume an invalid local reference is actually a direct pointer.
713 result = reinterpret_cast<Object*>(obj);
714 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700715 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700716 }
717 }
718
719 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700720 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
721 JniAbort(NULL);
722 } else {
723 if (result != kInvalidIndirectRefObject) {
724 Heap::VerifyObject(result);
725 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700726 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700727 return result;
728}
729
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700730class CountStackDepthVisitor : public Thread::StackVisitor {
731 public:
732 CountStackDepthVisitor() : depth(0) {}
733 virtual bool VisitFrame(const Frame&) {
734 ++depth;
735 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700736 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700737
738 int GetDepth() const {
739 return depth;
740 }
741
742 private:
743 uint32_t depth;
744};
745
746class BuildStackTraceVisitor : public Thread::StackVisitor {
747 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700748 explicit BuildStackTraceVisitor(int depth) : count(0) {
749 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700750 pc_trace = IntArray::Alloc(depth);
751 }
752
753 virtual ~BuildStackTraceVisitor() {}
754
755 virtual bool VisitFrame(const Frame& frame) {
756 method_trace->Set(count, frame.GetMethod());
757 pc_trace->Set(count, frame.GetPC());
758 ++count;
759 return true;
760 }
761
762 const Method* GetMethod(uint32_t i) {
763 DCHECK(i < count);
764 return method_trace->Get(i);
765 }
766
767 uintptr_t GetPC(uint32_t i) {
768 DCHECK(i < count);
769 return pc_trace->Get(i);
770 }
771
772 private:
773 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700774 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700775 IntArray* pc_trace;
776};
777
778void Thread::WalkStack(StackVisitor* visitor) {
779 Frame frame = Thread::Current()->GetTopOfStack();
780 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
781 // CHECK(native_to_managed_record_ != NULL);
782 NativeToManagedRecord* record = native_to_managed_record_;
783
784 while (frame.GetSP()) {
785 for ( ; frame.GetMethod() != 0; frame.Next()) {
786 visitor->VisitFrame(frame);
787 }
788 if (record == NULL) {
789 break;
790 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700791 frame.SetSP(reinterpret_cast<art::Method**>(record->last_top_of_managed_stack)); // last_tos should return Frame instead of sp?
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700792 record = record->link;
793 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700794}
795
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700796ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700797 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700798
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700799 CountStackDepthVisitor count_visitor;
800 WalkStack(&count_visitor);
801 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700802
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700803 BuildStackTraceVisitor build_trace_visitor(depth);
804 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700805
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700806 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700807
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700808 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700809 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700810 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700811 const Class* klass = method->GetDeclaringClass();
812 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700813 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700814 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700815
816 StackTraceElement* obj =
817 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700818 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700819 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700820 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700821 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700822 java_traces->Set(i, obj);
823 }
824 return java_traces;
825}
826
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700827void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700828 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700829 va_list args;
830 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700831 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700832 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700833
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700834 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700835 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700836 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700837 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700838 descriptor.erase(descriptor.length() - 1);
839
840 JNIEnv* env = GetJniEnv();
841 jclass exception_class = env->FindClass(descriptor.c_str());
842 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
843 int rc = env->ThrowNew(exception_class, msg.c_str());
844 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700845}
846
Elliott Hughes79082e32011-08-25 12:07:32 -0700847void Thread::ThrowOutOfMemoryError() {
848 UNIMPLEMENTED(FATAL);
849}
850
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700851Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
852 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
853 DCHECK(class_linker != NULL);
854
855 Frame cur_frame = GetTopOfStack();
856 for (int unwind_depth = 0; ; unwind_depth++) {
857 const Method* cur_method = cur_frame.GetMethod();
858 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
859 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
860
861 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
862 throw_pc,
863 dex_file,
864 class_linker);
865 if (handler_addr) {
866 *handler_pc = handler_addr;
867 return cur_frame;
868 } else {
869 // Check if we are at the last frame
870 if (cur_frame.HasNext()) {
871 cur_frame.Next();
872 } else {
873 // Either at the top of stack or next frame is native.
874 break;
875 }
876 }
877 }
878 *handler_pc = NULL;
879 return Frame();
880}
881
882void* Thread::FindExceptionHandlerInMethod(const Method* method,
883 void* throw_pc,
884 const DexFile& dex_file,
885 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700886 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700887 exception_ = NULL;
888
889 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700890 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700891 DexFile::CatchHandlerIterator iter;
892 for (iter = dex_file.dexFindCatchHandler(*code_item,
893 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
894 !iter.HasNext();
895 iter.Next()) {
896 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
897 DCHECK(klass != NULL);
898 if (exception_obj->InstanceOf(klass)) {
899 dex_pc = iter.Get().address_;
900 break;
901 }
902 }
903
904 exception_ = exception_obj;
905 if (iter.HasNext()) {
906 return NULL;
907 } else {
908 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
909 }
910}
911
Elliott Hughes410c0c82011-09-01 17:58:25 -0700912void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
913 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
914 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
915 jni_env_->locals.VisitRoots(visitor, arg);
916 jni_env_->monitors.VisitRoots(visitor, arg);
917 // visitThreadStack(visitor, thread, arg);
918 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
919}
920
Ian Rogersb033c752011-07-20 12:22:35 -0700921static const char* kStateNames[] = {
922 "New",
923 "Runnable",
924 "Blocked",
925 "Waiting",
926 "TimedWaiting",
927 "Native",
928 "Terminated",
929};
930std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
931 if (state >= Thread::kNew && state <= Thread::kTerminated) {
932 os << kStateNames[state-Thread::kNew];
933 } else {
934 os << "State[" << static_cast<int>(state) << "]";
935 }
936 return os;
937}
938
Elliott Hughes330304d2011-08-12 14:28:05 -0700939std::ostream& operator<<(std::ostream& os, const Thread& thread) {
940 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700941 << ",pthread_t=" << thread.GetImpl()
942 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700943 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700944 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700945 return os;
946}
947
Carl Shapiro61e019d2011-07-14 16:53:09 -0700948ThreadList* ThreadList::Create() {
949 return new ThreadList;
950}
951
Carl Shapirob5573532011-07-12 18:22:59 -0700952ThreadList::ThreadList() {
953 lock_ = Mutex::Create("ThreadList::Lock");
954}
955
956ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700957 if (Contains(Thread::Current())) {
958 Runtime::Current()->DetachCurrentThread();
959 }
960
961 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700962 // reach this point. This means that all daemon threads had been
963 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700964 // TODO: dump ThreadList if non-empty.
965 CHECK_EQ(list_.size(), 0U);
966
Carl Shapirob5573532011-07-12 18:22:59 -0700967 delete lock_;
968 lock_ = NULL;
969}
970
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700971bool ThreadList::Contains(Thread* thread) {
972 return find(list_.begin(), list_.end(), thread) != list_.end();
973}
974
Elliott Hughesd92bec42011-09-02 17:04:36 -0700975void ThreadList::Dump(std::ostream& os) {
976 MutexLock mu(lock_);
977 os << "DALVIK THREADS (" << list_.size() << "):\n";
978 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
979 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
980 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700981 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700982 }
983}
984
Carl Shapirob5573532011-07-12 18:22:59 -0700985void ThreadList::Register(Thread* thread) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700986 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700987 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700988 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700989 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700990}
991
Elliott Hughes02b48d12011-09-07 17:15:51 -0700992void ThreadList::Unregister() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700993 Thread* self = Thread::Current();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700994
995 //LOG(INFO) << "ThreadList::Unregister() " << self;
996 MutexLock mu(lock_);
997
998 // Remove this thread from the list.
Elliott Hughes02b48d12011-09-07 17:15:51 -0700999 CHECK(Contains(self));
1000 list_.remove(self);
Elliott Hughesbe759c62011-09-08 19:38:21 -07001001
1002 // Delete the Thread* and release the thin lock id.
Elliott Hughes02b48d12011-09-07 17:15:51 -07001003 uint32_t thin_lock_id = self->thin_lock_id_;
1004 delete self;
1005 ReleaseThreadId(thin_lock_id);
Elliott Hughesbe759c62011-09-08 19:38:21 -07001006
1007 // Clear the TLS data, so that thread is recognizably detached.
1008 // (It may wish to reattach later.)
1009 errno = pthread_setspecific(Thread::pthread_key_self_, NULL);
1010 if (errno != 0) {
1011 PLOG(FATAL) << "pthread_setspecific failed";
1012 }
Carl Shapirob5573532011-07-12 18:22:59 -07001013}
1014
Elliott Hughes410c0c82011-09-01 17:58:25 -07001015void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
1016 MutexLock mu(lock_);
1017 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
1018 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
1019 (*it)->VisitRoots(visitor, arg);
1020 }
1021}
1022
Elliott Hughes02b48d12011-09-07 17:15:51 -07001023uint32_t ThreadList::AllocThreadId() {
Elliott Hughes92b3b562011-09-08 16:32:26 -07001024 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001025 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1026 if (!allocated_ids_[i]) {
1027 allocated_ids_.set(i);
1028 return i + 1; // Zero is reserved to mean "invalid".
1029 }
1030 }
1031 LOG(FATAL) << "Out of internal thread ids";
1032 return 0;
1033}
1034
1035void ThreadList::ReleaseThreadId(uint32_t id) {
Elliott Hughes92b3b562011-09-08 16:32:26 -07001036 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001037 --id; // Zero is reserved to mean "invalid".
1038 DCHECK(allocated_ids_[id]) << id;
1039 allocated_ids_.reset(id);
1040}
1041
Carl Shapirob5573532011-07-12 18:22:59 -07001042} // namespace