blob: 98f7f78ea0ebc1ecc0b5937f55e9b3a89c862a43 [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
buzbee3ea4ec52011-08-22 17:37:19 -0700130void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700131#if defined(__arm__)
132 pShlLong = art_shl_long;
133 pShrLong = art_shr_long;
134 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700135 pIdiv = __aeabi_idiv;
136 pIdivmod = __aeabi_idivmod;
137 pI2f = __aeabi_i2f;
138 pF2iz = __aeabi_f2iz;
139 pD2f = __aeabi_d2f;
140 pF2d = __aeabi_f2d;
141 pD2iz = __aeabi_d2iz;
142 pL2f = __aeabi_l2f;
143 pL2d = __aeabi_l2d;
144 pFadd = __aeabi_fadd;
145 pFsub = __aeabi_fsub;
146 pFdiv = __aeabi_fdiv;
147 pFmul = __aeabi_fmul;
148 pFmodf = fmodf;
149 pDadd = __aeabi_dadd;
150 pDsub = __aeabi_dsub;
151 pDdiv = __aeabi_ddiv;
152 pDmul = __aeabi_dmul;
153 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -0700154 pF2l = F2L;
155 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -0700156 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700157 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700158 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700159#endif
buzbeedfd3d702011-08-28 12:56:51 -0700160 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700161 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700162 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700163 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700164 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700165 pGet32Static = Field::Get32StaticFromCode;
166 pSet32Static = Field::Set32StaticFromCode;
167 pGet64Static = Field::Get64StaticFromCode;
168 pSet64Static = Field::Set64StaticFromCode;
169 pGetObjStatic = Field::GetObjStaticFromCode;
170 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700171 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
172 pThrowException = ThrowException;
173 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700174 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700175 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700176 pInstanceofNonTrivialFromCode = Object::InstanceOf;
177 pCheckCastFromCode = CheckCastFromCode;
178 pLockObjectFromCode = LockObjectFromCode;
179 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700180 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700181 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700182}
183
Carl Shapirob5573532011-07-12 18:22:59 -0700184Mutex* Mutex::Create(const char* name) {
185 Mutex* mu = new Mutex(name);
186 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700187 CHECK_EQ(result, 0);
Carl Shapirob5573532011-07-12 18:22:59 -0700188 return mu;
189}
190
191void Mutex::Lock() {
192 int result = pthread_mutex_lock(&lock_impl_);
193 CHECK_EQ(result, 0);
194 SetOwner(Thread::Current());
195}
196
197bool Mutex::TryLock() {
198 int result = pthread_mutex_lock(&lock_impl_);
199 if (result == EBUSY) {
200 return false;
201 } else {
202 CHECK_EQ(result, 0);
203 SetOwner(Thread::Current());
204 return true;
205 }
206}
207
208void Mutex::Unlock() {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700209#ifndef NDEBUG
210 Thread* self = Thread::Current();
211 std::stringstream os;
212 os << "owner=";
213 if (owner_ != NULL) {
214 os << *owner_;
215 } else {
216 os << "NULL";
217 }
218 os << " self=";
219 if (self != NULL) {
220 os << *self;
221 } else {
222 os << "NULL";
223 }
224 DCHECK(HaveLock()) << os.str();
225#endif
226 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700227 int result = pthread_mutex_unlock(&lock_impl_);
228 CHECK_EQ(result, 0);
Carl Shapirob5573532011-07-12 18:22:59 -0700229}
230
Elliott Hughes02b48d12011-09-07 17:15:51 -0700231bool Mutex::HaveLock() {
232 return owner_ == Thread::Current();
233}
234
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700235void Frame::Next() {
236 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700237 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700238 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700239}
240
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700241uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700242 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700243 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700244 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700245}
246
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700247Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700248 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700249 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700250 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700251}
252
Carl Shapiro61e019d2011-07-14 16:53:09 -0700253void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700254 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700255 return NULL;
256}
257
Brian Carlstromb765be02011-08-17 23:54:10 -0700258Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700259 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
260
Brian Carlstromb765be02011-08-17 23:54:10 -0700261 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700262
263 Thread* new_thread = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700264
265 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700266 errno = pthread_attr_init(&attr);
267 if (errno != 0) {
268 PLOG(FATAL) << "pthread_attr_init failed";
269 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700270
Elliott Hughese27955c2011-08-26 15:21:24 -0700271 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
272 if (errno != 0) {
273 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
274 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700275
Elliott Hughese27955c2011-08-26 15:21:24 -0700276 errno = pthread_attr_setstacksize(&attr, stack_size);
277 if (errno != 0) {
278 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
279 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700280
Elliott Hughese27955c2011-08-26 15:21:24 -0700281 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
282 if (errno != 0) {
283 PLOG(FATAL) << "pthread_create failed";
284 }
285
286 errno = pthread_attr_destroy(&attr);
287 if (errno != 0) {
288 PLOG(FATAL) << "pthread_attr_destroy failed";
289 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700290
Elliott Hughesdcc24742011-09-07 14:02:44 -0700291 // TODO: get the "daemon" field from the java.lang.Thread.
292 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
293
Carl Shapiro61e019d2011-07-14 16:53:09 -0700294 return new_thread;
295}
296
Elliott Hughesdcc24742011-09-07 14:02:44 -0700297Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700298 Thread* self = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700299
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700300 self->tid_ = ::art::GetTid();
301 self->handle_ = pthread_self();
302 self->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700303
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700304 self->state_ = kRunnable;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700305
Elliott Hughesdcc24742011-09-07 14:02:44 -0700306 SetThreadName(name);
307
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700308 errno = pthread_setspecific(Thread::pthread_key_self_, self);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700309 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700310 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700311 }
312
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700313 self->jni_env_ = new JNIEnvExt(self, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700314
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700315 runtime->GetThreadList()->Register(self);
316
317 // If we're the main thread, ClassLinker won't be created until after we're attached,
318 // so that thread needs a two-stage attach. Regular threads don't need this hack.
319 if (self->thin_lock_id_ != ThreadList::kMainId) {
320 self->CreatePeer(name, as_daemon);
321 }
322
323 return self;
324}
325
326void Thread::CreatePeer(const char* name, bool as_daemon) {
327 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
328
329 JNIEnv* env = jni_env_;
330
331 jobject thread_group = NULL;
332 jobject thread_name = env->NewStringUTF(name);
333 jint thread_priority = 123;
334 jboolean thread_is_daemon = as_daemon;
335
336 jclass c = env->FindClass("java/lang/Thread");
337 LOG(INFO) << "java/lang/Thread=" << (void*)c;
338 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
339 LOG(INFO) << "java/lang/Thread.<init>=" << (void*)mid;
340 jobject o = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
341 LOG(INFO) << "Created new java.lang.Thread " << (void*) o << " decoded=" << (void*) DecodeJObject(o);
342
343 peer_ = DecodeJObject(o);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700344}
345
Elliott Hughesa0957642011-09-02 14:27:33 -0700346void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700347 /*
348 * Get the java.lang.Thread object. This function gets called from
349 * some weird debug contexts, so it's possible that there's a GC in
350 * progress on some other thread. To decrease the chances of the
351 * thread object being moved out from under us, we add the reference
352 * to the tracked allocation list, which pins it in place.
353 *
354 * If threadObj is NULL, the thread is still in the process of being
355 * attached to the VM, and there's really nothing interesting to
356 * say about it yet.
357 */
358 os << "TODO: pin Thread before dumping\n";
359#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700360 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
361 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700362 LOGI("Can't dump thread %d: threadObj not set", threadId);
363 return;
364 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700365 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700366#endif
367
368 DumpState(os);
369 DumpStack(os);
370
371#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700372 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700373#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700374}
375
Elliott Hughesd92bec42011-09-02 17:04:36 -0700376std::string GetSchedulerGroup(pid_t tid) {
377 // /proc/<pid>/group looks like this:
378 // 2:devices:/
379 // 1:cpuacct,cpu:/
380 // We want the third field from the line whose second field contains the "cpu" token.
381 std::string cgroup_file;
382 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
383 return "";
384 }
385 std::vector<std::string> cgroup_lines;
386 Split(cgroup_file, '\n', cgroup_lines);
387 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
388 std::vector<std::string> cgroup_fields;
389 Split(cgroup_lines[i], ':', cgroup_fields);
390 std::vector<std::string> cgroups;
391 Split(cgroup_fields[1], ',', cgroups);
392 for (size_t i = 0; i < cgroups.size(); ++i) {
393 if (cgroups[i] == "cpu") {
394 return cgroup_fields[2].substr(1); // Skip the leading slash.
395 }
396 }
397 }
398 return "";
399}
400
401void Thread::DumpState(std::ostream& os) const {
402 std::string thread_name("unknown");
403 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700404
Elliott Hughesd92bec42011-09-02 17:04:36 -0700405#if 0 // TODO
406 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
407 threadName = dvmCreateCstrFromString(nameStr);
408 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700409#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700410 {
411 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
412 std::string stats;
413 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
414 size_t start = stats.find('(') + 1;
415 size_t end = stats.find(')') - start;
416 thread_name = stats.substr(start, end);
417 }
418 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700419 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700420#endif
421
422 int policy;
423 sched_param sp;
424 errno = pthread_getschedparam(handle_, &policy, &sp);
425 if (errno != 0) {
426 PLOG(FATAL) << "pthread_getschedparam failed";
427 }
428
429 std::string scheduler_group(GetSchedulerGroup(GetTid()));
430 if (scheduler_group.empty()) {
431 scheduler_group = "default";
432 }
433
434 std::string group_name("(null; initializing?)");
435#if 0
436 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
437 if (groupObj != NULL) {
438 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
439 groupName = dvmCreateCstrFromString(nameStr);
440 }
441#else
442 group_name = "TODO";
443#endif
444
445 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700446 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700447 os << " daemon";
448 }
449 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700450 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700451 << " " << state_ << "\n";
452
453 int suspend_count = 0; // TODO
454 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700455 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700456 os << " | group=\"" << group_name << "\""
457 << " sCount=" << suspend_count
458 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700459 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700460 << " self=" << reinterpret_cast<const void*>(this) << "\n";
461 os << " | sysTid=" << GetTid()
462 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
463 << " sched=" << policy << "/" << sp.sched_priority
464 << " cgrp=" << scheduler_group
465 << " handle=" << GetImpl() << "\n";
466
467 // Grab the scheduler stats for this thread.
468 std::string scheduler_stats;
469 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
470 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
471 } else {
472 scheduler_stats = "0 0 0";
473 }
474
475 int utime = 0;
476 int stime = 0;
477 int task_cpu = 0;
478 std::string stats;
479 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
480 // Skip the command, which may contain spaces.
481 stats = stats.substr(stats.find(')') + 2);
482 // Extract the three fields we care about.
483 std::vector<std::string> fields;
484 Split(stats, ' ', fields);
485 utime = strtoull(fields[11].c_str(), NULL, 10);
486 stime = strtoull(fields[12].c_str(), NULL, 10);
487 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
488 }
489
490 os << " | schedstat=( " << scheduler_stats << " )"
491 << " utm=" << utime
492 << " stm=" << stime
493 << " core=" << task_cpu
494 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
495}
496
497void Thread::DumpStack(std::ostream& os) const {
498 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700499}
500
Carl Shapirob5573532011-07-12 18:22:59 -0700501static void ThreadExitCheck(void* arg) {
502 LG << "Thread exit check";
503}
504
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700505bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700506 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700507 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
508 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700509 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700510 return false;
511 }
512
513 // Double-check the TLS slot allocation.
514 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700515 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700516 return false;
517 }
518
519 // TODO: initialize other locks and condition variables
520
521 return true;
522}
523
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700524void Thread::Shutdown() {
525 errno = pthread_key_delete(Thread::pthread_key_self_);
526 if (errno != 0) {
527 PLOG(WARNING) << "pthread_key_delete failed";
528 }
529}
530
Elliott Hughesdcc24742011-09-07 14:02:44 -0700531Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700532 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700533 top_of_managed_stack_(),
534 native_to_managed_record_(NULL),
535 top_sirt_(NULL),
536 jni_env_(NULL),
537 exception_(NULL),
538 suspend_count_(0),
539 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700540 InitCpu();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700541 {
542 ThreadListLock mu;
543 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
544 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700545 InitFunctionPointers();
546}
547
Elliott Hughes02b48d12011-09-07 17:15:51 -0700548void MonitorExitVisitor(const Object* object, void*) {
549 Object* entered_monitor = const_cast<Object*>(object);
550 entered_monitor->MonitorExit();;
551}
552
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700553Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700554 // TODO: check we're not calling the JNI DetachCurrentThread function from
555 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
556
557 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
558 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
559
560 if (IsExceptionPending()) {
561 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
562 }
563
564 // TODO: ThreadGroup.removeThread(this);
565
566 // TODO: this.vmData = 0;
567
568 // TODO: say "bye" to the debugger.
569 //if (gDvm.debuggerConnected) {
570 // dvmDbgPostThreadDeath(self);
571 //}
572
573 // Thread.join() is implemented as an Object.wait() on the Thread.lock
574 // object. Signal anyone who is waiting.
575 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
576 //dvmLockObject(self, lock);
577 //dvmObjectNotifyAll(self, lock);
578 //dvmUnlockObject(self, lock);
579 //lock = NULL;
580
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700581 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700582 jni_env_ = NULL;
583
584 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700585}
586
Ian Rogers408f79a2011-08-23 18:22:33 -0700587size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700588 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700589 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700590 count += cur->NumberOfReferences();
591 }
592 return count;
593}
594
Ian Rogers408f79a2011-08-23 18:22:33 -0700595bool Thread::SirtContains(jobject obj) {
596 Object** sirt_entry = reinterpret_cast<Object**>(obj);
597 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700598 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700599 // A SIRT should always have a jobject/jclass as a native method is passed
600 // in a this pointer or a class
601 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700602 if ((&cur->References()[0] <= sirt_entry) &&
603 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700604 return true;
605 }
606 }
607 return false;
608}
609
Ian Rogers408f79a2011-08-23 18:22:33 -0700610Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700611 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700612 if (obj == NULL) {
613 return NULL;
614 }
615 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
616 IndirectRefKind kind = GetIndirectRefKind(ref);
617 Object* result;
618 switch (kind) {
619 case kLocal:
620 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700621 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700622 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700623 break;
624 }
625 case kGlobal:
626 {
627 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
628 IndirectReferenceTable& globals = vm->globals;
629 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700630 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700631 break;
632 }
633 case kWeakGlobal:
634 {
635 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
636 IndirectReferenceTable& weak_globals = vm->weak_globals;
637 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700638 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700639 if (result == kClearedJniWeakGlobal) {
640 // This is a special case where it's okay to return NULL.
641 return NULL;
642 }
643 break;
644 }
645 case kSirtOrInvalid:
646 default:
647 // TODO: make stack indirect reference table lookup more efficient
648 // Check if this is a local reference in the SIRT
649 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700650 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700651 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700652 // Assume an invalid local reference is actually a direct pointer.
653 result = reinterpret_cast<Object*>(obj);
654 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700655 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700656 }
657 }
658
659 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700660 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
661 JniAbort(NULL);
662 } else {
663 if (result != kInvalidIndirectRefObject) {
664 Heap::VerifyObject(result);
665 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700666 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700667 return result;
668}
669
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700670class CountStackDepthVisitor : public Thread::StackVisitor {
671 public:
672 CountStackDepthVisitor() : depth(0) {}
673 virtual bool VisitFrame(const Frame&) {
674 ++depth;
675 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700676 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700677
678 int GetDepth() const {
679 return depth;
680 }
681
682 private:
683 uint32_t depth;
684};
685
686class BuildStackTraceVisitor : public Thread::StackVisitor {
687 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700688 explicit BuildStackTraceVisitor(int depth) : count(0) {
689 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700690 pc_trace = IntArray::Alloc(depth);
691 }
692
693 virtual ~BuildStackTraceVisitor() {}
694
695 virtual bool VisitFrame(const Frame& frame) {
696 method_trace->Set(count, frame.GetMethod());
697 pc_trace->Set(count, frame.GetPC());
698 ++count;
699 return true;
700 }
701
702 const Method* GetMethod(uint32_t i) {
703 DCHECK(i < count);
704 return method_trace->Get(i);
705 }
706
707 uintptr_t GetPC(uint32_t i) {
708 DCHECK(i < count);
709 return pc_trace->Get(i);
710 }
711
712 private:
713 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700714 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700715 IntArray* pc_trace;
716};
717
718void Thread::WalkStack(StackVisitor* visitor) {
719 Frame frame = Thread::Current()->GetTopOfStack();
720 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
721 // CHECK(native_to_managed_record_ != NULL);
722 NativeToManagedRecord* record = native_to_managed_record_;
723
724 while (frame.GetSP()) {
725 for ( ; frame.GetMethod() != 0; frame.Next()) {
726 visitor->VisitFrame(frame);
727 }
728 if (record == NULL) {
729 break;
730 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700731 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 -0700732 record = record->link;
733 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700734}
735
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700736ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700737 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700738
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700739 CountStackDepthVisitor count_visitor;
740 WalkStack(&count_visitor);
741 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700742
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700743 BuildStackTraceVisitor build_trace_visitor(depth);
744 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700745
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700746 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700747
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700748 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700749 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700750 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700751 const Class* klass = method->GetDeclaringClass();
752 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700753 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700754 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700755
756 StackTraceElement* obj =
757 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700758 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700759 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700760 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700761 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700762 java_traces->Set(i, obj);
763 }
764 return java_traces;
765}
766
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700767void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700768 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700769 va_list args;
770 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700771 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700772 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700773
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700774 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700775 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700776 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700777 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700778 descriptor.erase(descriptor.length() - 1);
779
780 JNIEnv* env = GetJniEnv();
781 jclass exception_class = env->FindClass(descriptor.c_str());
782 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
783 int rc = env->ThrowNew(exception_class, msg.c_str());
784 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700785}
786
Elliott Hughes79082e32011-08-25 12:07:32 -0700787void Thread::ThrowOutOfMemoryError() {
788 UNIMPLEMENTED(FATAL);
789}
790
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700791Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
792 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
793 DCHECK(class_linker != NULL);
794
795 Frame cur_frame = GetTopOfStack();
796 for (int unwind_depth = 0; ; unwind_depth++) {
797 const Method* cur_method = cur_frame.GetMethod();
798 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
799 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
800
801 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
802 throw_pc,
803 dex_file,
804 class_linker);
805 if (handler_addr) {
806 *handler_pc = handler_addr;
807 return cur_frame;
808 } else {
809 // Check if we are at the last frame
810 if (cur_frame.HasNext()) {
811 cur_frame.Next();
812 } else {
813 // Either at the top of stack or next frame is native.
814 break;
815 }
816 }
817 }
818 *handler_pc = NULL;
819 return Frame();
820}
821
822void* Thread::FindExceptionHandlerInMethod(const Method* method,
823 void* throw_pc,
824 const DexFile& dex_file,
825 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700826 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700827 exception_ = NULL;
828
829 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700830 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700831 DexFile::CatchHandlerIterator iter;
832 for (iter = dex_file.dexFindCatchHandler(*code_item,
833 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
834 !iter.HasNext();
835 iter.Next()) {
836 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
837 DCHECK(klass != NULL);
838 if (exception_obj->InstanceOf(klass)) {
839 dex_pc = iter.Get().address_;
840 break;
841 }
842 }
843
844 exception_ = exception_obj;
845 if (iter.HasNext()) {
846 return NULL;
847 } else {
848 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
849 }
850}
851
Elliott Hughes410c0c82011-09-01 17:58:25 -0700852void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
853 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
854 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
855 jni_env_->locals.VisitRoots(visitor, arg);
856 jni_env_->monitors.VisitRoots(visitor, arg);
857 // visitThreadStack(visitor, thread, arg);
858 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
859}
860
Ian Rogersb033c752011-07-20 12:22:35 -0700861static const char* kStateNames[] = {
862 "New",
863 "Runnable",
864 "Blocked",
865 "Waiting",
866 "TimedWaiting",
867 "Native",
868 "Terminated",
869};
870std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
871 if (state >= Thread::kNew && state <= Thread::kTerminated) {
872 os << kStateNames[state-Thread::kNew];
873 } else {
874 os << "State[" << static_cast<int>(state) << "]";
875 }
876 return os;
877}
878
Elliott Hughes330304d2011-08-12 14:28:05 -0700879std::ostream& operator<<(std::ostream& os, const Thread& thread) {
880 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700881 << ",pthread_t=" << thread.GetImpl()
882 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700883 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700884 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700885 return os;
886}
887
Carl Shapiro61e019d2011-07-14 16:53:09 -0700888ThreadList* ThreadList::Create() {
889 return new ThreadList;
890}
891
Carl Shapirob5573532011-07-12 18:22:59 -0700892ThreadList::ThreadList() {
893 lock_ = Mutex::Create("ThreadList::Lock");
894}
895
896ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700897 if (Contains(Thread::Current())) {
898 Runtime::Current()->DetachCurrentThread();
899 }
900
901 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700902 // reach this point. This means that all daemon threads had been
903 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700904 // TODO: dump ThreadList if non-empty.
905 CHECK_EQ(list_.size(), 0U);
906
Carl Shapirob5573532011-07-12 18:22:59 -0700907 delete lock_;
908 lock_ = NULL;
909}
910
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700911bool ThreadList::Contains(Thread* thread) {
912 return find(list_.begin(), list_.end(), thread) != list_.end();
913}
914
Elliott Hughesd92bec42011-09-02 17:04:36 -0700915void ThreadList::Dump(std::ostream& os) {
916 MutexLock mu(lock_);
917 os << "DALVIK THREADS (" << list_.size() << "):\n";
918 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
919 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
920 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700921 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700922 }
923}
924
Carl Shapirob5573532011-07-12 18:22:59 -0700925void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700926 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700927 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700928 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700929 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700930}
931
Elliott Hughes02b48d12011-09-07 17:15:51 -0700932void ThreadList::Unregister() {
933 //LOG(INFO) << "ThreadList::Unregister() " << *Thread::Current();
Carl Shapirob5573532011-07-12 18:22:59 -0700934 MutexLock mu(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700935 Thread* self = Thread::Current();
936 CHECK(Contains(self));
937 list_.remove(self);
938 uint32_t thin_lock_id = self->thin_lock_id_;
939 delete self;
940 ReleaseThreadId(thin_lock_id);
Carl Shapirob5573532011-07-12 18:22:59 -0700941}
942
Elliott Hughes410c0c82011-09-01 17:58:25 -0700943void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
944 MutexLock mu(lock_);
945 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
946 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
947 (*it)->VisitRoots(visitor, arg);
948 }
949}
950
Elliott Hughes02b48d12011-09-07 17:15:51 -0700951uint32_t ThreadList::AllocThreadId() {
952 DCHECK(lock_->HaveLock());
953 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
954 if (!allocated_ids_[i]) {
955 allocated_ids_.set(i);
956 return i + 1; // Zero is reserved to mean "invalid".
957 }
958 }
959 LOG(FATAL) << "Out of internal thread ids";
960 return 0;
961}
962
963void ThreadList::ReleaseThreadId(uint32_t id) {
964 DCHECK(lock_->HaveLock());
965 --id; // Zero is reserved to mean "invalid".
966 DCHECK(allocated_ids_[id]) << id;
967 allocated_ids_.reset(id);
968}
969
Carl Shapirob5573532011-07-12 18:22:59 -0700970} // namespace