blob: d40451e3ad19556a48b2abda0f5ae54547f93214 [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
122 obj->MonitorExit();
123}
124
125// TODO: placeholder
126static void LockObjectFromCode(Thread* thread, Object* obj) {
127 // Need thread for ownership?
128 obj->MonitorEnter();
129}
130
buzbee3ea4ec52011-08-22 17:37:19 -0700131void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700132#if defined(__arm__)
133 pShlLong = art_shl_long;
134 pShrLong = art_shr_long;
135 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700136 pIdiv = __aeabi_idiv;
137 pIdivmod = __aeabi_idivmod;
138 pI2f = __aeabi_i2f;
139 pF2iz = __aeabi_f2iz;
140 pD2f = __aeabi_d2f;
141 pF2d = __aeabi_f2d;
142 pD2iz = __aeabi_d2iz;
143 pL2f = __aeabi_l2f;
144 pL2d = __aeabi_l2d;
145 pFadd = __aeabi_fadd;
146 pFsub = __aeabi_fsub;
147 pFdiv = __aeabi_fdiv;
148 pFmul = __aeabi_fmul;
149 pFmodf = fmodf;
150 pDadd = __aeabi_dadd;
151 pDsub = __aeabi_dsub;
152 pDdiv = __aeabi_ddiv;
153 pDmul = __aeabi_dmul;
154 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -0700155 pF2l = F2L;
156 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -0700157 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700158 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700159 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700160#endif
buzbeedfd3d702011-08-28 12:56:51 -0700161 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700162 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700163 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700164 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700165 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700166 pGet32Static = Field::Get32StaticFromCode;
167 pSet32Static = Field::Set32StaticFromCode;
168 pGet64Static = Field::Get64StaticFromCode;
169 pSet64Static = Field::Set64StaticFromCode;
170 pGetObjStatic = Field::GetObjStaticFromCode;
171 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700172 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
173 pThrowException = ThrowException;
174 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700175 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700176 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700177 pInstanceofNonTrivialFromCode = Object::InstanceOf;
178 pCheckCastFromCode = CheckCastFromCode;
179 pLockObjectFromCode = LockObjectFromCode;
180 pUnlockObjectFromCode = UnlockObjectFromCode;
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 Hughes02b48d12011-09-07 17:15:51 -0700209 DCHECK(HaveLock());
Carl Shapirob5573532011-07-12 18:22:59 -0700210 int result = pthread_mutex_unlock(&lock_impl_);
211 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700212 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700213}
214
Elliott Hughes02b48d12011-09-07 17:15:51 -0700215bool Mutex::HaveLock() {
216 return owner_ == Thread::Current();
217}
218
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700219void Frame::Next() {
220 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700221 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700222 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700223}
224
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700225uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700226 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700227 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700228 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700229}
230
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700231Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700232 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700233 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700234 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700235}
236
Carl Shapiro61e019d2011-07-14 16:53:09 -0700237void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700238 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700239 return NULL;
240}
241
Brian Carlstromb765be02011-08-17 23:54:10 -0700242Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700243 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
244
Brian Carlstromb765be02011-08-17 23:54:10 -0700245 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700246
247 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700248 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700249
250 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700251 errno = pthread_attr_init(&attr);
252 if (errno != 0) {
253 PLOG(FATAL) << "pthread_attr_init failed";
254 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700255
Elliott Hughese27955c2011-08-26 15:21:24 -0700256 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
257 if (errno != 0) {
258 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
259 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700260
Elliott Hughese27955c2011-08-26 15:21:24 -0700261 errno = pthread_attr_setstacksize(&attr, stack_size);
262 if (errno != 0) {
263 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
264 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700265
Elliott Hughese27955c2011-08-26 15:21:24 -0700266 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
267 if (errno != 0) {
268 PLOG(FATAL) << "pthread_create failed";
269 }
270
271 errno = pthread_attr_destroy(&attr);
272 if (errno != 0) {
273 PLOG(FATAL) << "pthread_attr_destroy failed";
274 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700275
Elliott Hughesdcc24742011-09-07 14:02:44 -0700276 // TODO: get the "daemon" field from the java.lang.Thread.
277 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
278
Carl Shapiro61e019d2011-07-14 16:53:09 -0700279 return new_thread;
280}
281
Elliott Hughesdcc24742011-09-07 14:02:44 -0700282Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700283 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700284 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700285
Elliott Hughes42ee1422011-09-06 12:33:32 -0700286 thread->tid_ = ::art::GetTid();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700287 thread->handle_ = pthread_self();
288 thread->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700289
290 thread->state_ = kRunnable;
291
Elliott Hughesdcc24742011-09-07 14:02:44 -0700292 SetThreadName(name);
293
Elliott Hughesa5780da2011-07-17 11:39:39 -0700294 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
295 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700296 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700297 }
298
Elliott Hughes75770752011-08-24 17:52:38 -0700299 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700300
Carl Shapiro61e019d2011-07-14 16:53:09 -0700301 return thread;
302}
303
Elliott Hughesa0957642011-09-02 14:27:33 -0700304void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700305 /*
306 * Get the java.lang.Thread object. This function gets called from
307 * some weird debug contexts, so it's possible that there's a GC in
308 * progress on some other thread. To decrease the chances of the
309 * thread object being moved out from under us, we add the reference
310 * to the tracked allocation list, which pins it in place.
311 *
312 * If threadObj is NULL, the thread is still in the process of being
313 * attached to the VM, and there's really nothing interesting to
314 * say about it yet.
315 */
316 os << "TODO: pin Thread before dumping\n";
317#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700318 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
319 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700320 LOGI("Can't dump thread %d: threadObj not set", threadId);
321 return;
322 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700323 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700324#endif
325
326 DumpState(os);
327 DumpStack(os);
328
329#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700330 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700331#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700332}
333
Elliott Hughesd92bec42011-09-02 17:04:36 -0700334std::string GetSchedulerGroup(pid_t tid) {
335 // /proc/<pid>/group looks like this:
336 // 2:devices:/
337 // 1:cpuacct,cpu:/
338 // We want the third field from the line whose second field contains the "cpu" token.
339 std::string cgroup_file;
340 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
341 return "";
342 }
343 std::vector<std::string> cgroup_lines;
344 Split(cgroup_file, '\n', cgroup_lines);
345 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
346 std::vector<std::string> cgroup_fields;
347 Split(cgroup_lines[i], ':', cgroup_fields);
348 std::vector<std::string> cgroups;
349 Split(cgroup_fields[1], ',', cgroups);
350 for (size_t i = 0; i < cgroups.size(); ++i) {
351 if (cgroups[i] == "cpu") {
352 return cgroup_fields[2].substr(1); // Skip the leading slash.
353 }
354 }
355 }
356 return "";
357}
358
359void Thread::DumpState(std::ostream& os) const {
360 std::string thread_name("unknown");
361 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700362
Elliott Hughesd92bec42011-09-02 17:04:36 -0700363#if 0 // TODO
364 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
365 threadName = dvmCreateCstrFromString(nameStr);
366 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700367#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700368 {
369 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
370 std::string stats;
371 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
372 size_t start = stats.find('(') + 1;
373 size_t end = stats.find(')') - start;
374 thread_name = stats.substr(start, end);
375 }
376 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700377 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700378#endif
379
380 int policy;
381 sched_param sp;
382 errno = pthread_getschedparam(handle_, &policy, &sp);
383 if (errno != 0) {
384 PLOG(FATAL) << "pthread_getschedparam failed";
385 }
386
387 std::string scheduler_group(GetSchedulerGroup(GetTid()));
388 if (scheduler_group.empty()) {
389 scheduler_group = "default";
390 }
391
392 std::string group_name("(null; initializing?)");
393#if 0
394 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
395 if (groupObj != NULL) {
396 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
397 groupName = dvmCreateCstrFromString(nameStr);
398 }
399#else
400 group_name = "TODO";
401#endif
402
403 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700404 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700405 os << " daemon";
406 }
407 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700408 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700409 << " " << state_ << "\n";
410
411 int suspend_count = 0; // TODO
412 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700413 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700414 os << " | group=\"" << group_name << "\""
415 << " sCount=" << suspend_count
416 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700417 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700418 << " self=" << reinterpret_cast<const void*>(this) << "\n";
419 os << " | sysTid=" << GetTid()
420 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
421 << " sched=" << policy << "/" << sp.sched_priority
422 << " cgrp=" << scheduler_group
423 << " handle=" << GetImpl() << "\n";
424
425 // Grab the scheduler stats for this thread.
426 std::string scheduler_stats;
427 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
428 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
429 } else {
430 scheduler_stats = "0 0 0";
431 }
432
433 int utime = 0;
434 int stime = 0;
435 int task_cpu = 0;
436 std::string stats;
437 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
438 // Skip the command, which may contain spaces.
439 stats = stats.substr(stats.find(')') + 2);
440 // Extract the three fields we care about.
441 std::vector<std::string> fields;
442 Split(stats, ' ', fields);
443 utime = strtoull(fields[11].c_str(), NULL, 10);
444 stime = strtoull(fields[12].c_str(), NULL, 10);
445 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
446 }
447
448 os << " | schedstat=( " << scheduler_stats << " )"
449 << " utm=" << utime
450 << " stm=" << stime
451 << " core=" << task_cpu
452 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
453}
454
455void Thread::DumpStack(std::ostream& os) const {
456 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700457}
458
Carl Shapirob5573532011-07-12 18:22:59 -0700459static void ThreadExitCheck(void* arg) {
460 LG << "Thread exit check";
461}
462
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700463bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700464 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700465 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
466 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700467 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700468 return false;
469 }
470
471 // Double-check the TLS slot allocation.
472 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700473 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700474 return false;
475 }
476
477 // TODO: initialize other locks and condition variables
478
479 return true;
480}
481
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700482void Thread::Shutdown() {
483 errno = pthread_key_delete(Thread::pthread_key_self_);
484 if (errno != 0) {
485 PLOG(WARNING) << "pthread_key_delete failed";
486 }
487}
488
Elliott Hughesdcc24742011-09-07 14:02:44 -0700489Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700490 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700491 top_of_managed_stack_(),
492 native_to_managed_record_(NULL),
493 top_sirt_(NULL),
494 jni_env_(NULL),
495 exception_(NULL),
496 suspend_count_(0),
497 class_loader_override_(NULL) {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700498 {
499 ThreadListLock mu;
500 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
501 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700502 InitFunctionPointers();
503}
504
Elliott Hughes02b48d12011-09-07 17:15:51 -0700505void MonitorExitVisitor(const Object* object, void*) {
506 Object* entered_monitor = const_cast<Object*>(object);
507 entered_monitor->MonitorExit();;
508}
509
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700510Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700511 // TODO: check we're not calling the JNI DetachCurrentThread function from
512 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
513
514 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
515 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
516
517 if (IsExceptionPending()) {
518 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
519 }
520
521 // TODO: ThreadGroup.removeThread(this);
522
523 // TODO: this.vmData = 0;
524
525 // TODO: say "bye" to the debugger.
526 //if (gDvm.debuggerConnected) {
527 // dvmDbgPostThreadDeath(self);
528 //}
529
530 // Thread.join() is implemented as an Object.wait() on the Thread.lock
531 // object. Signal anyone who is waiting.
532 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
533 //dvmLockObject(self, lock);
534 //dvmObjectNotifyAll(self, lock);
535 //dvmUnlockObject(self, lock);
536 //lock = NULL;
537
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700538 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700539 jni_env_ = NULL;
540
541 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700542}
543
Ian Rogers408f79a2011-08-23 18:22:33 -0700544size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700545 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700546 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700547 count += cur->NumberOfReferences();
548 }
549 return count;
550}
551
Ian Rogers408f79a2011-08-23 18:22:33 -0700552bool Thread::SirtContains(jobject obj) {
553 Object** sirt_entry = reinterpret_cast<Object**>(obj);
554 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700555 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700556 // A SIRT should always have a jobject/jclass as a native method is passed
557 // in a this pointer or a class
558 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700559 if ((&cur->References()[0] <= sirt_entry) &&
560 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700561 return true;
562 }
563 }
564 return false;
565}
566
Ian Rogers408f79a2011-08-23 18:22:33 -0700567Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700568 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700569 if (obj == NULL) {
570 return NULL;
571 }
572 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
573 IndirectRefKind kind = GetIndirectRefKind(ref);
574 Object* result;
575 switch (kind) {
576 case kLocal:
577 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700578 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700579 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700580 break;
581 }
582 case kGlobal:
583 {
584 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
585 IndirectReferenceTable& globals = vm->globals;
586 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700587 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700588 break;
589 }
590 case kWeakGlobal:
591 {
592 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
593 IndirectReferenceTable& weak_globals = vm->weak_globals;
594 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700595 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700596 if (result == kClearedJniWeakGlobal) {
597 // This is a special case where it's okay to return NULL.
598 return NULL;
599 }
600 break;
601 }
602 case kSirtOrInvalid:
603 default:
604 // TODO: make stack indirect reference table lookup more efficient
605 // Check if this is a local reference in the SIRT
606 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700607 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700608 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700609 // Assume an invalid local reference is actually a direct pointer.
610 result = reinterpret_cast<Object*>(obj);
611 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700612 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700613 }
614 }
615
616 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700617 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
618 JniAbort(NULL);
619 } else {
620 if (result != kInvalidIndirectRefObject) {
621 Heap::VerifyObject(result);
622 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700623 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700624 return result;
625}
626
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700627class CountStackDepthVisitor : public Thread::StackVisitor {
628 public:
629 CountStackDepthVisitor() : depth(0) {}
630 virtual bool VisitFrame(const Frame&) {
631 ++depth;
632 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700633 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700634
635 int GetDepth() const {
636 return depth;
637 }
638
639 private:
640 uint32_t depth;
641};
642
643class BuildStackTraceVisitor : public Thread::StackVisitor {
644 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700645 explicit BuildStackTraceVisitor(int depth) : count(0) {
646 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700647 pc_trace = IntArray::Alloc(depth);
648 }
649
650 virtual ~BuildStackTraceVisitor() {}
651
652 virtual bool VisitFrame(const Frame& frame) {
653 method_trace->Set(count, frame.GetMethod());
654 pc_trace->Set(count, frame.GetPC());
655 ++count;
656 return true;
657 }
658
659 const Method* GetMethod(uint32_t i) {
660 DCHECK(i < count);
661 return method_trace->Get(i);
662 }
663
664 uintptr_t GetPC(uint32_t i) {
665 DCHECK(i < count);
666 return pc_trace->Get(i);
667 }
668
669 private:
670 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700671 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700672 IntArray* pc_trace;
673};
674
675void Thread::WalkStack(StackVisitor* visitor) {
676 Frame frame = Thread::Current()->GetTopOfStack();
677 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
678 // CHECK(native_to_managed_record_ != NULL);
679 NativeToManagedRecord* record = native_to_managed_record_;
680
681 while (frame.GetSP()) {
682 for ( ; frame.GetMethod() != 0; frame.Next()) {
683 visitor->VisitFrame(frame);
684 }
685 if (record == NULL) {
686 break;
687 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700688 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 -0700689 record = record->link;
690 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700691}
692
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700693ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700694 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700695
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700696 CountStackDepthVisitor count_visitor;
697 WalkStack(&count_visitor);
698 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700699
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700700 BuildStackTraceVisitor build_trace_visitor(depth);
701 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700702
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700703 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700704
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700705 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700706 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700707 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700708 const Class* klass = method->GetDeclaringClass();
709 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700710 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700711 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700712
713 StackTraceElement* obj =
714 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700715 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700716 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700717 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700718 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700719 java_traces->Set(i, obj);
720 }
721 return java_traces;
722}
723
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700724void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700725 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700726 va_list args;
727 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700728 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700729 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700730
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700731 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700732 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700733 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700734 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700735 descriptor.erase(descriptor.length() - 1);
736
737 JNIEnv* env = GetJniEnv();
738 jclass exception_class = env->FindClass(descriptor.c_str());
739 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
740 int rc = env->ThrowNew(exception_class, msg.c_str());
741 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700742}
743
Elliott Hughes79082e32011-08-25 12:07:32 -0700744void Thread::ThrowOutOfMemoryError() {
745 UNIMPLEMENTED(FATAL);
746}
747
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700748Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
749 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
750 DCHECK(class_linker != NULL);
751
752 Frame cur_frame = GetTopOfStack();
753 for (int unwind_depth = 0; ; unwind_depth++) {
754 const Method* cur_method = cur_frame.GetMethod();
755 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
756 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
757
758 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
759 throw_pc,
760 dex_file,
761 class_linker);
762 if (handler_addr) {
763 *handler_pc = handler_addr;
764 return cur_frame;
765 } else {
766 // Check if we are at the last frame
767 if (cur_frame.HasNext()) {
768 cur_frame.Next();
769 } else {
770 // Either at the top of stack or next frame is native.
771 break;
772 }
773 }
774 }
775 *handler_pc = NULL;
776 return Frame();
777}
778
779void* Thread::FindExceptionHandlerInMethod(const Method* method,
780 void* throw_pc,
781 const DexFile& dex_file,
782 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700783 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700784 exception_ = NULL;
785
786 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700787 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700788 DexFile::CatchHandlerIterator iter;
789 for (iter = dex_file.dexFindCatchHandler(*code_item,
790 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
791 !iter.HasNext();
792 iter.Next()) {
793 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
794 DCHECK(klass != NULL);
795 if (exception_obj->InstanceOf(klass)) {
796 dex_pc = iter.Get().address_;
797 break;
798 }
799 }
800
801 exception_ = exception_obj;
802 if (iter.HasNext()) {
803 return NULL;
804 } else {
805 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
806 }
807}
808
Elliott Hughes410c0c82011-09-01 17:58:25 -0700809void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
810 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
811 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
812 jni_env_->locals.VisitRoots(visitor, arg);
813 jni_env_->monitors.VisitRoots(visitor, arg);
814 // visitThreadStack(visitor, thread, arg);
815 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
816}
817
Ian Rogersb033c752011-07-20 12:22:35 -0700818static const char* kStateNames[] = {
819 "New",
820 "Runnable",
821 "Blocked",
822 "Waiting",
823 "TimedWaiting",
824 "Native",
825 "Terminated",
826};
827std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
828 if (state >= Thread::kNew && state <= Thread::kTerminated) {
829 os << kStateNames[state-Thread::kNew];
830 } else {
831 os << "State[" << static_cast<int>(state) << "]";
832 }
833 return os;
834}
835
Elliott Hughes330304d2011-08-12 14:28:05 -0700836std::ostream& operator<<(std::ostream& os, const Thread& thread) {
837 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700838 << ",pthread_t=" << thread.GetImpl()
839 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700840 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700841 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700842 return os;
843}
844
Carl Shapiro61e019d2011-07-14 16:53:09 -0700845ThreadList* ThreadList::Create() {
846 return new ThreadList;
847}
848
Carl Shapirob5573532011-07-12 18:22:59 -0700849ThreadList::ThreadList() {
850 lock_ = Mutex::Create("ThreadList::Lock");
851}
852
853ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700854 if (Contains(Thread::Current())) {
855 Runtime::Current()->DetachCurrentThread();
856 }
857
858 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700859 // reach this point. This means that all daemon threads had been
860 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700861 // TODO: dump ThreadList if non-empty.
862 CHECK_EQ(list_.size(), 0U);
863
Carl Shapirob5573532011-07-12 18:22:59 -0700864 delete lock_;
865 lock_ = NULL;
866}
867
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700868bool ThreadList::Contains(Thread* thread) {
869 return find(list_.begin(), list_.end(), thread) != list_.end();
870}
871
Elliott Hughesd92bec42011-09-02 17:04:36 -0700872void ThreadList::Dump(std::ostream& os) {
873 MutexLock mu(lock_);
874 os << "DALVIK THREADS (" << list_.size() << "):\n";
875 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
876 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
877 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700878 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700879 }
880}
881
Carl Shapirob5573532011-07-12 18:22:59 -0700882void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700883 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700884 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700885 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700886 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700887}
888
Elliott Hughes02b48d12011-09-07 17:15:51 -0700889void ThreadList::Unregister() {
890 //LOG(INFO) << "ThreadList::Unregister() " << *Thread::Current();
Carl Shapirob5573532011-07-12 18:22:59 -0700891 MutexLock mu(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700892 Thread* self = Thread::Current();
893 CHECK(Contains(self));
894 list_.remove(self);
895 uint32_t thin_lock_id = self->thin_lock_id_;
896 delete self;
897 ReleaseThreadId(thin_lock_id);
Carl Shapirob5573532011-07-12 18:22:59 -0700898}
899
Elliott Hughes410c0c82011-09-01 17:58:25 -0700900void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
901 MutexLock mu(lock_);
902 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
903 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
904 (*it)->VisitRoots(visitor, arg);
905 }
906}
907
Elliott Hughes02b48d12011-09-07 17:15:51 -0700908uint32_t ThreadList::AllocThreadId() {
909 DCHECK(lock_->HaveLock());
910 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
911 if (!allocated_ids_[i]) {
912 allocated_ids_.set(i);
913 return i + 1; // Zero is reserved to mean "invalid".
914 }
915 }
916 LOG(FATAL) << "Out of internal thread ids";
917 return 0;
918}
919
920void ThreadList::ReleaseThreadId(uint32_t id) {
921 DCHECK(lock_->HaveLock());
922 --id; // Zero is reserved to mean "invalid".
923 DCHECK(allocated_ids_[id]) << id;
924 allocated_ids_.reset(id);
925}
926
Carl Shapirob5573532011-07-12 18:22:59 -0700927} // namespace