blob: a617fb48ecc134cc0361135cf44e45b2b6b4e8d1 [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
buzbee1da522d2011-09-04 11:22:20 -0700109// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
110static Array* CheckAndAllocFromCode(uint32_t type_index, Method* method,
111 int32_t component_count)
112{
113 /*
114 * Just a wrapper around Array::AllocFromCode() that additionally
115 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
116 */
117 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
118 return Array::AllocFromCode(type_index, method, component_count);
119}
120
buzbee3ea4ec52011-08-22 17:37:19 -0700121void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700122#if defined(__arm__)
123 pShlLong = art_shl_long;
124 pShrLong = art_shr_long;
125 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700126 pIdiv = __aeabi_idiv;
127 pIdivmod = __aeabi_idivmod;
128 pI2f = __aeabi_i2f;
129 pF2iz = __aeabi_f2iz;
130 pD2f = __aeabi_d2f;
131 pF2d = __aeabi_f2d;
132 pD2iz = __aeabi_d2iz;
133 pL2f = __aeabi_l2f;
134 pL2d = __aeabi_l2d;
135 pFadd = __aeabi_fadd;
136 pFsub = __aeabi_fsub;
137 pFdiv = __aeabi_fdiv;
138 pFmul = __aeabi_fmul;
139 pFmodf = fmodf;
140 pDadd = __aeabi_dadd;
141 pDsub = __aeabi_dsub;
142 pDdiv = __aeabi_ddiv;
143 pDmul = __aeabi_dmul;
144 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -0700145 pF2l = F2L;
146 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -0700147 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700148 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700149 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700150#endif
buzbeedfd3d702011-08-28 12:56:51 -0700151 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700152 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700153 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700154 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700155 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700156 pGet32Static = Field::Get32StaticFromCode;
157 pSet32Static = Field::Set32StaticFromCode;
158 pGet64Static = Field::Get64StaticFromCode;
159 pSet64Static = Field::Set64StaticFromCode;
160 pGetObjStatic = Field::GetObjStaticFromCode;
161 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700162 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
163 pThrowException = ThrowException;
164 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700165 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700166 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700167 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700168#if 0
buzbee1b4c8592011-08-31 10:43:51 -0700169bool (Thread::*pUnlockObject)(Thread*, Object*);
170int (Thread::*pInstanceofNonTrivialFromCode)(const Class*, const Class*);
buzbee1b4c8592011-08-31 10:43:51 -0700171bool (Thread::*pUnlockObjectFromCode)(Thread*, Object*);
172void (Thread::*pLockObjectFromCode)(Thread*, Object*);
buzbee3ea4ec52011-08-22 17:37:19 -0700173#endif
174}
175
Carl Shapirob5573532011-07-12 18:22:59 -0700176Mutex* Mutex::Create(const char* name) {
177 Mutex* mu = new Mutex(name);
178 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Ian Rogersb033c752011-07-20 12:22:35 -0700179 CHECK_EQ(0, result);
Carl Shapirob5573532011-07-12 18:22:59 -0700180 return mu;
181}
182
183void Mutex::Lock() {
184 int result = pthread_mutex_lock(&lock_impl_);
185 CHECK_EQ(result, 0);
186 SetOwner(Thread::Current());
187}
188
189bool Mutex::TryLock() {
190 int result = pthread_mutex_lock(&lock_impl_);
191 if (result == EBUSY) {
192 return false;
193 } else {
194 CHECK_EQ(result, 0);
195 SetOwner(Thread::Current());
196 return true;
197 }
198}
199
200void Mutex::Unlock() {
201 CHECK(GetOwner() == Thread::Current());
202 int result = pthread_mutex_unlock(&lock_impl_);
203 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700204 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700205}
206
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700207void Frame::Next() {
208 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700209 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700210 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700211}
212
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700213uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700214 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700215 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700216 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700217}
218
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700219Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700220 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700221 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700222 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700223}
224
Carl Shapiro61e019d2011-07-14 16:53:09 -0700225void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700226 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700227 return NULL;
228}
229
Brian Carlstromb765be02011-08-17 23:54:10 -0700230Thread* Thread::Create(const Runtime* runtime) {
231 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700232
233 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700234 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700235
236 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700237 errno = pthread_attr_init(&attr);
238 if (errno != 0) {
239 PLOG(FATAL) << "pthread_attr_init failed";
240 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700241
Elliott Hughese27955c2011-08-26 15:21:24 -0700242 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
243 if (errno != 0) {
244 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
245 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700246
Elliott Hughese27955c2011-08-26 15:21:24 -0700247 errno = pthread_attr_setstacksize(&attr, stack_size);
248 if (errno != 0) {
249 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
250 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700251
Elliott Hughese27955c2011-08-26 15:21:24 -0700252 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
253 if (errno != 0) {
254 PLOG(FATAL) << "pthread_create failed";
255 }
256
257 errno = pthread_attr_destroy(&attr);
258 if (errno != 0) {
259 PLOG(FATAL) << "pthread_attr_destroy failed";
260 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700261
262 return new_thread;
263}
264
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700265Thread* Thread::Attach(const Runtime* runtime) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700266 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700267 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700268
269 thread->handle_ = pthread_self();
Elliott Hughesd92bec42011-09-02 17:04:36 -0700270 thread->tid_ = gettid();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700271
272 thread->state_ = kRunnable;
273
Elliott Hughesa5780da2011-07-17 11:39:39 -0700274 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
275 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700276 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700277 }
278
Elliott Hughes75770752011-08-24 17:52:38 -0700279 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700280
Carl Shapiro61e019d2011-07-14 16:53:09 -0700281 return thread;
282}
283
Elliott Hughesa0957642011-09-02 14:27:33 -0700284void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700285 /*
286 * Get the java.lang.Thread object. This function gets called from
287 * some weird debug contexts, so it's possible that there's a GC in
288 * progress on some other thread. To decrease the chances of the
289 * thread object being moved out from under us, we add the reference
290 * to the tracked allocation list, which pins it in place.
291 *
292 * If threadObj is NULL, the thread is still in the process of being
293 * attached to the VM, and there's really nothing interesting to
294 * say about it yet.
295 */
296 os << "TODO: pin Thread before dumping\n";
297#if 0
298 if (java_thread_ == NULL) {
299 LOGI("Can't dump thread %d: threadObj not set", threadId);
300 return;
301 }
302 dvmAddTrackedAlloc(java_thread_, NULL);
303#endif
304
305 DumpState(os);
306 DumpStack(os);
307
308#if 0
309 dvmReleaseTrackedAlloc(java_thread_, NULL);
310#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700311}
312
Elliott Hughesd92bec42011-09-02 17:04:36 -0700313std::string GetSchedulerGroup(pid_t tid) {
314 // /proc/<pid>/group looks like this:
315 // 2:devices:/
316 // 1:cpuacct,cpu:/
317 // We want the third field from the line whose second field contains the "cpu" token.
318 std::string cgroup_file;
319 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
320 return "";
321 }
322 std::vector<std::string> cgroup_lines;
323 Split(cgroup_file, '\n', cgroup_lines);
324 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
325 std::vector<std::string> cgroup_fields;
326 Split(cgroup_lines[i], ':', cgroup_fields);
327 std::vector<std::string> cgroups;
328 Split(cgroup_fields[1], ',', cgroups);
329 for (size_t i = 0; i < cgroups.size(); ++i) {
330 if (cgroups[i] == "cpu") {
331 return cgroup_fields[2].substr(1); // Skip the leading slash.
332 }
333 }
334 }
335 return "";
336}
337
338void Thread::DumpState(std::ostream& os) const {
339 std::string thread_name("unknown");
340 int priority = -1;
341 bool is_daemon = false;
342#if 0 // TODO
343 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
344 threadName = dvmCreateCstrFromString(nameStr);
345 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
346 is_daemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
347#else
348 thread_name = "TODO";
349 priority = -1;
350 is_daemon = false;
351#endif
352
353 int policy;
354 sched_param sp;
355 errno = pthread_getschedparam(handle_, &policy, &sp);
356 if (errno != 0) {
357 PLOG(FATAL) << "pthread_getschedparam failed";
358 }
359
360 std::string scheduler_group(GetSchedulerGroup(GetTid()));
361 if (scheduler_group.empty()) {
362 scheduler_group = "default";
363 }
364
365 std::string group_name("(null; initializing?)");
366#if 0
367 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
368 if (groupObj != NULL) {
369 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
370 groupName = dvmCreateCstrFromString(nameStr);
371 }
372#else
373 group_name = "TODO";
374#endif
375
376 os << '"' << thread_name << '"';
377 if (is_daemon) {
378 os << " daemon";
379 }
380 os << " prio=" << priority
381 << " tid=" << GetId()
382 << " " << state_ << "\n";
383
384 int suspend_count = 0; // TODO
385 int debug_suspend_count = 0; // TODO
386 void* java_thread_ = NULL; // TODO
387 os << " | group=\"" << group_name << "\""
388 << " sCount=" << suspend_count
389 << " dsCount=" << debug_suspend_count
390 << " obj=" << reinterpret_cast<void*>(java_thread_)
391 << " self=" << reinterpret_cast<const void*>(this) << "\n";
392 os << " | sysTid=" << GetTid()
393 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
394 << " sched=" << policy << "/" << sp.sched_priority
395 << " cgrp=" << scheduler_group
396 << " handle=" << GetImpl() << "\n";
397
398 // Grab the scheduler stats for this thread.
399 std::string scheduler_stats;
400 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
401 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
402 } else {
403 scheduler_stats = "0 0 0";
404 }
405
406 int utime = 0;
407 int stime = 0;
408 int task_cpu = 0;
409 std::string stats;
410 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
411 // Skip the command, which may contain spaces.
412 stats = stats.substr(stats.find(')') + 2);
413 // Extract the three fields we care about.
414 std::vector<std::string> fields;
415 Split(stats, ' ', fields);
416 utime = strtoull(fields[11].c_str(), NULL, 10);
417 stime = strtoull(fields[12].c_str(), NULL, 10);
418 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
419 }
420
421 os << " | schedstat=( " << scheduler_stats << " )"
422 << " utm=" << utime
423 << " stm=" << stime
424 << " core=" << task_cpu
425 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
426}
427
428void Thread::DumpStack(std::ostream& os) const {
429 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700430}
431
Carl Shapirob5573532011-07-12 18:22:59 -0700432static void ThreadExitCheck(void* arg) {
433 LG << "Thread exit check";
434}
435
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700436bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700437 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700438 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
439 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700440 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700441 return false;
442 }
443
444 // Double-check the TLS slot allocation.
445 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700446 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700447 return false;
448 }
449
450 // TODO: initialize other locks and condition variables
451
452 return true;
453}
454
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700455void Thread::Shutdown() {
456 errno = pthread_key_delete(Thread::pthread_key_self_);
457 if (errno != 0) {
458 PLOG(WARNING) << "pthread_key_delete failed";
459 }
460}
461
462Thread::~Thread() {
463 delete jni_env_;
464}
465
Ian Rogers408f79a2011-08-23 18:22:33 -0700466size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700467 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700468 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700469 count += cur->NumberOfReferences();
470 }
471 return count;
472}
473
Ian Rogers408f79a2011-08-23 18:22:33 -0700474bool Thread::SirtContains(jobject obj) {
475 Object** sirt_entry = reinterpret_cast<Object**>(obj);
476 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700477 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700478 // A SIRT should always have a jobject/jclass as a native method is passed
479 // in a this pointer or a class
480 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700481 if ((&cur->References()[0] <= sirt_entry) &&
482 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700483 return true;
484 }
485 }
486 return false;
487}
488
Ian Rogers408f79a2011-08-23 18:22:33 -0700489Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700490 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700491 if (obj == NULL) {
492 return NULL;
493 }
494 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
495 IndirectRefKind kind = GetIndirectRefKind(ref);
496 Object* result;
497 switch (kind) {
498 case kLocal:
499 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700500 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700501 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700502 break;
503 }
504 case kGlobal:
505 {
506 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
507 IndirectReferenceTable& globals = vm->globals;
508 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700509 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700510 break;
511 }
512 case kWeakGlobal:
513 {
514 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
515 IndirectReferenceTable& weak_globals = vm->weak_globals;
516 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700517 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700518 if (result == kClearedJniWeakGlobal) {
519 // This is a special case where it's okay to return NULL.
520 return NULL;
521 }
522 break;
523 }
524 case kSirtOrInvalid:
525 default:
526 // TODO: make stack indirect reference table lookup more efficient
527 // Check if this is a local reference in the SIRT
528 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700529 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700530 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700531 // Assume an invalid local reference is actually a direct pointer.
532 result = reinterpret_cast<Object*>(obj);
533 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700534 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700535 }
536 }
537
538 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700539 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
540 JniAbort(NULL);
541 } else {
542 if (result != kInvalidIndirectRefObject) {
543 Heap::VerifyObject(result);
544 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700545 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700546 return result;
547}
548
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700549class CountStackDepthVisitor : public Thread::StackVisitor {
550 public:
551 CountStackDepthVisitor() : depth(0) {}
552 virtual bool VisitFrame(const Frame&) {
553 ++depth;
554 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700555 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700556
557 int GetDepth() const {
558 return depth;
559 }
560
561 private:
562 uint32_t depth;
563};
564
565class BuildStackTraceVisitor : public Thread::StackVisitor {
566 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567 explicit BuildStackTraceVisitor(int depth) : count(0) {
568 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700569 pc_trace = IntArray::Alloc(depth);
570 }
571
572 virtual ~BuildStackTraceVisitor() {}
573
574 virtual bool VisitFrame(const Frame& frame) {
575 method_trace->Set(count, frame.GetMethod());
576 pc_trace->Set(count, frame.GetPC());
577 ++count;
578 return true;
579 }
580
581 const Method* GetMethod(uint32_t i) {
582 DCHECK(i < count);
583 return method_trace->Get(i);
584 }
585
586 uintptr_t GetPC(uint32_t i) {
587 DCHECK(i < count);
588 return pc_trace->Get(i);
589 }
590
591 private:
592 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700593 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700594 IntArray* pc_trace;
595};
596
597void Thread::WalkStack(StackVisitor* visitor) {
598 Frame frame = Thread::Current()->GetTopOfStack();
599 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
600 // CHECK(native_to_managed_record_ != NULL);
601 NativeToManagedRecord* record = native_to_managed_record_;
602
603 while (frame.GetSP()) {
604 for ( ; frame.GetMethod() != 0; frame.Next()) {
605 visitor->VisitFrame(frame);
606 }
607 if (record == NULL) {
608 break;
609 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700610 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 -0700611 record = record->link;
612 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700613}
614
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700615ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700616 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700617
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700618 CountStackDepthVisitor count_visitor;
619 WalkStack(&count_visitor);
620 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700621
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700622 BuildStackTraceVisitor build_trace_visitor(depth);
623 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700624
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700625 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700626
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700627 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700628 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700629 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700630 const Class* klass = method->GetDeclaringClass();
631 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700632 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700633 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700634
635 StackTraceElement* obj =
636 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700637 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700638 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700639 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700640 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700641 java_traces->Set(i, obj);
642 }
643 return java_traces;
644}
645
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700646void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700647 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700648 va_list args;
649 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700650 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700651 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700652
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700653 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700654 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700655 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700656 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700657 descriptor.erase(descriptor.length() - 1);
658
659 JNIEnv* env = GetJniEnv();
660 jclass exception_class = env->FindClass(descriptor.c_str());
661 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
662 int rc = env->ThrowNew(exception_class, msg.c_str());
663 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700664}
665
Elliott Hughes79082e32011-08-25 12:07:32 -0700666void Thread::ThrowOutOfMemoryError() {
667 UNIMPLEMENTED(FATAL);
668}
669
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700670Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
671 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
672 DCHECK(class_linker != NULL);
673
674 Frame cur_frame = GetTopOfStack();
675 for (int unwind_depth = 0; ; unwind_depth++) {
676 const Method* cur_method = cur_frame.GetMethod();
677 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
678 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
679
680 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
681 throw_pc,
682 dex_file,
683 class_linker);
684 if (handler_addr) {
685 *handler_pc = handler_addr;
686 return cur_frame;
687 } else {
688 // Check if we are at the last frame
689 if (cur_frame.HasNext()) {
690 cur_frame.Next();
691 } else {
692 // Either at the top of stack or next frame is native.
693 break;
694 }
695 }
696 }
697 *handler_pc = NULL;
698 return Frame();
699}
700
701void* Thread::FindExceptionHandlerInMethod(const Method* method,
702 void* throw_pc,
703 const DexFile& dex_file,
704 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700705 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700706 exception_ = NULL;
707
708 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700709 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700710 DexFile::CatchHandlerIterator iter;
711 for (iter = dex_file.dexFindCatchHandler(*code_item,
712 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
713 !iter.HasNext();
714 iter.Next()) {
715 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
716 DCHECK(klass != NULL);
717 if (exception_obj->InstanceOf(klass)) {
718 dex_pc = iter.Get().address_;
719 break;
720 }
721 }
722
723 exception_ = exception_obj;
724 if (iter.HasNext()) {
725 return NULL;
726 } else {
727 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
728 }
729}
730
Elliott Hughes410c0c82011-09-01 17:58:25 -0700731void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
732 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
733 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
734 jni_env_->locals.VisitRoots(visitor, arg);
735 jni_env_->monitors.VisitRoots(visitor, arg);
736 // visitThreadStack(visitor, thread, arg);
737 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
738}
739
Ian Rogersb033c752011-07-20 12:22:35 -0700740static const char* kStateNames[] = {
741 "New",
742 "Runnable",
743 "Blocked",
744 "Waiting",
745 "TimedWaiting",
746 "Native",
747 "Terminated",
748};
749std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
750 if (state >= Thread::kNew && state <= Thread::kTerminated) {
751 os << kStateNames[state-Thread::kNew];
752 } else {
753 os << "State[" << static_cast<int>(state) << "]";
754 }
755 return os;
756}
757
Elliott Hughes330304d2011-08-12 14:28:05 -0700758std::ostream& operator<<(std::ostream& os, const Thread& thread) {
759 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700760 << ",pthread_t=" << thread.GetImpl()
761 << ",tid=" << thread.GetTid()
762 << ",id=" << thread.GetId()
763 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700764 return os;
765}
766
Carl Shapiro61e019d2011-07-14 16:53:09 -0700767ThreadList* ThreadList::Create() {
768 return new ThreadList;
769}
770
Carl Shapirob5573532011-07-12 18:22:59 -0700771ThreadList::ThreadList() {
772 lock_ = Mutex::Create("ThreadList::Lock");
773}
774
775ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700776 if (Contains(Thread::Current())) {
777 Runtime::Current()->DetachCurrentThread();
778 }
779
780 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700781 // reach this point. This means that all daemon threads had been
782 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700783 // TODO: dump ThreadList if non-empty.
784 CHECK_EQ(list_.size(), 0U);
785
Carl Shapirob5573532011-07-12 18:22:59 -0700786 delete lock_;
787 lock_ = NULL;
788}
789
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700790bool ThreadList::Contains(Thread* thread) {
791 return find(list_.begin(), list_.end(), thread) != list_.end();
792}
793
Elliott Hughesd92bec42011-09-02 17:04:36 -0700794void ThreadList::Dump(std::ostream& os) {
795 MutexLock mu(lock_);
796 os << "DALVIK THREADS (" << list_.size() << "):\n";
797 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
798 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
799 (*it)->Dump(os);
800 }
801}
802
Carl Shapirob5573532011-07-12 18:22:59 -0700803void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700804 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700805 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700806 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700807 list_.push_front(thread);
808}
809
810void ThreadList::Unregister(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700811 //LOG(INFO) << "ThreadList::Unregister() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700812 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700813 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700814 list_.remove(thread);
815}
816
Elliott Hughes410c0c82011-09-01 17:58:25 -0700817void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
818 MutexLock mu(lock_);
819 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
820 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
821 (*it)->VisitRoots(visitor, arg);
822 }
823}
824
Carl Shapirob5573532011-07-12 18:22:59 -0700825} // namespace