blob: 525e2a11e507a7eb2e788336299a2a6e0f12c2b5 [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 {
306 LOG(FATAL) << "Invalid indirect reference " << obj;
307 result = reinterpret_cast<Object*>(kInvalidIndirectRefObject);
308 }
309 }
310
311 if (result == NULL) {
312 LOG(FATAL) << "JNI ERROR (app bug): use of deleted " << kind << ": "
313 << obj;
314 }
315 Heap::VerifyObject(result);
316 return result;
317}
318
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700319class CountStackDepthVisitor : public Thread::StackVisitor {
320 public:
321 CountStackDepthVisitor() : depth(0) {}
322 virtual bool VisitFrame(const Frame&) {
323 ++depth;
324 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700325 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700326
327 int GetDepth() const {
328 return depth;
329 }
330
331 private:
332 uint32_t depth;
333};
334
335class BuildStackTraceVisitor : public Thread::StackVisitor {
336 public:
337 BuildStackTraceVisitor(int depth) : count(0) {
338 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<const Method>(depth);
339 pc_trace = IntArray::Alloc(depth);
340 }
341
342 virtual ~BuildStackTraceVisitor() {}
343
344 virtual bool VisitFrame(const Frame& frame) {
345 method_trace->Set(count, frame.GetMethod());
346 pc_trace->Set(count, frame.GetPC());
347 ++count;
348 return true;
349 }
350
351 const Method* GetMethod(uint32_t i) {
352 DCHECK(i < count);
353 return method_trace->Get(i);
354 }
355
356 uintptr_t GetPC(uint32_t i) {
357 DCHECK(i < count);
358 return pc_trace->Get(i);
359 }
360
361 private:
362 uint32_t count;
363 ObjectArray<const Method>* method_trace;
364 IntArray* pc_trace;
365};
366
367void Thread::WalkStack(StackVisitor* visitor) {
368 Frame frame = Thread::Current()->GetTopOfStack();
369 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
370 // CHECK(native_to_managed_record_ != NULL);
371 NativeToManagedRecord* record = native_to_managed_record_;
372
373 while (frame.GetSP()) {
374 for ( ; frame.GetMethod() != 0; frame.Next()) {
375 visitor->VisitFrame(frame);
376 }
377 if (record == NULL) {
378 break;
379 }
380 frame.SetSP(reinterpret_cast<const art::Method**>(record->last_top_of_managed_stack)); // last_tos should return Frame instead of sp?
381 record = record->link;
382 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700383}
384
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700385ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700386 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700387
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700388 CountStackDepthVisitor count_visitor;
389 WalkStack(&count_visitor);
390 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700391
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700392 BuildStackTraceVisitor build_trace_visitor(depth);
393 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700394
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700395 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700396
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700397 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700398 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700399 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700400 const Class* klass = method->GetDeclaringClass();
401 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700402 String* readable_descriptor = String::AllocFromModifiedUtf8(
403 PrettyDescriptor(klass->GetDescriptor()).c_str()
404 );
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700405
406 StackTraceElement* obj =
407 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700408 method->GetName(),
409 String::AllocFromModifiedUtf8(klass->source_file_),
410 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700411 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700412 java_traces->Set(i, obj);
413 }
414 return java_traces;
415}
416
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700417void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700418 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700419 va_list args;
420 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700421 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700422 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700423
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700424 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
425 CHECK(exception_class_descriptor[0] == 'L');
426 std::string descriptor(exception_class_descriptor + 1);
427 CHECK(descriptor[descriptor.length() - 1] == ';');
428 descriptor.erase(descriptor.length() - 1);
429
430 JNIEnv* env = GetJniEnv();
431 jclass exception_class = env->FindClass(descriptor.c_str());
432 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
433 int rc = env->ThrowNew(exception_class, msg.c_str());
434 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700435}
436
Elliott Hughes79082e32011-08-25 12:07:32 -0700437void Thread::ThrowOutOfMemoryError() {
438 UNIMPLEMENTED(FATAL);
439}
440
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700441Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
442 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
443 DCHECK(class_linker != NULL);
444
445 Frame cur_frame = GetTopOfStack();
446 for (int unwind_depth = 0; ; unwind_depth++) {
447 const Method* cur_method = cur_frame.GetMethod();
448 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
449 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
450
451 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
452 throw_pc,
453 dex_file,
454 class_linker);
455 if (handler_addr) {
456 *handler_pc = handler_addr;
457 return cur_frame;
458 } else {
459 // Check if we are at the last frame
460 if (cur_frame.HasNext()) {
461 cur_frame.Next();
462 } else {
463 // Either at the top of stack or next frame is native.
464 break;
465 }
466 }
467 }
468 *handler_pc = NULL;
469 return Frame();
470}
471
472void* Thread::FindExceptionHandlerInMethod(const Method* method,
473 void* throw_pc,
474 const DexFile& dex_file,
475 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700476 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700477 exception_ = NULL;
478
479 intptr_t dex_pc = -1;
480 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->code_off_);
481 DexFile::CatchHandlerIterator iter;
482 for (iter = dex_file.dexFindCatchHandler(*code_item,
483 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
484 !iter.HasNext();
485 iter.Next()) {
486 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
487 DCHECK(klass != NULL);
488 if (exception_obj->InstanceOf(klass)) {
489 dex_pc = iter.Get().address_;
490 break;
491 }
492 }
493
494 exception_ = exception_obj;
495 if (iter.HasNext()) {
496 return NULL;
497 } else {
498 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
499 }
500}
501
Ian Rogersb033c752011-07-20 12:22:35 -0700502static const char* kStateNames[] = {
503 "New",
504 "Runnable",
505 "Blocked",
506 "Waiting",
507 "TimedWaiting",
508 "Native",
509 "Terminated",
510};
511std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
512 if (state >= Thread::kNew && state <= Thread::kTerminated) {
513 os << kStateNames[state-Thread::kNew];
514 } else {
515 os << "State[" << static_cast<int>(state) << "]";
516 }
517 return os;
518}
519
Elliott Hughes330304d2011-08-12 14:28:05 -0700520std::ostream& operator<<(std::ostream& os, const Thread& thread) {
521 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700522 << ",pthread_t=" << thread.GetImpl()
523 << ",tid=" << thread.GetTid()
524 << ",id=" << thread.GetId()
525 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700526 return os;
527}
528
Carl Shapiro61e019d2011-07-14 16:53:09 -0700529ThreadList* ThreadList::Create() {
530 return new ThreadList;
531}
532
Carl Shapirob5573532011-07-12 18:22:59 -0700533ThreadList::ThreadList() {
534 lock_ = Mutex::Create("ThreadList::Lock");
535}
536
537ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700538 if (Contains(Thread::Current())) {
539 Runtime::Current()->DetachCurrentThread();
540 }
541
542 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700543 // reach this point. This means that all daemon threads had been
544 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700545 // TODO: dump ThreadList if non-empty.
546 CHECK_EQ(list_.size(), 0U);
547
Carl Shapirob5573532011-07-12 18:22:59 -0700548 delete lock_;
549 lock_ = NULL;
550}
551
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700552bool ThreadList::Contains(Thread* thread) {
553 return find(list_.begin(), list_.end(), thread) != list_.end();
554}
555
Carl Shapirob5573532011-07-12 18:22:59 -0700556void ThreadList::Register(Thread* thread) {
557 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700558 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700559 list_.push_front(thread);
560}
561
562void ThreadList::Unregister(Thread* thread) {
563 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700564 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700565 list_.remove(thread);
566}
567
Carl Shapirob5573532011-07-12 18:22:59 -0700568} // namespace