blob: c771c5b17373dfe053c8dda114af8cd77a93a99b [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
buzbee3ea4ec52011-08-22 17:37:19 -0700139void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700140#if defined(__arm__)
141 pShlLong = art_shl_long;
142 pShrLong = art_shr_long;
143 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700144 pIdiv = __aeabi_idiv;
145 pIdivmod = __aeabi_idivmod;
146 pI2f = __aeabi_i2f;
147 pF2iz = __aeabi_f2iz;
148 pD2f = __aeabi_d2f;
149 pF2d = __aeabi_f2d;
150 pD2iz = __aeabi_d2iz;
151 pL2f = __aeabi_l2f;
152 pL2d = __aeabi_l2d;
153 pFadd = __aeabi_fadd;
154 pFsub = __aeabi_fsub;
155 pFdiv = __aeabi_fdiv;
156 pFmul = __aeabi_fmul;
157 pFmodf = fmodf;
158 pDadd = __aeabi_dadd;
159 pDsub = __aeabi_dsub;
160 pDdiv = __aeabi_ddiv;
161 pDmul = __aeabi_dmul;
162 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -0700163 pF2l = F2L;
164 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -0700165 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700166 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700167 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700168#endif
buzbeedfd3d702011-08-28 12:56:51 -0700169 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700170 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700171 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700172 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700173 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700174 pGet32Static = Field::Get32StaticFromCode;
175 pSet32Static = Field::Set32StaticFromCode;
176 pGet64Static = Field::Get64StaticFromCode;
177 pSet64Static = Field::Set64StaticFromCode;
178 pGetObjStatic = Field::GetObjStaticFromCode;
179 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700180 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
181 pThrowException = ThrowException;
182 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700183 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700184 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700185 pInstanceofNonTrivialFromCode = Object::InstanceOf;
186 pCheckCastFromCode = CheckCastFromCode;
187 pLockObjectFromCode = LockObjectFromCode;
188 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700189 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700190 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700191 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700192}
193
Elliott Hughesbe759c62011-09-08 19:38:21 -0700194Mutex::~Mutex() {
195 errno = pthread_mutex_destroy(&mutex_);
196 if (errno != 0) {
197 PLOG(FATAL) << "pthread_mutex_destroy failed";
198 }
199}
200
Carl Shapirob5573532011-07-12 18:22:59 -0700201Mutex* Mutex::Create(const char* name) {
202 Mutex* mu = new Mutex(name);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700203#ifndef NDEBUG
204 pthread_mutexattr_t debug_attributes;
205 errno = pthread_mutexattr_init(&debug_attributes);
206 if (errno != 0) {
207 PLOG(FATAL) << "pthread_mutexattr_init failed";
208 }
209 errno = pthread_mutexattr_settype(&debug_attributes, PTHREAD_MUTEX_ERRORCHECK);
210 if (errno != 0) {
211 PLOG(FATAL) << "pthread_mutexattr_settype failed";
212 }
Elliott Hughesbe759c62011-09-08 19:38:21 -0700213 errno = pthread_mutex_init(&mu->mutex_, &debug_attributes);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700214 if (errno != 0) {
215 PLOG(FATAL) << "pthread_mutex_init failed";
216 }
217 errno = pthread_mutexattr_destroy(&debug_attributes);
218 if (errno != 0) {
219 PLOG(FATAL) << "pthread_mutexattr_destroy failed";
220 }
221#else
Elliott Hughesbe759c62011-09-08 19:38:21 -0700222 errno = pthread_mutex_init(&mu->mutex_, NULL);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700223 if (errno != 0) {
224 PLOG(FATAL) << "pthread_mutex_init failed";
225 }
226#endif
Carl Shapirob5573532011-07-12 18:22:59 -0700227 return mu;
228}
229
230void Mutex::Lock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700231 int result = pthread_mutex_lock(&mutex_);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700232 if (result != 0) {
233 errno = result;
234 PLOG(FATAL) << "pthread_mutex_lock failed";
235 }
Carl Shapirob5573532011-07-12 18:22:59 -0700236}
237
238bool Mutex::TryLock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700239 int result = pthread_mutex_trylock(&mutex_);
Carl Shapirob5573532011-07-12 18:22:59 -0700240 if (result == EBUSY) {
241 return false;
Carl Shapirob5573532011-07-12 18:22:59 -0700242 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700243 if (result != 0) {
244 errno = result;
245 PLOG(FATAL) << "pthread_mutex_trylock failed";
246 }
247 return true;
Carl Shapirob5573532011-07-12 18:22:59 -0700248}
249
250void Mutex::Unlock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700251 int result = pthread_mutex_unlock(&mutex_);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700252 if (result != 0) {
253 errno = result;
254 PLOG(FATAL) << "pthread_mutex_unlock failed";
255 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700256}
257
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700258void Frame::Next() {
259 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700260 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700261 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700262}
263
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700264uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700265 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700266 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700267 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700268}
269
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700271 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700272 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700273 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700274}
275
Carl Shapiro61e019d2011-07-14 16:53:09 -0700276void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700277 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700278 return NULL;
279}
280
Brian Carlstromb765be02011-08-17 23:54:10 -0700281Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700282 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
283
Elliott Hughesbe759c62011-09-08 19:38:21 -0700284 size_t stack_size = runtime->GetDefaultStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700285
286 Thread* new_thread = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700287
288 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700289 errno = pthread_attr_init(&attr);
290 if (errno != 0) {
291 PLOG(FATAL) << "pthread_attr_init failed";
292 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700293
Elliott Hughese27955c2011-08-26 15:21:24 -0700294 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
295 if (errno != 0) {
296 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
297 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700298
Elliott Hughese27955c2011-08-26 15:21:24 -0700299 errno = pthread_attr_setstacksize(&attr, stack_size);
300 if (errno != 0) {
301 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
302 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700303
Elliott Hughesbe759c62011-09-08 19:38:21 -0700304 errno = pthread_create(&new_thread->pthread_, &attr, ThreadStart, new_thread);
Elliott Hughese27955c2011-08-26 15:21:24 -0700305 if (errno != 0) {
306 PLOG(FATAL) << "pthread_create failed";
307 }
308
309 errno = pthread_attr_destroy(&attr);
310 if (errno != 0) {
311 PLOG(FATAL) << "pthread_attr_destroy failed";
312 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700313
Elliott Hughesdcc24742011-09-07 14:02:44 -0700314 // TODO: get the "daemon" field from the java.lang.Thread.
315 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
316
Carl Shapiro61e019d2011-07-14 16:53:09 -0700317 return new_thread;
318}
319
Elliott Hughesdcc24742011-09-07 14:02:44 -0700320Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700321 Thread* self = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700322
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700323 self->tid_ = ::art::GetTid();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700324 self->pthread_ = pthread_self();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700325 self->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700326
Elliott Hughesbe759c62011-09-08 19:38:21 -0700327 self->InitStackHwm();
328
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700329 self->state_ = kRunnable;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700330
Elliott Hughesdcc24742011-09-07 14:02:44 -0700331 SetThreadName(name);
332
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700333 errno = pthread_setspecific(Thread::pthread_key_self_, self);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700334 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700335 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700336 }
337
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700338 self->jni_env_ = new JNIEnvExt(self, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700339
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700340 runtime->GetThreadList()->Register(self);
341
342 // If we're the main thread, ClassLinker won't be created until after we're attached,
343 // so that thread needs a two-stage attach. Regular threads don't need this hack.
344 if (self->thin_lock_id_ != ThreadList::kMainId) {
345 self->CreatePeer(name, as_daemon);
346 }
347
348 return self;
349}
350
351void Thread::CreatePeer(const char* name, bool as_daemon) {
352 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
353
354 JNIEnv* env = jni_env_;
355
356 jobject thread_group = NULL;
357 jobject thread_name = env->NewStringUTF(name);
358 jint thread_priority = 123;
359 jboolean thread_is_daemon = as_daemon;
360
361 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700362 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700363 jobject o = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
364 LOG(INFO) << "Created new java.lang.Thread " << (void*) o << " decoded=" << (void*) DecodeJObject(o);
365
366 peer_ = DecodeJObject(o);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700367}
368
Elliott Hughesbe759c62011-09-08 19:38:21 -0700369void Thread::InitStackHwm() {
370 pthread_attr_t attributes;
371 errno = pthread_getattr_np(pthread_, &attributes);
372 if (errno != 0) {
373 PLOG(FATAL) << "pthread_getattr_np failed";
374 }
375
376 // stack_base is the "lowest addressable byte" of the stack.
377 void* stack_base;
378 size_t stack_size;
379 errno = pthread_attr_getstack(&attributes, &stack_base, &stack_size);
380 if (errno != 0) {
381 PLOG(FATAL) << "pthread_attr_getstack failed";
382 }
383
384 const size_t kStackOverflowReservedBytes = 1024; // Space to throw a StackOverflowError in.
385 if (stack_size <= kStackOverflowReservedBytes) {
386 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
387 }
388 stack_hwm_ = reinterpret_cast<byte*>(stack_base) + stack_size - kStackOverflowReservedBytes;
389
390 errno = pthread_attr_destroy(&attributes);
391 if (errno != 0) {
392 PLOG(FATAL) << "pthread_attr_destroy failed";
393 }
394}
395
Elliott Hughesa0957642011-09-02 14:27:33 -0700396void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700397 /*
398 * Get the java.lang.Thread object. This function gets called from
399 * some weird debug contexts, so it's possible that there's a GC in
400 * progress on some other thread. To decrease the chances of the
401 * thread object being moved out from under us, we add the reference
402 * to the tracked allocation list, which pins it in place.
403 *
404 * If threadObj is NULL, the thread is still in the process of being
405 * attached to the VM, and there's really nothing interesting to
406 * say about it yet.
407 */
408 os << "TODO: pin Thread before dumping\n";
409#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700410 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
411 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700412 LOGI("Can't dump thread %d: threadObj not set", threadId);
413 return;
414 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700415 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700416#endif
417
418 DumpState(os);
419 DumpStack(os);
420
421#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700422 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700423#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700424}
425
Elliott Hughesd92bec42011-09-02 17:04:36 -0700426std::string GetSchedulerGroup(pid_t tid) {
427 // /proc/<pid>/group looks like this:
428 // 2:devices:/
429 // 1:cpuacct,cpu:/
430 // We want the third field from the line whose second field contains the "cpu" token.
431 std::string cgroup_file;
432 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
433 return "";
434 }
435 std::vector<std::string> cgroup_lines;
436 Split(cgroup_file, '\n', cgroup_lines);
437 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
438 std::vector<std::string> cgroup_fields;
439 Split(cgroup_lines[i], ':', cgroup_fields);
440 std::vector<std::string> cgroups;
441 Split(cgroup_fields[1], ',', cgroups);
442 for (size_t i = 0; i < cgroups.size(); ++i) {
443 if (cgroups[i] == "cpu") {
444 return cgroup_fields[2].substr(1); // Skip the leading slash.
445 }
446 }
447 }
448 return "";
449}
450
451void Thread::DumpState(std::ostream& os) const {
452 std::string thread_name("unknown");
453 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700454
Elliott Hughesd92bec42011-09-02 17:04:36 -0700455#if 0 // TODO
456 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
457 threadName = dvmCreateCstrFromString(nameStr);
458 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700459#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700460 {
461 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
462 std::string stats;
463 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
464 size_t start = stats.find('(') + 1;
465 size_t end = stats.find(')') - start;
466 thread_name = stats.substr(start, end);
467 }
468 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700469 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700470#endif
471
472 int policy;
473 sched_param sp;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700474 errno = pthread_getschedparam(pthread_, &policy, &sp);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700475 if (errno != 0) {
476 PLOG(FATAL) << "pthread_getschedparam failed";
477 }
478
479 std::string scheduler_group(GetSchedulerGroup(GetTid()));
480 if (scheduler_group.empty()) {
481 scheduler_group = "default";
482 }
483
484 std::string group_name("(null; initializing?)");
485#if 0
486 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
487 if (groupObj != NULL) {
488 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
489 groupName = dvmCreateCstrFromString(nameStr);
490 }
491#else
492 group_name = "TODO";
493#endif
494
495 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700496 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700497 os << " daemon";
498 }
499 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700500 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700501 << " " << state_ << "\n";
502
503 int suspend_count = 0; // TODO
504 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700505 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700506 os << " | group=\"" << group_name << "\""
507 << " sCount=" << suspend_count
508 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700509 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700510 << " self=" << reinterpret_cast<const void*>(this) << "\n";
511 os << " | sysTid=" << GetTid()
512 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
513 << " sched=" << policy << "/" << sp.sched_priority
514 << " cgrp=" << scheduler_group
515 << " handle=" << GetImpl() << "\n";
516
517 // Grab the scheduler stats for this thread.
518 std::string scheduler_stats;
519 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
520 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
521 } else {
522 scheduler_stats = "0 0 0";
523 }
524
525 int utime = 0;
526 int stime = 0;
527 int task_cpu = 0;
528 std::string stats;
529 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
530 // Skip the command, which may contain spaces.
531 stats = stats.substr(stats.find(')') + 2);
532 // Extract the three fields we care about.
533 std::vector<std::string> fields;
534 Split(stats, ' ', fields);
535 utime = strtoull(fields[11].c_str(), NULL, 10);
536 stime = strtoull(fields[12].c_str(), NULL, 10);
537 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
538 }
539
540 os << " | schedstat=( " << scheduler_stats << " )"
541 << " utm=" << utime
542 << " stm=" << stime
543 << " core=" << task_cpu
544 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
545}
546
547void Thread::DumpStack(std::ostream& os) const {
548 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700549}
550
Elliott Hughesbe759c62011-09-08 19:38:21 -0700551void Thread::ThreadExitCallback(void* arg) {
552 Thread* self = reinterpret_cast<Thread*>(arg);
553 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700554}
555
Elliott Hughesbe759c62011-09-08 19:38:21 -0700556void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700557 // Allocate a TLS slot.
Elliott Hughesbe759c62011-09-08 19:38:21 -0700558 errno = pthread_key_create(&Thread::pthread_key_self_, Thread::ThreadExitCallback);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700559 if (errno != 0) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700560 PLOG(FATAL) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700561 }
562
563 // Double-check the TLS slot allocation.
564 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700565 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700566 }
567
568 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700569}
570
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700571void Thread::Shutdown() {
572 errno = pthread_key_delete(Thread::pthread_key_self_);
573 if (errno != 0) {
574 PLOG(WARNING) << "pthread_key_delete failed";
575 }
576}
577
Elliott Hughesdcc24742011-09-07 14:02:44 -0700578Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700579 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700580 top_of_managed_stack_(),
581 native_to_managed_record_(NULL),
582 top_sirt_(NULL),
583 jni_env_(NULL),
584 exception_(NULL),
585 suspend_count_(0),
586 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700587 InitCpu();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700588 {
589 ThreadListLock mu;
590 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
591 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700592 InitFunctionPointers();
593}
594
Elliott Hughes02b48d12011-09-07 17:15:51 -0700595void MonitorExitVisitor(const Object* object, void*) {
596 Object* entered_monitor = const_cast<Object*>(object);
597 entered_monitor->MonitorExit();;
598}
599
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700600Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700601 // TODO: check we're not calling the JNI DetachCurrentThread function from
602 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
603
604 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
605 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
606
607 if (IsExceptionPending()) {
608 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
609 }
610
611 // TODO: ThreadGroup.removeThread(this);
612
613 // TODO: this.vmData = 0;
614
615 // TODO: say "bye" to the debugger.
616 //if (gDvm.debuggerConnected) {
617 // dvmDbgPostThreadDeath(self);
618 //}
619
620 // Thread.join() is implemented as an Object.wait() on the Thread.lock
621 // object. Signal anyone who is waiting.
622 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
623 //dvmLockObject(self, lock);
624 //dvmObjectNotifyAll(self, lock);
625 //dvmUnlockObject(self, lock);
626 //lock = NULL;
627
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700628 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700629 jni_env_ = NULL;
630
631 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700632}
633
Ian Rogers408f79a2011-08-23 18:22:33 -0700634size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700635 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700636 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700637 count += cur->NumberOfReferences();
638 }
639 return count;
640}
641
Ian Rogers408f79a2011-08-23 18:22:33 -0700642bool Thread::SirtContains(jobject obj) {
643 Object** sirt_entry = reinterpret_cast<Object**>(obj);
644 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700645 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700646 // A SIRT should always have a jobject/jclass as a native method is passed
647 // in a this pointer or a class
648 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700649 if ((&cur->References()[0] <= sirt_entry) &&
650 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700651 return true;
652 }
653 }
654 return false;
655}
656
Ian Rogers408f79a2011-08-23 18:22:33 -0700657Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700658 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700659 if (obj == NULL) {
660 return NULL;
661 }
662 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
663 IndirectRefKind kind = GetIndirectRefKind(ref);
664 Object* result;
665 switch (kind) {
666 case kLocal:
667 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700668 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700669 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700670 break;
671 }
672 case kGlobal:
673 {
674 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
675 IndirectReferenceTable& globals = vm->globals;
676 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700677 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700678 break;
679 }
680 case kWeakGlobal:
681 {
682 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
683 IndirectReferenceTable& weak_globals = vm->weak_globals;
684 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700685 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700686 if (result == kClearedJniWeakGlobal) {
687 // This is a special case where it's okay to return NULL.
688 return NULL;
689 }
690 break;
691 }
692 case kSirtOrInvalid:
693 default:
694 // TODO: make stack indirect reference table lookup more efficient
695 // Check if this is a local reference in the SIRT
696 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700697 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700698 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700699 // Assume an invalid local reference is actually a direct pointer.
700 result = reinterpret_cast<Object*>(obj);
701 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700702 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700703 }
704 }
705
706 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700707 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
708 JniAbort(NULL);
709 } else {
710 if (result != kInvalidIndirectRefObject) {
711 Heap::VerifyObject(result);
712 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700713 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700714 return result;
715}
716
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700717class CountStackDepthVisitor : public Thread::StackVisitor {
718 public:
719 CountStackDepthVisitor() : depth(0) {}
720 virtual bool VisitFrame(const Frame&) {
721 ++depth;
722 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700723 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700724
725 int GetDepth() const {
726 return depth;
727 }
728
729 private:
730 uint32_t depth;
731};
732
733class BuildStackTraceVisitor : public Thread::StackVisitor {
734 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700735 explicit BuildStackTraceVisitor(int depth) : count(0) {
736 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700737 pc_trace = IntArray::Alloc(depth);
738 }
739
740 virtual ~BuildStackTraceVisitor() {}
741
742 virtual bool VisitFrame(const Frame& frame) {
743 method_trace->Set(count, frame.GetMethod());
744 pc_trace->Set(count, frame.GetPC());
745 ++count;
746 return true;
747 }
748
749 const Method* GetMethod(uint32_t i) {
750 DCHECK(i < count);
751 return method_trace->Get(i);
752 }
753
754 uintptr_t GetPC(uint32_t i) {
755 DCHECK(i < count);
756 return pc_trace->Get(i);
757 }
758
759 private:
760 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700761 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700762 IntArray* pc_trace;
763};
764
765void Thread::WalkStack(StackVisitor* visitor) {
766 Frame frame = Thread::Current()->GetTopOfStack();
767 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
768 // CHECK(native_to_managed_record_ != NULL);
769 NativeToManagedRecord* record = native_to_managed_record_;
770
771 while (frame.GetSP()) {
772 for ( ; frame.GetMethod() != 0; frame.Next()) {
773 visitor->VisitFrame(frame);
774 }
775 if (record == NULL) {
776 break;
777 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700778 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 -0700779 record = record->link;
780 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700781}
782
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700783ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700784 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700785
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700786 CountStackDepthVisitor count_visitor;
787 WalkStack(&count_visitor);
788 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700789
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700790 BuildStackTraceVisitor build_trace_visitor(depth);
791 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700792
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700793 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700794
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700795 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700796 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700797 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700798 const Class* klass = method->GetDeclaringClass();
799 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700800 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700801 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700802
803 StackTraceElement* obj =
804 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700805 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700806 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700807 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700808 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700809 java_traces->Set(i, obj);
810 }
811 return java_traces;
812}
813
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700814void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700815 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700816 va_list args;
817 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700818 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700819 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700820
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700821 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700822 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700823 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700824 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700825 descriptor.erase(descriptor.length() - 1);
826
827 JNIEnv* env = GetJniEnv();
828 jclass exception_class = env->FindClass(descriptor.c_str());
829 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
830 int rc = env->ThrowNew(exception_class, msg.c_str());
831 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700832}
833
Elliott Hughes79082e32011-08-25 12:07:32 -0700834void Thread::ThrowOutOfMemoryError() {
835 UNIMPLEMENTED(FATAL);
836}
837
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700838Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
839 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
840 DCHECK(class_linker != NULL);
841
842 Frame cur_frame = GetTopOfStack();
843 for (int unwind_depth = 0; ; unwind_depth++) {
844 const Method* cur_method = cur_frame.GetMethod();
845 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
846 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
847
848 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
849 throw_pc,
850 dex_file,
851 class_linker);
852 if (handler_addr) {
853 *handler_pc = handler_addr;
854 return cur_frame;
855 } else {
856 // Check if we are at the last frame
857 if (cur_frame.HasNext()) {
858 cur_frame.Next();
859 } else {
860 // Either at the top of stack or next frame is native.
861 break;
862 }
863 }
864 }
865 *handler_pc = NULL;
866 return Frame();
867}
868
869void* Thread::FindExceptionHandlerInMethod(const Method* method,
870 void* throw_pc,
871 const DexFile& dex_file,
872 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700873 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700874 exception_ = NULL;
875
876 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700877 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700878 DexFile::CatchHandlerIterator iter;
879 for (iter = dex_file.dexFindCatchHandler(*code_item,
880 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
881 !iter.HasNext();
882 iter.Next()) {
883 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
884 DCHECK(klass != NULL);
885 if (exception_obj->InstanceOf(klass)) {
886 dex_pc = iter.Get().address_;
887 break;
888 }
889 }
890
891 exception_ = exception_obj;
892 if (iter.HasNext()) {
893 return NULL;
894 } else {
895 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
896 }
897}
898
Elliott Hughes410c0c82011-09-01 17:58:25 -0700899void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
900 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
901 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
902 jni_env_->locals.VisitRoots(visitor, arg);
903 jni_env_->monitors.VisitRoots(visitor, arg);
904 // visitThreadStack(visitor, thread, arg);
905 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
906}
907
Ian Rogersb033c752011-07-20 12:22:35 -0700908static const char* kStateNames[] = {
909 "New",
910 "Runnable",
911 "Blocked",
912 "Waiting",
913 "TimedWaiting",
914 "Native",
915 "Terminated",
916};
917std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
918 if (state >= Thread::kNew && state <= Thread::kTerminated) {
919 os << kStateNames[state-Thread::kNew];
920 } else {
921 os << "State[" << static_cast<int>(state) << "]";
922 }
923 return os;
924}
925
Elliott Hughes330304d2011-08-12 14:28:05 -0700926std::ostream& operator<<(std::ostream& os, const Thread& thread) {
927 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700928 << ",pthread_t=" << thread.GetImpl()
929 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700930 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700931 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700932 return os;
933}
934
Carl Shapiro61e019d2011-07-14 16:53:09 -0700935ThreadList* ThreadList::Create() {
936 return new ThreadList;
937}
938
Carl Shapirob5573532011-07-12 18:22:59 -0700939ThreadList::ThreadList() {
940 lock_ = Mutex::Create("ThreadList::Lock");
941}
942
943ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700944 if (Contains(Thread::Current())) {
945 Runtime::Current()->DetachCurrentThread();
946 }
947
948 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700949 // reach this point. This means that all daemon threads had been
950 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700951 // TODO: dump ThreadList if non-empty.
952 CHECK_EQ(list_.size(), 0U);
953
Carl Shapirob5573532011-07-12 18:22:59 -0700954 delete lock_;
955 lock_ = NULL;
956}
957
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700958bool ThreadList::Contains(Thread* thread) {
959 return find(list_.begin(), list_.end(), thread) != list_.end();
960}
961
Elliott Hughesd92bec42011-09-02 17:04:36 -0700962void ThreadList::Dump(std::ostream& os) {
963 MutexLock mu(lock_);
964 os << "DALVIK THREADS (" << list_.size() << "):\n";
965 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
966 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
967 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700968 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700969 }
970}
971
Carl Shapirob5573532011-07-12 18:22:59 -0700972void ThreadList::Register(Thread* thread) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700973 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700974 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700975 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700976 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700977}
978
Elliott Hughes02b48d12011-09-07 17:15:51 -0700979void ThreadList::Unregister() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700980 Thread* self = Thread::Current();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700981
982 //LOG(INFO) << "ThreadList::Unregister() " << self;
983 MutexLock mu(lock_);
984
985 // Remove this thread from the list.
Elliott Hughes02b48d12011-09-07 17:15:51 -0700986 CHECK(Contains(self));
987 list_.remove(self);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700988
989 // Delete the Thread* and release the thin lock id.
Elliott Hughes02b48d12011-09-07 17:15:51 -0700990 uint32_t thin_lock_id = self->thin_lock_id_;
991 delete self;
992 ReleaseThreadId(thin_lock_id);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700993
994 // Clear the TLS data, so that thread is recognizably detached.
995 // (It may wish to reattach later.)
996 errno = pthread_setspecific(Thread::pthread_key_self_, NULL);
997 if (errno != 0) {
998 PLOG(FATAL) << "pthread_setspecific failed";
999 }
Carl Shapirob5573532011-07-12 18:22:59 -07001000}
1001
Elliott Hughes410c0c82011-09-01 17:58:25 -07001002void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
1003 MutexLock mu(lock_);
1004 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
1005 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
1006 (*it)->VisitRoots(visitor, arg);
1007 }
1008}
1009
Elliott Hughes02b48d12011-09-07 17:15:51 -07001010uint32_t ThreadList::AllocThreadId() {
Elliott Hughes92b3b562011-09-08 16:32:26 -07001011 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001012 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1013 if (!allocated_ids_[i]) {
1014 allocated_ids_.set(i);
1015 return i + 1; // Zero is reserved to mean "invalid".
1016 }
1017 }
1018 LOG(FATAL) << "Out of internal thread ids";
1019 return 0;
1020}
1021
1022void ThreadList::ReleaseThreadId(uint32_t id) {
Elliott Hughes92b3b562011-09-08 16:32:26 -07001023 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001024 --id; // Zero is reserved to mean "invalid".
1025 DCHECK(allocated_ids_[id]) << id;
1026 allocated_ids_.reset(id);
1027}
1028
Carl Shapirob5573532011-07-12 18:22:59 -07001029} // namespace