blob: 3081d91c86148f8a4f2d8035fabd255ed6a9211a [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;
buzbee4a3164f2011-09-03 11:25:10 -0700180 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700181}
182
Carl Shapirob5573532011-07-12 18:22:59 -0700183Mutex* Mutex::Create(const char* name) {
184 Mutex* mu = new Mutex(name);
185 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700186 CHECK_EQ(result, 0);
Carl Shapirob5573532011-07-12 18:22:59 -0700187 return mu;
188}
189
190void Mutex::Lock() {
191 int result = pthread_mutex_lock(&lock_impl_);
192 CHECK_EQ(result, 0);
193 SetOwner(Thread::Current());
194}
195
196bool Mutex::TryLock() {
197 int result = pthread_mutex_lock(&lock_impl_);
198 if (result == EBUSY) {
199 return false;
200 } else {
201 CHECK_EQ(result, 0);
202 SetOwner(Thread::Current());
203 return true;
204 }
205}
206
207void Mutex::Unlock() {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700208#ifndef NDEBUG
209 Thread* self = Thread::Current();
210 std::stringstream os;
211 os << "owner=";
212 if (owner_ != NULL) {
213 os << *owner_;
214 } else {
215 os << "NULL";
216 }
217 os << " self=";
218 if (self != NULL) {
219 os << *self;
220 } else {
221 os << "NULL";
222 }
223 DCHECK(HaveLock()) << os.str();
224#endif
225 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700226 int result = pthread_mutex_unlock(&lock_impl_);
227 CHECK_EQ(result, 0);
Carl Shapirob5573532011-07-12 18:22:59 -0700228}
229
Elliott Hughes02b48d12011-09-07 17:15:51 -0700230bool Mutex::HaveLock() {
231 return owner_ == Thread::Current();
232}
233
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700234void Frame::Next() {
235 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700236 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700237 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700238}
239
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700240uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700241 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700242 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700243 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700244}
245
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700246Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700247 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700248 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700249 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700250}
251
Carl Shapiro61e019d2011-07-14 16:53:09 -0700252void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700253 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700254 return NULL;
255}
256
Brian Carlstromb765be02011-08-17 23:54:10 -0700257Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700258 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
259
Brian Carlstromb765be02011-08-17 23:54:10 -0700260 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700261
262 Thread* new_thread = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700263
264 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700265 errno = pthread_attr_init(&attr);
266 if (errno != 0) {
267 PLOG(FATAL) << "pthread_attr_init failed";
268 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700269
Elliott Hughese27955c2011-08-26 15:21:24 -0700270 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
271 if (errno != 0) {
272 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
273 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700274
Elliott Hughese27955c2011-08-26 15:21:24 -0700275 errno = pthread_attr_setstacksize(&attr, stack_size);
276 if (errno != 0) {
277 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
278 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700279
Elliott Hughese27955c2011-08-26 15:21:24 -0700280 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
281 if (errno != 0) {
282 PLOG(FATAL) << "pthread_create failed";
283 }
284
285 errno = pthread_attr_destroy(&attr);
286 if (errno != 0) {
287 PLOG(FATAL) << "pthread_attr_destroy failed";
288 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700289
Elliott Hughesdcc24742011-09-07 14:02:44 -0700290 // TODO: get the "daemon" field from the java.lang.Thread.
291 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
292
Carl Shapiro61e019d2011-07-14 16:53:09 -0700293 return new_thread;
294}
295
Elliott Hughesdcc24742011-09-07 14:02:44 -0700296Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700297 Thread* self = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700298
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700299 self->tid_ = ::art::GetTid();
300 self->handle_ = pthread_self();
301 self->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700302
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700303 self->state_ = kRunnable;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700304
Elliott Hughesdcc24742011-09-07 14:02:44 -0700305 SetThreadName(name);
306
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700307 errno = pthread_setspecific(Thread::pthread_key_self_, self);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700308 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700309 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700310 }
311
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700312 self->jni_env_ = new JNIEnvExt(self, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700313
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700314 runtime->GetThreadList()->Register(self);
315
316 // If we're the main thread, ClassLinker won't be created until after we're attached,
317 // so that thread needs a two-stage attach. Regular threads don't need this hack.
318 if (self->thin_lock_id_ != ThreadList::kMainId) {
319 self->CreatePeer(name, as_daemon);
320 }
321
322 return self;
323}
324
325void Thread::CreatePeer(const char* name, bool as_daemon) {
326 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
327
328 JNIEnv* env = jni_env_;
329
330 jobject thread_group = NULL;
331 jobject thread_name = env->NewStringUTF(name);
332 jint thread_priority = 123;
333 jboolean thread_is_daemon = as_daemon;
334
335 jclass c = env->FindClass("java/lang/Thread");
336 LOG(INFO) << "java/lang/Thread=" << (void*)c;
337 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
338 LOG(INFO) << "java/lang/Thread.<init>=" << (void*)mid;
339 jobject o = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
340 LOG(INFO) << "Created new java.lang.Thread " << (void*) o << " decoded=" << (void*) DecodeJObject(o);
341
342 peer_ = DecodeJObject(o);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700343}
344
Elliott Hughesa0957642011-09-02 14:27:33 -0700345void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700346 /*
347 * Get the java.lang.Thread object. This function gets called from
348 * some weird debug contexts, so it's possible that there's a GC in
349 * progress on some other thread. To decrease the chances of the
350 * thread object being moved out from under us, we add the reference
351 * to the tracked allocation list, which pins it in place.
352 *
353 * If threadObj is NULL, the thread is still in the process of being
354 * attached to the VM, and there's really nothing interesting to
355 * say about it yet.
356 */
357 os << "TODO: pin Thread before dumping\n";
358#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700359 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
360 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700361 LOGI("Can't dump thread %d: threadObj not set", threadId);
362 return;
363 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700364 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700365#endif
366
367 DumpState(os);
368 DumpStack(os);
369
370#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700371 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700372#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700373}
374
Elliott Hughesd92bec42011-09-02 17:04:36 -0700375std::string GetSchedulerGroup(pid_t tid) {
376 // /proc/<pid>/group looks like this:
377 // 2:devices:/
378 // 1:cpuacct,cpu:/
379 // We want the third field from the line whose second field contains the "cpu" token.
380 std::string cgroup_file;
381 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
382 return "";
383 }
384 std::vector<std::string> cgroup_lines;
385 Split(cgroup_file, '\n', cgroup_lines);
386 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
387 std::vector<std::string> cgroup_fields;
388 Split(cgroup_lines[i], ':', cgroup_fields);
389 std::vector<std::string> cgroups;
390 Split(cgroup_fields[1], ',', cgroups);
391 for (size_t i = 0; i < cgroups.size(); ++i) {
392 if (cgroups[i] == "cpu") {
393 return cgroup_fields[2].substr(1); // Skip the leading slash.
394 }
395 }
396 }
397 return "";
398}
399
400void Thread::DumpState(std::ostream& os) const {
401 std::string thread_name("unknown");
402 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700403
Elliott Hughesd92bec42011-09-02 17:04:36 -0700404#if 0 // TODO
405 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
406 threadName = dvmCreateCstrFromString(nameStr);
407 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700408#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700409 {
410 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
411 std::string stats;
412 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
413 size_t start = stats.find('(') + 1;
414 size_t end = stats.find(')') - start;
415 thread_name = stats.substr(start, end);
416 }
417 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700418 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700419#endif
420
421 int policy;
422 sched_param sp;
423 errno = pthread_getschedparam(handle_, &policy, &sp);
424 if (errno != 0) {
425 PLOG(FATAL) << "pthread_getschedparam failed";
426 }
427
428 std::string scheduler_group(GetSchedulerGroup(GetTid()));
429 if (scheduler_group.empty()) {
430 scheduler_group = "default";
431 }
432
433 std::string group_name("(null; initializing?)");
434#if 0
435 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
436 if (groupObj != NULL) {
437 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
438 groupName = dvmCreateCstrFromString(nameStr);
439 }
440#else
441 group_name = "TODO";
442#endif
443
444 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700445 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700446 os << " daemon";
447 }
448 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700449 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700450 << " " << state_ << "\n";
451
452 int suspend_count = 0; // TODO
453 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700454 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700455 os << " | group=\"" << group_name << "\""
456 << " sCount=" << suspend_count
457 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700458 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700459 << " self=" << reinterpret_cast<const void*>(this) << "\n";
460 os << " | sysTid=" << GetTid()
461 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
462 << " sched=" << policy << "/" << sp.sched_priority
463 << " cgrp=" << scheduler_group
464 << " handle=" << GetImpl() << "\n";
465
466 // Grab the scheduler stats for this thread.
467 std::string scheduler_stats;
468 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
469 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
470 } else {
471 scheduler_stats = "0 0 0";
472 }
473
474 int utime = 0;
475 int stime = 0;
476 int task_cpu = 0;
477 std::string stats;
478 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
479 // Skip the command, which may contain spaces.
480 stats = stats.substr(stats.find(')') + 2);
481 // Extract the three fields we care about.
482 std::vector<std::string> fields;
483 Split(stats, ' ', fields);
484 utime = strtoull(fields[11].c_str(), NULL, 10);
485 stime = strtoull(fields[12].c_str(), NULL, 10);
486 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
487 }
488
489 os << " | schedstat=( " << scheduler_stats << " )"
490 << " utm=" << utime
491 << " stm=" << stime
492 << " core=" << task_cpu
493 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
494}
495
496void Thread::DumpStack(std::ostream& os) const {
497 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700498}
499
Carl Shapirob5573532011-07-12 18:22:59 -0700500static void ThreadExitCheck(void* arg) {
501 LG << "Thread exit check";
502}
503
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700504bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700505 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700506 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
507 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700508 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700509 return false;
510 }
511
512 // Double-check the TLS slot allocation.
513 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700514 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700515 return false;
516 }
517
518 // TODO: initialize other locks and condition variables
519
520 return true;
521}
522
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700523void Thread::Shutdown() {
524 errno = pthread_key_delete(Thread::pthread_key_self_);
525 if (errno != 0) {
526 PLOG(WARNING) << "pthread_key_delete failed";
527 }
528}
529
Elliott Hughesdcc24742011-09-07 14:02:44 -0700530Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700531 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700532 top_of_managed_stack_(),
533 native_to_managed_record_(NULL),
534 top_sirt_(NULL),
535 jni_env_(NULL),
536 exception_(NULL),
537 suspend_count_(0),
538 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700539 InitCpu();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700540 {
541 ThreadListLock mu;
542 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
543 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700544 InitFunctionPointers();
545}
546
Elliott Hughes02b48d12011-09-07 17:15:51 -0700547void MonitorExitVisitor(const Object* object, void*) {
548 Object* entered_monitor = const_cast<Object*>(object);
549 entered_monitor->MonitorExit();;
550}
551
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700552Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700553 // TODO: check we're not calling the JNI DetachCurrentThread function from
554 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
555
556 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
557 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
558
559 if (IsExceptionPending()) {
560 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
561 }
562
563 // TODO: ThreadGroup.removeThread(this);
564
565 // TODO: this.vmData = 0;
566
567 // TODO: say "bye" to the debugger.
568 //if (gDvm.debuggerConnected) {
569 // dvmDbgPostThreadDeath(self);
570 //}
571
572 // Thread.join() is implemented as an Object.wait() on the Thread.lock
573 // object. Signal anyone who is waiting.
574 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
575 //dvmLockObject(self, lock);
576 //dvmObjectNotifyAll(self, lock);
577 //dvmUnlockObject(self, lock);
578 //lock = NULL;
579
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700580 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700581 jni_env_ = NULL;
582
583 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700584}
585
Ian Rogers408f79a2011-08-23 18:22:33 -0700586size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700587 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700588 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700589 count += cur->NumberOfReferences();
590 }
591 return count;
592}
593
Ian Rogers408f79a2011-08-23 18:22:33 -0700594bool Thread::SirtContains(jobject obj) {
595 Object** sirt_entry = reinterpret_cast<Object**>(obj);
596 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700597 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700598 // A SIRT should always have a jobject/jclass as a native method is passed
599 // in a this pointer or a class
600 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700601 if ((&cur->References()[0] <= sirt_entry) &&
602 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700603 return true;
604 }
605 }
606 return false;
607}
608
Ian Rogers408f79a2011-08-23 18:22:33 -0700609Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700610 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700611 if (obj == NULL) {
612 return NULL;
613 }
614 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
615 IndirectRefKind kind = GetIndirectRefKind(ref);
616 Object* result;
617 switch (kind) {
618 case kLocal:
619 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700620 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700621 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700622 break;
623 }
624 case kGlobal:
625 {
626 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
627 IndirectReferenceTable& globals = vm->globals;
628 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700629 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700630 break;
631 }
632 case kWeakGlobal:
633 {
634 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
635 IndirectReferenceTable& weak_globals = vm->weak_globals;
636 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700637 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700638 if (result == kClearedJniWeakGlobal) {
639 // This is a special case where it's okay to return NULL.
640 return NULL;
641 }
642 break;
643 }
644 case kSirtOrInvalid:
645 default:
646 // TODO: make stack indirect reference table lookup more efficient
647 // Check if this is a local reference in the SIRT
648 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700650 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700651 // Assume an invalid local reference is actually a direct pointer.
652 result = reinterpret_cast<Object*>(obj);
653 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700654 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700655 }
656 }
657
658 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700659 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
660 JniAbort(NULL);
661 } else {
662 if (result != kInvalidIndirectRefObject) {
663 Heap::VerifyObject(result);
664 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700665 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700666 return result;
667}
668
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700669class CountStackDepthVisitor : public Thread::StackVisitor {
670 public:
671 CountStackDepthVisitor() : depth(0) {}
672 virtual bool VisitFrame(const Frame&) {
673 ++depth;
674 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700675 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700676
677 int GetDepth() const {
678 return depth;
679 }
680
681 private:
682 uint32_t depth;
683};
684
685class BuildStackTraceVisitor : public Thread::StackVisitor {
686 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700687 explicit BuildStackTraceVisitor(int depth) : count(0) {
688 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700689 pc_trace = IntArray::Alloc(depth);
690 }
691
692 virtual ~BuildStackTraceVisitor() {}
693
694 virtual bool VisitFrame(const Frame& frame) {
695 method_trace->Set(count, frame.GetMethod());
696 pc_trace->Set(count, frame.GetPC());
697 ++count;
698 return true;
699 }
700
701 const Method* GetMethod(uint32_t i) {
702 DCHECK(i < count);
703 return method_trace->Get(i);
704 }
705
706 uintptr_t GetPC(uint32_t i) {
707 DCHECK(i < count);
708 return pc_trace->Get(i);
709 }
710
711 private:
712 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700713 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700714 IntArray* pc_trace;
715};
716
717void Thread::WalkStack(StackVisitor* visitor) {
718 Frame frame = Thread::Current()->GetTopOfStack();
719 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
720 // CHECK(native_to_managed_record_ != NULL);
721 NativeToManagedRecord* record = native_to_managed_record_;
722
723 while (frame.GetSP()) {
724 for ( ; frame.GetMethod() != 0; frame.Next()) {
725 visitor->VisitFrame(frame);
726 }
727 if (record == NULL) {
728 break;
729 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700730 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 -0700731 record = record->link;
732 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700733}
734
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700735ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700736 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700737
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700738 CountStackDepthVisitor count_visitor;
739 WalkStack(&count_visitor);
740 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700741
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700742 BuildStackTraceVisitor build_trace_visitor(depth);
743 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700744
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700745 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700746
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700747 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700748 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700749 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700750 const Class* klass = method->GetDeclaringClass();
751 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700752 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700753 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700754
755 StackTraceElement* obj =
756 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700757 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700758 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700759 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700760 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700761 java_traces->Set(i, obj);
762 }
763 return java_traces;
764}
765
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700766void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700767 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700768 va_list args;
769 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700770 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700771 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700772
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700773 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700774 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700775 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700776 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700777 descriptor.erase(descriptor.length() - 1);
778
779 JNIEnv* env = GetJniEnv();
780 jclass exception_class = env->FindClass(descriptor.c_str());
781 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
782 int rc = env->ThrowNew(exception_class, msg.c_str());
783 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700784}
785
Elliott Hughes79082e32011-08-25 12:07:32 -0700786void Thread::ThrowOutOfMemoryError() {
787 UNIMPLEMENTED(FATAL);
788}
789
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700790Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
791 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
792 DCHECK(class_linker != NULL);
793
794 Frame cur_frame = GetTopOfStack();
795 for (int unwind_depth = 0; ; unwind_depth++) {
796 const Method* cur_method = cur_frame.GetMethod();
797 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
798 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
799
800 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
801 throw_pc,
802 dex_file,
803 class_linker);
804 if (handler_addr) {
805 *handler_pc = handler_addr;
806 return cur_frame;
807 } else {
808 // Check if we are at the last frame
809 if (cur_frame.HasNext()) {
810 cur_frame.Next();
811 } else {
812 // Either at the top of stack or next frame is native.
813 break;
814 }
815 }
816 }
817 *handler_pc = NULL;
818 return Frame();
819}
820
821void* Thread::FindExceptionHandlerInMethod(const Method* method,
822 void* throw_pc,
823 const DexFile& dex_file,
824 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700825 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700826 exception_ = NULL;
827
828 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700829 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700830 DexFile::CatchHandlerIterator iter;
831 for (iter = dex_file.dexFindCatchHandler(*code_item,
832 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
833 !iter.HasNext();
834 iter.Next()) {
835 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
836 DCHECK(klass != NULL);
837 if (exception_obj->InstanceOf(klass)) {
838 dex_pc = iter.Get().address_;
839 break;
840 }
841 }
842
843 exception_ = exception_obj;
844 if (iter.HasNext()) {
845 return NULL;
846 } else {
847 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
848 }
849}
850
Elliott Hughes410c0c82011-09-01 17:58:25 -0700851void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
852 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
853 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
854 jni_env_->locals.VisitRoots(visitor, arg);
855 jni_env_->monitors.VisitRoots(visitor, arg);
856 // visitThreadStack(visitor, thread, arg);
857 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
858}
859
Ian Rogersb033c752011-07-20 12:22:35 -0700860static const char* kStateNames[] = {
861 "New",
862 "Runnable",
863 "Blocked",
864 "Waiting",
865 "TimedWaiting",
866 "Native",
867 "Terminated",
868};
869std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
870 if (state >= Thread::kNew && state <= Thread::kTerminated) {
871 os << kStateNames[state-Thread::kNew];
872 } else {
873 os << "State[" << static_cast<int>(state) << "]";
874 }
875 return os;
876}
877
Elliott Hughes330304d2011-08-12 14:28:05 -0700878std::ostream& operator<<(std::ostream& os, const Thread& thread) {
879 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700880 << ",pthread_t=" << thread.GetImpl()
881 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700882 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700883 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700884 return os;
885}
886
Carl Shapiro61e019d2011-07-14 16:53:09 -0700887ThreadList* ThreadList::Create() {
888 return new ThreadList;
889}
890
Carl Shapirob5573532011-07-12 18:22:59 -0700891ThreadList::ThreadList() {
892 lock_ = Mutex::Create("ThreadList::Lock");
893}
894
895ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700896 if (Contains(Thread::Current())) {
897 Runtime::Current()->DetachCurrentThread();
898 }
899
900 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700901 // reach this point. This means that all daemon threads had been
902 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700903 // TODO: dump ThreadList if non-empty.
904 CHECK_EQ(list_.size(), 0U);
905
Carl Shapirob5573532011-07-12 18:22:59 -0700906 delete lock_;
907 lock_ = NULL;
908}
909
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700910bool ThreadList::Contains(Thread* thread) {
911 return find(list_.begin(), list_.end(), thread) != list_.end();
912}
913
Elliott Hughesd92bec42011-09-02 17:04:36 -0700914void ThreadList::Dump(std::ostream& os) {
915 MutexLock mu(lock_);
916 os << "DALVIK THREADS (" << list_.size() << "):\n";
917 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
918 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
919 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700920 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700921 }
922}
923
Carl Shapirob5573532011-07-12 18:22:59 -0700924void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700925 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700926 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700927 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700928 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700929}
930
Elliott Hughes02b48d12011-09-07 17:15:51 -0700931void ThreadList::Unregister() {
932 //LOG(INFO) << "ThreadList::Unregister() " << *Thread::Current();
Carl Shapirob5573532011-07-12 18:22:59 -0700933 MutexLock mu(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700934 Thread* self = Thread::Current();
935 CHECK(Contains(self));
936 list_.remove(self);
937 uint32_t thin_lock_id = self->thin_lock_id_;
938 delete self;
939 ReleaseThreadId(thin_lock_id);
Carl Shapirob5573532011-07-12 18:22:59 -0700940}
941
Elliott Hughes410c0c82011-09-01 17:58:25 -0700942void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
943 MutexLock mu(lock_);
944 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
945 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
946 (*it)->VisitRoots(visitor, arg);
947 }
948}
949
Elliott Hughes02b48d12011-09-07 17:15:51 -0700950uint32_t ThreadList::AllocThreadId() {
951 DCHECK(lock_->HaveLock());
952 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
953 if (!allocated_ids_[i]) {
954 allocated_ids_.set(i);
955 return i + 1; // Zero is reserved to mean "invalid".
956 }
957 }
958 LOG(FATAL) << "Out of internal thread ids";
959 return 0;
960}
961
962void ThreadList::ReleaseThreadId(uint32_t id) {
963 DCHECK(lock_->HaveLock());
964 --id; // Zero is reserved to mean "invalid".
965 DCHECK(allocated_ids_[id]) << id;
966 allocated_ids_.reset(id);
967}
968
Carl Shapirob5573532011-07-12 18:22:59 -0700969} // namespace