blob: 7f48fa16377940f82dffffd0909238a1b2b1b581 [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 Hugheseb4f6142011-07-15 17:43:51 -07009#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070010#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070011#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070012
Elliott Hughesa5b897e2011-08-16 11:33:06 -070013#include "class_linker.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070014#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070015#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070016#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070018#include "runtime_support.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070019#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070020
21namespace art {
22
Elliott Hughese27955c2011-08-26 15:21:24 -070023/* desktop Linux needs a little help with gettid() */
24#if !defined(HAVE_ANDROID_OS)
25#define __KERNEL__
26# include <linux/unistd.h>
27#ifdef _syscall0
28_syscall0(pid_t, gettid)
29#else
30pid_t gettid() { return syscall(__NR_gettid);}
31#endif
32#undef __KERNEL__
33#endif
34
Carl Shapirob5573532011-07-12 18:22:59 -070035pthread_key_t Thread::pthread_key_self_;
36
buzbee1b4c8592011-08-31 10:43:51 -070037// TODO: placeholder. This is what generated code will call to throw
38static void ThrowException(Thread* thread, Throwable* exception) {
39 /*
40 * exception may be NULL, in which case this routine should
41 * throw NPE. NOTE: this is a convenience for generated code,
42 * which previuosly did the null check inline and constructed
43 * and threw a NPE if NULL. This routine responsible for setting
44 * exception_ in thread.
45 */
46 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
47}
48
49// TODO: placeholder. Helper function to type
50static Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
51 /*
52 * Should initialize & fix up method->dex_cache_resolved_types_[].
53 * Returns initialized type. Does not return normally if an exception
54 * is thrown, but instead initiates the catch. Should be similar to
55 * ClassLinker::InitializeStaticStorageFromCode.
56 */
57 UNIMPLEMENTED(FATAL);
58 return NULL;
59}
60
buzbee3ea4ec52011-08-22 17:37:19 -070061void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -070062#if defined(__arm__)
63 pShlLong = art_shl_long;
64 pShrLong = art_shr_long;
65 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -070066 pIdiv = __aeabi_idiv;
67 pIdivmod = __aeabi_idivmod;
68 pI2f = __aeabi_i2f;
69 pF2iz = __aeabi_f2iz;
70 pD2f = __aeabi_d2f;
71 pF2d = __aeabi_f2d;
72 pD2iz = __aeabi_d2iz;
73 pL2f = __aeabi_l2f;
74 pL2d = __aeabi_l2d;
75 pFadd = __aeabi_fadd;
76 pFsub = __aeabi_fsub;
77 pFdiv = __aeabi_fdiv;
78 pFmul = __aeabi_fmul;
79 pFmodf = fmodf;
80 pDadd = __aeabi_dadd;
81 pDsub = __aeabi_dsub;
82 pDdiv = __aeabi_ddiv;
83 pDmul = __aeabi_dmul;
84 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -070085 pF2l = F2L;
86 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -070087 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -070088 pLmul = __aeabi_lmul;
buzbee54330722011-08-23 16:46:55 -070089#endif
buzbeedfd3d702011-08-28 12:56:51 -070090 pAllocFromCode = Array::AllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -070091 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -070092 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -070093 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -070094 pGet32Static = Field::Get32StaticFromCode;
95 pSet32Static = Field::Set32StaticFromCode;
96 pGet64Static = Field::Get64StaticFromCode;
97 pSet64Static = Field::Set64StaticFromCode;
98 pGetObjStatic = Field::GetObjStaticFromCode;
99 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700100 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
101 pThrowException = ThrowException;
102 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700103#if 0
buzbee1b4c8592011-08-31 10:43:51 -0700104bool (Thread::*pUnlockObject)(Thread*, Object*);
105int (Thread::*pInstanceofNonTrivialFromCode)(const Class*, const Class*);
106Method* (Thread::*pFindInterfaceMethodInCache)(Class*, uint32_t, const Method*, DvmDex*);
107bool (Thread::*pUnlockObjectFromCode)(Thread*, Object*);
108void (Thread::*pLockObjectFromCode)(Thread*, Object*);
109Object* (Thread::*pAllocObjectFromCode)(Class*, int);
110void (Thread::*pThrowException)(Thread*, Object*);
111bool (Thread::*pHandleFillArrayDataFromCode)(Array*, const uint16_t*);
buzbee3ea4ec52011-08-22 17:37:19 -0700112#endif
113}
114
Carl Shapirob5573532011-07-12 18:22:59 -0700115Mutex* Mutex::Create(const char* name) {
116 Mutex* mu = new Mutex(name);
117 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Ian Rogersb033c752011-07-20 12:22:35 -0700118 CHECK_EQ(0, result);
Carl Shapirob5573532011-07-12 18:22:59 -0700119 return mu;
120}
121
122void Mutex::Lock() {
123 int result = pthread_mutex_lock(&lock_impl_);
124 CHECK_EQ(result, 0);
125 SetOwner(Thread::Current());
126}
127
128bool Mutex::TryLock() {
129 int result = pthread_mutex_lock(&lock_impl_);
130 if (result == EBUSY) {
131 return false;
132 } else {
133 CHECK_EQ(result, 0);
134 SetOwner(Thread::Current());
135 return true;
136 }
137}
138
139void Mutex::Unlock() {
140 CHECK(GetOwner() == Thread::Current());
141 int result = pthread_mutex_unlock(&lock_impl_);
142 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700143 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700144}
145
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700146void Frame::Next() {
147 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700148 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700149 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700150}
151
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700152uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700153 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700154 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700155 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700156}
157
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700158Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700159 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700160 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700161 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700162}
163
Carl Shapiro61e019d2011-07-14 16:53:09 -0700164void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700165 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700166 return NULL;
167}
168
Brian Carlstromb765be02011-08-17 23:54:10 -0700169Thread* Thread::Create(const Runtime* runtime) {
170 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700171
172 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700173 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700174
175 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700176 errno = pthread_attr_init(&attr);
177 if (errno != 0) {
178 PLOG(FATAL) << "pthread_attr_init failed";
179 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700180
Elliott Hughese27955c2011-08-26 15:21:24 -0700181 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
182 if (errno != 0) {
183 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
184 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700185
Elliott Hughese27955c2011-08-26 15:21:24 -0700186 errno = pthread_attr_setstacksize(&attr, stack_size);
187 if (errno != 0) {
188 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
189 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700190
Elliott Hughese27955c2011-08-26 15:21:24 -0700191 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
192 if (errno != 0) {
193 PLOG(FATAL) << "pthread_create failed";
194 }
195
196 errno = pthread_attr_destroy(&attr);
197 if (errno != 0) {
198 PLOG(FATAL) << "pthread_attr_destroy failed";
199 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700200
201 return new_thread;
202}
203
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700204Thread* Thread::Attach(const Runtime* runtime) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700205 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700206 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700207
208 thread->handle_ = pthread_self();
209
210 thread->state_ = kRunnable;
211
Elliott Hughesa5780da2011-07-17 11:39:39 -0700212 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
213 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700214 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700215 }
216
Elliott Hughes75770752011-08-24 17:52:38 -0700217 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700218
Carl Shapiro61e019d2011-07-14 16:53:09 -0700219 return thread;
220}
221
Elliott Hughesa0957642011-09-02 14:27:33 -0700222void Thread::Dump(std::ostream& os) const {
223 os << "UNIMPLEMENTED: Thread::Dump\n";
224}
225
Elliott Hughese27955c2011-08-26 15:21:24 -0700226pid_t Thread::GetTid() const {
227 return gettid();
228}
229
Carl Shapirob5573532011-07-12 18:22:59 -0700230static void ThreadExitCheck(void* arg) {
231 LG << "Thread exit check";
232}
233
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700234bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700235 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700236 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
237 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700238 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700239 return false;
240 }
241
242 // Double-check the TLS slot allocation.
243 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700244 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700245 return false;
246 }
247
248 // TODO: initialize other locks and condition variables
249
250 return true;
251}
252
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700253void Thread::Shutdown() {
254 errno = pthread_key_delete(Thread::pthread_key_self_);
255 if (errno != 0) {
256 PLOG(WARNING) << "pthread_key_delete failed";
257 }
258}
259
260Thread::~Thread() {
261 delete jni_env_;
262}
263
Ian Rogers408f79a2011-08-23 18:22:33 -0700264size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700265 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700266 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700267 count += cur->NumberOfReferences();
268 }
269 return count;
270}
271
Ian Rogers408f79a2011-08-23 18:22:33 -0700272bool Thread::SirtContains(jobject obj) {
273 Object** sirt_entry = reinterpret_cast<Object**>(obj);
274 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700275 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700276 // A SIRT should always have a jobject/jclass as a native method is passed
277 // in a this pointer or a class
278 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700279 if ((&cur->References()[0] <= sirt_entry) &&
280 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700281 return true;
282 }
283 }
284 return false;
285}
286
Ian Rogers408f79a2011-08-23 18:22:33 -0700287Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700289 if (obj == NULL) {
290 return NULL;
291 }
292 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
293 IndirectRefKind kind = GetIndirectRefKind(ref);
294 Object* result;
295 switch (kind) {
296 case kLocal:
297 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700298 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700299 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700300 break;
301 }
302 case kGlobal:
303 {
304 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
305 IndirectReferenceTable& globals = vm->globals;
306 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700307 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700308 break;
309 }
310 case kWeakGlobal:
311 {
312 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
313 IndirectReferenceTable& weak_globals = vm->weak_globals;
314 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700315 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700316 if (result == kClearedJniWeakGlobal) {
317 // This is a special case where it's okay to return NULL.
318 return NULL;
319 }
320 break;
321 }
322 case kSirtOrInvalid:
323 default:
324 // TODO: make stack indirect reference table lookup more efficient
325 // Check if this is a local reference in the SIRT
326 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700327 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700328 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700329 // Assume an invalid local reference is actually a direct pointer.
330 result = reinterpret_cast<Object*>(obj);
331 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700332 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700333 }
334 }
335
336 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700337 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
338 JniAbort(NULL);
339 } else {
340 if (result != kInvalidIndirectRefObject) {
341 Heap::VerifyObject(result);
342 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700343 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700344 return result;
345}
346
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700347class CountStackDepthVisitor : public Thread::StackVisitor {
348 public:
349 CountStackDepthVisitor() : depth(0) {}
350 virtual bool VisitFrame(const Frame&) {
351 ++depth;
352 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700353 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700354
355 int GetDepth() const {
356 return depth;
357 }
358
359 private:
360 uint32_t depth;
361};
362
363class BuildStackTraceVisitor : public Thread::StackVisitor {
364 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700365 explicit BuildStackTraceVisitor(int depth) : count(0) {
366 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700367 pc_trace = IntArray::Alloc(depth);
368 }
369
370 virtual ~BuildStackTraceVisitor() {}
371
372 virtual bool VisitFrame(const Frame& frame) {
373 method_trace->Set(count, frame.GetMethod());
374 pc_trace->Set(count, frame.GetPC());
375 ++count;
376 return true;
377 }
378
379 const Method* GetMethod(uint32_t i) {
380 DCHECK(i < count);
381 return method_trace->Get(i);
382 }
383
384 uintptr_t GetPC(uint32_t i) {
385 DCHECK(i < count);
386 return pc_trace->Get(i);
387 }
388
389 private:
390 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700391 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700392 IntArray* pc_trace;
393};
394
395void Thread::WalkStack(StackVisitor* visitor) {
396 Frame frame = Thread::Current()->GetTopOfStack();
397 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
398 // CHECK(native_to_managed_record_ != NULL);
399 NativeToManagedRecord* record = native_to_managed_record_;
400
401 while (frame.GetSP()) {
402 for ( ; frame.GetMethod() != 0; frame.Next()) {
403 visitor->VisitFrame(frame);
404 }
405 if (record == NULL) {
406 break;
407 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700408 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 -0700409 record = record->link;
410 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700411}
412
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700413ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700414 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700415
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700416 CountStackDepthVisitor count_visitor;
417 WalkStack(&count_visitor);
418 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700419
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700420 BuildStackTraceVisitor build_trace_visitor(depth);
421 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700422
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700423 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700424
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700425 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700426 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700427 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700428 const Class* klass = method->GetDeclaringClass();
429 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700430 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700431 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700432
433 StackTraceElement* obj =
434 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700435 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700436 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700437 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700438 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700439 java_traces->Set(i, obj);
440 }
441 return java_traces;
442}
443
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700444void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700445 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700446 va_list args;
447 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700448 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700449 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700450
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700451 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700452 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700453 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700455 descriptor.erase(descriptor.length() - 1);
456
457 JNIEnv* env = GetJniEnv();
458 jclass exception_class = env->FindClass(descriptor.c_str());
459 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
460 int rc = env->ThrowNew(exception_class, msg.c_str());
461 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700462}
463
Elliott Hughes79082e32011-08-25 12:07:32 -0700464void Thread::ThrowOutOfMemoryError() {
465 UNIMPLEMENTED(FATAL);
466}
467
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700468Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
469 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
470 DCHECK(class_linker != NULL);
471
472 Frame cur_frame = GetTopOfStack();
473 for (int unwind_depth = 0; ; unwind_depth++) {
474 const Method* cur_method = cur_frame.GetMethod();
475 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
476 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
477
478 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
479 throw_pc,
480 dex_file,
481 class_linker);
482 if (handler_addr) {
483 *handler_pc = handler_addr;
484 return cur_frame;
485 } else {
486 // Check if we are at the last frame
487 if (cur_frame.HasNext()) {
488 cur_frame.Next();
489 } else {
490 // Either at the top of stack or next frame is native.
491 break;
492 }
493 }
494 }
495 *handler_pc = NULL;
496 return Frame();
497}
498
499void* Thread::FindExceptionHandlerInMethod(const Method* method,
500 void* throw_pc,
501 const DexFile& dex_file,
502 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700503 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700504 exception_ = NULL;
505
506 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700507 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700508 DexFile::CatchHandlerIterator iter;
509 for (iter = dex_file.dexFindCatchHandler(*code_item,
510 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
511 !iter.HasNext();
512 iter.Next()) {
513 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
514 DCHECK(klass != NULL);
515 if (exception_obj->InstanceOf(klass)) {
516 dex_pc = iter.Get().address_;
517 break;
518 }
519 }
520
521 exception_ = exception_obj;
522 if (iter.HasNext()) {
523 return NULL;
524 } else {
525 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
526 }
527}
528
Elliott Hughes410c0c82011-09-01 17:58:25 -0700529void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
530 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
531 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
532 jni_env_->locals.VisitRoots(visitor, arg);
533 jni_env_->monitors.VisitRoots(visitor, arg);
534 // visitThreadStack(visitor, thread, arg);
535 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
536}
537
Ian Rogersb033c752011-07-20 12:22:35 -0700538static const char* kStateNames[] = {
539 "New",
540 "Runnable",
541 "Blocked",
542 "Waiting",
543 "TimedWaiting",
544 "Native",
545 "Terminated",
546};
547std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
548 if (state >= Thread::kNew && state <= Thread::kTerminated) {
549 os << kStateNames[state-Thread::kNew];
550 } else {
551 os << "State[" << static_cast<int>(state) << "]";
552 }
553 return os;
554}
555
Elliott Hughes330304d2011-08-12 14:28:05 -0700556std::ostream& operator<<(std::ostream& os, const Thread& thread) {
557 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700558 << ",pthread_t=" << thread.GetImpl()
559 << ",tid=" << thread.GetTid()
560 << ",id=" << thread.GetId()
561 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700562 return os;
563}
564
Carl Shapiro61e019d2011-07-14 16:53:09 -0700565ThreadList* ThreadList::Create() {
566 return new ThreadList;
567}
568
Carl Shapirob5573532011-07-12 18:22:59 -0700569ThreadList::ThreadList() {
570 lock_ = Mutex::Create("ThreadList::Lock");
571}
572
573ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700574 if (Contains(Thread::Current())) {
575 Runtime::Current()->DetachCurrentThread();
576 }
577
578 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700579 // reach this point. This means that all daemon threads had been
580 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700581 // TODO: dump ThreadList if non-empty.
582 CHECK_EQ(list_.size(), 0U);
583
Carl Shapirob5573532011-07-12 18:22:59 -0700584 delete lock_;
585 lock_ = NULL;
586}
587
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700588bool ThreadList::Contains(Thread* thread) {
589 return find(list_.begin(), list_.end(), thread) != list_.end();
590}
591
Carl Shapirob5573532011-07-12 18:22:59 -0700592void ThreadList::Register(Thread* thread) {
593 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700594 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700595 list_.push_front(thread);
596}
597
598void ThreadList::Unregister(Thread* thread) {
599 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700600 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700601 list_.remove(thread);
602}
603
Elliott Hughes410c0c82011-09-01 17:58:25 -0700604void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
605 MutexLock mu(lock_);
606 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
607 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
608 (*it)->VisitRoots(visitor, arg);
609 }
610}
611
Carl Shapirob5573532011-07-12 18:22:59 -0700612} // namespace