blob: e1de92d0d062c11d5ccdb3d43d139baf4976dcbc [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
Elliott Hughesbe759c62011-09-08 19:38:21 -0700376 void* stack_base;
377 size_t stack_size;
378 errno = pthread_attr_getstack(&attributes, &stack_base, &stack_size);
379 if (errno != 0) {
380 PLOG(FATAL) << "pthread_attr_getstack failed";
381 }
382
383 const size_t kStackOverflowReservedBytes = 1024; // Space to throw a StackOverflowError in.
384 if (stack_size <= kStackOverflowReservedBytes) {
385 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
386 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700387
388 // stack_base is the "lowest addressable byte" of the stack.
389 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
390 // to throw a StackOverflowError.
391 stack_end_ = reinterpret_cast<byte*>(stack_base) - kStackOverflowReservedBytes;
392
393 // Sanity check.
394 int stack_variable;
395 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700396
397 errno = pthread_attr_destroy(&attributes);
398 if (errno != 0) {
399 PLOG(FATAL) << "pthread_attr_destroy failed";
400 }
401}
402
Elliott Hughesa0957642011-09-02 14:27:33 -0700403void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700404 /*
405 * Get the java.lang.Thread object. This function gets called from
406 * some weird debug contexts, so it's possible that there's a GC in
407 * progress on some other thread. To decrease the chances of the
408 * thread object being moved out from under us, we add the reference
409 * to the tracked allocation list, which pins it in place.
410 *
411 * If threadObj is NULL, the thread is still in the process of being
412 * attached to the VM, and there's really nothing interesting to
413 * say about it yet.
414 */
415 os << "TODO: pin Thread before dumping\n";
416#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700417 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
418 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700419 LOGI("Can't dump thread %d: threadObj not set", threadId);
420 return;
421 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700422 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700423#endif
424
425 DumpState(os);
426 DumpStack(os);
427
428#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700429 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700430#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700431}
432
Elliott Hughesd92bec42011-09-02 17:04:36 -0700433std::string GetSchedulerGroup(pid_t tid) {
434 // /proc/<pid>/group looks like this:
435 // 2:devices:/
436 // 1:cpuacct,cpu:/
437 // We want the third field from the line whose second field contains the "cpu" token.
438 std::string cgroup_file;
439 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
440 return "";
441 }
442 std::vector<std::string> cgroup_lines;
443 Split(cgroup_file, '\n', cgroup_lines);
444 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
445 std::vector<std::string> cgroup_fields;
446 Split(cgroup_lines[i], ':', cgroup_fields);
447 std::vector<std::string> cgroups;
448 Split(cgroup_fields[1], ',', cgroups);
449 for (size_t i = 0; i < cgroups.size(); ++i) {
450 if (cgroups[i] == "cpu") {
451 return cgroup_fields[2].substr(1); // Skip the leading slash.
452 }
453 }
454 }
455 return "";
456}
457
458void Thread::DumpState(std::ostream& os) const {
459 std::string thread_name("unknown");
460 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700461
Elliott Hughesd92bec42011-09-02 17:04:36 -0700462#if 0 // TODO
463 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
464 threadName = dvmCreateCstrFromString(nameStr);
465 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700466#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700467 {
468 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
469 std::string stats;
470 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
471 size_t start = stats.find('(') + 1;
472 size_t end = stats.find(')') - start;
473 thread_name = stats.substr(start, end);
474 }
475 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700476 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700477#endif
478
479 int policy;
480 sched_param sp;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700481 errno = pthread_getschedparam(pthread_, &policy, &sp);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700482 if (errno != 0) {
483 PLOG(FATAL) << "pthread_getschedparam failed";
484 }
485
486 std::string scheduler_group(GetSchedulerGroup(GetTid()));
487 if (scheduler_group.empty()) {
488 scheduler_group = "default";
489 }
490
491 std::string group_name("(null; initializing?)");
492#if 0
493 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
494 if (groupObj != NULL) {
495 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
496 groupName = dvmCreateCstrFromString(nameStr);
497 }
498#else
499 group_name = "TODO";
500#endif
501
502 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700503 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700504 os << " daemon";
505 }
506 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700507 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700508 << " " << state_ << "\n";
509
510 int suspend_count = 0; // TODO
511 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700512 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700513 os << " | group=\"" << group_name << "\""
514 << " sCount=" << suspend_count
515 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700516 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700517 << " self=" << reinterpret_cast<const void*>(this) << "\n";
518 os << " | sysTid=" << GetTid()
519 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
520 << " sched=" << policy << "/" << sp.sched_priority
521 << " cgrp=" << scheduler_group
522 << " handle=" << GetImpl() << "\n";
523
524 // Grab the scheduler stats for this thread.
525 std::string scheduler_stats;
526 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
527 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
528 } else {
529 scheduler_stats = "0 0 0";
530 }
531
532 int utime = 0;
533 int stime = 0;
534 int task_cpu = 0;
535 std::string stats;
536 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
537 // Skip the command, which may contain spaces.
538 stats = stats.substr(stats.find(')') + 2);
539 // Extract the three fields we care about.
540 std::vector<std::string> fields;
541 Split(stats, ' ', fields);
542 utime = strtoull(fields[11].c_str(), NULL, 10);
543 stime = strtoull(fields[12].c_str(), NULL, 10);
544 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
545 }
546
547 os << " | schedstat=( " << scheduler_stats << " )"
548 << " utm=" << utime
549 << " stm=" << stime
550 << " core=" << task_cpu
551 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
552}
553
554void Thread::DumpStack(std::ostream& os) const {
555 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700556}
557
Elliott Hughesbe759c62011-09-08 19:38:21 -0700558void Thread::ThreadExitCallback(void* arg) {
559 Thread* self = reinterpret_cast<Thread*>(arg);
560 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700561}
562
Elliott Hughesbe759c62011-09-08 19:38:21 -0700563void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700564 // Allocate a TLS slot.
Elliott Hughesbe759c62011-09-08 19:38:21 -0700565 errno = pthread_key_create(&Thread::pthread_key_self_, Thread::ThreadExitCallback);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700566 if (errno != 0) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700567 PLOG(FATAL) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700568 }
569
570 // Double-check the TLS slot allocation.
571 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700572 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700573 }
574
575 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700576}
577
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700578void Thread::Shutdown() {
579 errno = pthread_key_delete(Thread::pthread_key_self_);
580 if (errno != 0) {
581 PLOG(WARNING) << "pthread_key_delete failed";
582 }
583}
584
Elliott Hughesdcc24742011-09-07 14:02:44 -0700585Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700586 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700587 top_of_managed_stack_(),
588 native_to_managed_record_(NULL),
589 top_sirt_(NULL),
590 jni_env_(NULL),
591 exception_(NULL),
592 suspend_count_(0),
593 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700594 InitCpu();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700595 {
596 ThreadListLock mu;
597 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
598 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700599 InitFunctionPointers();
600}
601
Elliott Hughes02b48d12011-09-07 17:15:51 -0700602void MonitorExitVisitor(const Object* object, void*) {
603 Object* entered_monitor = const_cast<Object*>(object);
604 entered_monitor->MonitorExit();;
605}
606
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700607Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700608 // TODO: check we're not calling the JNI DetachCurrentThread function from
609 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
610
611 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
612 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
613
614 if (IsExceptionPending()) {
615 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
616 }
617
618 // TODO: ThreadGroup.removeThread(this);
619
620 // TODO: this.vmData = 0;
621
622 // TODO: say "bye" to the debugger.
623 //if (gDvm.debuggerConnected) {
624 // dvmDbgPostThreadDeath(self);
625 //}
626
627 // Thread.join() is implemented as an Object.wait() on the Thread.lock
628 // object. Signal anyone who is waiting.
629 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
630 //dvmLockObject(self, lock);
631 //dvmObjectNotifyAll(self, lock);
632 //dvmUnlockObject(self, lock);
633 //lock = NULL;
634
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700635 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700636 jni_env_ = NULL;
637
638 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700639}
640
Ian Rogers408f79a2011-08-23 18:22:33 -0700641size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700642 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700643 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700644 count += cur->NumberOfReferences();
645 }
646 return count;
647}
648
Ian Rogers408f79a2011-08-23 18:22:33 -0700649bool Thread::SirtContains(jobject obj) {
650 Object** sirt_entry = reinterpret_cast<Object**>(obj);
651 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700652 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700653 // A SIRT should always have a jobject/jclass as a native method is passed
654 // in a this pointer or a class
655 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700656 if ((&cur->References()[0] <= sirt_entry) &&
657 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700658 return true;
659 }
660 }
661 return false;
662}
663
Ian Rogers408f79a2011-08-23 18:22:33 -0700664Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700665 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700666 if (obj == NULL) {
667 return NULL;
668 }
669 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
670 IndirectRefKind kind = GetIndirectRefKind(ref);
671 Object* result;
672 switch (kind) {
673 case kLocal:
674 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700675 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700676 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700677 break;
678 }
679 case kGlobal:
680 {
681 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
682 IndirectReferenceTable& globals = vm->globals;
683 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700684 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700685 break;
686 }
687 case kWeakGlobal:
688 {
689 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
690 IndirectReferenceTable& weak_globals = vm->weak_globals;
691 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700692 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700693 if (result == kClearedJniWeakGlobal) {
694 // This is a special case where it's okay to return NULL.
695 return NULL;
696 }
697 break;
698 }
699 case kSirtOrInvalid:
700 default:
701 // TODO: make stack indirect reference table lookup more efficient
702 // Check if this is a local reference in the SIRT
703 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700704 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700705 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700706 // Assume an invalid local reference is actually a direct pointer.
707 result = reinterpret_cast<Object*>(obj);
708 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700709 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700710 }
711 }
712
713 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700714 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
715 JniAbort(NULL);
716 } else {
717 if (result != kInvalidIndirectRefObject) {
718 Heap::VerifyObject(result);
719 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700720 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700721 return result;
722}
723
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700724class CountStackDepthVisitor : public Thread::StackVisitor {
725 public:
726 CountStackDepthVisitor() : depth(0) {}
727 virtual bool VisitFrame(const Frame&) {
728 ++depth;
729 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700730 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700731
732 int GetDepth() const {
733 return depth;
734 }
735
736 private:
737 uint32_t depth;
738};
739
740class BuildStackTraceVisitor : public Thread::StackVisitor {
741 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700742 explicit BuildStackTraceVisitor(int depth) : count(0) {
743 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700744 pc_trace = IntArray::Alloc(depth);
745 }
746
747 virtual ~BuildStackTraceVisitor() {}
748
749 virtual bool VisitFrame(const Frame& frame) {
750 method_trace->Set(count, frame.GetMethod());
751 pc_trace->Set(count, frame.GetPC());
752 ++count;
753 return true;
754 }
755
756 const Method* GetMethod(uint32_t i) {
757 DCHECK(i < count);
758 return method_trace->Get(i);
759 }
760
761 uintptr_t GetPC(uint32_t i) {
762 DCHECK(i < count);
763 return pc_trace->Get(i);
764 }
765
766 private:
767 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700768 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700769 IntArray* pc_trace;
770};
771
772void Thread::WalkStack(StackVisitor* visitor) {
773 Frame frame = Thread::Current()->GetTopOfStack();
774 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
775 // CHECK(native_to_managed_record_ != NULL);
776 NativeToManagedRecord* record = native_to_managed_record_;
777
778 while (frame.GetSP()) {
779 for ( ; frame.GetMethod() != 0; frame.Next()) {
780 visitor->VisitFrame(frame);
781 }
782 if (record == NULL) {
783 break;
784 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700785 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 -0700786 record = record->link;
787 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700788}
789
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700790ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700791 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700792
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700793 CountStackDepthVisitor count_visitor;
794 WalkStack(&count_visitor);
795 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700796
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700797 BuildStackTraceVisitor build_trace_visitor(depth);
798 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700799
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700800 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700801
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700802 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700803 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700804 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700805 const Class* klass = method->GetDeclaringClass();
806 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700807 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700808 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700809
810 StackTraceElement* obj =
811 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700812 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700813 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700814 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700815 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700816 java_traces->Set(i, obj);
817 }
818 return java_traces;
819}
820
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700821void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700822 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700823 va_list args;
824 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700825 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700826 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700827
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700828 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700829 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700830 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700831 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700832 descriptor.erase(descriptor.length() - 1);
833
834 JNIEnv* env = GetJniEnv();
835 jclass exception_class = env->FindClass(descriptor.c_str());
836 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
837 int rc = env->ThrowNew(exception_class, msg.c_str());
838 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700839}
840
Elliott Hughes79082e32011-08-25 12:07:32 -0700841void Thread::ThrowOutOfMemoryError() {
842 UNIMPLEMENTED(FATAL);
843}
844
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700845Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
846 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
847 DCHECK(class_linker != NULL);
848
849 Frame cur_frame = GetTopOfStack();
850 for (int unwind_depth = 0; ; unwind_depth++) {
851 const Method* cur_method = cur_frame.GetMethod();
852 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
853 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
854
855 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
856 throw_pc,
857 dex_file,
858 class_linker);
859 if (handler_addr) {
860 *handler_pc = handler_addr;
861 return cur_frame;
862 } else {
863 // Check if we are at the last frame
864 if (cur_frame.HasNext()) {
865 cur_frame.Next();
866 } else {
867 // Either at the top of stack or next frame is native.
868 break;
869 }
870 }
871 }
872 *handler_pc = NULL;
873 return Frame();
874}
875
876void* Thread::FindExceptionHandlerInMethod(const Method* method,
877 void* throw_pc,
878 const DexFile& dex_file,
879 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700880 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700881 exception_ = NULL;
882
883 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700884 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700885 DexFile::CatchHandlerIterator iter;
886 for (iter = dex_file.dexFindCatchHandler(*code_item,
887 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
888 !iter.HasNext();
889 iter.Next()) {
890 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
891 DCHECK(klass != NULL);
892 if (exception_obj->InstanceOf(klass)) {
893 dex_pc = iter.Get().address_;
894 break;
895 }
896 }
897
898 exception_ = exception_obj;
899 if (iter.HasNext()) {
900 return NULL;
901 } else {
902 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
903 }
904}
905
Elliott Hughes410c0c82011-09-01 17:58:25 -0700906void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
907 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
908 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
909 jni_env_->locals.VisitRoots(visitor, arg);
910 jni_env_->monitors.VisitRoots(visitor, arg);
911 // visitThreadStack(visitor, thread, arg);
912 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
913}
914
Ian Rogersb033c752011-07-20 12:22:35 -0700915static const char* kStateNames[] = {
916 "New",
917 "Runnable",
918 "Blocked",
919 "Waiting",
920 "TimedWaiting",
921 "Native",
922 "Terminated",
923};
924std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
925 if (state >= Thread::kNew && state <= Thread::kTerminated) {
926 os << kStateNames[state-Thread::kNew];
927 } else {
928 os << "State[" << static_cast<int>(state) << "]";
929 }
930 return os;
931}
932
Elliott Hughes330304d2011-08-12 14:28:05 -0700933std::ostream& operator<<(std::ostream& os, const Thread& thread) {
934 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700935 << ",pthread_t=" << thread.GetImpl()
936 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700937 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700938 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700939 return os;
940}
941
Carl Shapiro61e019d2011-07-14 16:53:09 -0700942ThreadList* ThreadList::Create() {
943 return new ThreadList;
944}
945
Carl Shapirob5573532011-07-12 18:22:59 -0700946ThreadList::ThreadList() {
947 lock_ = Mutex::Create("ThreadList::Lock");
948}
949
950ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700951 if (Contains(Thread::Current())) {
952 Runtime::Current()->DetachCurrentThread();
953 }
954
955 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700956 // reach this point. This means that all daemon threads had been
957 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700958 // TODO: dump ThreadList if non-empty.
959 CHECK_EQ(list_.size(), 0U);
960
Carl Shapirob5573532011-07-12 18:22:59 -0700961 delete lock_;
962 lock_ = NULL;
963}
964
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700965bool ThreadList::Contains(Thread* thread) {
966 return find(list_.begin(), list_.end(), thread) != list_.end();
967}
968
Elliott Hughesd92bec42011-09-02 17:04:36 -0700969void ThreadList::Dump(std::ostream& os) {
970 MutexLock mu(lock_);
971 os << "DALVIK THREADS (" << list_.size() << "):\n";
972 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
973 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
974 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700975 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700976 }
977}
978
Carl Shapirob5573532011-07-12 18:22:59 -0700979void ThreadList::Register(Thread* thread) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700980 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700981 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700982 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700983 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700984}
985
Elliott Hughes02b48d12011-09-07 17:15:51 -0700986void ThreadList::Unregister() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700987 Thread* self = Thread::Current();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700988
989 //LOG(INFO) << "ThreadList::Unregister() " << self;
990 MutexLock mu(lock_);
991
992 // Remove this thread from the list.
Elliott Hughes02b48d12011-09-07 17:15:51 -0700993 CHECK(Contains(self));
994 list_.remove(self);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700995
996 // Delete the Thread* and release the thin lock id.
Elliott Hughes02b48d12011-09-07 17:15:51 -0700997 uint32_t thin_lock_id = self->thin_lock_id_;
998 delete self;
999 ReleaseThreadId(thin_lock_id);
Elliott Hughesbe759c62011-09-08 19:38:21 -07001000
1001 // Clear the TLS data, so that thread is recognizably detached.
1002 // (It may wish to reattach later.)
1003 errno = pthread_setspecific(Thread::pthread_key_self_, NULL);
1004 if (errno != 0) {
1005 PLOG(FATAL) << "pthread_setspecific failed";
1006 }
Carl Shapirob5573532011-07-12 18:22:59 -07001007}
1008
Elliott Hughes410c0c82011-09-01 17:58:25 -07001009void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
1010 MutexLock mu(lock_);
1011 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
1012 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
1013 (*it)->VisitRoots(visitor, arg);
1014 }
1015}
1016
Elliott Hughes02b48d12011-09-07 17:15:51 -07001017uint32_t ThreadList::AllocThreadId() {
Elliott Hughes92b3b562011-09-08 16:32:26 -07001018 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001019 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1020 if (!allocated_ids_[i]) {
1021 allocated_ids_.set(i);
1022 return i + 1; // Zero is reserved to mean "invalid".
1023 }
1024 }
1025 LOG(FATAL) << "Out of internal thread ids";
1026 return 0;
1027}
1028
1029void ThreadList::ReleaseThreadId(uint32_t id) {
Elliott Hughes92b3b562011-09-08 16:32:26 -07001030 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001031 --id; // Zero is reserved to mean "invalid".
1032 DCHECK(allocated_ids_[id]) << id;
1033 allocated_ids_.reset(id);
1034}
1035
Carl Shapirob5573532011-07-12 18:22:59 -07001036} // namespace