blob: b99e38a56418b6eeb2b62ff1475fbf33d6bace4c [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 Hughesdcc24742011-09-07 14:02:44 -07009#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070010#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070011#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070012#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070013
Elliott Hughesa5b897e2011-08-16 11:33:06 -070014#include "class_linker.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070015#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070016#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070017#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070018#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070019#include "runtime_support.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070020#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070021
22namespace art {
23
24pthread_key_t Thread::pthread_key_self_;
25
buzbee4a3164f2011-09-03 11:25:10 -070026// Temporary debugging hook for compiler.
27static void DebugMe(Method* method, uint32_t info) {
28 LOG(INFO) << "DebugMe";
29 if (method != NULL)
30 LOG(INFO) << PrettyMethod(method);
31 LOG(INFO) << "Info: " << info;
32}
33
34/*
35 * TODO: placeholder for a method that can be called by the
36 * invoke-interface trampoline to unwind and handle exception. The
37 * trampoline will arrange it so that the caller appears to be the
38 * callsite of the failed invoke-interface. See comments in
39 * compiler/runtime_support.S
40 */
41extern "C" void artFailedInvokeInterface()
42{
43 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
44}
45
46// TODO: placeholder. See comments in compiler/runtime_support.S
47extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
48 Object* this_object , Method* caller_method)
49{
50 /*
51 * Note: this_object has not yet been null-checked. To match
52 * the old-world state, nullcheck this_object and load
53 * Class* this_class = this_object->GetClass().
54 * See comments and possible thrown exceptions in old-world
55 * Interp.cpp:dvmInterpFindInterfaceMethod, and complete with
56 * new-world FindVirtualMethodForInterface.
57 */
58 UNIMPLEMENTED(FATAL) << "Unimplemented invoke interface";
59 return 0LL;
60}
61
buzbee1b4c8592011-08-31 10:43:51 -070062// TODO: placeholder. This is what generated code will call to throw
63static void ThrowException(Thread* thread, Throwable* exception) {
64 /*
65 * exception may be NULL, in which case this routine should
66 * throw NPE. NOTE: this is a convenience for generated code,
67 * which previuosly did the null check inline and constructed
68 * and threw a NPE if NULL. This routine responsible for setting
69 * exception_ in thread.
70 */
71 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
72}
73
74// TODO: placeholder. Helper function to type
75static Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
76 /*
77 * Should initialize & fix up method->dex_cache_resolved_types_[].
78 * Returns initialized type. Does not return normally if an exception
79 * is thrown, but instead initiates the catch. Should be similar to
80 * ClassLinker::InitializeStaticStorageFromCode.
81 */
82 UNIMPLEMENTED(FATAL);
83 return NULL;
84}
85
buzbee561227c2011-09-02 15:28:19 -070086// TODO: placeholder. Helper function to resolve virtual method
87static void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
88 /*
89 * Slow-path handler on invoke virtual method path in which
90 * base method is unresolved at compile-time. Doesn't need to
91 * return anything - just either ensure that
92 * method->dex_cache_resolved_methods_(method_idx) != NULL or
93 * throw and unwind. The caller will restart call sequence
94 * from the beginning.
95 */
96}
97
buzbee1da522d2011-09-04 11:22:20 -070098// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
99static Array* CheckAndAllocFromCode(uint32_t type_index, Method* method,
100 int32_t component_count)
101{
102 /*
103 * Just a wrapper around Array::AllocFromCode() that additionally
104 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
105 */
106 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
107 return Array::AllocFromCode(type_index, method, component_count);
108}
109
buzbee3ea4ec52011-08-22 17:37:19 -0700110void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700111#if defined(__arm__)
112 pShlLong = art_shl_long;
113 pShrLong = art_shr_long;
114 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700115 pIdiv = __aeabi_idiv;
116 pIdivmod = __aeabi_idivmod;
117 pI2f = __aeabi_i2f;
118 pF2iz = __aeabi_f2iz;
119 pD2f = __aeabi_d2f;
120 pF2d = __aeabi_f2d;
121 pD2iz = __aeabi_d2iz;
122 pL2f = __aeabi_l2f;
123 pL2d = __aeabi_l2d;
124 pFadd = __aeabi_fadd;
125 pFsub = __aeabi_fsub;
126 pFdiv = __aeabi_fdiv;
127 pFmul = __aeabi_fmul;
128 pFmodf = fmodf;
129 pDadd = __aeabi_dadd;
130 pDsub = __aeabi_dsub;
131 pDdiv = __aeabi_ddiv;
132 pDmul = __aeabi_dmul;
133 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -0700134 pF2l = F2L;
135 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -0700136 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700137 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700138 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700139#endif
buzbeedfd3d702011-08-28 12:56:51 -0700140 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700141 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700142 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700143 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700144 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700145 pGet32Static = Field::Get32StaticFromCode;
146 pSet32Static = Field::Set32StaticFromCode;
147 pGet64Static = Field::Get64StaticFromCode;
148 pSet64Static = Field::Set64StaticFromCode;
149 pGetObjStatic = Field::GetObjStaticFromCode;
150 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700151 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
152 pThrowException = ThrowException;
153 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700154 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700155 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700156 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700157#if 0
buzbee1b4c8592011-08-31 10:43:51 -0700158bool (Thread::*pUnlockObject)(Thread*, Object*);
159int (Thread::*pInstanceofNonTrivialFromCode)(const Class*, const Class*);
buzbee1b4c8592011-08-31 10:43:51 -0700160bool (Thread::*pUnlockObjectFromCode)(Thread*, Object*);
161void (Thread::*pLockObjectFromCode)(Thread*, Object*);
buzbee3ea4ec52011-08-22 17:37:19 -0700162#endif
163}
164
Carl Shapirob5573532011-07-12 18:22:59 -0700165Mutex* Mutex::Create(const char* name) {
166 Mutex* mu = new Mutex(name);
167 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700168 CHECK_EQ(result, 0);
Carl Shapirob5573532011-07-12 18:22:59 -0700169 return mu;
170}
171
172void Mutex::Lock() {
173 int result = pthread_mutex_lock(&lock_impl_);
174 CHECK_EQ(result, 0);
175 SetOwner(Thread::Current());
176}
177
178bool Mutex::TryLock() {
179 int result = pthread_mutex_lock(&lock_impl_);
180 if (result == EBUSY) {
181 return false;
182 } else {
183 CHECK_EQ(result, 0);
184 SetOwner(Thread::Current());
185 return true;
186 }
187}
188
189void Mutex::Unlock() {
190 CHECK(GetOwner() == Thread::Current());
191 int result = pthread_mutex_unlock(&lock_impl_);
192 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700193 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700194}
195
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700196void Frame::Next() {
197 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700198 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700199 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700200}
201
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700202uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700203 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700204 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700205 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700206}
207
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700208Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700209 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700210 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700211 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700212}
213
Carl Shapiro61e019d2011-07-14 16:53:09 -0700214void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700215 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700216 return NULL;
217}
218
Brian Carlstromb765be02011-08-17 23:54:10 -0700219Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700220 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
221
Brian Carlstromb765be02011-08-17 23:54:10 -0700222 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700223
224 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700225 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700226
227 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700228 errno = pthread_attr_init(&attr);
229 if (errno != 0) {
230 PLOG(FATAL) << "pthread_attr_init failed";
231 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700232
Elliott Hughese27955c2011-08-26 15:21:24 -0700233 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
234 if (errno != 0) {
235 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
236 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700237
Elliott Hughese27955c2011-08-26 15:21:24 -0700238 errno = pthread_attr_setstacksize(&attr, stack_size);
239 if (errno != 0) {
240 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
241 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700242
Elliott Hughese27955c2011-08-26 15:21:24 -0700243 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
244 if (errno != 0) {
245 PLOG(FATAL) << "pthread_create failed";
246 }
247
248 errno = pthread_attr_destroy(&attr);
249 if (errno != 0) {
250 PLOG(FATAL) << "pthread_attr_destroy failed";
251 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700252
Elliott Hughesdcc24742011-09-07 14:02:44 -0700253 // TODO: get the "daemon" field from the java.lang.Thread.
254 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
255
Carl Shapiro61e019d2011-07-14 16:53:09 -0700256 return new_thread;
257}
258
Elliott Hughesdcc24742011-09-07 14:02:44 -0700259static const uint32_t kMaxThreadId = ((1 << 16) - 1);
260std::bitset<kMaxThreadId> gAllocatedThreadIds;
261
262uint32_t AllocThreadId() {
263 Runtime::Current()->GetThreadList()->Lock();
264 for (size_t i = 0; i < gAllocatedThreadIds.size(); ++i) {
265 if (!gAllocatedThreadIds[i]) {
266 gAllocatedThreadIds.set(i);
267 Runtime::Current()->GetThreadList()->Unlock();
268 return i + 1; // Zero is reserved to mean "invalid".
269 }
270 }
271 LOG(FATAL) << "Out of internal thread ids";
272 return 0;
273}
274
275void ReleaseThreadId(uint32_t id) {
276 Runtime::Current()->GetThreadList()->Lock();
277 CHECK(gAllocatedThreadIds[id]);
278 gAllocatedThreadIds.reset(id);
279 Runtime::Current()->GetThreadList()->Unlock();
280}
281
282Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700283 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700284 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700285
Elliott Hughesdcc24742011-09-07 14:02:44 -0700286 thread->thin_lock_id_ = AllocThreadId();
Elliott Hughes42ee1422011-09-06 12:33:32 -0700287 thread->tid_ = ::art::GetTid();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700288 thread->handle_ = pthread_self();
289 thread->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700290
291 thread->state_ = kRunnable;
292
Elliott Hughesdcc24742011-09-07 14:02:44 -0700293 SetThreadName(name);
294
Elliott Hughesa5780da2011-07-17 11:39:39 -0700295 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
296 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700297 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700298 }
299
Elliott Hughes75770752011-08-24 17:52:38 -0700300 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700301
Carl Shapiro61e019d2011-07-14 16:53:09 -0700302 return thread;
303}
304
Elliott Hughesa0957642011-09-02 14:27:33 -0700305void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700306 /*
307 * Get the java.lang.Thread object. This function gets called from
308 * some weird debug contexts, so it's possible that there's a GC in
309 * progress on some other thread. To decrease the chances of the
310 * thread object being moved out from under us, we add the reference
311 * to the tracked allocation list, which pins it in place.
312 *
313 * If threadObj is NULL, the thread is still in the process of being
314 * attached to the VM, and there's really nothing interesting to
315 * say about it yet.
316 */
317 os << "TODO: pin Thread before dumping\n";
318#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700319 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
320 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700321 LOGI("Can't dump thread %d: threadObj not set", threadId);
322 return;
323 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700324 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700325#endif
326
327 DumpState(os);
328 DumpStack(os);
329
330#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700331 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700332#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700333}
334
Elliott Hughesd92bec42011-09-02 17:04:36 -0700335std::string GetSchedulerGroup(pid_t tid) {
336 // /proc/<pid>/group looks like this:
337 // 2:devices:/
338 // 1:cpuacct,cpu:/
339 // We want the third field from the line whose second field contains the "cpu" token.
340 std::string cgroup_file;
341 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
342 return "";
343 }
344 std::vector<std::string> cgroup_lines;
345 Split(cgroup_file, '\n', cgroup_lines);
346 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
347 std::vector<std::string> cgroup_fields;
348 Split(cgroup_lines[i], ':', cgroup_fields);
349 std::vector<std::string> cgroups;
350 Split(cgroup_fields[1], ',', cgroups);
351 for (size_t i = 0; i < cgroups.size(); ++i) {
352 if (cgroups[i] == "cpu") {
353 return cgroup_fields[2].substr(1); // Skip the leading slash.
354 }
355 }
356 }
357 return "";
358}
359
360void Thread::DumpState(std::ostream& os) const {
361 std::string thread_name("unknown");
362 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700363
Elliott Hughesd92bec42011-09-02 17:04:36 -0700364#if 0 // TODO
365 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
366 threadName = dvmCreateCstrFromString(nameStr);
367 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700368#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700369 {
370 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
371 std::string stats;
372 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
373 size_t start = stats.find('(') + 1;
374 size_t end = stats.find(')') - start;
375 thread_name = stats.substr(start, end);
376 }
377 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700378 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700379#endif
380
381 int policy;
382 sched_param sp;
383 errno = pthread_getschedparam(handle_, &policy, &sp);
384 if (errno != 0) {
385 PLOG(FATAL) << "pthread_getschedparam failed";
386 }
387
388 std::string scheduler_group(GetSchedulerGroup(GetTid()));
389 if (scheduler_group.empty()) {
390 scheduler_group = "default";
391 }
392
393 std::string group_name("(null; initializing?)");
394#if 0
395 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
396 if (groupObj != NULL) {
397 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
398 groupName = dvmCreateCstrFromString(nameStr);
399 }
400#else
401 group_name = "TODO";
402#endif
403
404 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700405 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700406 os << " daemon";
407 }
408 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700409 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700410 << " " << state_ << "\n";
411
412 int suspend_count = 0; // TODO
413 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700414 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700415 os << " | group=\"" << group_name << "\""
416 << " sCount=" << suspend_count
417 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700418 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700419 << " self=" << reinterpret_cast<const void*>(this) << "\n";
420 os << " | sysTid=" << GetTid()
421 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
422 << " sched=" << policy << "/" << sp.sched_priority
423 << " cgrp=" << scheduler_group
424 << " handle=" << GetImpl() << "\n";
425
426 // Grab the scheduler stats for this thread.
427 std::string scheduler_stats;
428 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
429 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
430 } else {
431 scheduler_stats = "0 0 0";
432 }
433
434 int utime = 0;
435 int stime = 0;
436 int task_cpu = 0;
437 std::string stats;
438 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
439 // Skip the command, which may contain spaces.
440 stats = stats.substr(stats.find(')') + 2);
441 // Extract the three fields we care about.
442 std::vector<std::string> fields;
443 Split(stats, ' ', fields);
444 utime = strtoull(fields[11].c_str(), NULL, 10);
445 stime = strtoull(fields[12].c_str(), NULL, 10);
446 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
447 }
448
449 os << " | schedstat=( " << scheduler_stats << " )"
450 << " utm=" << utime
451 << " stm=" << stime
452 << " core=" << task_cpu
453 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
454}
455
456void Thread::DumpStack(std::ostream& os) const {
457 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700458}
459
Carl Shapirob5573532011-07-12 18:22:59 -0700460static void ThreadExitCheck(void* arg) {
461 LG << "Thread exit check";
462}
463
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700464bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700465 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700466 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
467 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700468 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700469 return false;
470 }
471
472 // Double-check the TLS slot allocation.
473 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700474 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700475 return false;
476 }
477
478 // TODO: initialize other locks and condition variables
479
480 return true;
481}
482
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700483void Thread::Shutdown() {
484 errno = pthread_key_delete(Thread::pthread_key_self_);
485 if (errno != 0) {
486 PLOG(WARNING) << "pthread_key_delete failed";
487 }
488}
489
Elliott Hughesdcc24742011-09-07 14:02:44 -0700490Thread::Thread()
491 : thin_lock_id_(0),
492 peer_(NULL),
493 top_of_managed_stack_(),
494 native_to_managed_record_(NULL),
495 top_sirt_(NULL),
496 jni_env_(NULL),
497 exception_(NULL),
498 suspend_count_(0),
499 class_loader_override_(NULL) {
500 InitFunctionPointers();
501}
502
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700503Thread::~Thread() {
504 delete jni_env_;
505}
506
Ian Rogers408f79a2011-08-23 18:22:33 -0700507size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700508 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700509 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700510 count += cur->NumberOfReferences();
511 }
512 return count;
513}
514
Ian Rogers408f79a2011-08-23 18:22:33 -0700515bool Thread::SirtContains(jobject obj) {
516 Object** sirt_entry = reinterpret_cast<Object**>(obj);
517 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700518 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700519 // A SIRT should always have a jobject/jclass as a native method is passed
520 // in a this pointer or a class
521 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700522 if ((&cur->References()[0] <= sirt_entry) &&
523 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700524 return true;
525 }
526 }
527 return false;
528}
529
Ian Rogers408f79a2011-08-23 18:22:33 -0700530Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700531 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700532 if (obj == NULL) {
533 return NULL;
534 }
535 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
536 IndirectRefKind kind = GetIndirectRefKind(ref);
537 Object* result;
538 switch (kind) {
539 case kLocal:
540 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700541 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700542 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700543 break;
544 }
545 case kGlobal:
546 {
547 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
548 IndirectReferenceTable& globals = vm->globals;
549 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700550 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700551 break;
552 }
553 case kWeakGlobal:
554 {
555 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
556 IndirectReferenceTable& weak_globals = vm->weak_globals;
557 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700558 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700559 if (result == kClearedJniWeakGlobal) {
560 // This is a special case where it's okay to return NULL.
561 return NULL;
562 }
563 break;
564 }
565 case kSirtOrInvalid:
566 default:
567 // TODO: make stack indirect reference table lookup more efficient
568 // Check if this is a local reference in the SIRT
569 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700570 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700571 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700572 // Assume an invalid local reference is actually a direct pointer.
573 result = reinterpret_cast<Object*>(obj);
574 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700575 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700576 }
577 }
578
579 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700580 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
581 JniAbort(NULL);
582 } else {
583 if (result != kInvalidIndirectRefObject) {
584 Heap::VerifyObject(result);
585 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700586 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700587 return result;
588}
589
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700590class CountStackDepthVisitor : public Thread::StackVisitor {
591 public:
592 CountStackDepthVisitor() : depth(0) {}
593 virtual bool VisitFrame(const Frame&) {
594 ++depth;
595 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700596 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700597
598 int GetDepth() const {
599 return depth;
600 }
601
602 private:
603 uint32_t depth;
604};
605
606class BuildStackTraceVisitor : public Thread::StackVisitor {
607 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700608 explicit BuildStackTraceVisitor(int depth) : count(0) {
609 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700610 pc_trace = IntArray::Alloc(depth);
611 }
612
613 virtual ~BuildStackTraceVisitor() {}
614
615 virtual bool VisitFrame(const Frame& frame) {
616 method_trace->Set(count, frame.GetMethod());
617 pc_trace->Set(count, frame.GetPC());
618 ++count;
619 return true;
620 }
621
622 const Method* GetMethod(uint32_t i) {
623 DCHECK(i < count);
624 return method_trace->Get(i);
625 }
626
627 uintptr_t GetPC(uint32_t i) {
628 DCHECK(i < count);
629 return pc_trace->Get(i);
630 }
631
632 private:
633 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700634 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700635 IntArray* pc_trace;
636};
637
638void Thread::WalkStack(StackVisitor* visitor) {
639 Frame frame = Thread::Current()->GetTopOfStack();
640 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
641 // CHECK(native_to_managed_record_ != NULL);
642 NativeToManagedRecord* record = native_to_managed_record_;
643
644 while (frame.GetSP()) {
645 for ( ; frame.GetMethod() != 0; frame.Next()) {
646 visitor->VisitFrame(frame);
647 }
648 if (record == NULL) {
649 break;
650 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700651 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 -0700652 record = record->link;
653 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700654}
655
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700656ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700657 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700658
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700659 CountStackDepthVisitor count_visitor;
660 WalkStack(&count_visitor);
661 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700662
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700663 BuildStackTraceVisitor build_trace_visitor(depth);
664 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700665
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700666 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700667
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700668 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700669 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700670 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700671 const Class* klass = method->GetDeclaringClass();
672 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700673 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700674 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700675
676 StackTraceElement* obj =
677 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700678 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700679 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700680 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700681 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700682 java_traces->Set(i, obj);
683 }
684 return java_traces;
685}
686
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700687void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700688 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700689 va_list args;
690 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700691 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700692 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700693
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700694 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700695 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700696 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700697 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700698 descriptor.erase(descriptor.length() - 1);
699
700 JNIEnv* env = GetJniEnv();
701 jclass exception_class = env->FindClass(descriptor.c_str());
702 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
703 int rc = env->ThrowNew(exception_class, msg.c_str());
704 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700705}
706
Elliott Hughes79082e32011-08-25 12:07:32 -0700707void Thread::ThrowOutOfMemoryError() {
708 UNIMPLEMENTED(FATAL);
709}
710
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700711Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
712 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
713 DCHECK(class_linker != NULL);
714
715 Frame cur_frame = GetTopOfStack();
716 for (int unwind_depth = 0; ; unwind_depth++) {
717 const Method* cur_method = cur_frame.GetMethod();
718 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
719 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
720
721 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
722 throw_pc,
723 dex_file,
724 class_linker);
725 if (handler_addr) {
726 *handler_pc = handler_addr;
727 return cur_frame;
728 } else {
729 // Check if we are at the last frame
730 if (cur_frame.HasNext()) {
731 cur_frame.Next();
732 } else {
733 // Either at the top of stack or next frame is native.
734 break;
735 }
736 }
737 }
738 *handler_pc = NULL;
739 return Frame();
740}
741
742void* Thread::FindExceptionHandlerInMethod(const Method* method,
743 void* throw_pc,
744 const DexFile& dex_file,
745 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700746 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700747 exception_ = NULL;
748
749 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700750 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700751 DexFile::CatchHandlerIterator iter;
752 for (iter = dex_file.dexFindCatchHandler(*code_item,
753 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
754 !iter.HasNext();
755 iter.Next()) {
756 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
757 DCHECK(klass != NULL);
758 if (exception_obj->InstanceOf(klass)) {
759 dex_pc = iter.Get().address_;
760 break;
761 }
762 }
763
764 exception_ = exception_obj;
765 if (iter.HasNext()) {
766 return NULL;
767 } else {
768 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
769 }
770}
771
Elliott Hughes410c0c82011-09-01 17:58:25 -0700772void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
773 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
774 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
775 jni_env_->locals.VisitRoots(visitor, arg);
776 jni_env_->monitors.VisitRoots(visitor, arg);
777 // visitThreadStack(visitor, thread, arg);
778 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
779}
780
Ian Rogersb033c752011-07-20 12:22:35 -0700781static const char* kStateNames[] = {
782 "New",
783 "Runnable",
784 "Blocked",
785 "Waiting",
786 "TimedWaiting",
787 "Native",
788 "Terminated",
789};
790std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
791 if (state >= Thread::kNew && state <= Thread::kTerminated) {
792 os << kStateNames[state-Thread::kNew];
793 } else {
794 os << "State[" << static_cast<int>(state) << "]";
795 }
796 return os;
797}
798
Elliott Hughes330304d2011-08-12 14:28:05 -0700799std::ostream& operator<<(std::ostream& os, const Thread& thread) {
800 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700801 << ",pthread_t=" << thread.GetImpl()
802 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700803 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700804 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700805 return os;
806}
807
Carl Shapiro61e019d2011-07-14 16:53:09 -0700808ThreadList* ThreadList::Create() {
809 return new ThreadList;
810}
811
Carl Shapirob5573532011-07-12 18:22:59 -0700812ThreadList::ThreadList() {
813 lock_ = Mutex::Create("ThreadList::Lock");
814}
815
816ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700817 if (Contains(Thread::Current())) {
818 Runtime::Current()->DetachCurrentThread();
819 }
820
821 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700822 // reach this point. This means that all daemon threads had been
823 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700824 // TODO: dump ThreadList if non-empty.
825 CHECK_EQ(list_.size(), 0U);
826
Carl Shapirob5573532011-07-12 18:22:59 -0700827 delete lock_;
828 lock_ = NULL;
829}
830
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700831bool ThreadList::Contains(Thread* thread) {
832 return find(list_.begin(), list_.end(), thread) != list_.end();
833}
834
Elliott Hughesd92bec42011-09-02 17:04:36 -0700835void ThreadList::Dump(std::ostream& os) {
836 MutexLock mu(lock_);
837 os << "DALVIK THREADS (" << list_.size() << "):\n";
838 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
839 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
840 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700841 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700842 }
843}
844
Carl Shapirob5573532011-07-12 18:22:59 -0700845void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700846 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700847 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700848 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700849 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700850}
851
852void ThreadList::Unregister(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700853 //LOG(INFO) << "ThreadList::Unregister() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700854 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700855 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700856 list_.remove(thread);
857}
858
Elliott Hughes410c0c82011-09-01 17:58:25 -0700859void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
860 MutexLock mu(lock_);
861 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
862 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
863 (*it)->VisitRoots(visitor, arg);
864 }
865}
866
Carl Shapirob5573532011-07-12 18:22:59 -0700867} // namespace