blob: 7d909c936fb231438857f89c7965b6185446cfb1 [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 Hughes02b48d12011-09-07 17:15:51 -0700208 DCHECK(HaveLock());
Carl Shapirob5573532011-07-12 18:22:59 -0700209 int result = pthread_mutex_unlock(&lock_impl_);
210 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700211 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700212}
213
Elliott Hughes02b48d12011-09-07 17:15:51 -0700214bool Mutex::HaveLock() {
215 return owner_ == Thread::Current();
216}
217
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700218void Frame::Next() {
219 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700220 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700221 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700222}
223
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700224uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700225 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700226 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700227 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700228}
229
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700230Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700231 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700232 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700233 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700234}
235
Carl Shapiro61e019d2011-07-14 16:53:09 -0700236void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700237 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700238 return NULL;
239}
240
Brian Carlstromb765be02011-08-17 23:54:10 -0700241Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700242 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
243
Brian Carlstromb765be02011-08-17 23:54:10 -0700244 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700245
246 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700247 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700248
249 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700250 errno = pthread_attr_init(&attr);
251 if (errno != 0) {
252 PLOG(FATAL) << "pthread_attr_init failed";
253 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700254
Elliott Hughese27955c2011-08-26 15:21:24 -0700255 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
256 if (errno != 0) {
257 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
258 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700259
Elliott Hughese27955c2011-08-26 15:21:24 -0700260 errno = pthread_attr_setstacksize(&attr, stack_size);
261 if (errno != 0) {
262 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
263 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700264
Elliott Hughese27955c2011-08-26 15:21:24 -0700265 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
266 if (errno != 0) {
267 PLOG(FATAL) << "pthread_create failed";
268 }
269
270 errno = pthread_attr_destroy(&attr);
271 if (errno != 0) {
272 PLOG(FATAL) << "pthread_attr_destroy failed";
273 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700274
Elliott Hughesdcc24742011-09-07 14:02:44 -0700275 // TODO: get the "daemon" field from the java.lang.Thread.
276 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
277
Carl Shapiro61e019d2011-07-14 16:53:09 -0700278 return new_thread;
279}
280
Elliott Hughesdcc24742011-09-07 14:02:44 -0700281Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700282 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700283 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700284
Elliott Hughes42ee1422011-09-06 12:33:32 -0700285 thread->tid_ = ::art::GetTid();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700286 thread->handle_ = pthread_self();
287 thread->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700288
289 thread->state_ = kRunnable;
290
Elliott Hughesdcc24742011-09-07 14:02:44 -0700291 SetThreadName(name);
292
Elliott Hughesa5780da2011-07-17 11:39:39 -0700293 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
294 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700295 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700296 }
297
Elliott Hughes75770752011-08-24 17:52:38 -0700298 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700299
Carl Shapiro61e019d2011-07-14 16:53:09 -0700300 return thread;
301}
302
Elliott Hughesa0957642011-09-02 14:27:33 -0700303void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700304 /*
305 * Get the java.lang.Thread object. This function gets called from
306 * some weird debug contexts, so it's possible that there's a GC in
307 * progress on some other thread. To decrease the chances of the
308 * thread object being moved out from under us, we add the reference
309 * to the tracked allocation list, which pins it in place.
310 *
311 * If threadObj is NULL, the thread is still in the process of being
312 * attached to the VM, and there's really nothing interesting to
313 * say about it yet.
314 */
315 os << "TODO: pin Thread before dumping\n";
316#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700317 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
318 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700319 LOGI("Can't dump thread %d: threadObj not set", threadId);
320 return;
321 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700322 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700323#endif
324
325 DumpState(os);
326 DumpStack(os);
327
328#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700329 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700330#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700331}
332
Elliott Hughesd92bec42011-09-02 17:04:36 -0700333std::string GetSchedulerGroup(pid_t tid) {
334 // /proc/<pid>/group looks like this:
335 // 2:devices:/
336 // 1:cpuacct,cpu:/
337 // We want the third field from the line whose second field contains the "cpu" token.
338 std::string cgroup_file;
339 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
340 return "";
341 }
342 std::vector<std::string> cgroup_lines;
343 Split(cgroup_file, '\n', cgroup_lines);
344 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
345 std::vector<std::string> cgroup_fields;
346 Split(cgroup_lines[i], ':', cgroup_fields);
347 std::vector<std::string> cgroups;
348 Split(cgroup_fields[1], ',', cgroups);
349 for (size_t i = 0; i < cgroups.size(); ++i) {
350 if (cgroups[i] == "cpu") {
351 return cgroup_fields[2].substr(1); // Skip the leading slash.
352 }
353 }
354 }
355 return "";
356}
357
358void Thread::DumpState(std::ostream& os) const {
359 std::string thread_name("unknown");
360 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700361
Elliott Hughesd92bec42011-09-02 17:04:36 -0700362#if 0 // TODO
363 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
364 threadName = dvmCreateCstrFromString(nameStr);
365 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700366#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700367 {
368 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
369 std::string stats;
370 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
371 size_t start = stats.find('(') + 1;
372 size_t end = stats.find(')') - start;
373 thread_name = stats.substr(start, end);
374 }
375 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700376 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700377#endif
378
379 int policy;
380 sched_param sp;
381 errno = pthread_getschedparam(handle_, &policy, &sp);
382 if (errno != 0) {
383 PLOG(FATAL) << "pthread_getschedparam failed";
384 }
385
386 std::string scheduler_group(GetSchedulerGroup(GetTid()));
387 if (scheduler_group.empty()) {
388 scheduler_group = "default";
389 }
390
391 std::string group_name("(null; initializing?)");
392#if 0
393 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
394 if (groupObj != NULL) {
395 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
396 groupName = dvmCreateCstrFromString(nameStr);
397 }
398#else
399 group_name = "TODO";
400#endif
401
402 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700403 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700404 os << " daemon";
405 }
406 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700407 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700408 << " " << state_ << "\n";
409
410 int suspend_count = 0; // TODO
411 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700412 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700413 os << " | group=\"" << group_name << "\""
414 << " sCount=" << suspend_count
415 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700416 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700417 << " self=" << reinterpret_cast<const void*>(this) << "\n";
418 os << " | sysTid=" << GetTid()
419 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
420 << " sched=" << policy << "/" << sp.sched_priority
421 << " cgrp=" << scheduler_group
422 << " handle=" << GetImpl() << "\n";
423
424 // Grab the scheduler stats for this thread.
425 std::string scheduler_stats;
426 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
427 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
428 } else {
429 scheduler_stats = "0 0 0";
430 }
431
432 int utime = 0;
433 int stime = 0;
434 int task_cpu = 0;
435 std::string stats;
436 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
437 // Skip the command, which may contain spaces.
438 stats = stats.substr(stats.find(')') + 2);
439 // Extract the three fields we care about.
440 std::vector<std::string> fields;
441 Split(stats, ' ', fields);
442 utime = strtoull(fields[11].c_str(), NULL, 10);
443 stime = strtoull(fields[12].c_str(), NULL, 10);
444 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
445 }
446
447 os << " | schedstat=( " << scheduler_stats << " )"
448 << " utm=" << utime
449 << " stm=" << stime
450 << " core=" << task_cpu
451 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
452}
453
454void Thread::DumpStack(std::ostream& os) const {
455 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700456}
457
Carl Shapirob5573532011-07-12 18:22:59 -0700458static void ThreadExitCheck(void* arg) {
459 LG << "Thread exit check";
460}
461
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700462bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700463 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700464 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
465 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700466 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700467 return false;
468 }
469
470 // Double-check the TLS slot allocation.
471 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700472 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700473 return false;
474 }
475
476 // TODO: initialize other locks and condition variables
477
478 return true;
479}
480
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700481void Thread::Shutdown() {
482 errno = pthread_key_delete(Thread::pthread_key_self_);
483 if (errno != 0) {
484 PLOG(WARNING) << "pthread_key_delete failed";
485 }
486}
487
Elliott Hughesdcc24742011-09-07 14:02:44 -0700488Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700489 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700490 top_of_managed_stack_(),
491 native_to_managed_record_(NULL),
492 top_sirt_(NULL),
493 jni_env_(NULL),
494 exception_(NULL),
495 suspend_count_(0),
496 class_loader_override_(NULL) {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700497 {
498 ThreadListLock mu;
499 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
500 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700501 InitFunctionPointers();
502}
503
Elliott Hughes02b48d12011-09-07 17:15:51 -0700504void MonitorExitVisitor(const Object* object, void*) {
505 Object* entered_monitor = const_cast<Object*>(object);
506 entered_monitor->MonitorExit();;
507}
508
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700509Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700510 // TODO: check we're not calling the JNI DetachCurrentThread function from
511 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
512
513 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
514 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
515
516 if (IsExceptionPending()) {
517 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
518 }
519
520 // TODO: ThreadGroup.removeThread(this);
521
522 // TODO: this.vmData = 0;
523
524 // TODO: say "bye" to the debugger.
525 //if (gDvm.debuggerConnected) {
526 // dvmDbgPostThreadDeath(self);
527 //}
528
529 // Thread.join() is implemented as an Object.wait() on the Thread.lock
530 // object. Signal anyone who is waiting.
531 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
532 //dvmLockObject(self, lock);
533 //dvmObjectNotifyAll(self, lock);
534 //dvmUnlockObject(self, lock);
535 //lock = NULL;
536
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700537 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700538 jni_env_ = NULL;
539
540 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700541}
542
Ian Rogers408f79a2011-08-23 18:22:33 -0700543size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700544 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700545 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700546 count += cur->NumberOfReferences();
547 }
548 return count;
549}
550
Ian Rogers408f79a2011-08-23 18:22:33 -0700551bool Thread::SirtContains(jobject obj) {
552 Object** sirt_entry = reinterpret_cast<Object**>(obj);
553 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700554 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700555 // A SIRT should always have a jobject/jclass as a native method is passed
556 // in a this pointer or a class
557 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700558 if ((&cur->References()[0] <= sirt_entry) &&
559 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700560 return true;
561 }
562 }
563 return false;
564}
565
Ian Rogers408f79a2011-08-23 18:22:33 -0700566Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700568 if (obj == NULL) {
569 return NULL;
570 }
571 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
572 IndirectRefKind kind = GetIndirectRefKind(ref);
573 Object* result;
574 switch (kind) {
575 case kLocal:
576 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700577 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700578 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700579 break;
580 }
581 case kGlobal:
582 {
583 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
584 IndirectReferenceTable& globals = vm->globals;
585 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700586 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700587 break;
588 }
589 case kWeakGlobal:
590 {
591 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
592 IndirectReferenceTable& weak_globals = vm->weak_globals;
593 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700594 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700595 if (result == kClearedJniWeakGlobal) {
596 // This is a special case where it's okay to return NULL.
597 return NULL;
598 }
599 break;
600 }
601 case kSirtOrInvalid:
602 default:
603 // TODO: make stack indirect reference table lookup more efficient
604 // Check if this is a local reference in the SIRT
605 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700606 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700607 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700608 // Assume an invalid local reference is actually a direct pointer.
609 result = reinterpret_cast<Object*>(obj);
610 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700611 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700612 }
613 }
614
615 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700616 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
617 JniAbort(NULL);
618 } else {
619 if (result != kInvalidIndirectRefObject) {
620 Heap::VerifyObject(result);
621 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700622 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700623 return result;
624}
625
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700626class CountStackDepthVisitor : public Thread::StackVisitor {
627 public:
628 CountStackDepthVisitor() : depth(0) {}
629 virtual bool VisitFrame(const Frame&) {
630 ++depth;
631 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700632 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700633
634 int GetDepth() const {
635 return depth;
636 }
637
638 private:
639 uint32_t depth;
640};
641
642class BuildStackTraceVisitor : public Thread::StackVisitor {
643 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700644 explicit BuildStackTraceVisitor(int depth) : count(0) {
645 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700646 pc_trace = IntArray::Alloc(depth);
647 }
648
649 virtual ~BuildStackTraceVisitor() {}
650
651 virtual bool VisitFrame(const Frame& frame) {
652 method_trace->Set(count, frame.GetMethod());
653 pc_trace->Set(count, frame.GetPC());
654 ++count;
655 return true;
656 }
657
658 const Method* GetMethod(uint32_t i) {
659 DCHECK(i < count);
660 return method_trace->Get(i);
661 }
662
663 uintptr_t GetPC(uint32_t i) {
664 DCHECK(i < count);
665 return pc_trace->Get(i);
666 }
667
668 private:
669 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700670 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700671 IntArray* pc_trace;
672};
673
674void Thread::WalkStack(StackVisitor* visitor) {
675 Frame frame = Thread::Current()->GetTopOfStack();
676 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
677 // CHECK(native_to_managed_record_ != NULL);
678 NativeToManagedRecord* record = native_to_managed_record_;
679
680 while (frame.GetSP()) {
681 for ( ; frame.GetMethod() != 0; frame.Next()) {
682 visitor->VisitFrame(frame);
683 }
684 if (record == NULL) {
685 break;
686 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700687 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 -0700688 record = record->link;
689 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700690}
691
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700692ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700693 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700694
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700695 CountStackDepthVisitor count_visitor;
696 WalkStack(&count_visitor);
697 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700698
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700699 BuildStackTraceVisitor build_trace_visitor(depth);
700 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700701
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700702 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700703
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700704 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700705 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700706 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700707 const Class* klass = method->GetDeclaringClass();
708 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700709 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700710 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700711
712 StackTraceElement* obj =
713 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700714 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700715 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700716 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700717 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700718 java_traces->Set(i, obj);
719 }
720 return java_traces;
721}
722
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700723void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700724 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700725 va_list args;
726 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700727 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700728 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700729
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700730 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700731 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700732 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700733 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700734 descriptor.erase(descriptor.length() - 1);
735
736 JNIEnv* env = GetJniEnv();
737 jclass exception_class = env->FindClass(descriptor.c_str());
738 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
739 int rc = env->ThrowNew(exception_class, msg.c_str());
740 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700741}
742
Elliott Hughes79082e32011-08-25 12:07:32 -0700743void Thread::ThrowOutOfMemoryError() {
744 UNIMPLEMENTED(FATAL);
745}
746
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700747Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
748 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
749 DCHECK(class_linker != NULL);
750
751 Frame cur_frame = GetTopOfStack();
752 for (int unwind_depth = 0; ; unwind_depth++) {
753 const Method* cur_method = cur_frame.GetMethod();
754 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
755 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
756
757 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
758 throw_pc,
759 dex_file,
760 class_linker);
761 if (handler_addr) {
762 *handler_pc = handler_addr;
763 return cur_frame;
764 } else {
765 // Check if we are at the last frame
766 if (cur_frame.HasNext()) {
767 cur_frame.Next();
768 } else {
769 // Either at the top of stack or next frame is native.
770 break;
771 }
772 }
773 }
774 *handler_pc = NULL;
775 return Frame();
776}
777
778void* Thread::FindExceptionHandlerInMethod(const Method* method,
779 void* throw_pc,
780 const DexFile& dex_file,
781 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700782 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700783 exception_ = NULL;
784
785 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700786 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700787 DexFile::CatchHandlerIterator iter;
788 for (iter = dex_file.dexFindCatchHandler(*code_item,
789 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
790 !iter.HasNext();
791 iter.Next()) {
792 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
793 DCHECK(klass != NULL);
794 if (exception_obj->InstanceOf(klass)) {
795 dex_pc = iter.Get().address_;
796 break;
797 }
798 }
799
800 exception_ = exception_obj;
801 if (iter.HasNext()) {
802 return NULL;
803 } else {
804 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
805 }
806}
807
Elliott Hughes410c0c82011-09-01 17:58:25 -0700808void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
809 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
810 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
811 jni_env_->locals.VisitRoots(visitor, arg);
812 jni_env_->monitors.VisitRoots(visitor, arg);
813 // visitThreadStack(visitor, thread, arg);
814 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
815}
816
Ian Rogersb033c752011-07-20 12:22:35 -0700817static const char* kStateNames[] = {
818 "New",
819 "Runnable",
820 "Blocked",
821 "Waiting",
822 "TimedWaiting",
823 "Native",
824 "Terminated",
825};
826std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
827 if (state >= Thread::kNew && state <= Thread::kTerminated) {
828 os << kStateNames[state-Thread::kNew];
829 } else {
830 os << "State[" << static_cast<int>(state) << "]";
831 }
832 return os;
833}
834
Elliott Hughes330304d2011-08-12 14:28:05 -0700835std::ostream& operator<<(std::ostream& os, const Thread& thread) {
836 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700837 << ",pthread_t=" << thread.GetImpl()
838 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700839 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700840 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700841 return os;
842}
843
Carl Shapiro61e019d2011-07-14 16:53:09 -0700844ThreadList* ThreadList::Create() {
845 return new ThreadList;
846}
847
Carl Shapirob5573532011-07-12 18:22:59 -0700848ThreadList::ThreadList() {
849 lock_ = Mutex::Create("ThreadList::Lock");
850}
851
852ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700853 if (Contains(Thread::Current())) {
854 Runtime::Current()->DetachCurrentThread();
855 }
856
857 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700858 // reach this point. This means that all daemon threads had been
859 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700860 // TODO: dump ThreadList if non-empty.
861 CHECK_EQ(list_.size(), 0U);
862
Carl Shapirob5573532011-07-12 18:22:59 -0700863 delete lock_;
864 lock_ = NULL;
865}
866
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700867bool ThreadList::Contains(Thread* thread) {
868 return find(list_.begin(), list_.end(), thread) != list_.end();
869}
870
Elliott Hughesd92bec42011-09-02 17:04:36 -0700871void ThreadList::Dump(std::ostream& os) {
872 MutexLock mu(lock_);
873 os << "DALVIK THREADS (" << list_.size() << "):\n";
874 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
875 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
876 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700877 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700878 }
879}
880
Carl Shapirob5573532011-07-12 18:22:59 -0700881void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700882 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700883 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700884 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700885 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700886}
887
Elliott Hughes02b48d12011-09-07 17:15:51 -0700888void ThreadList::Unregister() {
889 //LOG(INFO) << "ThreadList::Unregister() " << *Thread::Current();
Carl Shapirob5573532011-07-12 18:22:59 -0700890 MutexLock mu(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700891 Thread* self = Thread::Current();
892 CHECK(Contains(self));
893 list_.remove(self);
894 uint32_t thin_lock_id = self->thin_lock_id_;
895 delete self;
896 ReleaseThreadId(thin_lock_id);
Carl Shapirob5573532011-07-12 18:22:59 -0700897}
898
Elliott Hughes410c0c82011-09-01 17:58:25 -0700899void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
900 MutexLock mu(lock_);
901 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
902 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
903 (*it)->VisitRoots(visitor, arg);
904 }
905}
906
Elliott Hughes02b48d12011-09-07 17:15:51 -0700907uint32_t ThreadList::AllocThreadId() {
908 DCHECK(lock_->HaveLock());
909 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
910 if (!allocated_ids_[i]) {
911 allocated_ids_.set(i);
912 return i + 1; // Zero is reserved to mean "invalid".
913 }
914 }
915 LOG(FATAL) << "Out of internal thread ids";
916 return 0;
917}
918
919void ThreadList::ReleaseThreadId(uint32_t id) {
920 DCHECK(lock_->HaveLock());
921 --id; // Zero is reserved to mean "invalid".
922 DCHECK(allocated_ids_[id]) << id;
923 allocated_ids_.reset(id);
924}
925
Carl Shapirob5573532011-07-12 18:22:59 -0700926} // namespace