blob: aa24bec75574cc6a70bfbb1a909347b2b82a708e [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
buzbee561227c2011-09-02 15:28:19 -070061// TODO: placeholder. Helper function to resolve virtual method
62static void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
63 /*
64 * Slow-path handler on invoke virtual method path in which
65 * base method is unresolved at compile-time. Doesn't need to
66 * return anything - just either ensure that
67 * method->dex_cache_resolved_methods_(method_idx) != NULL or
68 * throw and unwind. The caller will restart call sequence
69 * from the beginning.
70 */
71}
72
buzbee3ea4ec52011-08-22 17:37:19 -070073void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -070074#if defined(__arm__)
75 pShlLong = art_shl_long;
76 pShrLong = art_shr_long;
77 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -070078 pIdiv = __aeabi_idiv;
79 pIdivmod = __aeabi_idivmod;
80 pI2f = __aeabi_i2f;
81 pF2iz = __aeabi_f2iz;
82 pD2f = __aeabi_d2f;
83 pF2d = __aeabi_f2d;
84 pD2iz = __aeabi_d2iz;
85 pL2f = __aeabi_l2f;
86 pL2d = __aeabi_l2d;
87 pFadd = __aeabi_fadd;
88 pFsub = __aeabi_fsub;
89 pFdiv = __aeabi_fdiv;
90 pFmul = __aeabi_fmul;
91 pFmodf = fmodf;
92 pDadd = __aeabi_dadd;
93 pDsub = __aeabi_dsub;
94 pDdiv = __aeabi_ddiv;
95 pDmul = __aeabi_dmul;
96 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -070097 pF2l = F2L;
98 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -070099 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700100 pLmul = __aeabi_lmul;
buzbee54330722011-08-23 16:46:55 -0700101#endif
buzbeedfd3d702011-08-28 12:56:51 -0700102 pAllocFromCode = Array::AllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700103 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700104 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700105 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700106 pGet32Static = Field::Get32StaticFromCode;
107 pSet32Static = Field::Set32StaticFromCode;
108 pGet64Static = Field::Get64StaticFromCode;
109 pSet64Static = Field::Set64StaticFromCode;
110 pGetObjStatic = Field::GetObjStaticFromCode;
111 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700112 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
113 pThrowException = ThrowException;
114 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700115 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700116#if 0
buzbee1b4c8592011-08-31 10:43:51 -0700117bool (Thread::*pUnlockObject)(Thread*, Object*);
118int (Thread::*pInstanceofNonTrivialFromCode)(const Class*, const Class*);
119Method* (Thread::*pFindInterfaceMethodInCache)(Class*, uint32_t, const Method*, DvmDex*);
120bool (Thread::*pUnlockObjectFromCode)(Thread*, Object*);
121void (Thread::*pLockObjectFromCode)(Thread*, Object*);
122Object* (Thread::*pAllocObjectFromCode)(Class*, int);
123void (Thread::*pThrowException)(Thread*, Object*);
124bool (Thread::*pHandleFillArrayDataFromCode)(Array*, const uint16_t*);
buzbee3ea4ec52011-08-22 17:37:19 -0700125#endif
126}
127
Carl Shapirob5573532011-07-12 18:22:59 -0700128Mutex* Mutex::Create(const char* name) {
129 Mutex* mu = new Mutex(name);
130 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Ian Rogersb033c752011-07-20 12:22:35 -0700131 CHECK_EQ(0, result);
Carl Shapirob5573532011-07-12 18:22:59 -0700132 return mu;
133}
134
135void Mutex::Lock() {
136 int result = pthread_mutex_lock(&lock_impl_);
137 CHECK_EQ(result, 0);
138 SetOwner(Thread::Current());
139}
140
141bool Mutex::TryLock() {
142 int result = pthread_mutex_lock(&lock_impl_);
143 if (result == EBUSY) {
144 return false;
145 } else {
146 CHECK_EQ(result, 0);
147 SetOwner(Thread::Current());
148 return true;
149 }
150}
151
152void Mutex::Unlock() {
153 CHECK(GetOwner() == Thread::Current());
154 int result = pthread_mutex_unlock(&lock_impl_);
155 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700156 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700157}
158
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700159void Frame::Next() {
160 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700161 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700162 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700163}
164
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700165uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700166 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700167 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700168 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700169}
170
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700171Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700172 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700173 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700174 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700175}
176
Carl Shapiro61e019d2011-07-14 16:53:09 -0700177void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700178 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700179 return NULL;
180}
181
Brian Carlstromb765be02011-08-17 23:54:10 -0700182Thread* Thread::Create(const Runtime* runtime) {
183 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700184
185 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700186 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700187
188 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700189 errno = pthread_attr_init(&attr);
190 if (errno != 0) {
191 PLOG(FATAL) << "pthread_attr_init failed";
192 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700193
Elliott Hughese27955c2011-08-26 15:21:24 -0700194 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
195 if (errno != 0) {
196 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
197 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700198
Elliott Hughese27955c2011-08-26 15:21:24 -0700199 errno = pthread_attr_setstacksize(&attr, stack_size);
200 if (errno != 0) {
201 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
202 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700203
Elliott Hughese27955c2011-08-26 15:21:24 -0700204 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
205 if (errno != 0) {
206 PLOG(FATAL) << "pthread_create failed";
207 }
208
209 errno = pthread_attr_destroy(&attr);
210 if (errno != 0) {
211 PLOG(FATAL) << "pthread_attr_destroy failed";
212 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700213
214 return new_thread;
215}
216
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700217Thread* Thread::Attach(const Runtime* runtime) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700218 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700219 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700220
221 thread->handle_ = pthread_self();
Elliott Hughesd92bec42011-09-02 17:04:36 -0700222 thread->tid_ = gettid();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700223
224 thread->state_ = kRunnable;
225
Elliott Hughesa5780da2011-07-17 11:39:39 -0700226 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
227 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700228 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700229 }
230
Elliott Hughes75770752011-08-24 17:52:38 -0700231 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700232
Carl Shapiro61e019d2011-07-14 16:53:09 -0700233 return thread;
234}
235
Elliott Hughesa0957642011-09-02 14:27:33 -0700236void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700237 /*
238 * Get the java.lang.Thread object. This function gets called from
239 * some weird debug contexts, so it's possible that there's a GC in
240 * progress on some other thread. To decrease the chances of the
241 * thread object being moved out from under us, we add the reference
242 * to the tracked allocation list, which pins it in place.
243 *
244 * If threadObj is NULL, the thread is still in the process of being
245 * attached to the VM, and there's really nothing interesting to
246 * say about it yet.
247 */
248 os << "TODO: pin Thread before dumping\n";
249#if 0
250 if (java_thread_ == NULL) {
251 LOGI("Can't dump thread %d: threadObj not set", threadId);
252 return;
253 }
254 dvmAddTrackedAlloc(java_thread_, NULL);
255#endif
256
257 DumpState(os);
258 DumpStack(os);
259
260#if 0
261 dvmReleaseTrackedAlloc(java_thread_, NULL);
262#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700263}
264
Elliott Hughesd92bec42011-09-02 17:04:36 -0700265std::string GetSchedulerGroup(pid_t tid) {
266 // /proc/<pid>/group looks like this:
267 // 2:devices:/
268 // 1:cpuacct,cpu:/
269 // We want the third field from the line whose second field contains the "cpu" token.
270 std::string cgroup_file;
271 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
272 return "";
273 }
274 std::vector<std::string> cgroup_lines;
275 Split(cgroup_file, '\n', cgroup_lines);
276 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
277 std::vector<std::string> cgroup_fields;
278 Split(cgroup_lines[i], ':', cgroup_fields);
279 std::vector<std::string> cgroups;
280 Split(cgroup_fields[1], ',', cgroups);
281 for (size_t i = 0; i < cgroups.size(); ++i) {
282 if (cgroups[i] == "cpu") {
283 return cgroup_fields[2].substr(1); // Skip the leading slash.
284 }
285 }
286 }
287 return "";
288}
289
290void Thread::DumpState(std::ostream& os) const {
291 std::string thread_name("unknown");
292 int priority = -1;
293 bool is_daemon = false;
294#if 0 // TODO
295 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
296 threadName = dvmCreateCstrFromString(nameStr);
297 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
298 is_daemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
299#else
300 thread_name = "TODO";
301 priority = -1;
302 is_daemon = false;
303#endif
304
305 int policy;
306 sched_param sp;
307 errno = pthread_getschedparam(handle_, &policy, &sp);
308 if (errno != 0) {
309 PLOG(FATAL) << "pthread_getschedparam failed";
310 }
311
312 std::string scheduler_group(GetSchedulerGroup(GetTid()));
313 if (scheduler_group.empty()) {
314 scheduler_group = "default";
315 }
316
317 std::string group_name("(null; initializing?)");
318#if 0
319 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
320 if (groupObj != NULL) {
321 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
322 groupName = dvmCreateCstrFromString(nameStr);
323 }
324#else
325 group_name = "TODO";
326#endif
327
328 os << '"' << thread_name << '"';
329 if (is_daemon) {
330 os << " daemon";
331 }
332 os << " prio=" << priority
333 << " tid=" << GetId()
334 << " " << state_ << "\n";
335
336 int suspend_count = 0; // TODO
337 int debug_suspend_count = 0; // TODO
338 void* java_thread_ = NULL; // TODO
339 os << " | group=\"" << group_name << "\""
340 << " sCount=" << suspend_count
341 << " dsCount=" << debug_suspend_count
342 << " obj=" << reinterpret_cast<void*>(java_thread_)
343 << " self=" << reinterpret_cast<const void*>(this) << "\n";
344 os << " | sysTid=" << GetTid()
345 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
346 << " sched=" << policy << "/" << sp.sched_priority
347 << " cgrp=" << scheduler_group
348 << " handle=" << GetImpl() << "\n";
349
350 // Grab the scheduler stats for this thread.
351 std::string scheduler_stats;
352 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
353 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
354 } else {
355 scheduler_stats = "0 0 0";
356 }
357
358 int utime = 0;
359 int stime = 0;
360 int task_cpu = 0;
361 std::string stats;
362 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
363 // Skip the command, which may contain spaces.
364 stats = stats.substr(stats.find(')') + 2);
365 // Extract the three fields we care about.
366 std::vector<std::string> fields;
367 Split(stats, ' ', fields);
368 utime = strtoull(fields[11].c_str(), NULL, 10);
369 stime = strtoull(fields[12].c_str(), NULL, 10);
370 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
371 }
372
373 os << " | schedstat=( " << scheduler_stats << " )"
374 << " utm=" << utime
375 << " stm=" << stime
376 << " core=" << task_cpu
377 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
378}
379
380void Thread::DumpStack(std::ostream& os) const {
381 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700382}
383
Carl Shapirob5573532011-07-12 18:22:59 -0700384static void ThreadExitCheck(void* arg) {
385 LG << "Thread exit check";
386}
387
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700388bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700389 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700390 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
391 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700392 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700393 return false;
394 }
395
396 // Double-check the TLS slot allocation.
397 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700398 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700399 return false;
400 }
401
402 // TODO: initialize other locks and condition variables
403
404 return true;
405}
406
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700407void Thread::Shutdown() {
408 errno = pthread_key_delete(Thread::pthread_key_self_);
409 if (errno != 0) {
410 PLOG(WARNING) << "pthread_key_delete failed";
411 }
412}
413
414Thread::~Thread() {
415 delete jni_env_;
416}
417
Ian Rogers408f79a2011-08-23 18:22:33 -0700418size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700419 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700420 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700421 count += cur->NumberOfReferences();
422 }
423 return count;
424}
425
Ian Rogers408f79a2011-08-23 18:22:33 -0700426bool Thread::SirtContains(jobject obj) {
427 Object** sirt_entry = reinterpret_cast<Object**>(obj);
428 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700429 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700430 // A SIRT should always have a jobject/jclass as a native method is passed
431 // in a this pointer or a class
432 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700433 if ((&cur->References()[0] <= sirt_entry) &&
434 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700435 return true;
436 }
437 }
438 return false;
439}
440
Ian Rogers408f79a2011-08-23 18:22:33 -0700441Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700442 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700443 if (obj == NULL) {
444 return NULL;
445 }
446 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
447 IndirectRefKind kind = GetIndirectRefKind(ref);
448 Object* result;
449 switch (kind) {
450 case kLocal:
451 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700452 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700453 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700454 break;
455 }
456 case kGlobal:
457 {
458 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
459 IndirectReferenceTable& globals = vm->globals;
460 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700461 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700462 break;
463 }
464 case kWeakGlobal:
465 {
466 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
467 IndirectReferenceTable& weak_globals = vm->weak_globals;
468 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700469 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700470 if (result == kClearedJniWeakGlobal) {
471 // This is a special case where it's okay to return NULL.
472 return NULL;
473 }
474 break;
475 }
476 case kSirtOrInvalid:
477 default:
478 // TODO: make stack indirect reference table lookup more efficient
479 // Check if this is a local reference in the SIRT
480 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700481 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700482 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700483 // Assume an invalid local reference is actually a direct pointer.
484 result = reinterpret_cast<Object*>(obj);
485 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700486 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700487 }
488 }
489
490 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700491 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
492 JniAbort(NULL);
493 } else {
494 if (result != kInvalidIndirectRefObject) {
495 Heap::VerifyObject(result);
496 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700497 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700498 return result;
499}
500
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700501class CountStackDepthVisitor : public Thread::StackVisitor {
502 public:
503 CountStackDepthVisitor() : depth(0) {}
504 virtual bool VisitFrame(const Frame&) {
505 ++depth;
506 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700507 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700508
509 int GetDepth() const {
510 return depth;
511 }
512
513 private:
514 uint32_t depth;
515};
516
517class BuildStackTraceVisitor : public Thread::StackVisitor {
518 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700519 explicit BuildStackTraceVisitor(int depth) : count(0) {
520 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700521 pc_trace = IntArray::Alloc(depth);
522 }
523
524 virtual ~BuildStackTraceVisitor() {}
525
526 virtual bool VisitFrame(const Frame& frame) {
527 method_trace->Set(count, frame.GetMethod());
528 pc_trace->Set(count, frame.GetPC());
529 ++count;
530 return true;
531 }
532
533 const Method* GetMethod(uint32_t i) {
534 DCHECK(i < count);
535 return method_trace->Get(i);
536 }
537
538 uintptr_t GetPC(uint32_t i) {
539 DCHECK(i < count);
540 return pc_trace->Get(i);
541 }
542
543 private:
544 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700545 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700546 IntArray* pc_trace;
547};
548
549void Thread::WalkStack(StackVisitor* visitor) {
550 Frame frame = Thread::Current()->GetTopOfStack();
551 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
552 // CHECK(native_to_managed_record_ != NULL);
553 NativeToManagedRecord* record = native_to_managed_record_;
554
555 while (frame.GetSP()) {
556 for ( ; frame.GetMethod() != 0; frame.Next()) {
557 visitor->VisitFrame(frame);
558 }
559 if (record == NULL) {
560 break;
561 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700562 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 -0700563 record = record->link;
564 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700565}
566
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700567ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700568 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700569
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700570 CountStackDepthVisitor count_visitor;
571 WalkStack(&count_visitor);
572 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700573
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700574 BuildStackTraceVisitor build_trace_visitor(depth);
575 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700576
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700577 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700578
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700579 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700580 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700581 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700582 const Class* klass = method->GetDeclaringClass();
583 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700584 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700585 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700586
587 StackTraceElement* obj =
588 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700589 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700590 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700591 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700592 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700593 java_traces->Set(i, obj);
594 }
595 return java_traces;
596}
597
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700598void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700599 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700600 va_list args;
601 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700602 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700603 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700604
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700605 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700606 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700607 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700608 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700609 descriptor.erase(descriptor.length() - 1);
610
611 JNIEnv* env = GetJniEnv();
612 jclass exception_class = env->FindClass(descriptor.c_str());
613 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
614 int rc = env->ThrowNew(exception_class, msg.c_str());
615 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700616}
617
Elliott Hughes79082e32011-08-25 12:07:32 -0700618void Thread::ThrowOutOfMemoryError() {
619 UNIMPLEMENTED(FATAL);
620}
621
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700622Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
623 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
624 DCHECK(class_linker != NULL);
625
626 Frame cur_frame = GetTopOfStack();
627 for (int unwind_depth = 0; ; unwind_depth++) {
628 const Method* cur_method = cur_frame.GetMethod();
629 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
630 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
631
632 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
633 throw_pc,
634 dex_file,
635 class_linker);
636 if (handler_addr) {
637 *handler_pc = handler_addr;
638 return cur_frame;
639 } else {
640 // Check if we are at the last frame
641 if (cur_frame.HasNext()) {
642 cur_frame.Next();
643 } else {
644 // Either at the top of stack or next frame is native.
645 break;
646 }
647 }
648 }
649 *handler_pc = NULL;
650 return Frame();
651}
652
653void* Thread::FindExceptionHandlerInMethod(const Method* method,
654 void* throw_pc,
655 const DexFile& dex_file,
656 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700657 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700658 exception_ = NULL;
659
660 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700661 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700662 DexFile::CatchHandlerIterator iter;
663 for (iter = dex_file.dexFindCatchHandler(*code_item,
664 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
665 !iter.HasNext();
666 iter.Next()) {
667 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
668 DCHECK(klass != NULL);
669 if (exception_obj->InstanceOf(klass)) {
670 dex_pc = iter.Get().address_;
671 break;
672 }
673 }
674
675 exception_ = exception_obj;
676 if (iter.HasNext()) {
677 return NULL;
678 } else {
679 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
680 }
681}
682
Elliott Hughes410c0c82011-09-01 17:58:25 -0700683void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
684 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
685 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
686 jni_env_->locals.VisitRoots(visitor, arg);
687 jni_env_->monitors.VisitRoots(visitor, arg);
688 // visitThreadStack(visitor, thread, arg);
689 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
690}
691
Ian Rogersb033c752011-07-20 12:22:35 -0700692static const char* kStateNames[] = {
693 "New",
694 "Runnable",
695 "Blocked",
696 "Waiting",
697 "TimedWaiting",
698 "Native",
699 "Terminated",
700};
701std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
702 if (state >= Thread::kNew && state <= Thread::kTerminated) {
703 os << kStateNames[state-Thread::kNew];
704 } else {
705 os << "State[" << static_cast<int>(state) << "]";
706 }
707 return os;
708}
709
Elliott Hughes330304d2011-08-12 14:28:05 -0700710std::ostream& operator<<(std::ostream& os, const Thread& thread) {
711 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700712 << ",pthread_t=" << thread.GetImpl()
713 << ",tid=" << thread.GetTid()
714 << ",id=" << thread.GetId()
715 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700716 return os;
717}
718
Carl Shapiro61e019d2011-07-14 16:53:09 -0700719ThreadList* ThreadList::Create() {
720 return new ThreadList;
721}
722
Carl Shapirob5573532011-07-12 18:22:59 -0700723ThreadList::ThreadList() {
724 lock_ = Mutex::Create("ThreadList::Lock");
725}
726
727ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700728 if (Contains(Thread::Current())) {
729 Runtime::Current()->DetachCurrentThread();
730 }
731
732 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700733 // reach this point. This means that all daemon threads had been
734 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700735 // TODO: dump ThreadList if non-empty.
736 CHECK_EQ(list_.size(), 0U);
737
Carl Shapirob5573532011-07-12 18:22:59 -0700738 delete lock_;
739 lock_ = NULL;
740}
741
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700742bool ThreadList::Contains(Thread* thread) {
743 return find(list_.begin(), list_.end(), thread) != list_.end();
744}
745
Elliott Hughesd92bec42011-09-02 17:04:36 -0700746void ThreadList::Dump(std::ostream& os) {
747 MutexLock mu(lock_);
748 os << "DALVIK THREADS (" << list_.size() << "):\n";
749 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
750 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
751 (*it)->Dump(os);
752 }
753}
754
Carl Shapirob5573532011-07-12 18:22:59 -0700755void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700756 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700757 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700758 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700759 list_.push_front(thread);
760}
761
762void ThreadList::Unregister(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700763 //LOG(INFO) << "ThreadList::Unregister() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700764 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700765 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700766 list_.remove(thread);
767}
768
Elliott Hughes410c0c82011-09-01 17:58:25 -0700769void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
770 MutexLock mu(lock_);
771 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
772 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
773 (*it)->VisitRoots(visitor, arg);
774 }
775}
776
Carl Shapirob5573532011-07-12 18:22:59 -0700777} // namespace