blob: c0e986ce7ca79526d0666d963538a057623d94bc [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();
Elliott Hughesd92bec42011-09-02 17:04:36 -0700209 thread->tid_ = gettid();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700210
211 thread->state_ = kRunnable;
212
Elliott Hughesa5780da2011-07-17 11:39:39 -0700213 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
214 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700215 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700216 }
217
Elliott Hughes75770752011-08-24 17:52:38 -0700218 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700219
Carl Shapiro61e019d2011-07-14 16:53:09 -0700220 return thread;
221}
222
Elliott Hughesa0957642011-09-02 14:27:33 -0700223void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700224 /*
225 * Get the java.lang.Thread object. This function gets called from
226 * some weird debug contexts, so it's possible that there's a GC in
227 * progress on some other thread. To decrease the chances of the
228 * thread object being moved out from under us, we add the reference
229 * to the tracked allocation list, which pins it in place.
230 *
231 * If threadObj is NULL, the thread is still in the process of being
232 * attached to the VM, and there's really nothing interesting to
233 * say about it yet.
234 */
235 os << "TODO: pin Thread before dumping\n";
236#if 0
237 if (java_thread_ == NULL) {
238 LOGI("Can't dump thread %d: threadObj not set", threadId);
239 return;
240 }
241 dvmAddTrackedAlloc(java_thread_, NULL);
242#endif
243
244 DumpState(os);
245 DumpStack(os);
246
247#if 0
248 dvmReleaseTrackedAlloc(java_thread_, NULL);
249#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700250}
251
Elliott Hughesd92bec42011-09-02 17:04:36 -0700252std::string GetSchedulerGroup(pid_t tid) {
253 // /proc/<pid>/group looks like this:
254 // 2:devices:/
255 // 1:cpuacct,cpu:/
256 // We want the third field from the line whose second field contains the "cpu" token.
257 std::string cgroup_file;
258 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
259 return "";
260 }
261 std::vector<std::string> cgroup_lines;
262 Split(cgroup_file, '\n', cgroup_lines);
263 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
264 std::vector<std::string> cgroup_fields;
265 Split(cgroup_lines[i], ':', cgroup_fields);
266 std::vector<std::string> cgroups;
267 Split(cgroup_fields[1], ',', cgroups);
268 for (size_t i = 0; i < cgroups.size(); ++i) {
269 if (cgroups[i] == "cpu") {
270 return cgroup_fields[2].substr(1); // Skip the leading slash.
271 }
272 }
273 }
274 return "";
275}
276
277void Thread::DumpState(std::ostream& os) const {
278 std::string thread_name("unknown");
279 int priority = -1;
280 bool is_daemon = false;
281#if 0 // TODO
282 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
283 threadName = dvmCreateCstrFromString(nameStr);
284 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
285 is_daemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
286#else
287 thread_name = "TODO";
288 priority = -1;
289 is_daemon = false;
290#endif
291
292 int policy;
293 sched_param sp;
294 errno = pthread_getschedparam(handle_, &policy, &sp);
295 if (errno != 0) {
296 PLOG(FATAL) << "pthread_getschedparam failed";
297 }
298
299 std::string scheduler_group(GetSchedulerGroup(GetTid()));
300 if (scheduler_group.empty()) {
301 scheduler_group = "default";
302 }
303
304 std::string group_name("(null; initializing?)");
305#if 0
306 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
307 if (groupObj != NULL) {
308 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
309 groupName = dvmCreateCstrFromString(nameStr);
310 }
311#else
312 group_name = "TODO";
313#endif
314
315 os << '"' << thread_name << '"';
316 if (is_daemon) {
317 os << " daemon";
318 }
319 os << " prio=" << priority
320 << " tid=" << GetId()
321 << " " << state_ << "\n";
322
323 int suspend_count = 0; // TODO
324 int debug_suspend_count = 0; // TODO
325 void* java_thread_ = NULL; // TODO
326 os << " | group=\"" << group_name << "\""
327 << " sCount=" << suspend_count
328 << " dsCount=" << debug_suspend_count
329 << " obj=" << reinterpret_cast<void*>(java_thread_)
330 << " self=" << reinterpret_cast<const void*>(this) << "\n";
331 os << " | sysTid=" << GetTid()
332 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
333 << " sched=" << policy << "/" << sp.sched_priority
334 << " cgrp=" << scheduler_group
335 << " handle=" << GetImpl() << "\n";
336
337 // Grab the scheduler stats for this thread.
338 std::string scheduler_stats;
339 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
340 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
341 } else {
342 scheduler_stats = "0 0 0";
343 }
344
345 int utime = 0;
346 int stime = 0;
347 int task_cpu = 0;
348 std::string stats;
349 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
350 // Skip the command, which may contain spaces.
351 stats = stats.substr(stats.find(')') + 2);
352 // Extract the three fields we care about.
353 std::vector<std::string> fields;
354 Split(stats, ' ', fields);
355 utime = strtoull(fields[11].c_str(), NULL, 10);
356 stime = strtoull(fields[12].c_str(), NULL, 10);
357 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
358 }
359
360 os << " | schedstat=( " << scheduler_stats << " )"
361 << " utm=" << utime
362 << " stm=" << stime
363 << " core=" << task_cpu
364 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
365}
366
367void Thread::DumpStack(std::ostream& os) const {
368 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700369}
370
Carl Shapirob5573532011-07-12 18:22:59 -0700371static void ThreadExitCheck(void* arg) {
372 LG << "Thread exit check";
373}
374
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700375bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700376 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700377 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
378 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700379 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700380 return false;
381 }
382
383 // Double-check the TLS slot allocation.
384 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700385 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700386 return false;
387 }
388
389 // TODO: initialize other locks and condition variables
390
391 return true;
392}
393
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700394void Thread::Shutdown() {
395 errno = pthread_key_delete(Thread::pthread_key_self_);
396 if (errno != 0) {
397 PLOG(WARNING) << "pthread_key_delete failed";
398 }
399}
400
401Thread::~Thread() {
402 delete jni_env_;
403}
404
Ian Rogers408f79a2011-08-23 18:22:33 -0700405size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700406 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700407 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700408 count += cur->NumberOfReferences();
409 }
410 return count;
411}
412
Ian Rogers408f79a2011-08-23 18:22:33 -0700413bool Thread::SirtContains(jobject obj) {
414 Object** sirt_entry = reinterpret_cast<Object**>(obj);
415 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700416 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700417 // A SIRT should always have a jobject/jclass as a native method is passed
418 // in a this pointer or a class
419 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700420 if ((&cur->References()[0] <= sirt_entry) &&
421 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700422 return true;
423 }
424 }
425 return false;
426}
427
Ian Rogers408f79a2011-08-23 18:22:33 -0700428Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700429 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700430 if (obj == NULL) {
431 return NULL;
432 }
433 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
434 IndirectRefKind kind = GetIndirectRefKind(ref);
435 Object* result;
436 switch (kind) {
437 case kLocal:
438 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700439 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700440 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700441 break;
442 }
443 case kGlobal:
444 {
445 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
446 IndirectReferenceTable& globals = vm->globals;
447 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700448 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700449 break;
450 }
451 case kWeakGlobal:
452 {
453 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
454 IndirectReferenceTable& weak_globals = vm->weak_globals;
455 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700456 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700457 if (result == kClearedJniWeakGlobal) {
458 // This is a special case where it's okay to return NULL.
459 return NULL;
460 }
461 break;
462 }
463 case kSirtOrInvalid:
464 default:
465 // TODO: make stack indirect reference table lookup more efficient
466 // Check if this is a local reference in the SIRT
467 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700468 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700469 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700470 // Assume an invalid local reference is actually a direct pointer.
471 result = reinterpret_cast<Object*>(obj);
472 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700473 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700474 }
475 }
476
477 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700478 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
479 JniAbort(NULL);
480 } else {
481 if (result != kInvalidIndirectRefObject) {
482 Heap::VerifyObject(result);
483 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700484 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700485 return result;
486}
487
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700488class CountStackDepthVisitor : public Thread::StackVisitor {
489 public:
490 CountStackDepthVisitor() : depth(0) {}
491 virtual bool VisitFrame(const Frame&) {
492 ++depth;
493 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700494 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700495
496 int GetDepth() const {
497 return depth;
498 }
499
500 private:
501 uint32_t depth;
502};
503
504class BuildStackTraceVisitor : public Thread::StackVisitor {
505 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700506 explicit BuildStackTraceVisitor(int depth) : count(0) {
507 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700508 pc_trace = IntArray::Alloc(depth);
509 }
510
511 virtual ~BuildStackTraceVisitor() {}
512
513 virtual bool VisitFrame(const Frame& frame) {
514 method_trace->Set(count, frame.GetMethod());
515 pc_trace->Set(count, frame.GetPC());
516 ++count;
517 return true;
518 }
519
520 const Method* GetMethod(uint32_t i) {
521 DCHECK(i < count);
522 return method_trace->Get(i);
523 }
524
525 uintptr_t GetPC(uint32_t i) {
526 DCHECK(i < count);
527 return pc_trace->Get(i);
528 }
529
530 private:
531 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700532 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700533 IntArray* pc_trace;
534};
535
536void Thread::WalkStack(StackVisitor* visitor) {
537 Frame frame = Thread::Current()->GetTopOfStack();
538 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
539 // CHECK(native_to_managed_record_ != NULL);
540 NativeToManagedRecord* record = native_to_managed_record_;
541
542 while (frame.GetSP()) {
543 for ( ; frame.GetMethod() != 0; frame.Next()) {
544 visitor->VisitFrame(frame);
545 }
546 if (record == NULL) {
547 break;
548 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700549 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 -0700550 record = record->link;
551 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700552}
553
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700554ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700555 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700556
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700557 CountStackDepthVisitor count_visitor;
558 WalkStack(&count_visitor);
559 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700560
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700561 BuildStackTraceVisitor build_trace_visitor(depth);
562 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700563
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700564 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700565
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700566 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700567 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700568 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700569 const Class* klass = method->GetDeclaringClass();
570 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700571 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700573
574 StackTraceElement* obj =
575 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700576 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700577 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700578 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700579 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700580 java_traces->Set(i, obj);
581 }
582 return java_traces;
583}
584
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700585void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700586 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700587 va_list args;
588 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700589 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700590 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700591
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700592 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700593 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700594 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700595 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700596 descriptor.erase(descriptor.length() - 1);
597
598 JNIEnv* env = GetJniEnv();
599 jclass exception_class = env->FindClass(descriptor.c_str());
600 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
601 int rc = env->ThrowNew(exception_class, msg.c_str());
602 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700603}
604
Elliott Hughes79082e32011-08-25 12:07:32 -0700605void Thread::ThrowOutOfMemoryError() {
606 UNIMPLEMENTED(FATAL);
607}
608
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700609Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
610 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
611 DCHECK(class_linker != NULL);
612
613 Frame cur_frame = GetTopOfStack();
614 for (int unwind_depth = 0; ; unwind_depth++) {
615 const Method* cur_method = cur_frame.GetMethod();
616 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
617 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
618
619 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
620 throw_pc,
621 dex_file,
622 class_linker);
623 if (handler_addr) {
624 *handler_pc = handler_addr;
625 return cur_frame;
626 } else {
627 // Check if we are at the last frame
628 if (cur_frame.HasNext()) {
629 cur_frame.Next();
630 } else {
631 // Either at the top of stack or next frame is native.
632 break;
633 }
634 }
635 }
636 *handler_pc = NULL;
637 return Frame();
638}
639
640void* Thread::FindExceptionHandlerInMethod(const Method* method,
641 void* throw_pc,
642 const DexFile& dex_file,
643 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700644 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700645 exception_ = NULL;
646
647 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700648 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700649 DexFile::CatchHandlerIterator iter;
650 for (iter = dex_file.dexFindCatchHandler(*code_item,
651 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
652 !iter.HasNext();
653 iter.Next()) {
654 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
655 DCHECK(klass != NULL);
656 if (exception_obj->InstanceOf(klass)) {
657 dex_pc = iter.Get().address_;
658 break;
659 }
660 }
661
662 exception_ = exception_obj;
663 if (iter.HasNext()) {
664 return NULL;
665 } else {
666 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
667 }
668}
669
Elliott Hughes410c0c82011-09-01 17:58:25 -0700670void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
671 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
672 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
673 jni_env_->locals.VisitRoots(visitor, arg);
674 jni_env_->monitors.VisitRoots(visitor, arg);
675 // visitThreadStack(visitor, thread, arg);
676 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
677}
678
Ian Rogersb033c752011-07-20 12:22:35 -0700679static const char* kStateNames[] = {
680 "New",
681 "Runnable",
682 "Blocked",
683 "Waiting",
684 "TimedWaiting",
685 "Native",
686 "Terminated",
687};
688std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
689 if (state >= Thread::kNew && state <= Thread::kTerminated) {
690 os << kStateNames[state-Thread::kNew];
691 } else {
692 os << "State[" << static_cast<int>(state) << "]";
693 }
694 return os;
695}
696
Elliott Hughes330304d2011-08-12 14:28:05 -0700697std::ostream& operator<<(std::ostream& os, const Thread& thread) {
698 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700699 << ",pthread_t=" << thread.GetImpl()
700 << ",tid=" << thread.GetTid()
701 << ",id=" << thread.GetId()
702 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700703 return os;
704}
705
Carl Shapiro61e019d2011-07-14 16:53:09 -0700706ThreadList* ThreadList::Create() {
707 return new ThreadList;
708}
709
Carl Shapirob5573532011-07-12 18:22:59 -0700710ThreadList::ThreadList() {
711 lock_ = Mutex::Create("ThreadList::Lock");
712}
713
714ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700715 if (Contains(Thread::Current())) {
716 Runtime::Current()->DetachCurrentThread();
717 }
718
719 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700720 // reach this point. This means that all daemon threads had been
721 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700722 // TODO: dump ThreadList if non-empty.
723 CHECK_EQ(list_.size(), 0U);
724
Carl Shapirob5573532011-07-12 18:22:59 -0700725 delete lock_;
726 lock_ = NULL;
727}
728
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700729bool ThreadList::Contains(Thread* thread) {
730 return find(list_.begin(), list_.end(), thread) != list_.end();
731}
732
Elliott Hughesd92bec42011-09-02 17:04:36 -0700733void ThreadList::Dump(std::ostream& os) {
734 MutexLock mu(lock_);
735 os << "DALVIK THREADS (" << list_.size() << "):\n";
736 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
737 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
738 (*it)->Dump(os);
739 }
740}
741
Carl Shapirob5573532011-07-12 18:22:59 -0700742void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700743 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700744 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700745 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700746 list_.push_front(thread);
747}
748
749void ThreadList::Unregister(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700750 //LOG(INFO) << "ThreadList::Unregister() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700751 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700752 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700753 list_.remove(thread);
754}
755
Elliott Hughes410c0c82011-09-01 17:58:25 -0700756void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
757 MutexLock mu(lock_);
758 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
759 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
760 (*it)->VisitRoots(visitor, arg);
761 }
762}
763
Carl Shapirob5573532011-07-12 18:22:59 -0700764} // namespace