blob: 89ec844c696348f1b9b4ea98b3d8cd282c0f0797 [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
buzbee1b4c8592011-08-31 10:43:51 -070035// TODO: placeholder. This is what generated code will call to throw
36static void ThrowException(Thread* thread, Throwable* exception) {
37 /*
38 * exception may be NULL, in which case this routine should
39 * throw NPE. NOTE: this is a convenience for generated code,
40 * which previuosly did the null check inline and constructed
41 * and threw a NPE if NULL. This routine responsible for setting
42 * exception_ in thread.
43 */
44 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
45}
46
47// TODO: placeholder. Helper function to type
48static Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
49 /*
50 * Should initialize & fix up method->dex_cache_resolved_types_[].
51 * Returns initialized type. Does not return normally if an exception
52 * is thrown, but instead initiates the catch. Should be similar to
53 * ClassLinker::InitializeStaticStorageFromCode.
54 */
55 UNIMPLEMENTED(FATAL);
56 return NULL;
57}
58
buzbee3ea4ec52011-08-22 17:37:19 -070059void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -070060#if defined(__arm__)
61 pShlLong = art_shl_long;
62 pShrLong = art_shr_long;
63 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -070064 pIdiv = __aeabi_idiv;
65 pIdivmod = __aeabi_idivmod;
66 pI2f = __aeabi_i2f;
67 pF2iz = __aeabi_f2iz;
68 pD2f = __aeabi_d2f;
69 pF2d = __aeabi_f2d;
70 pD2iz = __aeabi_d2iz;
71 pL2f = __aeabi_l2f;
72 pL2d = __aeabi_l2d;
73 pFadd = __aeabi_fadd;
74 pFsub = __aeabi_fsub;
75 pFdiv = __aeabi_fdiv;
76 pFmul = __aeabi_fmul;
77 pFmodf = fmodf;
78 pDadd = __aeabi_dadd;
79 pDsub = __aeabi_dsub;
80 pDdiv = __aeabi_ddiv;
81 pDmul = __aeabi_dmul;
82 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -070083 pF2l = F2L;
84 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -070085 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -070086 pLmul = __aeabi_lmul;
buzbee54330722011-08-23 16:46:55 -070087#endif
buzbeedfd3d702011-08-28 12:56:51 -070088 pAllocFromCode = Array::AllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -070089 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -070090 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -070091 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -070092 pGet32Static = Field::Get32StaticFromCode;
93 pSet32Static = Field::Set32StaticFromCode;
94 pGet64Static = Field::Get64StaticFromCode;
95 pSet64Static = Field::Set64StaticFromCode;
96 pGetObjStatic = Field::GetObjStaticFromCode;
97 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -070098 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
99 pThrowException = ThrowException;
100 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700101#if 0
buzbee1b4c8592011-08-31 10:43:51 -0700102bool (Thread::*pUnlockObject)(Thread*, Object*);
103int (Thread::*pInstanceofNonTrivialFromCode)(const Class*, const Class*);
104Method* (Thread::*pFindInterfaceMethodInCache)(Class*, uint32_t, const Method*, DvmDex*);
105bool (Thread::*pUnlockObjectFromCode)(Thread*, Object*);
106void (Thread::*pLockObjectFromCode)(Thread*, Object*);
107Object* (Thread::*pAllocObjectFromCode)(Class*, int);
108void (Thread::*pThrowException)(Thread*, Object*);
109bool (Thread::*pHandleFillArrayDataFromCode)(Array*, const uint16_t*);
buzbee3ea4ec52011-08-22 17:37:19 -0700110#endif
111}
112
Carl Shapirob5573532011-07-12 18:22:59 -0700113Mutex* Mutex::Create(const char* name) {
114 Mutex* mu = new Mutex(name);
115 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Ian Rogersb033c752011-07-20 12:22:35 -0700116 CHECK_EQ(0, result);
Carl Shapirob5573532011-07-12 18:22:59 -0700117 return mu;
118}
119
120void Mutex::Lock() {
121 int result = pthread_mutex_lock(&lock_impl_);
122 CHECK_EQ(result, 0);
123 SetOwner(Thread::Current());
124}
125
126bool Mutex::TryLock() {
127 int result = pthread_mutex_lock(&lock_impl_);
128 if (result == EBUSY) {
129 return false;
130 } else {
131 CHECK_EQ(result, 0);
132 SetOwner(Thread::Current());
133 return true;
134 }
135}
136
137void Mutex::Unlock() {
138 CHECK(GetOwner() == Thread::Current());
139 int result = pthread_mutex_unlock(&lock_impl_);
140 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700141 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700142}
143
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700144void Frame::Next() {
145 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700146 GetMethod()->GetFrameSizeInBytes();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700147 sp_ = reinterpret_cast<const Method**>(next_sp);
148}
149
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700150uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700151 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700152 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700153 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700154}
155
156const Method* Frame::NextMethod() const {
157 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700158 GetMethod()->GetFrameSizeInBytes();
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700159 return *reinterpret_cast<const Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700160}
161
Carl Shapiro61e019d2011-07-14 16:53:09 -0700162void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700163 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700164 return NULL;
165}
166
Brian Carlstromb765be02011-08-17 23:54:10 -0700167Thread* Thread::Create(const Runtime* runtime) {
168 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700169
170 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700171 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700172
173 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700174 errno = pthread_attr_init(&attr);
175 if (errno != 0) {
176 PLOG(FATAL) << "pthread_attr_init failed";
177 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700178
Elliott Hughese27955c2011-08-26 15:21:24 -0700179 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
180 if (errno != 0) {
181 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
182 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700183
Elliott Hughese27955c2011-08-26 15:21:24 -0700184 errno = pthread_attr_setstacksize(&attr, stack_size);
185 if (errno != 0) {
186 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
187 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700188
Elliott Hughese27955c2011-08-26 15:21:24 -0700189 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
190 if (errno != 0) {
191 PLOG(FATAL) << "pthread_create failed";
192 }
193
194 errno = pthread_attr_destroy(&attr);
195 if (errno != 0) {
196 PLOG(FATAL) << "pthread_attr_destroy failed";
197 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700198
199 return new_thread;
200}
201
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700202Thread* Thread::Attach(const Runtime* runtime) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700203 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700204 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700205
206 thread->handle_ = pthread_self();
207
208 thread->state_ = kRunnable;
209
Elliott Hughesa5780da2011-07-17 11:39:39 -0700210 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
211 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700212 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700213 }
214
Elliott Hughes75770752011-08-24 17:52:38 -0700215 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700216
Carl Shapiro61e019d2011-07-14 16:53:09 -0700217 return thread;
218}
219
Elliott Hughese27955c2011-08-26 15:21:24 -0700220pid_t Thread::GetTid() const {
221 return gettid();
222}
223
Carl Shapirob5573532011-07-12 18:22:59 -0700224static void ThreadExitCheck(void* arg) {
225 LG << "Thread exit check";
226}
227
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700228bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700229 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700230 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
231 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700232 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700233 return false;
234 }
235
236 // Double-check the TLS slot allocation.
237 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700238 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700239 return false;
240 }
241
242 // TODO: initialize other locks and condition variables
243
244 return true;
245}
246
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700247void Thread::Shutdown() {
248 errno = pthread_key_delete(Thread::pthread_key_self_);
249 if (errno != 0) {
250 PLOG(WARNING) << "pthread_key_delete failed";
251 }
252}
253
254Thread::~Thread() {
255 delete jni_env_;
256}
257
Ian Rogers408f79a2011-08-23 18:22:33 -0700258size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700259 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700260 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700261 count += cur->NumberOfReferences();
262 }
263 return count;
264}
265
Ian Rogers408f79a2011-08-23 18:22:33 -0700266bool Thread::SirtContains(jobject obj) {
267 Object** sirt_entry = reinterpret_cast<Object**>(obj);
268 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700269 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700270 // A SIRT should always have a jobject/jclass as a native method is passed
271 // in a this pointer or a class
272 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700273 if ((&cur->References()[0] <= sirt_entry) &&
274 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700275 return true;
276 }
277 }
278 return false;
279}
280
Ian Rogers408f79a2011-08-23 18:22:33 -0700281Object* Thread::DecodeJObject(jobject obj) {
282 // TODO: Only allowed to hold Object* when in the runnable state
283 // DCHECK(state_ == kRunnable);
284 if (obj == NULL) {
285 return NULL;
286 }
287 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
288 IndirectRefKind kind = GetIndirectRefKind(ref);
289 Object* result;
290 switch (kind) {
291 case kLocal:
292 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700293 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700294 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700295 break;
296 }
297 case kGlobal:
298 {
299 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
300 IndirectReferenceTable& globals = vm->globals;
301 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700302 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700303 break;
304 }
305 case kWeakGlobal:
306 {
307 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
308 IndirectReferenceTable& weak_globals = vm->weak_globals;
309 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700310 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700311 if (result == kClearedJniWeakGlobal) {
312 // This is a special case where it's okay to return NULL.
313 return NULL;
314 }
315 break;
316 }
317 case kSirtOrInvalid:
318 default:
319 // TODO: make stack indirect reference table lookup more efficient
320 // Check if this is a local reference in the SIRT
321 if (SirtContains(obj)) {
322 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700323 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700324 // Assume an invalid local reference is actually a direct pointer.
325 result = reinterpret_cast<Object*>(obj);
326 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700327 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700328 }
329 }
330
331 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700332 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
333 JniAbort(NULL);
334 } else {
335 if (result != kInvalidIndirectRefObject) {
336 Heap::VerifyObject(result);
337 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700338 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700339 return result;
340}
341
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700342class CountStackDepthVisitor : public Thread::StackVisitor {
343 public:
344 CountStackDepthVisitor() : depth(0) {}
345 virtual bool VisitFrame(const Frame&) {
346 ++depth;
347 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700348 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700349
350 int GetDepth() const {
351 return depth;
352 }
353
354 private:
355 uint32_t depth;
356};
357
358class BuildStackTraceVisitor : public Thread::StackVisitor {
359 public:
360 BuildStackTraceVisitor(int depth) : count(0) {
361 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<const Method>(depth);
362 pc_trace = IntArray::Alloc(depth);
363 }
364
365 virtual ~BuildStackTraceVisitor() {}
366
367 virtual bool VisitFrame(const Frame& frame) {
368 method_trace->Set(count, frame.GetMethod());
369 pc_trace->Set(count, frame.GetPC());
370 ++count;
371 return true;
372 }
373
374 const Method* GetMethod(uint32_t i) {
375 DCHECK(i < count);
376 return method_trace->Get(i);
377 }
378
379 uintptr_t GetPC(uint32_t i) {
380 DCHECK(i < count);
381 return pc_trace->Get(i);
382 }
383
384 private:
385 uint32_t count;
386 ObjectArray<const Method>* method_trace;
387 IntArray* pc_trace;
388};
389
390void Thread::WalkStack(StackVisitor* visitor) {
391 Frame frame = Thread::Current()->GetTopOfStack();
392 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
393 // CHECK(native_to_managed_record_ != NULL);
394 NativeToManagedRecord* record = native_to_managed_record_;
395
396 while (frame.GetSP()) {
397 for ( ; frame.GetMethod() != 0; frame.Next()) {
398 visitor->VisitFrame(frame);
399 }
400 if (record == NULL) {
401 break;
402 }
403 frame.SetSP(reinterpret_cast<const art::Method**>(record->last_top_of_managed_stack)); // last_tos should return Frame instead of sp?
404 record = record->link;
405 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700406}
407
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700408ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700409 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700410
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700411 CountStackDepthVisitor count_visitor;
412 WalkStack(&count_visitor);
413 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700414
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700415 BuildStackTraceVisitor build_trace_visitor(depth);
416 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700417
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700418 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700419
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700420 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700421 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700422 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700423 const Class* klass = method->GetDeclaringClass();
424 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700425 String* readable_descriptor = String::AllocFromModifiedUtf8(
426 PrettyDescriptor(klass->GetDescriptor()).c_str()
427 );
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700428
429 StackTraceElement* obj =
430 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700431 method->GetName(),
432 String::AllocFromModifiedUtf8(klass->source_file_),
433 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700434 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700435 java_traces->Set(i, obj);
436 }
437 return java_traces;
438}
439
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700440void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700441 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700442 va_list args;
443 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700444 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700445 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700446
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700447 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
448 CHECK(exception_class_descriptor[0] == 'L');
449 std::string descriptor(exception_class_descriptor + 1);
450 CHECK(descriptor[descriptor.length() - 1] == ';');
451 descriptor.erase(descriptor.length() - 1);
452
453 JNIEnv* env = GetJniEnv();
454 jclass exception_class = env->FindClass(descriptor.c_str());
455 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
456 int rc = env->ThrowNew(exception_class, msg.c_str());
457 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700458}
459
Elliott Hughes79082e32011-08-25 12:07:32 -0700460void Thread::ThrowOutOfMemoryError() {
461 UNIMPLEMENTED(FATAL);
462}
463
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700464Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
465 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
466 DCHECK(class_linker != NULL);
467
468 Frame cur_frame = GetTopOfStack();
469 for (int unwind_depth = 0; ; unwind_depth++) {
470 const Method* cur_method = cur_frame.GetMethod();
471 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
472 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
473
474 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
475 throw_pc,
476 dex_file,
477 class_linker);
478 if (handler_addr) {
479 *handler_pc = handler_addr;
480 return cur_frame;
481 } else {
482 // Check if we are at the last frame
483 if (cur_frame.HasNext()) {
484 cur_frame.Next();
485 } else {
486 // Either at the top of stack or next frame is native.
487 break;
488 }
489 }
490 }
491 *handler_pc = NULL;
492 return Frame();
493}
494
495void* Thread::FindExceptionHandlerInMethod(const Method* method,
496 void* throw_pc,
497 const DexFile& dex_file,
498 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700499 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700500 exception_ = NULL;
501
502 intptr_t dex_pc = -1;
503 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->code_off_);
504 DexFile::CatchHandlerIterator iter;
505 for (iter = dex_file.dexFindCatchHandler(*code_item,
506 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
507 !iter.HasNext();
508 iter.Next()) {
509 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
510 DCHECK(klass != NULL);
511 if (exception_obj->InstanceOf(klass)) {
512 dex_pc = iter.Get().address_;
513 break;
514 }
515 }
516
517 exception_ = exception_obj;
518 if (iter.HasNext()) {
519 return NULL;
520 } else {
521 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
522 }
523}
524
Ian Rogersb033c752011-07-20 12:22:35 -0700525static const char* kStateNames[] = {
526 "New",
527 "Runnable",
528 "Blocked",
529 "Waiting",
530 "TimedWaiting",
531 "Native",
532 "Terminated",
533};
534std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
535 if (state >= Thread::kNew && state <= Thread::kTerminated) {
536 os << kStateNames[state-Thread::kNew];
537 } else {
538 os << "State[" << static_cast<int>(state) << "]";
539 }
540 return os;
541}
542
Elliott Hughes330304d2011-08-12 14:28:05 -0700543std::ostream& operator<<(std::ostream& os, const Thread& thread) {
544 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700545 << ",pthread_t=" << thread.GetImpl()
546 << ",tid=" << thread.GetTid()
547 << ",id=" << thread.GetId()
548 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700549 return os;
550}
551
Carl Shapiro61e019d2011-07-14 16:53:09 -0700552ThreadList* ThreadList::Create() {
553 return new ThreadList;
554}
555
Carl Shapirob5573532011-07-12 18:22:59 -0700556ThreadList::ThreadList() {
557 lock_ = Mutex::Create("ThreadList::Lock");
558}
559
560ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700561 if (Contains(Thread::Current())) {
562 Runtime::Current()->DetachCurrentThread();
563 }
564
565 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700566 // reach this point. This means that all daemon threads had been
567 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700568 // TODO: dump ThreadList if non-empty.
569 CHECK_EQ(list_.size(), 0U);
570
Carl Shapirob5573532011-07-12 18:22:59 -0700571 delete lock_;
572 lock_ = NULL;
573}
574
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700575bool ThreadList::Contains(Thread* thread) {
576 return find(list_.begin(), list_.end(), thread) != list_.end();
577}
578
Carl Shapirob5573532011-07-12 18:22:59 -0700579void ThreadList::Register(Thread* thread) {
580 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700581 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700582 list_.push_front(thread);
583}
584
585void ThreadList::Unregister(Thread* thread) {
586 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700587 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700588 list_.remove(thread);
589}
590
Carl Shapirob5573532011-07-12 18:22:59 -0700591} // namespace