blob: c90c74516c5ef155cc6519bf642feb3551bb4890 [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>
Carl Shapirob5573532011-07-12 18:22:59 -07007#include <algorithm>
Elliott Hugheseb4f6142011-07-15 17:43:51 -07008#include <cerrno>
Carl Shapirob5573532011-07-12 18:22:59 -07009#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070010
Elliott Hughesa5b897e2011-08-16 11:33:06 -070011#include "class_linker.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070012#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070013#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070014#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070015#include "runtime.h"
16#include "utils.h"
buzbee54330722011-08-23 16:46:55 -070017#include "runtime_support.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
19namespace art {
20
Elliott Hughese27955c2011-08-26 15:21:24 -070021/* desktop Linux needs a little help with gettid() */
22#if !defined(HAVE_ANDROID_OS)
23#define __KERNEL__
24# include <linux/unistd.h>
25#ifdef _syscall0
26_syscall0(pid_t, gettid)
27#else
28pid_t gettid() { return syscall(__NR_gettid);}
29#endif
30#undef __KERNEL__
31#endif
32
Carl Shapirob5573532011-07-12 18:22:59 -070033pthread_key_t Thread::pthread_key_self_;
34
buzbee3ea4ec52011-08-22 17:37:19 -070035void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -070036#if defined(__arm__)
37 pShlLong = art_shl_long;
38 pShrLong = art_shr_long;
39 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -070040 pIdiv = __aeabi_idiv;
41 pIdivmod = __aeabi_idivmod;
42 pI2f = __aeabi_i2f;
43 pF2iz = __aeabi_f2iz;
44 pD2f = __aeabi_d2f;
45 pF2d = __aeabi_f2d;
46 pD2iz = __aeabi_d2iz;
47 pL2f = __aeabi_l2f;
48 pL2d = __aeabi_l2d;
49 pFadd = __aeabi_fadd;
50 pFsub = __aeabi_fsub;
51 pFdiv = __aeabi_fdiv;
52 pFmul = __aeabi_fmul;
53 pFmodf = fmodf;
54 pDadd = __aeabi_dadd;
55 pDsub = __aeabi_dsub;
56 pDdiv = __aeabi_ddiv;
57 pDmul = __aeabi_dmul;
58 pFmod = fmod;
59 pArtF2l = artF2L;
60 pArtD2l = artD2L;
61 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -070062 pLmul = __aeabi_lmul;
buzbee54330722011-08-23 16:46:55 -070063#endif
buzbeedfd3d702011-08-28 12:56:51 -070064 pAllocFromCode = Array::AllocFromCode;
65 pNewInstanceFromCode = Class::NewInstanceFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -070066 pMemcpy = memcpy;
buzbeee6d61962011-08-27 11:58:19 -070067 pArtHandleFillArrayDataNoThrow = artHandleFillArrayDataNoThrow;
buzbeee1931742011-08-28 21:15:53 -070068 pGet32Static = Field::Get32StaticFromCode;
69 pSet32Static = Field::Set32StaticFromCode;
70 pGet64Static = Field::Get64StaticFromCode;
71 pSet64Static = Field::Set64StaticFromCode;
72 pGetObjStatic = Field::GetObjStaticFromCode;
73 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -070074#if 0
buzbee3ea4ec52011-08-22 17:37:19 -070075bool (Thread::*pArtUnlockObject)(struct Thread*, struct Object*);
76bool (Thread::*pArtCanPutArrayElementNoThrow)(const struct ClassObject*,
77 const struct ClassObject*);
78int (Thread::*pArtInstanceofNonTrivialNoThrow)
79 (const struct ClassObject*, const struct ClassObject*);
80int (Thread::*pArtInstanceofNonTrivial) (const struct ClassObject*,
81 const struct ClassObject*);
82struct Method* (Thread::*pArtFindInterfaceMethodInCache)(ClassObject*, uint32_t,
83 const struct Method*, struct DvmDex*);
84bool (Thread::*pArtUnlockObjectNoThrow)(struct Thread*, struct Object*);
85void (Thread::*pArtLockObjectNoThrow)(struct Thread*, struct Object*);
86struct Object* (Thread::*pArtAllocObjectNoThrow)(struct ClassObject*, int);
87void (Thread::*pArtThrowException)(struct Thread*, struct Object*);
88bool (Thread::*pArtHandleFillArrayDataNoThrow)(struct ArrayObject*, const uint16_t*);
89#endif
90}
91
Carl Shapirob5573532011-07-12 18:22:59 -070092Mutex* Mutex::Create(const char* name) {
93 Mutex* mu = new Mutex(name);
94 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Ian Rogersb033c752011-07-20 12:22:35 -070095 CHECK_EQ(0, result);
Carl Shapirob5573532011-07-12 18:22:59 -070096 return mu;
97}
98
99void Mutex::Lock() {
100 int result = pthread_mutex_lock(&lock_impl_);
101 CHECK_EQ(result, 0);
102 SetOwner(Thread::Current());
103}
104
105bool Mutex::TryLock() {
106 int result = pthread_mutex_lock(&lock_impl_);
107 if (result == EBUSY) {
108 return false;
109 } else {
110 CHECK_EQ(result, 0);
111 SetOwner(Thread::Current());
112 return true;
113 }
114}
115
116void Mutex::Unlock() {
117 CHECK(GetOwner() == Thread::Current());
118 int result = pthread_mutex_unlock(&lock_impl_);
119 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700120 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700121}
122
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700123void Frame::Next() {
124 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700125 GetMethod()->GetFrameSizeInBytes();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700126 sp_ = reinterpret_cast<const Method**>(next_sp);
127}
128
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700129uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700130 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700131 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700132 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700133}
134
135const Method* Frame::NextMethod() const {
136 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700137 GetMethod()->GetFrameSizeInBytes();
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700138 return *reinterpret_cast<const Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700139}
140
Carl Shapiro61e019d2011-07-14 16:53:09 -0700141void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700142 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700143 return NULL;
144}
145
Brian Carlstromb765be02011-08-17 23:54:10 -0700146Thread* Thread::Create(const Runtime* runtime) {
147 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700148
149 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700150 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700151
152 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700153 errno = pthread_attr_init(&attr);
154 if (errno != 0) {
155 PLOG(FATAL) << "pthread_attr_init failed";
156 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700157
Elliott Hughese27955c2011-08-26 15:21:24 -0700158 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
159 if (errno != 0) {
160 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
161 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700162
Elliott Hughese27955c2011-08-26 15:21:24 -0700163 errno = pthread_attr_setstacksize(&attr, stack_size);
164 if (errno != 0) {
165 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
166 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700167
Elliott Hughese27955c2011-08-26 15:21:24 -0700168 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
169 if (errno != 0) {
170 PLOG(FATAL) << "pthread_create failed";
171 }
172
173 errno = pthread_attr_destroy(&attr);
174 if (errno != 0) {
175 PLOG(FATAL) << "pthread_attr_destroy failed";
176 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700177
178 return new_thread;
179}
180
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700181Thread* Thread::Attach(const Runtime* runtime) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700182 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700183 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700184
185 thread->handle_ = pthread_self();
186
187 thread->state_ = kRunnable;
188
Elliott Hughesa5780da2011-07-17 11:39:39 -0700189 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
190 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700191 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700192 }
193
Elliott Hughes75770752011-08-24 17:52:38 -0700194 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700195
Carl Shapiro61e019d2011-07-14 16:53:09 -0700196 return thread;
197}
198
Elliott Hughese27955c2011-08-26 15:21:24 -0700199pid_t Thread::GetTid() const {
200 return gettid();
201}
202
Carl Shapirob5573532011-07-12 18:22:59 -0700203static void ThreadExitCheck(void* arg) {
204 LG << "Thread exit check";
205}
206
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700207bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700208 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700209 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
210 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700211 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700212 return false;
213 }
214
215 // Double-check the TLS slot allocation.
216 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700217 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700218 return false;
219 }
220
221 // TODO: initialize other locks and condition variables
222
223 return true;
224}
225
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700226void Thread::Shutdown() {
227 errno = pthread_key_delete(Thread::pthread_key_self_);
228 if (errno != 0) {
229 PLOG(WARNING) << "pthread_key_delete failed";
230 }
231}
232
233Thread::~Thread() {
234 delete jni_env_;
235}
236
Ian Rogers408f79a2011-08-23 18:22:33 -0700237size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700238 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700239 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700240 count += cur->NumberOfReferences();
241 }
242 return count;
243}
244
Ian Rogers408f79a2011-08-23 18:22:33 -0700245bool Thread::SirtContains(jobject obj) {
246 Object** sirt_entry = reinterpret_cast<Object**>(obj);
247 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700248 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700249 // A SIRT should always have a jobject/jclass as a native method is passed
250 // in a this pointer or a class
251 DCHECK_GT(num_refs, 0u);
252 if ((&cur->References()[0] >= sirt_entry) &&
253 (sirt_entry <= (&cur->References()[num_refs-1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700254 return true;
255 }
256 }
257 return false;
258}
259
Ian Rogers408f79a2011-08-23 18:22:33 -0700260Object* Thread::DecodeJObject(jobject obj) {
261 // TODO: Only allowed to hold Object* when in the runnable state
262 // DCHECK(state_ == kRunnable);
263 if (obj == NULL) {
264 return NULL;
265 }
266 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
267 IndirectRefKind kind = GetIndirectRefKind(ref);
268 Object* result;
269 switch (kind) {
270 case kLocal:
271 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700272 IndirectReferenceTable& locals = jni_env_->locals;
Ian Rogers408f79a2011-08-23 18:22:33 -0700273 result = locals.Get(ref);
274 break;
275 }
276 case kGlobal:
277 {
278 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
279 IndirectReferenceTable& globals = vm->globals;
280 MutexLock mu(vm->globals_lock);
281 result = globals.Get(ref);
282 break;
283 }
284 case kWeakGlobal:
285 {
286 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
287 IndirectReferenceTable& weak_globals = vm->weak_globals;
288 MutexLock mu(vm->weak_globals_lock);
289 result = weak_globals.Get(ref);
290 if (result == kClearedJniWeakGlobal) {
291 // This is a special case where it's okay to return NULL.
292 return NULL;
293 }
294 break;
295 }
296 case kSirtOrInvalid:
297 default:
298 // TODO: make stack indirect reference table lookup more efficient
299 // Check if this is a local reference in the SIRT
300 if (SirtContains(obj)) {
301 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
302 } else if (false /*gDvmJni.workAroundAppJniBugs*/) { // TODO
303 // Assume an invalid local reference is actually a direct pointer.
304 result = reinterpret_cast<Object*>(obj);
305 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700306 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700307 }
308 }
309
310 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700311 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
312 JniAbort(NULL);
313 } else {
314 if (result != kInvalidIndirectRefObject) {
315 Heap::VerifyObject(result);
316 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700317 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700318 return result;
319}
320
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700321class CountStackDepthVisitor : public Thread::StackVisitor {
322 public:
323 CountStackDepthVisitor() : depth(0) {}
324 virtual bool VisitFrame(const Frame&) {
325 ++depth;
326 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700327 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700328
329 int GetDepth() const {
330 return depth;
331 }
332
333 private:
334 uint32_t depth;
335};
336
337class BuildStackTraceVisitor : public Thread::StackVisitor {
338 public:
339 BuildStackTraceVisitor(int depth) : count(0) {
340 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<const Method>(depth);
341 pc_trace = IntArray::Alloc(depth);
342 }
343
344 virtual ~BuildStackTraceVisitor() {}
345
346 virtual bool VisitFrame(const Frame& frame) {
347 method_trace->Set(count, frame.GetMethod());
348 pc_trace->Set(count, frame.GetPC());
349 ++count;
350 return true;
351 }
352
353 const Method* GetMethod(uint32_t i) {
354 DCHECK(i < count);
355 return method_trace->Get(i);
356 }
357
358 uintptr_t GetPC(uint32_t i) {
359 DCHECK(i < count);
360 return pc_trace->Get(i);
361 }
362
363 private:
364 uint32_t count;
365 ObjectArray<const Method>* method_trace;
366 IntArray* pc_trace;
367};
368
369void Thread::WalkStack(StackVisitor* visitor) {
370 Frame frame = Thread::Current()->GetTopOfStack();
371 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
372 // CHECK(native_to_managed_record_ != NULL);
373 NativeToManagedRecord* record = native_to_managed_record_;
374
375 while (frame.GetSP()) {
376 for ( ; frame.GetMethod() != 0; frame.Next()) {
377 visitor->VisitFrame(frame);
378 }
379 if (record == NULL) {
380 break;
381 }
382 frame.SetSP(reinterpret_cast<const art::Method**>(record->last_top_of_managed_stack)); // last_tos should return Frame instead of sp?
383 record = record->link;
384 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700385}
386
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700387ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700388 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700389
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700390 CountStackDepthVisitor count_visitor;
391 WalkStack(&count_visitor);
392 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700393
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700394 BuildStackTraceVisitor build_trace_visitor(depth);
395 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700396
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700397 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700398
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700399 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700400 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700401 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700402 const Class* klass = method->GetDeclaringClass();
403 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700404 String* readable_descriptor = String::AllocFromModifiedUtf8(
405 PrettyDescriptor(klass->GetDescriptor()).c_str()
406 );
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700407
408 StackTraceElement* obj =
409 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700410 method->GetName(),
411 String::AllocFromModifiedUtf8(klass->source_file_),
412 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700413 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700414 java_traces->Set(i, obj);
415 }
416 return java_traces;
417}
418
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700419void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700420 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700421 va_list args;
422 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700423 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700424 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700425
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700426 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
427 CHECK(exception_class_descriptor[0] == 'L');
428 std::string descriptor(exception_class_descriptor + 1);
429 CHECK(descriptor[descriptor.length() - 1] == ';');
430 descriptor.erase(descriptor.length() - 1);
431
432 JNIEnv* env = GetJniEnv();
433 jclass exception_class = env->FindClass(descriptor.c_str());
434 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
435 int rc = env->ThrowNew(exception_class, msg.c_str());
436 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700437}
438
Elliott Hughes79082e32011-08-25 12:07:32 -0700439void Thread::ThrowOutOfMemoryError() {
440 UNIMPLEMENTED(FATAL);
441}
442
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700443Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
444 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
445 DCHECK(class_linker != NULL);
446
447 Frame cur_frame = GetTopOfStack();
448 for (int unwind_depth = 0; ; unwind_depth++) {
449 const Method* cur_method = cur_frame.GetMethod();
450 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
451 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
452
453 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
454 throw_pc,
455 dex_file,
456 class_linker);
457 if (handler_addr) {
458 *handler_pc = handler_addr;
459 return cur_frame;
460 } else {
461 // Check if we are at the last frame
462 if (cur_frame.HasNext()) {
463 cur_frame.Next();
464 } else {
465 // Either at the top of stack or next frame is native.
466 break;
467 }
468 }
469 }
470 *handler_pc = NULL;
471 return Frame();
472}
473
474void* Thread::FindExceptionHandlerInMethod(const Method* method,
475 void* throw_pc,
476 const DexFile& dex_file,
477 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700478 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700479 exception_ = NULL;
480
481 intptr_t dex_pc = -1;
482 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->code_off_);
483 DexFile::CatchHandlerIterator iter;
484 for (iter = dex_file.dexFindCatchHandler(*code_item,
485 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
486 !iter.HasNext();
487 iter.Next()) {
488 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
489 DCHECK(klass != NULL);
490 if (exception_obj->InstanceOf(klass)) {
491 dex_pc = iter.Get().address_;
492 break;
493 }
494 }
495
496 exception_ = exception_obj;
497 if (iter.HasNext()) {
498 return NULL;
499 } else {
500 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
501 }
502}
503
Ian Rogersb033c752011-07-20 12:22:35 -0700504static const char* kStateNames[] = {
505 "New",
506 "Runnable",
507 "Blocked",
508 "Waiting",
509 "TimedWaiting",
510 "Native",
511 "Terminated",
512};
513std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
514 if (state >= Thread::kNew && state <= Thread::kTerminated) {
515 os << kStateNames[state-Thread::kNew];
516 } else {
517 os << "State[" << static_cast<int>(state) << "]";
518 }
519 return os;
520}
521
Elliott Hughes330304d2011-08-12 14:28:05 -0700522std::ostream& operator<<(std::ostream& os, const Thread& thread) {
523 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700524 << ",pthread_t=" << thread.GetImpl()
525 << ",tid=" << thread.GetTid()
526 << ",id=" << thread.GetId()
527 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700528 return os;
529}
530
Carl Shapiro61e019d2011-07-14 16:53:09 -0700531ThreadList* ThreadList::Create() {
532 return new ThreadList;
533}
534
Carl Shapirob5573532011-07-12 18:22:59 -0700535ThreadList::ThreadList() {
536 lock_ = Mutex::Create("ThreadList::Lock");
537}
538
539ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700540 if (Contains(Thread::Current())) {
541 Runtime::Current()->DetachCurrentThread();
542 }
543
544 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700545 // reach this point. This means that all daemon threads had been
546 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700547 // TODO: dump ThreadList if non-empty.
548 CHECK_EQ(list_.size(), 0U);
549
Carl Shapirob5573532011-07-12 18:22:59 -0700550 delete lock_;
551 lock_ = NULL;
552}
553
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700554bool ThreadList::Contains(Thread* thread) {
555 return find(list_.begin(), list_.end(), thread) != list_.end();
556}
557
Carl Shapirob5573532011-07-12 18:22:59 -0700558void ThreadList::Register(Thread* thread) {
559 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700560 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700561 list_.push_front(thread);
562}
563
564void ThreadList::Unregister(Thread* thread) {
565 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700566 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700567 list_.remove(thread);
568}
569
Carl Shapirob5573532011-07-12 18:22:59 -0700570} // namespace