blob: 6109825c22d9e32f897ddca5d5a97811d2eb49e6 [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);
196 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700197 CHECK_EQ(result, 0);
Carl Shapirob5573532011-07-12 18:22:59 -0700198 return mu;
199}
200
201void Mutex::Lock() {
202 int result = pthread_mutex_lock(&lock_impl_);
203 CHECK_EQ(result, 0);
204 SetOwner(Thread::Current());
205}
206
207bool Mutex::TryLock() {
208 int result = pthread_mutex_lock(&lock_impl_);
209 if (result == EBUSY) {
210 return false;
211 } else {
212 CHECK_EQ(result, 0);
213 SetOwner(Thread::Current());
214 return true;
215 }
216}
217
218void Mutex::Unlock() {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700219#ifndef NDEBUG
220 Thread* self = Thread::Current();
221 std::stringstream os;
222 os << "owner=";
223 if (owner_ != NULL) {
224 os << *owner_;
225 } else {
226 os << "NULL";
227 }
228 os << " self=";
229 if (self != NULL) {
230 os << *self;
231 } else {
232 os << "NULL";
233 }
234 DCHECK(HaveLock()) << os.str();
235#endif
236 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700237 int result = pthread_mutex_unlock(&lock_impl_);
238 CHECK_EQ(result, 0);
Carl Shapirob5573532011-07-12 18:22:59 -0700239}
240
Elliott Hughes02b48d12011-09-07 17:15:51 -0700241bool Mutex::HaveLock() {
242 return owner_ == Thread::Current();
243}
244
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700245void Frame::Next() {
246 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700247 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700248 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700249}
250
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700251uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700252 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700253 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700254 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700255}
256
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700257Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700258 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700259 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700260 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700261}
262
Carl Shapiro61e019d2011-07-14 16:53:09 -0700263void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700264 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700265 return NULL;
266}
267
Brian Carlstromb765be02011-08-17 23:54:10 -0700268Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700269 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
270
Brian Carlstromb765be02011-08-17 23:54:10 -0700271 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700272
273 Thread* new_thread = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700274
275 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700276 errno = pthread_attr_init(&attr);
277 if (errno != 0) {
278 PLOG(FATAL) << "pthread_attr_init failed";
279 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700280
Elliott Hughese27955c2011-08-26 15:21:24 -0700281 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
282 if (errno != 0) {
283 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
284 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700285
Elliott Hughese27955c2011-08-26 15:21:24 -0700286 errno = pthread_attr_setstacksize(&attr, stack_size);
287 if (errno != 0) {
288 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
289 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700290
Elliott Hughese27955c2011-08-26 15:21:24 -0700291 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
292 if (errno != 0) {
293 PLOG(FATAL) << "pthread_create failed";
294 }
295
296 errno = pthread_attr_destroy(&attr);
297 if (errno != 0) {
298 PLOG(FATAL) << "pthread_attr_destroy failed";
299 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700300
Elliott Hughesdcc24742011-09-07 14:02:44 -0700301 // TODO: get the "daemon" field from the java.lang.Thread.
302 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
303
Carl Shapiro61e019d2011-07-14 16:53:09 -0700304 return new_thread;
305}
306
Elliott Hughesdcc24742011-09-07 14:02:44 -0700307Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700308 Thread* self = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700309
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700310 self->tid_ = ::art::GetTid();
311 self->handle_ = pthread_self();
312 self->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700313
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700314 self->state_ = kRunnable;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700315
Elliott Hughesdcc24742011-09-07 14:02:44 -0700316 SetThreadName(name);
317
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700318 errno = pthread_setspecific(Thread::pthread_key_self_, self);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700319 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700320 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700321 }
322
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700323 self->jni_env_ = new JNIEnvExt(self, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700324
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700325 runtime->GetThreadList()->Register(self);
326
327 // If we're the main thread, ClassLinker won't be created until after we're attached,
328 // so that thread needs a two-stage attach. Regular threads don't need this hack.
329 if (self->thin_lock_id_ != ThreadList::kMainId) {
330 self->CreatePeer(name, as_daemon);
331 }
332
333 return self;
334}
335
336void Thread::CreatePeer(const char* name, bool as_daemon) {
337 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
338
339 JNIEnv* env = jni_env_;
340
341 jobject thread_group = NULL;
342 jobject thread_name = env->NewStringUTF(name);
343 jint thread_priority = 123;
344 jboolean thread_is_daemon = as_daemon;
345
346 jclass c = env->FindClass("java/lang/Thread");
347 LOG(INFO) << "java/lang/Thread=" << (void*)c;
348 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
349 LOG(INFO) << "java/lang/Thread.<init>=" << (void*)mid;
350 jobject o = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
351 LOG(INFO) << "Created new java.lang.Thread " << (void*) o << " decoded=" << (void*) DecodeJObject(o);
352
353 peer_ = DecodeJObject(o);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700354}
355
Elliott Hughesa0957642011-09-02 14:27:33 -0700356void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700357 /*
358 * Get the java.lang.Thread object. This function gets called from
359 * some weird debug contexts, so it's possible that there's a GC in
360 * progress on some other thread. To decrease the chances of the
361 * thread object being moved out from under us, we add the reference
362 * to the tracked allocation list, which pins it in place.
363 *
364 * If threadObj is NULL, the thread is still in the process of being
365 * attached to the VM, and there's really nothing interesting to
366 * say about it yet.
367 */
368 os << "TODO: pin Thread before dumping\n";
369#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700370 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
371 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700372 LOGI("Can't dump thread %d: threadObj not set", threadId);
373 return;
374 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700375 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700376#endif
377
378 DumpState(os);
379 DumpStack(os);
380
381#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700382 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700383#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700384}
385
Elliott Hughesd92bec42011-09-02 17:04:36 -0700386std::string GetSchedulerGroup(pid_t tid) {
387 // /proc/<pid>/group looks like this:
388 // 2:devices:/
389 // 1:cpuacct,cpu:/
390 // We want the third field from the line whose second field contains the "cpu" token.
391 std::string cgroup_file;
392 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
393 return "";
394 }
395 std::vector<std::string> cgroup_lines;
396 Split(cgroup_file, '\n', cgroup_lines);
397 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
398 std::vector<std::string> cgroup_fields;
399 Split(cgroup_lines[i], ':', cgroup_fields);
400 std::vector<std::string> cgroups;
401 Split(cgroup_fields[1], ',', cgroups);
402 for (size_t i = 0; i < cgroups.size(); ++i) {
403 if (cgroups[i] == "cpu") {
404 return cgroup_fields[2].substr(1); // Skip the leading slash.
405 }
406 }
407 }
408 return "";
409}
410
411void Thread::DumpState(std::ostream& os) const {
412 std::string thread_name("unknown");
413 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700414
Elliott Hughesd92bec42011-09-02 17:04:36 -0700415#if 0 // TODO
416 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
417 threadName = dvmCreateCstrFromString(nameStr);
418 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700419#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700420 {
421 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
422 std::string stats;
423 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
424 size_t start = stats.find('(') + 1;
425 size_t end = stats.find(')') - start;
426 thread_name = stats.substr(start, end);
427 }
428 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700429 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700430#endif
431
432 int policy;
433 sched_param sp;
434 errno = pthread_getschedparam(handle_, &policy, &sp);
435 if (errno != 0) {
436 PLOG(FATAL) << "pthread_getschedparam failed";
437 }
438
439 std::string scheduler_group(GetSchedulerGroup(GetTid()));
440 if (scheduler_group.empty()) {
441 scheduler_group = "default";
442 }
443
444 std::string group_name("(null; initializing?)");
445#if 0
446 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
447 if (groupObj != NULL) {
448 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
449 groupName = dvmCreateCstrFromString(nameStr);
450 }
451#else
452 group_name = "TODO";
453#endif
454
455 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700456 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700457 os << " daemon";
458 }
459 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700460 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700461 << " " << state_ << "\n";
462
463 int suspend_count = 0; // TODO
464 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700465 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700466 os << " | group=\"" << group_name << "\""
467 << " sCount=" << suspend_count
468 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700469 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700470 << " self=" << reinterpret_cast<const void*>(this) << "\n";
471 os << " | sysTid=" << GetTid()
472 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
473 << " sched=" << policy << "/" << sp.sched_priority
474 << " cgrp=" << scheduler_group
475 << " handle=" << GetImpl() << "\n";
476
477 // Grab the scheduler stats for this thread.
478 std::string scheduler_stats;
479 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
480 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
481 } else {
482 scheduler_stats = "0 0 0";
483 }
484
485 int utime = 0;
486 int stime = 0;
487 int task_cpu = 0;
488 std::string stats;
489 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
490 // Skip the command, which may contain spaces.
491 stats = stats.substr(stats.find(')') + 2);
492 // Extract the three fields we care about.
493 std::vector<std::string> fields;
494 Split(stats, ' ', fields);
495 utime = strtoull(fields[11].c_str(), NULL, 10);
496 stime = strtoull(fields[12].c_str(), NULL, 10);
497 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
498 }
499
500 os << " | schedstat=( " << scheduler_stats << " )"
501 << " utm=" << utime
502 << " stm=" << stime
503 << " core=" << task_cpu
504 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
505}
506
507void Thread::DumpStack(std::ostream& os) const {
508 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700509}
510
Carl Shapirob5573532011-07-12 18:22:59 -0700511static void ThreadExitCheck(void* arg) {
512 LG << "Thread exit check";
513}
514
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700515bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700516 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700517 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
518 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700519 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700520 return false;
521 }
522
523 // Double-check the TLS slot allocation.
524 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700525 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700526 return false;
527 }
528
529 // TODO: initialize other locks and condition variables
530
531 return true;
532}
533
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700534void Thread::Shutdown() {
535 errno = pthread_key_delete(Thread::pthread_key_self_);
536 if (errno != 0) {
537 PLOG(WARNING) << "pthread_key_delete failed";
538 }
539}
540
Elliott Hughesdcc24742011-09-07 14:02:44 -0700541Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700542 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700543 top_of_managed_stack_(),
544 native_to_managed_record_(NULL),
545 top_sirt_(NULL),
546 jni_env_(NULL),
547 exception_(NULL),
548 suspend_count_(0),
549 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700550 InitCpu();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700551 {
552 ThreadListLock mu;
553 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
554 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700555 InitFunctionPointers();
556}
557
Elliott Hughes02b48d12011-09-07 17:15:51 -0700558void MonitorExitVisitor(const Object* object, void*) {
559 Object* entered_monitor = const_cast<Object*>(object);
560 entered_monitor->MonitorExit();;
561}
562
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700563Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700564 // TODO: check we're not calling the JNI DetachCurrentThread function from
565 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
566
567 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
568 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
569
570 if (IsExceptionPending()) {
571 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
572 }
573
574 // TODO: ThreadGroup.removeThread(this);
575
576 // TODO: this.vmData = 0;
577
578 // TODO: say "bye" to the debugger.
579 //if (gDvm.debuggerConnected) {
580 // dvmDbgPostThreadDeath(self);
581 //}
582
583 // Thread.join() is implemented as an Object.wait() on the Thread.lock
584 // object. Signal anyone who is waiting.
585 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
586 //dvmLockObject(self, lock);
587 //dvmObjectNotifyAll(self, lock);
588 //dvmUnlockObject(self, lock);
589 //lock = NULL;
590
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700591 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700592 jni_env_ = NULL;
593
594 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700595}
596
Ian Rogers408f79a2011-08-23 18:22:33 -0700597size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700598 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700599 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700600 count += cur->NumberOfReferences();
601 }
602 return count;
603}
604
Ian Rogers408f79a2011-08-23 18:22:33 -0700605bool Thread::SirtContains(jobject obj) {
606 Object** sirt_entry = reinterpret_cast<Object**>(obj);
607 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700608 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700609 // A SIRT should always have a jobject/jclass as a native method is passed
610 // in a this pointer or a class
611 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700612 if ((&cur->References()[0] <= sirt_entry) &&
613 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700614 return true;
615 }
616 }
617 return false;
618}
619
Ian Rogers408f79a2011-08-23 18:22:33 -0700620Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700621 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700622 if (obj == NULL) {
623 return NULL;
624 }
625 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
626 IndirectRefKind kind = GetIndirectRefKind(ref);
627 Object* result;
628 switch (kind) {
629 case kLocal:
630 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700631 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700632 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700633 break;
634 }
635 case kGlobal:
636 {
637 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
638 IndirectReferenceTable& globals = vm->globals;
639 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700640 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700641 break;
642 }
643 case kWeakGlobal:
644 {
645 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
646 IndirectReferenceTable& weak_globals = vm->weak_globals;
647 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700648 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700649 if (result == kClearedJniWeakGlobal) {
650 // This is a special case where it's okay to return NULL.
651 return NULL;
652 }
653 break;
654 }
655 case kSirtOrInvalid:
656 default:
657 // TODO: make stack indirect reference table lookup more efficient
658 // Check if this is a local reference in the SIRT
659 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700660 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700661 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700662 // Assume an invalid local reference is actually a direct pointer.
663 result = reinterpret_cast<Object*>(obj);
664 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700665 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700666 }
667 }
668
669 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700670 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
671 JniAbort(NULL);
672 } else {
673 if (result != kInvalidIndirectRefObject) {
674 Heap::VerifyObject(result);
675 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700676 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700677 return result;
678}
679
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700680class CountStackDepthVisitor : public Thread::StackVisitor {
681 public:
682 CountStackDepthVisitor() : depth(0) {}
683 virtual bool VisitFrame(const Frame&) {
684 ++depth;
685 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700686 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700687
688 int GetDepth() const {
689 return depth;
690 }
691
692 private:
693 uint32_t depth;
694};
695
696class BuildStackTraceVisitor : public Thread::StackVisitor {
697 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700698 explicit BuildStackTraceVisitor(int depth) : count(0) {
699 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700700 pc_trace = IntArray::Alloc(depth);
701 }
702
703 virtual ~BuildStackTraceVisitor() {}
704
705 virtual bool VisitFrame(const Frame& frame) {
706 method_trace->Set(count, frame.GetMethod());
707 pc_trace->Set(count, frame.GetPC());
708 ++count;
709 return true;
710 }
711
712 const Method* GetMethod(uint32_t i) {
713 DCHECK(i < count);
714 return method_trace->Get(i);
715 }
716
717 uintptr_t GetPC(uint32_t i) {
718 DCHECK(i < count);
719 return pc_trace->Get(i);
720 }
721
722 private:
723 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700724 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700725 IntArray* pc_trace;
726};
727
728void Thread::WalkStack(StackVisitor* visitor) {
729 Frame frame = Thread::Current()->GetTopOfStack();
730 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
731 // CHECK(native_to_managed_record_ != NULL);
732 NativeToManagedRecord* record = native_to_managed_record_;
733
734 while (frame.GetSP()) {
735 for ( ; frame.GetMethod() != 0; frame.Next()) {
736 visitor->VisitFrame(frame);
737 }
738 if (record == NULL) {
739 break;
740 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700741 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 -0700742 record = record->link;
743 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700744}
745
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700746ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700747 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700748
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700749 CountStackDepthVisitor count_visitor;
750 WalkStack(&count_visitor);
751 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700752
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700753 BuildStackTraceVisitor build_trace_visitor(depth);
754 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700755
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700756 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700757
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700758 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700759 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700760 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700761 const Class* klass = method->GetDeclaringClass();
762 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700763 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700764 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700765
766 StackTraceElement* obj =
767 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700768 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700769 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700770 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700771 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700772 java_traces->Set(i, obj);
773 }
774 return java_traces;
775}
776
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700777void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700778 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700779 va_list args;
780 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700781 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700782 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700783
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700784 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700785 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700786 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700787 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700788 descriptor.erase(descriptor.length() - 1);
789
790 JNIEnv* env = GetJniEnv();
791 jclass exception_class = env->FindClass(descriptor.c_str());
792 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
793 int rc = env->ThrowNew(exception_class, msg.c_str());
794 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700795}
796
Elliott Hughes79082e32011-08-25 12:07:32 -0700797void Thread::ThrowOutOfMemoryError() {
798 UNIMPLEMENTED(FATAL);
799}
800
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700801Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
802 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
803 DCHECK(class_linker != NULL);
804
805 Frame cur_frame = GetTopOfStack();
806 for (int unwind_depth = 0; ; unwind_depth++) {
807 const Method* cur_method = cur_frame.GetMethod();
808 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
809 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
810
811 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
812 throw_pc,
813 dex_file,
814 class_linker);
815 if (handler_addr) {
816 *handler_pc = handler_addr;
817 return cur_frame;
818 } else {
819 // Check if we are at the last frame
820 if (cur_frame.HasNext()) {
821 cur_frame.Next();
822 } else {
823 // Either at the top of stack or next frame is native.
824 break;
825 }
826 }
827 }
828 *handler_pc = NULL;
829 return Frame();
830}
831
832void* Thread::FindExceptionHandlerInMethod(const Method* method,
833 void* throw_pc,
834 const DexFile& dex_file,
835 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700836 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700837 exception_ = NULL;
838
839 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700840 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700841 DexFile::CatchHandlerIterator iter;
842 for (iter = dex_file.dexFindCatchHandler(*code_item,
843 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
844 !iter.HasNext();
845 iter.Next()) {
846 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
847 DCHECK(klass != NULL);
848 if (exception_obj->InstanceOf(klass)) {
849 dex_pc = iter.Get().address_;
850 break;
851 }
852 }
853
854 exception_ = exception_obj;
855 if (iter.HasNext()) {
856 return NULL;
857 } else {
858 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
859 }
860}
861
Elliott Hughes410c0c82011-09-01 17:58:25 -0700862void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
863 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
864 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
865 jni_env_->locals.VisitRoots(visitor, arg);
866 jni_env_->monitors.VisitRoots(visitor, arg);
867 // visitThreadStack(visitor, thread, arg);
868 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
869}
870
Ian Rogersb033c752011-07-20 12:22:35 -0700871static const char* kStateNames[] = {
872 "New",
873 "Runnable",
874 "Blocked",
875 "Waiting",
876 "TimedWaiting",
877 "Native",
878 "Terminated",
879};
880std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
881 if (state >= Thread::kNew && state <= Thread::kTerminated) {
882 os << kStateNames[state-Thread::kNew];
883 } else {
884 os << "State[" << static_cast<int>(state) << "]";
885 }
886 return os;
887}
888
Elliott Hughes330304d2011-08-12 14:28:05 -0700889std::ostream& operator<<(std::ostream& os, const Thread& thread) {
890 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700891 << ",pthread_t=" << thread.GetImpl()
892 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700893 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700894 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700895 return os;
896}
897
Carl Shapiro61e019d2011-07-14 16:53:09 -0700898ThreadList* ThreadList::Create() {
899 return new ThreadList;
900}
901
Carl Shapirob5573532011-07-12 18:22:59 -0700902ThreadList::ThreadList() {
903 lock_ = Mutex::Create("ThreadList::Lock");
904}
905
906ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700907 if (Contains(Thread::Current())) {
908 Runtime::Current()->DetachCurrentThread();
909 }
910
911 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700912 // reach this point. This means that all daemon threads had been
913 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700914 // TODO: dump ThreadList if non-empty.
915 CHECK_EQ(list_.size(), 0U);
916
Carl Shapirob5573532011-07-12 18:22:59 -0700917 delete lock_;
918 lock_ = NULL;
919}
920
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700921bool ThreadList::Contains(Thread* thread) {
922 return find(list_.begin(), list_.end(), thread) != list_.end();
923}
924
Elliott Hughesd92bec42011-09-02 17:04:36 -0700925void ThreadList::Dump(std::ostream& os) {
926 MutexLock mu(lock_);
927 os << "DALVIK THREADS (" << list_.size() << "):\n";
928 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
929 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
930 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700931 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700932 }
933}
934
Carl Shapirob5573532011-07-12 18:22:59 -0700935void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700936 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700937 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700938 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700939 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700940}
941
Elliott Hughes02b48d12011-09-07 17:15:51 -0700942void ThreadList::Unregister() {
943 //LOG(INFO) << "ThreadList::Unregister() " << *Thread::Current();
Carl Shapirob5573532011-07-12 18:22:59 -0700944 MutexLock mu(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700945 Thread* self = Thread::Current();
946 CHECK(Contains(self));
947 list_.remove(self);
948 uint32_t thin_lock_id = self->thin_lock_id_;
949 delete self;
950 ReleaseThreadId(thin_lock_id);
Carl Shapirob5573532011-07-12 18:22:59 -0700951}
952
Elliott Hughes410c0c82011-09-01 17:58:25 -0700953void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
954 MutexLock mu(lock_);
955 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
956 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
957 (*it)->VisitRoots(visitor, arg);
958 }
959}
960
Elliott Hughes02b48d12011-09-07 17:15:51 -0700961uint32_t ThreadList::AllocThreadId() {
962 DCHECK(lock_->HaveLock());
963 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
964 if (!allocated_ids_[i]) {
965 allocated_ids_.set(i);
966 return i + 1; // Zero is reserved to mean "invalid".
967 }
968 }
969 LOG(FATAL) << "Out of internal thread ids";
970 return 0;
971}
972
973void ThreadList::ReleaseThreadId(uint32_t id) {
974 DCHECK(lock_->HaveLock());
975 --id; // Zero is reserved to mean "invalid".
976 DCHECK(allocated_ids_[id]) << id;
977 allocated_ids_.reset(id);
978}
979
Carl Shapirob5573532011-07-12 18:22:59 -0700980} // namespace