blob: ae926adfe2bd597695f3fa876ac62bafc2cff203 [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
buzbee2a475e72011-09-07 17:19:17 -0700110// TODO: placeholder (throw on failure)
111static void CheckCastFromCode(const Class* a, const Class* b) {
112 if (a->IsAssignableFrom(b)) {
113 return;
114 }
115 UNIMPLEMENTED(FATAL);
116}
117
118// TODO: placeholder
119static void UnlockObjectFromCode(Thread* thread, Object* obj) {
120 // TODO: throw and unwind if lock not held
121 // TODO: throw and unwind on NPE
buzbee4ef76522011-09-08 10:00:32 -0700122 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700123}
124
125// TODO: placeholder
126static void LockObjectFromCode(Thread* thread, Object* obj) {
buzbee4ef76522011-09-08 10:00:32 -0700127 obj->MonitorEnter(thread);
buzbee2a475e72011-09-07 17:19:17 -0700128}
129
buzbee0d966cf2011-09-08 17:34:58 -0700130// TODO: placeholder
131static void CheckSuspendFromCode(Thread* thread) {
132 /*
133 * Code is at a safe point, suspend if needed.
134 * Also, this is where a pending safepoint callback
135 * would be fired.
136 */
137}
138
buzbee3ea4ec52011-08-22 17:37:19 -0700139void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700140#if defined(__arm__)
141 pShlLong = art_shl_long;
142 pShrLong = art_shr_long;
143 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700144 pIdiv = __aeabi_idiv;
145 pIdivmod = __aeabi_idivmod;
146 pI2f = __aeabi_i2f;
147 pF2iz = __aeabi_f2iz;
148 pD2f = __aeabi_d2f;
149 pF2d = __aeabi_f2d;
150 pD2iz = __aeabi_d2iz;
151 pL2f = __aeabi_l2f;
152 pL2d = __aeabi_l2d;
153 pFadd = __aeabi_fadd;
154 pFsub = __aeabi_fsub;
155 pFdiv = __aeabi_fdiv;
156 pFmul = __aeabi_fmul;
157 pFmodf = fmodf;
158 pDadd = __aeabi_dadd;
159 pDsub = __aeabi_dsub;
160 pDdiv = __aeabi_ddiv;
161 pDmul = __aeabi_dmul;
162 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -0700163 pF2l = F2L;
164 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -0700165 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700166 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700167 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700168#endif
buzbeedfd3d702011-08-28 12:56:51 -0700169 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700170 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700171 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700172 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700173 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700174 pGet32Static = Field::Get32StaticFromCode;
175 pSet32Static = Field::Set32StaticFromCode;
176 pGet64Static = Field::Get64StaticFromCode;
177 pSet64Static = Field::Set64StaticFromCode;
178 pGetObjStatic = Field::GetObjStaticFromCode;
179 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700180 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
181 pThrowException = ThrowException;
182 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700183 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700184 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700185 pInstanceofNonTrivialFromCode = Object::InstanceOf;
186 pCheckCastFromCode = CheckCastFromCode;
187 pLockObjectFromCode = LockObjectFromCode;
188 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700189 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700190 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700191 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700192}
193
Carl Shapirob5573532011-07-12 18:22:59 -0700194Mutex* Mutex::Create(const char* name) {
195 Mutex* mu = new Mutex(name);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700196#ifndef NDEBUG
197 pthread_mutexattr_t debug_attributes;
198 errno = pthread_mutexattr_init(&debug_attributes);
199 if (errno != 0) {
200 PLOG(FATAL) << "pthread_mutexattr_init failed";
201 }
202 errno = pthread_mutexattr_settype(&debug_attributes, PTHREAD_MUTEX_ERRORCHECK);
203 if (errno != 0) {
204 PLOG(FATAL) << "pthread_mutexattr_settype failed";
205 }
206 errno = pthread_mutex_init(&mu->lock_impl_, &debug_attributes);
207 if (errno != 0) {
208 PLOG(FATAL) << "pthread_mutex_init failed";
209 }
210 errno = pthread_mutexattr_destroy(&debug_attributes);
211 if (errno != 0) {
212 PLOG(FATAL) << "pthread_mutexattr_destroy failed";
213 }
214#else
215 errno = pthread_mutex_init(&mu->lock_impl_, NULL);
216 if (errno != 0) {
217 PLOG(FATAL) << "pthread_mutex_init failed";
218 }
219#endif
Carl Shapirob5573532011-07-12 18:22:59 -0700220 return mu;
221}
222
223void Mutex::Lock() {
224 int result = pthread_mutex_lock(&lock_impl_);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700225 if (result != 0) {
226 errno = result;
227 PLOG(FATAL) << "pthread_mutex_lock failed";
228 }
Carl Shapirob5573532011-07-12 18:22:59 -0700229}
230
231bool Mutex::TryLock() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700232 int result = pthread_mutex_trylock(&lock_impl_);
Carl Shapirob5573532011-07-12 18:22:59 -0700233 if (result == EBUSY) {
234 return false;
Carl Shapirob5573532011-07-12 18:22:59 -0700235 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700236 if (result != 0) {
237 errno = result;
238 PLOG(FATAL) << "pthread_mutex_trylock failed";
239 }
240 return true;
Carl Shapirob5573532011-07-12 18:22:59 -0700241}
242
243void Mutex::Unlock() {
Carl Shapirob5573532011-07-12 18:22:59 -0700244 int result = pthread_mutex_unlock(&lock_impl_);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700245 if (result != 0) {
246 errno = result;
247 PLOG(FATAL) << "pthread_mutex_unlock failed";
248 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700249}
250
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700251void Frame::Next() {
252 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700253 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700254 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700255}
256
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700257uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700258 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700259 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700260 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700261}
262
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700263Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700264 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700265 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700266 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700267}
268
Carl Shapiro61e019d2011-07-14 16:53:09 -0700269void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700270 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700271 return NULL;
272}
273
Brian Carlstromb765be02011-08-17 23:54:10 -0700274Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700275 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
276
Brian Carlstromb765be02011-08-17 23:54:10 -0700277 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700278
279 Thread* new_thread = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700280
281 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700282 errno = pthread_attr_init(&attr);
283 if (errno != 0) {
284 PLOG(FATAL) << "pthread_attr_init failed";
285 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700286
Elliott Hughese27955c2011-08-26 15:21:24 -0700287 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
288 if (errno != 0) {
289 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
290 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700291
Elliott Hughese27955c2011-08-26 15:21:24 -0700292 errno = pthread_attr_setstacksize(&attr, stack_size);
293 if (errno != 0) {
294 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
295 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700296
Elliott Hughese27955c2011-08-26 15:21:24 -0700297 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
298 if (errno != 0) {
299 PLOG(FATAL) << "pthread_create failed";
300 }
301
302 errno = pthread_attr_destroy(&attr);
303 if (errno != 0) {
304 PLOG(FATAL) << "pthread_attr_destroy failed";
305 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700306
Elliott Hughesdcc24742011-09-07 14:02:44 -0700307 // TODO: get the "daemon" field from the java.lang.Thread.
308 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
309
Carl Shapiro61e019d2011-07-14 16:53:09 -0700310 return new_thread;
311}
312
Elliott Hughesdcc24742011-09-07 14:02:44 -0700313Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700314 Thread* self = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700315
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700316 self->tid_ = ::art::GetTid();
317 self->handle_ = pthread_self();
318 self->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700319
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700320 self->state_ = kRunnable;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700321
Elliott Hughesdcc24742011-09-07 14:02:44 -0700322 SetThreadName(name);
323
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700324 errno = pthread_setspecific(Thread::pthread_key_self_, self);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700325 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700326 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700327 }
328
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700329 self->jni_env_ = new JNIEnvExt(self, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700330
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700331 runtime->GetThreadList()->Register(self);
332
333 // If we're the main thread, ClassLinker won't be created until after we're attached,
334 // so that thread needs a two-stage attach. Regular threads don't need this hack.
335 if (self->thin_lock_id_ != ThreadList::kMainId) {
336 self->CreatePeer(name, as_daemon);
337 }
338
339 return self;
340}
341
342void Thread::CreatePeer(const char* name, bool as_daemon) {
343 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
344
345 JNIEnv* env = jni_env_;
346
347 jobject thread_group = NULL;
348 jobject thread_name = env->NewStringUTF(name);
349 jint thread_priority = 123;
350 jboolean thread_is_daemon = as_daemon;
351
352 jclass c = env->FindClass("java/lang/Thread");
353 LOG(INFO) << "java/lang/Thread=" << (void*)c;
354 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
355 LOG(INFO) << "java/lang/Thread.<init>=" << (void*)mid;
356 jobject o = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
357 LOG(INFO) << "Created new java.lang.Thread " << (void*) o << " decoded=" << (void*) DecodeJObject(o);
358
359 peer_ = DecodeJObject(o);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700360}
361
Elliott Hughesa0957642011-09-02 14:27:33 -0700362void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700363 /*
364 * Get the java.lang.Thread object. This function gets called from
365 * some weird debug contexts, so it's possible that there's a GC in
366 * progress on some other thread. To decrease the chances of the
367 * thread object being moved out from under us, we add the reference
368 * to the tracked allocation list, which pins it in place.
369 *
370 * If threadObj is NULL, the thread is still in the process of being
371 * attached to the VM, and there's really nothing interesting to
372 * say about it yet.
373 */
374 os << "TODO: pin Thread before dumping\n";
375#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700376 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
377 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700378 LOGI("Can't dump thread %d: threadObj not set", threadId);
379 return;
380 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700381 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700382#endif
383
384 DumpState(os);
385 DumpStack(os);
386
387#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700388 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700389#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700390}
391
Elliott Hughesd92bec42011-09-02 17:04:36 -0700392std::string GetSchedulerGroup(pid_t tid) {
393 // /proc/<pid>/group looks like this:
394 // 2:devices:/
395 // 1:cpuacct,cpu:/
396 // We want the third field from the line whose second field contains the "cpu" token.
397 std::string cgroup_file;
398 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
399 return "";
400 }
401 std::vector<std::string> cgroup_lines;
402 Split(cgroup_file, '\n', cgroup_lines);
403 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
404 std::vector<std::string> cgroup_fields;
405 Split(cgroup_lines[i], ':', cgroup_fields);
406 std::vector<std::string> cgroups;
407 Split(cgroup_fields[1], ',', cgroups);
408 for (size_t i = 0; i < cgroups.size(); ++i) {
409 if (cgroups[i] == "cpu") {
410 return cgroup_fields[2].substr(1); // Skip the leading slash.
411 }
412 }
413 }
414 return "";
415}
416
417void Thread::DumpState(std::ostream& os) const {
418 std::string thread_name("unknown");
419 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700420
Elliott Hughesd92bec42011-09-02 17:04:36 -0700421#if 0 // TODO
422 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
423 threadName = dvmCreateCstrFromString(nameStr);
424 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700425#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700426 {
427 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
428 std::string stats;
429 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
430 size_t start = stats.find('(') + 1;
431 size_t end = stats.find(')') - start;
432 thread_name = stats.substr(start, end);
433 }
434 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700435 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700436#endif
437
438 int policy;
439 sched_param sp;
440 errno = pthread_getschedparam(handle_, &policy, &sp);
441 if (errno != 0) {
442 PLOG(FATAL) << "pthread_getschedparam failed";
443 }
444
445 std::string scheduler_group(GetSchedulerGroup(GetTid()));
446 if (scheduler_group.empty()) {
447 scheduler_group = "default";
448 }
449
450 std::string group_name("(null; initializing?)");
451#if 0
452 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
453 if (groupObj != NULL) {
454 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
455 groupName = dvmCreateCstrFromString(nameStr);
456 }
457#else
458 group_name = "TODO";
459#endif
460
461 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700462 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700463 os << " daemon";
464 }
465 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700466 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700467 << " " << state_ << "\n";
468
469 int suspend_count = 0; // TODO
470 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700471 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700472 os << " | group=\"" << group_name << "\""
473 << " sCount=" << suspend_count
474 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700475 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700476 << " self=" << reinterpret_cast<const void*>(this) << "\n";
477 os << " | sysTid=" << GetTid()
478 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
479 << " sched=" << policy << "/" << sp.sched_priority
480 << " cgrp=" << scheduler_group
481 << " handle=" << GetImpl() << "\n";
482
483 // Grab the scheduler stats for this thread.
484 std::string scheduler_stats;
485 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
486 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
487 } else {
488 scheduler_stats = "0 0 0";
489 }
490
491 int utime = 0;
492 int stime = 0;
493 int task_cpu = 0;
494 std::string stats;
495 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
496 // Skip the command, which may contain spaces.
497 stats = stats.substr(stats.find(')') + 2);
498 // Extract the three fields we care about.
499 std::vector<std::string> fields;
500 Split(stats, ' ', fields);
501 utime = strtoull(fields[11].c_str(), NULL, 10);
502 stime = strtoull(fields[12].c_str(), NULL, 10);
503 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
504 }
505
506 os << " | schedstat=( " << scheduler_stats << " )"
507 << " utm=" << utime
508 << " stm=" << stime
509 << " core=" << task_cpu
510 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
511}
512
513void Thread::DumpStack(std::ostream& os) const {
514 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700515}
516
Carl Shapirob5573532011-07-12 18:22:59 -0700517static void ThreadExitCheck(void* arg) {
518 LG << "Thread exit check";
519}
520
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700521bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700522 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700523 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
524 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700525 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700526 return false;
527 }
528
529 // Double-check the TLS slot allocation.
530 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700531 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700532 return false;
533 }
534
535 // TODO: initialize other locks and condition variables
536
537 return true;
538}
539
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700540void Thread::Shutdown() {
541 errno = pthread_key_delete(Thread::pthread_key_self_);
542 if (errno != 0) {
543 PLOG(WARNING) << "pthread_key_delete failed";
544 }
545}
546
Elliott Hughesdcc24742011-09-07 14:02:44 -0700547Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700548 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700549 top_of_managed_stack_(),
550 native_to_managed_record_(NULL),
551 top_sirt_(NULL),
552 jni_env_(NULL),
553 exception_(NULL),
554 suspend_count_(0),
555 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700556 InitCpu();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700557 {
558 ThreadListLock mu;
559 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
560 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700561 InitFunctionPointers();
562}
563
Elliott Hughes02b48d12011-09-07 17:15:51 -0700564void MonitorExitVisitor(const Object* object, void*) {
565 Object* entered_monitor = const_cast<Object*>(object);
566 entered_monitor->MonitorExit();;
567}
568
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700569Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700570 // TODO: check we're not calling the JNI DetachCurrentThread function from
571 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
572
573 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
574 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
575
576 if (IsExceptionPending()) {
577 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
578 }
579
580 // TODO: ThreadGroup.removeThread(this);
581
582 // TODO: this.vmData = 0;
583
584 // TODO: say "bye" to the debugger.
585 //if (gDvm.debuggerConnected) {
586 // dvmDbgPostThreadDeath(self);
587 //}
588
589 // Thread.join() is implemented as an Object.wait() on the Thread.lock
590 // object. Signal anyone who is waiting.
591 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
592 //dvmLockObject(self, lock);
593 //dvmObjectNotifyAll(self, lock);
594 //dvmUnlockObject(self, lock);
595 //lock = NULL;
596
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700597 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700598 jni_env_ = NULL;
599
600 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700601}
602
Ian Rogers408f79a2011-08-23 18:22:33 -0700603size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700604 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700605 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700606 count += cur->NumberOfReferences();
607 }
608 return count;
609}
610
Ian Rogers408f79a2011-08-23 18:22:33 -0700611bool Thread::SirtContains(jobject obj) {
612 Object** sirt_entry = reinterpret_cast<Object**>(obj);
613 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700614 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700615 // A SIRT should always have a jobject/jclass as a native method is passed
616 // in a this pointer or a class
617 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700618 if ((&cur->References()[0] <= sirt_entry) &&
619 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700620 return true;
621 }
622 }
623 return false;
624}
625
Ian Rogers408f79a2011-08-23 18:22:33 -0700626Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700627 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700628 if (obj == NULL) {
629 return NULL;
630 }
631 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
632 IndirectRefKind kind = GetIndirectRefKind(ref);
633 Object* result;
634 switch (kind) {
635 case kLocal:
636 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700637 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700638 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700639 break;
640 }
641 case kGlobal:
642 {
643 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
644 IndirectReferenceTable& globals = vm->globals;
645 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700646 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700647 break;
648 }
649 case kWeakGlobal:
650 {
651 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
652 IndirectReferenceTable& weak_globals = vm->weak_globals;
653 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700654 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700655 if (result == kClearedJniWeakGlobal) {
656 // This is a special case where it's okay to return NULL.
657 return NULL;
658 }
659 break;
660 }
661 case kSirtOrInvalid:
662 default:
663 // TODO: make stack indirect reference table lookup more efficient
664 // Check if this is a local reference in the SIRT
665 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700666 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700667 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700668 // Assume an invalid local reference is actually a direct pointer.
669 result = reinterpret_cast<Object*>(obj);
670 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700671 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700672 }
673 }
674
675 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700676 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
677 JniAbort(NULL);
678 } else {
679 if (result != kInvalidIndirectRefObject) {
680 Heap::VerifyObject(result);
681 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700682 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700683 return result;
684}
685
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700686class CountStackDepthVisitor : public Thread::StackVisitor {
687 public:
688 CountStackDepthVisitor() : depth(0) {}
689 virtual bool VisitFrame(const Frame&) {
690 ++depth;
691 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700692 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700693
694 int GetDepth() const {
695 return depth;
696 }
697
698 private:
699 uint32_t depth;
700};
701
702class BuildStackTraceVisitor : public Thread::StackVisitor {
703 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700704 explicit BuildStackTraceVisitor(int depth) : count(0) {
705 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700706 pc_trace = IntArray::Alloc(depth);
707 }
708
709 virtual ~BuildStackTraceVisitor() {}
710
711 virtual bool VisitFrame(const Frame& frame) {
712 method_trace->Set(count, frame.GetMethod());
713 pc_trace->Set(count, frame.GetPC());
714 ++count;
715 return true;
716 }
717
718 const Method* GetMethod(uint32_t i) {
719 DCHECK(i < count);
720 return method_trace->Get(i);
721 }
722
723 uintptr_t GetPC(uint32_t i) {
724 DCHECK(i < count);
725 return pc_trace->Get(i);
726 }
727
728 private:
729 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700730 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700731 IntArray* pc_trace;
732};
733
734void Thread::WalkStack(StackVisitor* visitor) {
735 Frame frame = Thread::Current()->GetTopOfStack();
736 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
737 // CHECK(native_to_managed_record_ != NULL);
738 NativeToManagedRecord* record = native_to_managed_record_;
739
740 while (frame.GetSP()) {
741 for ( ; frame.GetMethod() != 0; frame.Next()) {
742 visitor->VisitFrame(frame);
743 }
744 if (record == NULL) {
745 break;
746 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700747 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 -0700748 record = record->link;
749 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700750}
751
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700752ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700753 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700754
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700755 CountStackDepthVisitor count_visitor;
756 WalkStack(&count_visitor);
757 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700758
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700759 BuildStackTraceVisitor build_trace_visitor(depth);
760 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700761
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700762 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700763
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700764 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700765 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700766 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700767 const Class* klass = method->GetDeclaringClass();
768 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700769 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700770 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700771
772 StackTraceElement* obj =
773 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700774 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700775 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700776 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700777 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700778 java_traces->Set(i, obj);
779 }
780 return java_traces;
781}
782
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700783void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700784 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700785 va_list args;
786 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700787 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700788 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700789
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700790 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700791 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700792 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700793 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700794 descriptor.erase(descriptor.length() - 1);
795
796 JNIEnv* env = GetJniEnv();
797 jclass exception_class = env->FindClass(descriptor.c_str());
798 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
799 int rc = env->ThrowNew(exception_class, msg.c_str());
800 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700801}
802
Elliott Hughes79082e32011-08-25 12:07:32 -0700803void Thread::ThrowOutOfMemoryError() {
804 UNIMPLEMENTED(FATAL);
805}
806
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700807Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
808 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
809 DCHECK(class_linker != NULL);
810
811 Frame cur_frame = GetTopOfStack();
812 for (int unwind_depth = 0; ; unwind_depth++) {
813 const Method* cur_method = cur_frame.GetMethod();
814 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
815 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
816
817 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
818 throw_pc,
819 dex_file,
820 class_linker);
821 if (handler_addr) {
822 *handler_pc = handler_addr;
823 return cur_frame;
824 } else {
825 // Check if we are at the last frame
826 if (cur_frame.HasNext()) {
827 cur_frame.Next();
828 } else {
829 // Either at the top of stack or next frame is native.
830 break;
831 }
832 }
833 }
834 *handler_pc = NULL;
835 return Frame();
836}
837
838void* Thread::FindExceptionHandlerInMethod(const Method* method,
839 void* throw_pc,
840 const DexFile& dex_file,
841 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700842 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700843 exception_ = NULL;
844
845 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700846 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700847 DexFile::CatchHandlerIterator iter;
848 for (iter = dex_file.dexFindCatchHandler(*code_item,
849 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
850 !iter.HasNext();
851 iter.Next()) {
852 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
853 DCHECK(klass != NULL);
854 if (exception_obj->InstanceOf(klass)) {
855 dex_pc = iter.Get().address_;
856 break;
857 }
858 }
859
860 exception_ = exception_obj;
861 if (iter.HasNext()) {
862 return NULL;
863 } else {
864 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
865 }
866}
867
Elliott Hughes410c0c82011-09-01 17:58:25 -0700868void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
869 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
870 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
871 jni_env_->locals.VisitRoots(visitor, arg);
872 jni_env_->monitors.VisitRoots(visitor, arg);
873 // visitThreadStack(visitor, thread, arg);
874 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
875}
876
Ian Rogersb033c752011-07-20 12:22:35 -0700877static const char* kStateNames[] = {
878 "New",
879 "Runnable",
880 "Blocked",
881 "Waiting",
882 "TimedWaiting",
883 "Native",
884 "Terminated",
885};
886std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
887 if (state >= Thread::kNew && state <= Thread::kTerminated) {
888 os << kStateNames[state-Thread::kNew];
889 } else {
890 os << "State[" << static_cast<int>(state) << "]";
891 }
892 return os;
893}
894
Elliott Hughes330304d2011-08-12 14:28:05 -0700895std::ostream& operator<<(std::ostream& os, const Thread& thread) {
896 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700897 << ",pthread_t=" << thread.GetImpl()
898 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700899 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700900 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700901 return os;
902}
903
Carl Shapiro61e019d2011-07-14 16:53:09 -0700904ThreadList* ThreadList::Create() {
905 return new ThreadList;
906}
907
Carl Shapirob5573532011-07-12 18:22:59 -0700908ThreadList::ThreadList() {
909 lock_ = Mutex::Create("ThreadList::Lock");
910}
911
912ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700913 if (Contains(Thread::Current())) {
914 Runtime::Current()->DetachCurrentThread();
915 }
916
917 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700918 // reach this point. This means that all daemon threads had been
919 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700920 // TODO: dump ThreadList if non-empty.
921 CHECK_EQ(list_.size(), 0U);
922
Carl Shapirob5573532011-07-12 18:22:59 -0700923 delete lock_;
924 lock_ = NULL;
925}
926
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700927bool ThreadList::Contains(Thread* thread) {
928 return find(list_.begin(), list_.end(), thread) != list_.end();
929}
930
Elliott Hughesd92bec42011-09-02 17:04:36 -0700931void ThreadList::Dump(std::ostream& os) {
932 MutexLock mu(lock_);
933 os << "DALVIK THREADS (" << list_.size() << "):\n";
934 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
935 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
936 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700937 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700938 }
939}
940
Carl Shapirob5573532011-07-12 18:22:59 -0700941void ThreadList::Register(Thread* thread) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700942 LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700943 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700944 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700945 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700946}
947
Elliott Hughes02b48d12011-09-07 17:15:51 -0700948void ThreadList::Unregister() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700949 LOG(INFO) << "ThreadList::Unregister() " << *Thread::Current();
Carl Shapirob5573532011-07-12 18:22:59 -0700950 MutexLock mu(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700951 Thread* self = Thread::Current();
952 CHECK(Contains(self));
953 list_.remove(self);
954 uint32_t thin_lock_id = self->thin_lock_id_;
955 delete self;
956 ReleaseThreadId(thin_lock_id);
Carl Shapirob5573532011-07-12 18:22:59 -0700957}
958
Elliott Hughes410c0c82011-09-01 17:58:25 -0700959void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
960 MutexLock mu(lock_);
961 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
962 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
963 (*it)->VisitRoots(visitor, arg);
964 }
965}
966
Elliott Hughes02b48d12011-09-07 17:15:51 -0700967uint32_t ThreadList::AllocThreadId() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700968 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700969 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
970 if (!allocated_ids_[i]) {
971 allocated_ids_.set(i);
972 return i + 1; // Zero is reserved to mean "invalid".
973 }
974 }
975 LOG(FATAL) << "Out of internal thread ids";
976 return 0;
977}
978
979void ThreadList::ReleaseThreadId(uint32_t id) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700980 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700981 --id; // Zero is reserved to mean "invalid".
982 DCHECK(allocated_ids_[id]) << id;
983 allocated_ids_.reset(id);
984}
985
Carl Shapirob5573532011-07-12 18:22:59 -0700986} // namespace