blob: 31786c9970bb88129caed24ab23f5c7e6b7f8ba6 [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
buzbee4a3164f2011-09-03 11:25:10 -070037// Temporary debugging hook for compiler.
38static void DebugMe(Method* method, uint32_t info) {
39 LOG(INFO) << "DebugMe";
40 if (method != NULL)
41 LOG(INFO) << PrettyMethod(method);
42 LOG(INFO) << "Info: " << info;
43}
44
45/*
46 * TODO: placeholder for a method that can be called by the
47 * invoke-interface trampoline to unwind and handle exception. The
48 * trampoline will arrange it so that the caller appears to be the
49 * callsite of the failed invoke-interface. See comments in
50 * compiler/runtime_support.S
51 */
52extern "C" void artFailedInvokeInterface()
53{
54 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
55}
56
57// TODO: placeholder. See comments in compiler/runtime_support.S
58extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
59 Object* this_object , Method* caller_method)
60{
61 /*
62 * Note: this_object has not yet been null-checked. To match
63 * the old-world state, nullcheck this_object and load
64 * Class* this_class = this_object->GetClass().
65 * See comments and possible thrown exceptions in old-world
66 * Interp.cpp:dvmInterpFindInterfaceMethod, and complete with
67 * new-world FindVirtualMethodForInterface.
68 */
69 UNIMPLEMENTED(FATAL) << "Unimplemented invoke interface";
70 return 0LL;
71}
72
buzbee1b4c8592011-08-31 10:43:51 -070073// TODO: placeholder. This is what generated code will call to throw
74static void ThrowException(Thread* thread, Throwable* exception) {
75 /*
76 * exception may be NULL, in which case this routine should
77 * throw NPE. NOTE: this is a convenience for generated code,
78 * which previuosly did the null check inline and constructed
79 * and threw a NPE if NULL. This routine responsible for setting
80 * exception_ in thread.
81 */
82 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
83}
84
85// TODO: placeholder. Helper function to type
86static Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
87 /*
88 * Should initialize & fix up method->dex_cache_resolved_types_[].
89 * Returns initialized type. Does not return normally if an exception
90 * is thrown, but instead initiates the catch. Should be similar to
91 * ClassLinker::InitializeStaticStorageFromCode.
92 */
93 UNIMPLEMENTED(FATAL);
94 return NULL;
95}
96
buzbee561227c2011-09-02 15:28:19 -070097// TODO: placeholder. Helper function to resolve virtual method
98static void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
99 /*
100 * Slow-path handler on invoke virtual method path in which
101 * base method is unresolved at compile-time. Doesn't need to
102 * return anything - just either ensure that
103 * method->dex_cache_resolved_methods_(method_idx) != NULL or
104 * throw and unwind. The caller will restart call sequence
105 * from the beginning.
106 */
107}
108
buzbee3ea4ec52011-08-22 17:37:19 -0700109void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700110#if defined(__arm__)
111 pShlLong = art_shl_long;
112 pShrLong = art_shr_long;
113 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700114 pIdiv = __aeabi_idiv;
115 pIdivmod = __aeabi_idivmod;
116 pI2f = __aeabi_i2f;
117 pF2iz = __aeabi_f2iz;
118 pD2f = __aeabi_d2f;
119 pF2d = __aeabi_f2d;
120 pD2iz = __aeabi_d2iz;
121 pL2f = __aeabi_l2f;
122 pL2d = __aeabi_l2d;
123 pFadd = __aeabi_fadd;
124 pFsub = __aeabi_fsub;
125 pFdiv = __aeabi_fdiv;
126 pFmul = __aeabi_fmul;
127 pFmodf = fmodf;
128 pDadd = __aeabi_dadd;
129 pDsub = __aeabi_dsub;
130 pDdiv = __aeabi_ddiv;
131 pDmul = __aeabi_dmul;
132 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -0700133 pF2l = F2L;
134 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -0700135 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700136 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700137 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700138#endif
buzbeedfd3d702011-08-28 12:56:51 -0700139 pAllocFromCode = Array::AllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700140 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700141 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700142 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700143 pGet32Static = Field::Get32StaticFromCode;
144 pSet32Static = Field::Set32StaticFromCode;
145 pGet64Static = Field::Get64StaticFromCode;
146 pSet64Static = Field::Set64StaticFromCode;
147 pGetObjStatic = Field::GetObjStaticFromCode;
148 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700149 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
150 pThrowException = ThrowException;
151 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700152 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700153 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700154#if 0
buzbee1b4c8592011-08-31 10:43:51 -0700155bool (Thread::*pUnlockObject)(Thread*, Object*);
156int (Thread::*pInstanceofNonTrivialFromCode)(const Class*, const Class*);
buzbee1b4c8592011-08-31 10:43:51 -0700157bool (Thread::*pUnlockObjectFromCode)(Thread*, Object*);
158void (Thread::*pLockObjectFromCode)(Thread*, Object*);
buzbee3ea4ec52011-08-22 17:37:19 -0700159#endif
160}
161
Carl Shapirob5573532011-07-12 18:22:59 -0700162Mutex* Mutex::Create(const char* name) {
163 Mutex* mu = new Mutex(name);
164 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Ian Rogersb033c752011-07-20 12:22:35 -0700165 CHECK_EQ(0, result);
Carl Shapirob5573532011-07-12 18:22:59 -0700166 return mu;
167}
168
169void Mutex::Lock() {
170 int result = pthread_mutex_lock(&lock_impl_);
171 CHECK_EQ(result, 0);
172 SetOwner(Thread::Current());
173}
174
175bool Mutex::TryLock() {
176 int result = pthread_mutex_lock(&lock_impl_);
177 if (result == EBUSY) {
178 return false;
179 } else {
180 CHECK_EQ(result, 0);
181 SetOwner(Thread::Current());
182 return true;
183 }
184}
185
186void Mutex::Unlock() {
187 CHECK(GetOwner() == Thread::Current());
188 int result = pthread_mutex_unlock(&lock_impl_);
189 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700190 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700191}
192
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700193void Frame::Next() {
194 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700195 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700196 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700197}
198
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700199uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700200 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700201 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700202 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700203}
204
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700205Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700206 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700207 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700208 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700209}
210
Carl Shapiro61e019d2011-07-14 16:53:09 -0700211void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700212 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700213 return NULL;
214}
215
Brian Carlstromb765be02011-08-17 23:54:10 -0700216Thread* Thread::Create(const Runtime* runtime) {
217 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700218
219 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700220 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700221
222 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700223 errno = pthread_attr_init(&attr);
224 if (errno != 0) {
225 PLOG(FATAL) << "pthread_attr_init failed";
226 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700227
Elliott Hughese27955c2011-08-26 15:21:24 -0700228 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
229 if (errno != 0) {
230 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
231 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700232
Elliott Hughese27955c2011-08-26 15:21:24 -0700233 errno = pthread_attr_setstacksize(&attr, stack_size);
234 if (errno != 0) {
235 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
236 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700237
Elliott Hughese27955c2011-08-26 15:21:24 -0700238 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
239 if (errno != 0) {
240 PLOG(FATAL) << "pthread_create failed";
241 }
242
243 errno = pthread_attr_destroy(&attr);
244 if (errno != 0) {
245 PLOG(FATAL) << "pthread_attr_destroy failed";
246 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700247
248 return new_thread;
249}
250
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700251Thread* Thread::Attach(const Runtime* runtime) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700252 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700253 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700254
255 thread->handle_ = pthread_self();
Elliott Hughesd92bec42011-09-02 17:04:36 -0700256 thread->tid_ = gettid();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700257
258 thread->state_ = kRunnable;
259
Elliott Hughesa5780da2011-07-17 11:39:39 -0700260 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
261 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700262 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700263 }
264
Elliott Hughes75770752011-08-24 17:52:38 -0700265 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700266
Carl Shapiro61e019d2011-07-14 16:53:09 -0700267 return thread;
268}
269
Elliott Hughesa0957642011-09-02 14:27:33 -0700270void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700271 /*
272 * Get the java.lang.Thread object. This function gets called from
273 * some weird debug contexts, so it's possible that there's a GC in
274 * progress on some other thread. To decrease the chances of the
275 * thread object being moved out from under us, we add the reference
276 * to the tracked allocation list, which pins it in place.
277 *
278 * If threadObj is NULL, the thread is still in the process of being
279 * attached to the VM, and there's really nothing interesting to
280 * say about it yet.
281 */
282 os << "TODO: pin Thread before dumping\n";
283#if 0
284 if (java_thread_ == NULL) {
285 LOGI("Can't dump thread %d: threadObj not set", threadId);
286 return;
287 }
288 dvmAddTrackedAlloc(java_thread_, NULL);
289#endif
290
291 DumpState(os);
292 DumpStack(os);
293
294#if 0
295 dvmReleaseTrackedAlloc(java_thread_, NULL);
296#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700297}
298
Elliott Hughesd92bec42011-09-02 17:04:36 -0700299std::string GetSchedulerGroup(pid_t tid) {
300 // /proc/<pid>/group looks like this:
301 // 2:devices:/
302 // 1:cpuacct,cpu:/
303 // We want the third field from the line whose second field contains the "cpu" token.
304 std::string cgroup_file;
305 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
306 return "";
307 }
308 std::vector<std::string> cgroup_lines;
309 Split(cgroup_file, '\n', cgroup_lines);
310 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
311 std::vector<std::string> cgroup_fields;
312 Split(cgroup_lines[i], ':', cgroup_fields);
313 std::vector<std::string> cgroups;
314 Split(cgroup_fields[1], ',', cgroups);
315 for (size_t i = 0; i < cgroups.size(); ++i) {
316 if (cgroups[i] == "cpu") {
317 return cgroup_fields[2].substr(1); // Skip the leading slash.
318 }
319 }
320 }
321 return "";
322}
323
324void Thread::DumpState(std::ostream& os) const {
325 std::string thread_name("unknown");
326 int priority = -1;
327 bool is_daemon = false;
328#if 0 // TODO
329 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
330 threadName = dvmCreateCstrFromString(nameStr);
331 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
332 is_daemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
333#else
334 thread_name = "TODO";
335 priority = -1;
336 is_daemon = false;
337#endif
338
339 int policy;
340 sched_param sp;
341 errno = pthread_getschedparam(handle_, &policy, &sp);
342 if (errno != 0) {
343 PLOG(FATAL) << "pthread_getschedparam failed";
344 }
345
346 std::string scheduler_group(GetSchedulerGroup(GetTid()));
347 if (scheduler_group.empty()) {
348 scheduler_group = "default";
349 }
350
351 std::string group_name("(null; initializing?)");
352#if 0
353 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
354 if (groupObj != NULL) {
355 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
356 groupName = dvmCreateCstrFromString(nameStr);
357 }
358#else
359 group_name = "TODO";
360#endif
361
362 os << '"' << thread_name << '"';
363 if (is_daemon) {
364 os << " daemon";
365 }
366 os << " prio=" << priority
367 << " tid=" << GetId()
368 << " " << state_ << "\n";
369
370 int suspend_count = 0; // TODO
371 int debug_suspend_count = 0; // TODO
372 void* java_thread_ = NULL; // TODO
373 os << " | group=\"" << group_name << "\""
374 << " sCount=" << suspend_count
375 << " dsCount=" << debug_suspend_count
376 << " obj=" << reinterpret_cast<void*>(java_thread_)
377 << " self=" << reinterpret_cast<const void*>(this) << "\n";
378 os << " | sysTid=" << GetTid()
379 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
380 << " sched=" << policy << "/" << sp.sched_priority
381 << " cgrp=" << scheduler_group
382 << " handle=" << GetImpl() << "\n";
383
384 // Grab the scheduler stats for this thread.
385 std::string scheduler_stats;
386 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
387 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
388 } else {
389 scheduler_stats = "0 0 0";
390 }
391
392 int utime = 0;
393 int stime = 0;
394 int task_cpu = 0;
395 std::string stats;
396 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
397 // Skip the command, which may contain spaces.
398 stats = stats.substr(stats.find(')') + 2);
399 // Extract the three fields we care about.
400 std::vector<std::string> fields;
401 Split(stats, ' ', fields);
402 utime = strtoull(fields[11].c_str(), NULL, 10);
403 stime = strtoull(fields[12].c_str(), NULL, 10);
404 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
405 }
406
407 os << " | schedstat=( " << scheduler_stats << " )"
408 << " utm=" << utime
409 << " stm=" << stime
410 << " core=" << task_cpu
411 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
412}
413
414void Thread::DumpStack(std::ostream& os) const {
415 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700416}
417
Carl Shapirob5573532011-07-12 18:22:59 -0700418static void ThreadExitCheck(void* arg) {
419 LG << "Thread exit check";
420}
421
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700422bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700423 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700424 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
425 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700426 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700427 return false;
428 }
429
430 // Double-check the TLS slot allocation.
431 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700432 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700433 return false;
434 }
435
436 // TODO: initialize other locks and condition variables
437
438 return true;
439}
440
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700441void Thread::Shutdown() {
442 errno = pthread_key_delete(Thread::pthread_key_self_);
443 if (errno != 0) {
444 PLOG(WARNING) << "pthread_key_delete failed";
445 }
446}
447
448Thread::~Thread() {
449 delete jni_env_;
450}
451
Ian Rogers408f79a2011-08-23 18:22:33 -0700452size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700453 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700454 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700455 count += cur->NumberOfReferences();
456 }
457 return count;
458}
459
Ian Rogers408f79a2011-08-23 18:22:33 -0700460bool Thread::SirtContains(jobject obj) {
461 Object** sirt_entry = reinterpret_cast<Object**>(obj);
462 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700463 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700464 // A SIRT should always have a jobject/jclass as a native method is passed
465 // in a this pointer or a class
466 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700467 if ((&cur->References()[0] <= sirt_entry) &&
468 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700469 return true;
470 }
471 }
472 return false;
473}
474
Ian Rogers408f79a2011-08-23 18:22:33 -0700475Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700477 if (obj == NULL) {
478 return NULL;
479 }
480 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
481 IndirectRefKind kind = GetIndirectRefKind(ref);
482 Object* result;
483 switch (kind) {
484 case kLocal:
485 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700486 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700487 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700488 break;
489 }
490 case kGlobal:
491 {
492 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
493 IndirectReferenceTable& globals = vm->globals;
494 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700495 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700496 break;
497 }
498 case kWeakGlobal:
499 {
500 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
501 IndirectReferenceTable& weak_globals = vm->weak_globals;
502 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700503 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700504 if (result == kClearedJniWeakGlobal) {
505 // This is a special case where it's okay to return NULL.
506 return NULL;
507 }
508 break;
509 }
510 case kSirtOrInvalid:
511 default:
512 // TODO: make stack indirect reference table lookup more efficient
513 // Check if this is a local reference in the SIRT
514 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700515 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700516 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700517 // Assume an invalid local reference is actually a direct pointer.
518 result = reinterpret_cast<Object*>(obj);
519 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700520 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700521 }
522 }
523
524 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700525 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
526 JniAbort(NULL);
527 } else {
528 if (result != kInvalidIndirectRefObject) {
529 Heap::VerifyObject(result);
530 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700531 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700532 return result;
533}
534
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700535class CountStackDepthVisitor : public Thread::StackVisitor {
536 public:
537 CountStackDepthVisitor() : depth(0) {}
538 virtual bool VisitFrame(const Frame&) {
539 ++depth;
540 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700541 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700542
543 int GetDepth() const {
544 return depth;
545 }
546
547 private:
548 uint32_t depth;
549};
550
551class BuildStackTraceVisitor : public Thread::StackVisitor {
552 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700553 explicit BuildStackTraceVisitor(int depth) : count(0) {
554 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700555 pc_trace = IntArray::Alloc(depth);
556 }
557
558 virtual ~BuildStackTraceVisitor() {}
559
560 virtual bool VisitFrame(const Frame& frame) {
561 method_trace->Set(count, frame.GetMethod());
562 pc_trace->Set(count, frame.GetPC());
563 ++count;
564 return true;
565 }
566
567 const Method* GetMethod(uint32_t i) {
568 DCHECK(i < count);
569 return method_trace->Get(i);
570 }
571
572 uintptr_t GetPC(uint32_t i) {
573 DCHECK(i < count);
574 return pc_trace->Get(i);
575 }
576
577 private:
578 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700579 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700580 IntArray* pc_trace;
581};
582
583void Thread::WalkStack(StackVisitor* visitor) {
584 Frame frame = Thread::Current()->GetTopOfStack();
585 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
586 // CHECK(native_to_managed_record_ != NULL);
587 NativeToManagedRecord* record = native_to_managed_record_;
588
589 while (frame.GetSP()) {
590 for ( ; frame.GetMethod() != 0; frame.Next()) {
591 visitor->VisitFrame(frame);
592 }
593 if (record == NULL) {
594 break;
595 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700596 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 -0700597 record = record->link;
598 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700599}
600
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700601ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700602 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700603
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700604 CountStackDepthVisitor count_visitor;
605 WalkStack(&count_visitor);
606 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700607
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700608 BuildStackTraceVisitor build_trace_visitor(depth);
609 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700610
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700611 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700612
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700613 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700614 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700615 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700616 const Class* klass = method->GetDeclaringClass();
617 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700618 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700619 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700620
621 StackTraceElement* obj =
622 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700623 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700624 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700625 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700626 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700627 java_traces->Set(i, obj);
628 }
629 return java_traces;
630}
631
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700632void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700633 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700634 va_list args;
635 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700636 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700637 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700638
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700639 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700640 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700641 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700642 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700643 descriptor.erase(descriptor.length() - 1);
644
645 JNIEnv* env = GetJniEnv();
646 jclass exception_class = env->FindClass(descriptor.c_str());
647 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
648 int rc = env->ThrowNew(exception_class, msg.c_str());
649 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700650}
651
Elliott Hughes79082e32011-08-25 12:07:32 -0700652void Thread::ThrowOutOfMemoryError() {
653 UNIMPLEMENTED(FATAL);
654}
655
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700656Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
657 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
658 DCHECK(class_linker != NULL);
659
660 Frame cur_frame = GetTopOfStack();
661 for (int unwind_depth = 0; ; unwind_depth++) {
662 const Method* cur_method = cur_frame.GetMethod();
663 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
664 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
665
666 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
667 throw_pc,
668 dex_file,
669 class_linker);
670 if (handler_addr) {
671 *handler_pc = handler_addr;
672 return cur_frame;
673 } else {
674 // Check if we are at the last frame
675 if (cur_frame.HasNext()) {
676 cur_frame.Next();
677 } else {
678 // Either at the top of stack or next frame is native.
679 break;
680 }
681 }
682 }
683 *handler_pc = NULL;
684 return Frame();
685}
686
687void* Thread::FindExceptionHandlerInMethod(const Method* method,
688 void* throw_pc,
689 const DexFile& dex_file,
690 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700691 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700692 exception_ = NULL;
693
694 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700695 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700696 DexFile::CatchHandlerIterator iter;
697 for (iter = dex_file.dexFindCatchHandler(*code_item,
698 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
699 !iter.HasNext();
700 iter.Next()) {
701 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
702 DCHECK(klass != NULL);
703 if (exception_obj->InstanceOf(klass)) {
704 dex_pc = iter.Get().address_;
705 break;
706 }
707 }
708
709 exception_ = exception_obj;
710 if (iter.HasNext()) {
711 return NULL;
712 } else {
713 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
714 }
715}
716
Elliott Hughes410c0c82011-09-01 17:58:25 -0700717void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
718 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
719 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
720 jni_env_->locals.VisitRoots(visitor, arg);
721 jni_env_->monitors.VisitRoots(visitor, arg);
722 // visitThreadStack(visitor, thread, arg);
723 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
724}
725
Ian Rogersb033c752011-07-20 12:22:35 -0700726static const char* kStateNames[] = {
727 "New",
728 "Runnable",
729 "Blocked",
730 "Waiting",
731 "TimedWaiting",
732 "Native",
733 "Terminated",
734};
735std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
736 if (state >= Thread::kNew && state <= Thread::kTerminated) {
737 os << kStateNames[state-Thread::kNew];
738 } else {
739 os << "State[" << static_cast<int>(state) << "]";
740 }
741 return os;
742}
743
Elliott Hughes330304d2011-08-12 14:28:05 -0700744std::ostream& operator<<(std::ostream& os, const Thread& thread) {
745 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700746 << ",pthread_t=" << thread.GetImpl()
747 << ",tid=" << thread.GetTid()
748 << ",id=" << thread.GetId()
749 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700750 return os;
751}
752
Carl Shapiro61e019d2011-07-14 16:53:09 -0700753ThreadList* ThreadList::Create() {
754 return new ThreadList;
755}
756
Carl Shapirob5573532011-07-12 18:22:59 -0700757ThreadList::ThreadList() {
758 lock_ = Mutex::Create("ThreadList::Lock");
759}
760
761ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700762 if (Contains(Thread::Current())) {
763 Runtime::Current()->DetachCurrentThread();
764 }
765
766 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700767 // reach this point. This means that all daemon threads had been
768 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700769 // TODO: dump ThreadList if non-empty.
770 CHECK_EQ(list_.size(), 0U);
771
Carl Shapirob5573532011-07-12 18:22:59 -0700772 delete lock_;
773 lock_ = NULL;
774}
775
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700776bool ThreadList::Contains(Thread* thread) {
777 return find(list_.begin(), list_.end(), thread) != list_.end();
778}
779
Elliott Hughesd92bec42011-09-02 17:04:36 -0700780void ThreadList::Dump(std::ostream& os) {
781 MutexLock mu(lock_);
782 os << "DALVIK THREADS (" << list_.size() << "):\n";
783 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
784 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
785 (*it)->Dump(os);
786 }
787}
788
Carl Shapirob5573532011-07-12 18:22:59 -0700789void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700790 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700791 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700792 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700793 list_.push_front(thread);
794}
795
796void ThreadList::Unregister(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700797 //LOG(INFO) << "ThreadList::Unregister() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700798 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700799 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700800 list_.remove(thread);
801}
802
Elliott Hughes410c0c82011-09-01 17:58:25 -0700803void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
804 MutexLock mu(lock_);
805 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
806 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
807 (*it)->VisitRoots(visitor, arg);
808 }
809}
810
Carl Shapirob5573532011-07-12 18:22:59 -0700811} // namespace