blob: 97cc8ea33ac617e081c9c9d15755d525d3e971c7 [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
23pthread_key_t Thread::pthread_key_self_;
24
buzbee4a3164f2011-09-03 11:25:10 -070025// Temporary debugging hook for compiler.
26static void DebugMe(Method* method, uint32_t info) {
27 LOG(INFO) << "DebugMe";
28 if (method != NULL)
29 LOG(INFO) << PrettyMethod(method);
30 LOG(INFO) << "Info: " << info;
31}
32
33/*
34 * TODO: placeholder for a method that can be called by the
35 * invoke-interface trampoline to unwind and handle exception. The
36 * trampoline will arrange it so that the caller appears to be the
37 * callsite of the failed invoke-interface. See comments in
38 * compiler/runtime_support.S
39 */
40extern "C" void artFailedInvokeInterface()
41{
42 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
43}
44
45// TODO: placeholder. See comments in compiler/runtime_support.S
46extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
47 Object* this_object , Method* caller_method)
48{
49 /*
50 * Note: this_object has not yet been null-checked. To match
51 * the old-world state, nullcheck this_object and load
52 * Class* this_class = this_object->GetClass().
53 * See comments and possible thrown exceptions in old-world
54 * Interp.cpp:dvmInterpFindInterfaceMethod, and complete with
55 * new-world FindVirtualMethodForInterface.
56 */
57 UNIMPLEMENTED(FATAL) << "Unimplemented invoke interface";
58 return 0LL;
59}
60
buzbee1b4c8592011-08-31 10:43:51 -070061// TODO: placeholder. This is what generated code will call to throw
62static void ThrowException(Thread* thread, Throwable* exception) {
63 /*
64 * exception may be NULL, in which case this routine should
65 * throw NPE. NOTE: this is a convenience for generated code,
66 * which previuosly did the null check inline and constructed
67 * and threw a NPE if NULL. This routine responsible for setting
68 * exception_ in thread.
69 */
70 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
71}
72
73// TODO: placeholder. Helper function to type
74static Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
75 /*
76 * Should initialize & fix up method->dex_cache_resolved_types_[].
77 * Returns initialized type. Does not return normally if an exception
78 * is thrown, but instead initiates the catch. Should be similar to
79 * ClassLinker::InitializeStaticStorageFromCode.
80 */
81 UNIMPLEMENTED(FATAL);
82 return NULL;
83}
84
buzbee561227c2011-09-02 15:28:19 -070085// TODO: placeholder. Helper function to resolve virtual method
86static void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
87 /*
88 * Slow-path handler on invoke virtual method path in which
89 * base method is unresolved at compile-time. Doesn't need to
90 * return anything - just either ensure that
91 * method->dex_cache_resolved_methods_(method_idx) != NULL or
92 * throw and unwind. The caller will restart call sequence
93 * from the beginning.
94 */
95}
96
buzbee1da522d2011-09-04 11:22:20 -070097// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
98static Array* CheckAndAllocFromCode(uint32_t type_index, Method* method,
99 int32_t component_count)
100{
101 /*
102 * Just a wrapper around Array::AllocFromCode() that additionally
103 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
104 */
105 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
106 return Array::AllocFromCode(type_index, method, component_count);
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;
buzbee1da522d2011-09-04 11:22:20 -0700140 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700141 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700142 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700143 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700144 pGet32Static = Field::Get32StaticFromCode;
145 pSet32Static = Field::Set32StaticFromCode;
146 pGet64Static = Field::Get64StaticFromCode;
147 pSet64Static = Field::Set64StaticFromCode;
148 pGetObjStatic = Field::GetObjStaticFromCode;
149 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700150 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
151 pThrowException = ThrowException;
152 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700153 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700154 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700155 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700156#if 0
buzbee1b4c8592011-08-31 10:43:51 -0700157bool (Thread::*pUnlockObject)(Thread*, Object*);
158int (Thread::*pInstanceofNonTrivialFromCode)(const Class*, const Class*);
buzbee1b4c8592011-08-31 10:43:51 -0700159bool (Thread::*pUnlockObjectFromCode)(Thread*, Object*);
160void (Thread::*pLockObjectFromCode)(Thread*, Object*);
buzbee3ea4ec52011-08-22 17:37:19 -0700161#endif
162}
163
Carl Shapirob5573532011-07-12 18:22:59 -0700164Mutex* Mutex::Create(const char* name) {
165 Mutex* mu = new Mutex(name);
166 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700167 CHECK_EQ(result, 0);
Carl Shapirob5573532011-07-12 18:22:59 -0700168 return mu;
169}
170
171void Mutex::Lock() {
172 int result = pthread_mutex_lock(&lock_impl_);
173 CHECK_EQ(result, 0);
174 SetOwner(Thread::Current());
175}
176
177bool Mutex::TryLock() {
178 int result = pthread_mutex_lock(&lock_impl_);
179 if (result == EBUSY) {
180 return false;
181 } else {
182 CHECK_EQ(result, 0);
183 SetOwner(Thread::Current());
184 return true;
185 }
186}
187
188void Mutex::Unlock() {
189 CHECK(GetOwner() == Thread::Current());
190 int result = pthread_mutex_unlock(&lock_impl_);
191 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700192 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700193}
194
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700195void Frame::Next() {
196 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700197 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700198 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700199}
200
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700201uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700202 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700203 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700204 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700205}
206
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700207Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700208 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 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700211}
212
Carl Shapiro61e019d2011-07-14 16:53:09 -0700213void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700214 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700215 return NULL;
216}
217
Brian Carlstromb765be02011-08-17 23:54:10 -0700218Thread* Thread::Create(const Runtime* runtime) {
219 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700220
221 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700222 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700223
224 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700225 errno = pthread_attr_init(&attr);
226 if (errno != 0) {
227 PLOG(FATAL) << "pthread_attr_init failed";
228 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700229
Elliott Hughese27955c2011-08-26 15:21:24 -0700230 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
231 if (errno != 0) {
232 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
233 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700234
Elliott Hughese27955c2011-08-26 15:21:24 -0700235 errno = pthread_attr_setstacksize(&attr, stack_size);
236 if (errno != 0) {
237 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
238 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700239
Elliott Hughese27955c2011-08-26 15:21:24 -0700240 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
241 if (errno != 0) {
242 PLOG(FATAL) << "pthread_create failed";
243 }
244
245 errno = pthread_attr_destroy(&attr);
246 if (errno != 0) {
247 PLOG(FATAL) << "pthread_attr_destroy failed";
248 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700249
250 return new_thread;
251}
252
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700253Thread* Thread::Attach(const Runtime* runtime) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700254 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700255 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700256
257 thread->handle_ = pthread_self();
Elliott Hughes42ee1422011-09-06 12:33:32 -0700258 thread->tid_ = ::art::GetTid();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700259
260 thread->state_ = kRunnable;
261
Elliott Hughesa5780da2011-07-17 11:39:39 -0700262 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
263 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700264 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700265 }
266
Elliott Hughes75770752011-08-24 17:52:38 -0700267 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700268
Carl Shapiro61e019d2011-07-14 16:53:09 -0700269 return thread;
270}
271
Elliott Hughesa0957642011-09-02 14:27:33 -0700272void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700273 /*
274 * Get the java.lang.Thread object. This function gets called from
275 * some weird debug contexts, so it's possible that there's a GC in
276 * progress on some other thread. To decrease the chances of the
277 * thread object being moved out from under us, we add the reference
278 * to the tracked allocation list, which pins it in place.
279 *
280 * If threadObj is NULL, the thread is still in the process of being
281 * attached to the VM, and there's really nothing interesting to
282 * say about it yet.
283 */
284 os << "TODO: pin Thread before dumping\n";
285#if 0
286 if (java_thread_ == NULL) {
287 LOGI("Can't dump thread %d: threadObj not set", threadId);
288 return;
289 }
290 dvmAddTrackedAlloc(java_thread_, NULL);
291#endif
292
293 DumpState(os);
294 DumpStack(os);
295
296#if 0
297 dvmReleaseTrackedAlloc(java_thread_, NULL);
298#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700299}
300
Elliott Hughesd92bec42011-09-02 17:04:36 -0700301std::string GetSchedulerGroup(pid_t tid) {
302 // /proc/<pid>/group looks like this:
303 // 2:devices:/
304 // 1:cpuacct,cpu:/
305 // We want the third field from the line whose second field contains the "cpu" token.
306 std::string cgroup_file;
307 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
308 return "";
309 }
310 std::vector<std::string> cgroup_lines;
311 Split(cgroup_file, '\n', cgroup_lines);
312 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
313 std::vector<std::string> cgroup_fields;
314 Split(cgroup_lines[i], ':', cgroup_fields);
315 std::vector<std::string> cgroups;
316 Split(cgroup_fields[1], ',', cgroups);
317 for (size_t i = 0; i < cgroups.size(); ++i) {
318 if (cgroups[i] == "cpu") {
319 return cgroup_fields[2].substr(1); // Skip the leading slash.
320 }
321 }
322 }
323 return "";
324}
325
326void Thread::DumpState(std::ostream& os) const {
327 std::string thread_name("unknown");
328 int priority = -1;
329 bool is_daemon = false;
330#if 0 // TODO
331 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
332 threadName = dvmCreateCstrFromString(nameStr);
333 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
334 is_daemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
335#else
336 thread_name = "TODO";
337 priority = -1;
338 is_daemon = false;
339#endif
340
341 int policy;
342 sched_param sp;
343 errno = pthread_getschedparam(handle_, &policy, &sp);
344 if (errno != 0) {
345 PLOG(FATAL) << "pthread_getschedparam failed";
346 }
347
348 std::string scheduler_group(GetSchedulerGroup(GetTid()));
349 if (scheduler_group.empty()) {
350 scheduler_group = "default";
351 }
352
353 std::string group_name("(null; initializing?)");
354#if 0
355 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
356 if (groupObj != NULL) {
357 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
358 groupName = dvmCreateCstrFromString(nameStr);
359 }
360#else
361 group_name = "TODO";
362#endif
363
364 os << '"' << thread_name << '"';
365 if (is_daemon) {
366 os << " daemon";
367 }
368 os << " prio=" << priority
369 << " tid=" << GetId()
370 << " " << state_ << "\n";
371
372 int suspend_count = 0; // TODO
373 int debug_suspend_count = 0; // TODO
374 void* java_thread_ = NULL; // TODO
375 os << " | group=\"" << group_name << "\""
376 << " sCount=" << suspend_count
377 << " dsCount=" << debug_suspend_count
378 << " obj=" << reinterpret_cast<void*>(java_thread_)
379 << " self=" << reinterpret_cast<const void*>(this) << "\n";
380 os << " | sysTid=" << GetTid()
381 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
382 << " sched=" << policy << "/" << sp.sched_priority
383 << " cgrp=" << scheduler_group
384 << " handle=" << GetImpl() << "\n";
385
386 // Grab the scheduler stats for this thread.
387 std::string scheduler_stats;
388 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
389 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
390 } else {
391 scheduler_stats = "0 0 0";
392 }
393
394 int utime = 0;
395 int stime = 0;
396 int task_cpu = 0;
397 std::string stats;
398 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
399 // Skip the command, which may contain spaces.
400 stats = stats.substr(stats.find(')') + 2);
401 // Extract the three fields we care about.
402 std::vector<std::string> fields;
403 Split(stats, ' ', fields);
404 utime = strtoull(fields[11].c_str(), NULL, 10);
405 stime = strtoull(fields[12].c_str(), NULL, 10);
406 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
407 }
408
409 os << " | schedstat=( " << scheduler_stats << " )"
410 << " utm=" << utime
411 << " stm=" << stime
412 << " core=" << task_cpu
413 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
414}
415
416void Thread::DumpStack(std::ostream& os) const {
417 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700418}
419
Carl Shapirob5573532011-07-12 18:22:59 -0700420static void ThreadExitCheck(void* arg) {
421 LG << "Thread exit check";
422}
423
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700424bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700425 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700426 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
427 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700428 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700429 return false;
430 }
431
432 // Double-check the TLS slot allocation.
433 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700434 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700435 return false;
436 }
437
438 // TODO: initialize other locks and condition variables
439
440 return true;
441}
442
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700443void Thread::Shutdown() {
444 errno = pthread_key_delete(Thread::pthread_key_self_);
445 if (errno != 0) {
446 PLOG(WARNING) << "pthread_key_delete failed";
447 }
448}
449
450Thread::~Thread() {
451 delete jni_env_;
452}
453
Ian Rogers408f79a2011-08-23 18:22:33 -0700454size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700455 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700456 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700457 count += cur->NumberOfReferences();
458 }
459 return count;
460}
461
Ian Rogers408f79a2011-08-23 18:22:33 -0700462bool Thread::SirtContains(jobject obj) {
463 Object** sirt_entry = reinterpret_cast<Object**>(obj);
464 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700465 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700466 // A SIRT should always have a jobject/jclass as a native method is passed
467 // in a this pointer or a class
468 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700469 if ((&cur->References()[0] <= sirt_entry) &&
470 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700471 return true;
472 }
473 }
474 return false;
475}
476
Ian Rogers408f79a2011-08-23 18:22:33 -0700477Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700478 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700479 if (obj == NULL) {
480 return NULL;
481 }
482 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
483 IndirectRefKind kind = GetIndirectRefKind(ref);
484 Object* result;
485 switch (kind) {
486 case kLocal:
487 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700488 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700489 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700490 break;
491 }
492 case kGlobal:
493 {
494 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
495 IndirectReferenceTable& globals = vm->globals;
496 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700497 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700498 break;
499 }
500 case kWeakGlobal:
501 {
502 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
503 IndirectReferenceTable& weak_globals = vm->weak_globals;
504 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700505 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700506 if (result == kClearedJniWeakGlobal) {
507 // This is a special case where it's okay to return NULL.
508 return NULL;
509 }
510 break;
511 }
512 case kSirtOrInvalid:
513 default:
514 // TODO: make stack indirect reference table lookup more efficient
515 // Check if this is a local reference in the SIRT
516 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700517 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700518 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700519 // Assume an invalid local reference is actually a direct pointer.
520 result = reinterpret_cast<Object*>(obj);
521 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700522 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700523 }
524 }
525
526 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700527 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
528 JniAbort(NULL);
529 } else {
530 if (result != kInvalidIndirectRefObject) {
531 Heap::VerifyObject(result);
532 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700533 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700534 return result;
535}
536
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700537class CountStackDepthVisitor : public Thread::StackVisitor {
538 public:
539 CountStackDepthVisitor() : depth(0) {}
540 virtual bool VisitFrame(const Frame&) {
541 ++depth;
542 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700543 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700544
545 int GetDepth() const {
546 return depth;
547 }
548
549 private:
550 uint32_t depth;
551};
552
553class BuildStackTraceVisitor : public Thread::StackVisitor {
554 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700555 explicit BuildStackTraceVisitor(int depth) : count(0) {
556 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700557 pc_trace = IntArray::Alloc(depth);
558 }
559
560 virtual ~BuildStackTraceVisitor() {}
561
562 virtual bool VisitFrame(const Frame& frame) {
563 method_trace->Set(count, frame.GetMethod());
564 pc_trace->Set(count, frame.GetPC());
565 ++count;
566 return true;
567 }
568
569 const Method* GetMethod(uint32_t i) {
570 DCHECK(i < count);
571 return method_trace->Get(i);
572 }
573
574 uintptr_t GetPC(uint32_t i) {
575 DCHECK(i < count);
576 return pc_trace->Get(i);
577 }
578
579 private:
580 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700581 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700582 IntArray* pc_trace;
583};
584
585void Thread::WalkStack(StackVisitor* visitor) {
586 Frame frame = Thread::Current()->GetTopOfStack();
587 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
588 // CHECK(native_to_managed_record_ != NULL);
589 NativeToManagedRecord* record = native_to_managed_record_;
590
591 while (frame.GetSP()) {
592 for ( ; frame.GetMethod() != 0; frame.Next()) {
593 visitor->VisitFrame(frame);
594 }
595 if (record == NULL) {
596 break;
597 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700598 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 -0700599 record = record->link;
600 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700601}
602
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700603ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700604 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700605
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700606 CountStackDepthVisitor count_visitor;
607 WalkStack(&count_visitor);
608 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700609
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700610 BuildStackTraceVisitor build_trace_visitor(depth);
611 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700612
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700613 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700614
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700615 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700616 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700617 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700618 const Class* klass = method->GetDeclaringClass();
619 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700620 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700621 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700622
623 StackTraceElement* obj =
624 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700625 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700626 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700627 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700628 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700629 java_traces->Set(i, obj);
630 }
631 return java_traces;
632}
633
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700634void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700635 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700636 va_list args;
637 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700638 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700639 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700640
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700641 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700642 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700643 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700644 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700645 descriptor.erase(descriptor.length() - 1);
646
647 JNIEnv* env = GetJniEnv();
648 jclass exception_class = env->FindClass(descriptor.c_str());
649 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
650 int rc = env->ThrowNew(exception_class, msg.c_str());
651 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700652}
653
Elliott Hughes79082e32011-08-25 12:07:32 -0700654void Thread::ThrowOutOfMemoryError() {
655 UNIMPLEMENTED(FATAL);
656}
657
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700658Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
659 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
660 DCHECK(class_linker != NULL);
661
662 Frame cur_frame = GetTopOfStack();
663 for (int unwind_depth = 0; ; unwind_depth++) {
664 const Method* cur_method = cur_frame.GetMethod();
665 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
666 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
667
668 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
669 throw_pc,
670 dex_file,
671 class_linker);
672 if (handler_addr) {
673 *handler_pc = handler_addr;
674 return cur_frame;
675 } else {
676 // Check if we are at the last frame
677 if (cur_frame.HasNext()) {
678 cur_frame.Next();
679 } else {
680 // Either at the top of stack or next frame is native.
681 break;
682 }
683 }
684 }
685 *handler_pc = NULL;
686 return Frame();
687}
688
689void* Thread::FindExceptionHandlerInMethod(const Method* method,
690 void* throw_pc,
691 const DexFile& dex_file,
692 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700693 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700694 exception_ = NULL;
695
696 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700697 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700698 DexFile::CatchHandlerIterator iter;
699 for (iter = dex_file.dexFindCatchHandler(*code_item,
700 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
701 !iter.HasNext();
702 iter.Next()) {
703 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
704 DCHECK(klass != NULL);
705 if (exception_obj->InstanceOf(klass)) {
706 dex_pc = iter.Get().address_;
707 break;
708 }
709 }
710
711 exception_ = exception_obj;
712 if (iter.HasNext()) {
713 return NULL;
714 } else {
715 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
716 }
717}
718
Elliott Hughes410c0c82011-09-01 17:58:25 -0700719void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
720 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
721 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
722 jni_env_->locals.VisitRoots(visitor, arg);
723 jni_env_->monitors.VisitRoots(visitor, arg);
724 // visitThreadStack(visitor, thread, arg);
725 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
726}
727
Ian Rogersb033c752011-07-20 12:22:35 -0700728static const char* kStateNames[] = {
729 "New",
730 "Runnable",
731 "Blocked",
732 "Waiting",
733 "TimedWaiting",
734 "Native",
735 "Terminated",
736};
737std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
738 if (state >= Thread::kNew && state <= Thread::kTerminated) {
739 os << kStateNames[state-Thread::kNew];
740 } else {
741 os << "State[" << static_cast<int>(state) << "]";
742 }
743 return os;
744}
745
Elliott Hughes330304d2011-08-12 14:28:05 -0700746std::ostream& operator<<(std::ostream& os, const Thread& thread) {
747 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700748 << ",pthread_t=" << thread.GetImpl()
749 << ",tid=" << thread.GetTid()
750 << ",id=" << thread.GetId()
751 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700752 return os;
753}
754
Carl Shapiro61e019d2011-07-14 16:53:09 -0700755ThreadList* ThreadList::Create() {
756 return new ThreadList;
757}
758
Carl Shapirob5573532011-07-12 18:22:59 -0700759ThreadList::ThreadList() {
760 lock_ = Mutex::Create("ThreadList::Lock");
761}
762
763ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700764 if (Contains(Thread::Current())) {
765 Runtime::Current()->DetachCurrentThread();
766 }
767
768 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700769 // reach this point. This means that all daemon threads had been
770 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700771 // TODO: dump ThreadList if non-empty.
772 CHECK_EQ(list_.size(), 0U);
773
Carl Shapirob5573532011-07-12 18:22:59 -0700774 delete lock_;
775 lock_ = NULL;
776}
777
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700778bool ThreadList::Contains(Thread* thread) {
779 return find(list_.begin(), list_.end(), thread) != list_.end();
780}
781
Elliott Hughesd92bec42011-09-02 17:04:36 -0700782void ThreadList::Dump(std::ostream& os) {
783 MutexLock mu(lock_);
784 os << "DALVIK THREADS (" << list_.size() << "):\n";
785 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
786 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
787 (*it)->Dump(os);
788 }
Elliott Hughes42ee1422011-09-06 12:33:32 -0700789 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700790}
791
Carl Shapirob5573532011-07-12 18:22:59 -0700792void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700793 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700794 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700795 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700796 list_.push_front(thread);
797}
798
799void ThreadList::Unregister(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700800 //LOG(INFO) << "ThreadList::Unregister() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700801 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700802 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700803 list_.remove(thread);
804}
805
Elliott Hughes410c0c82011-09-01 17:58:25 -0700806void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
807 MutexLock mu(lock_);
808 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
809 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
810 (*it)->VisitRoots(visitor, arg);
811 }
812}
813
Carl Shapirob5573532011-07-12 18:22:59 -0700814} // namespace