blob: f5c1343c4c7d4c97b47df5939e1674bc073dd869 [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();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700149 sp_ = reinterpret_cast<const Method**>(next_sp);
150}
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
158const Method* Frame::NextMethod() const {
159 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700160 GetMethod()->GetFrameSizeInBytes();
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700161 return *reinterpret_cast<const 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) {
288 // TODO: Only allowed to hold Object* when in the runnable state
289 // DCHECK(state_ == kRunnable);
290 if (obj == NULL) {
291 return NULL;
292 }
293 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
294 IndirectRefKind kind = GetIndirectRefKind(ref);
295 Object* result;
296 switch (kind) {
297 case kLocal:
298 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700299 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700300 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700301 break;
302 }
303 case kGlobal:
304 {
305 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
306 IndirectReferenceTable& globals = vm->globals;
307 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700308 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700309 break;
310 }
311 case kWeakGlobal:
312 {
313 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
314 IndirectReferenceTable& weak_globals = vm->weak_globals;
315 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700316 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700317 if (result == kClearedJniWeakGlobal) {
318 // This is a special case where it's okay to return NULL.
319 return NULL;
320 }
321 break;
322 }
323 case kSirtOrInvalid:
324 default:
325 // TODO: make stack indirect reference table lookup more efficient
326 // Check if this is a local reference in the SIRT
327 if (SirtContains(obj)) {
328 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700329 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700330 // Assume an invalid local reference is actually a direct pointer.
331 result = reinterpret_cast<Object*>(obj);
332 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700333 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700334 }
335 }
336
337 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700338 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
339 JniAbort(NULL);
340 } else {
341 if (result != kInvalidIndirectRefObject) {
342 Heap::VerifyObject(result);
343 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700344 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700345 return result;
346}
347
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700348class CountStackDepthVisitor : public Thread::StackVisitor {
349 public:
350 CountStackDepthVisitor() : depth(0) {}
351 virtual bool VisitFrame(const Frame&) {
352 ++depth;
353 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700354 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700355
356 int GetDepth() const {
357 return depth;
358 }
359
360 private:
361 uint32_t depth;
362};
363
364class BuildStackTraceVisitor : public Thread::StackVisitor {
365 public:
366 BuildStackTraceVisitor(int depth) : count(0) {
367 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<const Method>(depth);
368 pc_trace = IntArray::Alloc(depth);
369 }
370
371 virtual ~BuildStackTraceVisitor() {}
372
373 virtual bool VisitFrame(const Frame& frame) {
374 method_trace->Set(count, frame.GetMethod());
375 pc_trace->Set(count, frame.GetPC());
376 ++count;
377 return true;
378 }
379
380 const Method* GetMethod(uint32_t i) {
381 DCHECK(i < count);
382 return method_trace->Get(i);
383 }
384
385 uintptr_t GetPC(uint32_t i) {
386 DCHECK(i < count);
387 return pc_trace->Get(i);
388 }
389
390 private:
391 uint32_t count;
392 ObjectArray<const Method>* method_trace;
393 IntArray* pc_trace;
394};
395
396void Thread::WalkStack(StackVisitor* visitor) {
397 Frame frame = Thread::Current()->GetTopOfStack();
398 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
399 // CHECK(native_to_managed_record_ != NULL);
400 NativeToManagedRecord* record = native_to_managed_record_;
401
402 while (frame.GetSP()) {
403 for ( ; frame.GetMethod() != 0; frame.Next()) {
404 visitor->VisitFrame(frame);
405 }
406 if (record == NULL) {
407 break;
408 }
409 frame.SetSP(reinterpret_cast<const art::Method**>(record->last_top_of_managed_stack)); // last_tos should return Frame instead of sp?
410 record = record->link;
411 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700412}
413
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700414ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700415 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700416
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700417 CountStackDepthVisitor count_visitor;
418 WalkStack(&count_visitor);
419 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700420
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700421 BuildStackTraceVisitor build_trace_visitor(depth);
422 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700423
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700424 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700425
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700426 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700427 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700428 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700429 const Class* klass = method->GetDeclaringClass();
430 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700431 String* readable_descriptor = String::AllocFromModifiedUtf8(
432 PrettyDescriptor(klass->GetDescriptor()).c_str()
433 );
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700434
435 StackTraceElement* obj =
436 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700437 method->GetName(),
438 String::AllocFromModifiedUtf8(klass->source_file_),
439 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700440 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700441 java_traces->Set(i, obj);
442 }
443 return java_traces;
444}
445
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700446void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700447 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700448 va_list args;
449 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700450 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700451 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700452
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700453 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
454 CHECK(exception_class_descriptor[0] == 'L');
455 std::string descriptor(exception_class_descriptor + 1);
456 CHECK(descriptor[descriptor.length() - 1] == ';');
457 descriptor.erase(descriptor.length() - 1);
458
459 JNIEnv* env = GetJniEnv();
460 jclass exception_class = env->FindClass(descriptor.c_str());
461 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
462 int rc = env->ThrowNew(exception_class, msg.c_str());
463 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700464}
465
Elliott Hughes79082e32011-08-25 12:07:32 -0700466void Thread::ThrowOutOfMemoryError() {
467 UNIMPLEMENTED(FATAL);
468}
469
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700470Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
471 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
472 DCHECK(class_linker != NULL);
473
474 Frame cur_frame = GetTopOfStack();
475 for (int unwind_depth = 0; ; unwind_depth++) {
476 const Method* cur_method = cur_frame.GetMethod();
477 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
478 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
479
480 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
481 throw_pc,
482 dex_file,
483 class_linker);
484 if (handler_addr) {
485 *handler_pc = handler_addr;
486 return cur_frame;
487 } else {
488 // Check if we are at the last frame
489 if (cur_frame.HasNext()) {
490 cur_frame.Next();
491 } else {
492 // Either at the top of stack or next frame is native.
493 break;
494 }
495 }
496 }
497 *handler_pc = NULL;
498 return Frame();
499}
500
501void* Thread::FindExceptionHandlerInMethod(const Method* method,
502 void* throw_pc,
503 const DexFile& dex_file,
504 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700505 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700506 exception_ = NULL;
507
508 intptr_t dex_pc = -1;
509 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->code_off_);
510 DexFile::CatchHandlerIterator iter;
511 for (iter = dex_file.dexFindCatchHandler(*code_item,
512 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
513 !iter.HasNext();
514 iter.Next()) {
515 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
516 DCHECK(klass != NULL);
517 if (exception_obj->InstanceOf(klass)) {
518 dex_pc = iter.Get().address_;
519 break;
520 }
521 }
522
523 exception_ = exception_obj;
524 if (iter.HasNext()) {
525 return NULL;
526 } else {
527 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
528 }
529}
530
Elliott Hughes410c0c82011-09-01 17:58:25 -0700531void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
532 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
533 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
534 jni_env_->locals.VisitRoots(visitor, arg);
535 jni_env_->monitors.VisitRoots(visitor, arg);
536 // visitThreadStack(visitor, thread, arg);
537 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
538}
539
Ian Rogersb033c752011-07-20 12:22:35 -0700540static const char* kStateNames[] = {
541 "New",
542 "Runnable",
543 "Blocked",
544 "Waiting",
545 "TimedWaiting",
546 "Native",
547 "Terminated",
548};
549std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
550 if (state >= Thread::kNew && state <= Thread::kTerminated) {
551 os << kStateNames[state-Thread::kNew];
552 } else {
553 os << "State[" << static_cast<int>(state) << "]";
554 }
555 return os;
556}
557
Elliott Hughes330304d2011-08-12 14:28:05 -0700558std::ostream& operator<<(std::ostream& os, const Thread& thread) {
559 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700560 << ",pthread_t=" << thread.GetImpl()
561 << ",tid=" << thread.GetTid()
562 << ",id=" << thread.GetId()
563 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700564 return os;
565}
566
Carl Shapiro61e019d2011-07-14 16:53:09 -0700567ThreadList* ThreadList::Create() {
568 return new ThreadList;
569}
570
Carl Shapirob5573532011-07-12 18:22:59 -0700571ThreadList::ThreadList() {
572 lock_ = Mutex::Create("ThreadList::Lock");
573}
574
575ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700576 if (Contains(Thread::Current())) {
577 Runtime::Current()->DetachCurrentThread();
578 }
579
580 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700581 // reach this point. This means that all daemon threads had been
582 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700583 // TODO: dump ThreadList if non-empty.
584 CHECK_EQ(list_.size(), 0U);
585
Carl Shapirob5573532011-07-12 18:22:59 -0700586 delete lock_;
587 lock_ = NULL;
588}
589
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700590bool ThreadList::Contains(Thread* thread) {
591 return find(list_.begin(), list_.end(), thread) != list_.end();
592}
593
Carl Shapirob5573532011-07-12 18:22:59 -0700594void ThreadList::Register(Thread* thread) {
595 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700596 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700597 list_.push_front(thread);
598}
599
600void ThreadList::Unregister(Thread* thread) {
601 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700602 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700603 list_.remove(thread);
604}
605
Elliott Hughes410c0c82011-09-01 17:58:25 -0700606void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
607 MutexLock mu(lock_);
608 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
609 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
610 (*it)->VisitRoots(visitor, arg);
611 }
612}
613
Carl Shapirob5573532011-07-12 18:22:59 -0700614} // namespace