blob: f7938f1c958eaa471cfa68435d0e6fe58622dee1 [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
buzbee3ea4ec52011-08-22 17:37:19 -0700110void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700111#if defined(__arm__)
112 pShlLong = art_shl_long;
113 pShrLong = art_shr_long;
114 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700115 pIdiv = __aeabi_idiv;
116 pIdivmod = __aeabi_idivmod;
117 pI2f = __aeabi_i2f;
118 pF2iz = __aeabi_f2iz;
119 pD2f = __aeabi_d2f;
120 pF2d = __aeabi_f2d;
121 pD2iz = __aeabi_d2iz;
122 pL2f = __aeabi_l2f;
123 pL2d = __aeabi_l2d;
124 pFadd = __aeabi_fadd;
125 pFsub = __aeabi_fsub;
126 pFdiv = __aeabi_fdiv;
127 pFmul = __aeabi_fmul;
128 pFmodf = fmodf;
129 pDadd = __aeabi_dadd;
130 pDsub = __aeabi_dsub;
131 pDdiv = __aeabi_ddiv;
132 pDmul = __aeabi_dmul;
133 pFmod = fmod;
buzbee1b4c8592011-08-31 10:43:51 -0700134 pF2l = F2L;
135 pD2l = D2L;
buzbee7b1b86d2011-08-26 18:59:10 -0700136 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700137 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700138 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700139#endif
buzbeedfd3d702011-08-28 12:56:51 -0700140 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700141 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700142 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700143 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700144 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700145 pGet32Static = Field::Get32StaticFromCode;
146 pSet32Static = Field::Set32StaticFromCode;
147 pGet64Static = Field::Get64StaticFromCode;
148 pSet64Static = Field::Set64StaticFromCode;
149 pGetObjStatic = Field::GetObjStaticFromCode;
150 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700151 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
152 pThrowException = ThrowException;
153 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700154 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700155 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700156 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700157#if 0
buzbee1b4c8592011-08-31 10:43:51 -0700158bool (Thread::*pUnlockObject)(Thread*, Object*);
159int (Thread::*pInstanceofNonTrivialFromCode)(const Class*, const Class*);
buzbee1b4c8592011-08-31 10:43:51 -0700160bool (Thread::*pUnlockObjectFromCode)(Thread*, Object*);
161void (Thread::*pLockObjectFromCode)(Thread*, Object*);
buzbee3ea4ec52011-08-22 17:37:19 -0700162#endif
163}
164
Carl Shapirob5573532011-07-12 18:22:59 -0700165Mutex* Mutex::Create(const char* name) {
166 Mutex* mu = new Mutex(name);
167 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Elliott Hughes0f4c41d2011-09-04 14:58:03 -0700168 CHECK_EQ(result, 0);
Carl Shapirob5573532011-07-12 18:22:59 -0700169 return mu;
170}
171
172void Mutex::Lock() {
173 int result = pthread_mutex_lock(&lock_impl_);
174 CHECK_EQ(result, 0);
175 SetOwner(Thread::Current());
176}
177
178bool Mutex::TryLock() {
179 int result = pthread_mutex_lock(&lock_impl_);
180 if (result == EBUSY) {
181 return false;
182 } else {
183 CHECK_EQ(result, 0);
184 SetOwner(Thread::Current());
185 return true;
186 }
187}
188
189void Mutex::Unlock() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700190 DCHECK(HaveLock());
Carl Shapirob5573532011-07-12 18:22:59 -0700191 int result = pthread_mutex_unlock(&lock_impl_);
192 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700193 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700194}
195
Elliott Hughes02b48d12011-09-07 17:15:51 -0700196bool Mutex::HaveLock() {
197 return owner_ == Thread::Current();
198}
199
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700200void Frame::Next() {
201 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700202 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700203 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700204}
205
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700206uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700207 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700208 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700209 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700210}
211
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700212Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700213 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700214 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700215 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700216}
217
Carl Shapiro61e019d2011-07-14 16:53:09 -0700218void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700219 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700220 return NULL;
221}
222
Brian Carlstromb765be02011-08-17 23:54:10 -0700223Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700224 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
225
Brian Carlstromb765be02011-08-17 23:54:10 -0700226 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700227
228 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700229 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700230
231 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700232 errno = pthread_attr_init(&attr);
233 if (errno != 0) {
234 PLOG(FATAL) << "pthread_attr_init failed";
235 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700236
Elliott Hughese27955c2011-08-26 15:21:24 -0700237 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
238 if (errno != 0) {
239 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
240 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700241
Elliott Hughese27955c2011-08-26 15:21:24 -0700242 errno = pthread_attr_setstacksize(&attr, stack_size);
243 if (errno != 0) {
244 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
245 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700246
Elliott Hughese27955c2011-08-26 15:21:24 -0700247 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
248 if (errno != 0) {
249 PLOG(FATAL) << "pthread_create failed";
250 }
251
252 errno = pthread_attr_destroy(&attr);
253 if (errno != 0) {
254 PLOG(FATAL) << "pthread_attr_destroy failed";
255 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700256
Elliott Hughesdcc24742011-09-07 14:02:44 -0700257 // TODO: get the "daemon" field from the java.lang.Thread.
258 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
259
Carl Shapiro61e019d2011-07-14 16:53:09 -0700260 return new_thread;
261}
262
Elliott Hughesdcc24742011-09-07 14:02:44 -0700263Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700264 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700265 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700266
Elliott Hughes42ee1422011-09-06 12:33:32 -0700267 thread->tid_ = ::art::GetTid();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700268 thread->handle_ = pthread_self();
269 thread->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700270
271 thread->state_ = kRunnable;
272
Elliott Hughesdcc24742011-09-07 14:02:44 -0700273 SetThreadName(name);
274
Elliott Hughesa5780da2011-07-17 11:39:39 -0700275 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
276 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700277 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700278 }
279
Elliott Hughes75770752011-08-24 17:52:38 -0700280 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700281
Carl Shapiro61e019d2011-07-14 16:53:09 -0700282 return thread;
283}
284
Elliott Hughesa0957642011-09-02 14:27:33 -0700285void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700286 /*
287 * Get the java.lang.Thread object. This function gets called from
288 * some weird debug contexts, so it's possible that there's a GC in
289 * progress on some other thread. To decrease the chances of the
290 * thread object being moved out from under us, we add the reference
291 * to the tracked allocation list, which pins it in place.
292 *
293 * If threadObj is NULL, the thread is still in the process of being
294 * attached to the VM, and there's really nothing interesting to
295 * say about it yet.
296 */
297 os << "TODO: pin Thread before dumping\n";
298#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700299 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
300 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700301 LOGI("Can't dump thread %d: threadObj not set", threadId);
302 return;
303 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700304 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700305#endif
306
307 DumpState(os);
308 DumpStack(os);
309
310#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700311 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700312#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700313}
314
Elliott Hughesd92bec42011-09-02 17:04:36 -0700315std::string GetSchedulerGroup(pid_t tid) {
316 // /proc/<pid>/group looks like this:
317 // 2:devices:/
318 // 1:cpuacct,cpu:/
319 // We want the third field from the line whose second field contains the "cpu" token.
320 std::string cgroup_file;
321 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
322 return "";
323 }
324 std::vector<std::string> cgroup_lines;
325 Split(cgroup_file, '\n', cgroup_lines);
326 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
327 std::vector<std::string> cgroup_fields;
328 Split(cgroup_lines[i], ':', cgroup_fields);
329 std::vector<std::string> cgroups;
330 Split(cgroup_fields[1], ',', cgroups);
331 for (size_t i = 0; i < cgroups.size(); ++i) {
332 if (cgroups[i] == "cpu") {
333 return cgroup_fields[2].substr(1); // Skip the leading slash.
334 }
335 }
336 }
337 return "";
338}
339
340void Thread::DumpState(std::ostream& os) const {
341 std::string thread_name("unknown");
342 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700343
Elliott Hughesd92bec42011-09-02 17:04:36 -0700344#if 0 // TODO
345 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
346 threadName = dvmCreateCstrFromString(nameStr);
347 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700348#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700349 {
350 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
351 std::string stats;
352 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
353 size_t start = stats.find('(') + 1;
354 size_t end = stats.find(')') - start;
355 thread_name = stats.substr(start, end);
356 }
357 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700358 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700359#endif
360
361 int policy;
362 sched_param sp;
363 errno = pthread_getschedparam(handle_, &policy, &sp);
364 if (errno != 0) {
365 PLOG(FATAL) << "pthread_getschedparam failed";
366 }
367
368 std::string scheduler_group(GetSchedulerGroup(GetTid()));
369 if (scheduler_group.empty()) {
370 scheduler_group = "default";
371 }
372
373 std::string group_name("(null; initializing?)");
374#if 0
375 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
376 if (groupObj != NULL) {
377 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
378 groupName = dvmCreateCstrFromString(nameStr);
379 }
380#else
381 group_name = "TODO";
382#endif
383
384 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700385 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700386 os << " daemon";
387 }
388 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700389 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700390 << " " << state_ << "\n";
391
392 int suspend_count = 0; // TODO
393 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700394 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700395 os << " | group=\"" << group_name << "\""
396 << " sCount=" << suspend_count
397 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700398 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700399 << " self=" << reinterpret_cast<const void*>(this) << "\n";
400 os << " | sysTid=" << GetTid()
401 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
402 << " sched=" << policy << "/" << sp.sched_priority
403 << " cgrp=" << scheduler_group
404 << " handle=" << GetImpl() << "\n";
405
406 // Grab the scheduler stats for this thread.
407 std::string scheduler_stats;
408 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
409 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
410 } else {
411 scheduler_stats = "0 0 0";
412 }
413
414 int utime = 0;
415 int stime = 0;
416 int task_cpu = 0;
417 std::string stats;
418 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
419 // Skip the command, which may contain spaces.
420 stats = stats.substr(stats.find(')') + 2);
421 // Extract the three fields we care about.
422 std::vector<std::string> fields;
423 Split(stats, ' ', fields);
424 utime = strtoull(fields[11].c_str(), NULL, 10);
425 stime = strtoull(fields[12].c_str(), NULL, 10);
426 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
427 }
428
429 os << " | schedstat=( " << scheduler_stats << " )"
430 << " utm=" << utime
431 << " stm=" << stime
432 << " core=" << task_cpu
433 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
434}
435
436void Thread::DumpStack(std::ostream& os) const {
437 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700438}
439
Carl Shapirob5573532011-07-12 18:22:59 -0700440static void ThreadExitCheck(void* arg) {
441 LG << "Thread exit check";
442}
443
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700444bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700445 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700446 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
447 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700448 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700449 return false;
450 }
451
452 // Double-check the TLS slot allocation.
453 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700454 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700455 return false;
456 }
457
458 // TODO: initialize other locks and condition variables
459
460 return true;
461}
462
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700463void Thread::Shutdown() {
464 errno = pthread_key_delete(Thread::pthread_key_self_);
465 if (errno != 0) {
466 PLOG(WARNING) << "pthread_key_delete failed";
467 }
468}
469
Elliott Hughesdcc24742011-09-07 14:02:44 -0700470Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700471 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700472 top_of_managed_stack_(),
473 native_to_managed_record_(NULL),
474 top_sirt_(NULL),
475 jni_env_(NULL),
476 exception_(NULL),
477 suspend_count_(0),
478 class_loader_override_(NULL) {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700479 {
480 ThreadListLock mu;
481 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
482 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700483 InitFunctionPointers();
484}
485
Elliott Hughes02b48d12011-09-07 17:15:51 -0700486void MonitorExitVisitor(const Object* object, void*) {
487 Object* entered_monitor = const_cast<Object*>(object);
488 entered_monitor->MonitorExit();;
489}
490
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700491Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700492 // TODO: check we're not calling the JNI DetachCurrentThread function from
493 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
494
495 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
496 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
497
498 if (IsExceptionPending()) {
499 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
500 }
501
502 // TODO: ThreadGroup.removeThread(this);
503
504 // TODO: this.vmData = 0;
505
506 // TODO: say "bye" to the debugger.
507 //if (gDvm.debuggerConnected) {
508 // dvmDbgPostThreadDeath(self);
509 //}
510
511 // Thread.join() is implemented as an Object.wait() on the Thread.lock
512 // object. Signal anyone who is waiting.
513 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
514 //dvmLockObject(self, lock);
515 //dvmObjectNotifyAll(self, lock);
516 //dvmUnlockObject(self, lock);
517 //lock = NULL;
518
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700519 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700520 jni_env_ = NULL;
521
522 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700523}
524
Ian Rogers408f79a2011-08-23 18:22:33 -0700525size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700526 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700527 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700528 count += cur->NumberOfReferences();
529 }
530 return count;
531}
532
Ian Rogers408f79a2011-08-23 18:22:33 -0700533bool Thread::SirtContains(jobject obj) {
534 Object** sirt_entry = reinterpret_cast<Object**>(obj);
535 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700536 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700537 // A SIRT should always have a jobject/jclass as a native method is passed
538 // in a this pointer or a class
539 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700540 if ((&cur->References()[0] <= sirt_entry) &&
541 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700542 return true;
543 }
544 }
545 return false;
546}
547
Ian Rogers408f79a2011-08-23 18:22:33 -0700548Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700549 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700550 if (obj == NULL) {
551 return NULL;
552 }
553 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
554 IndirectRefKind kind = GetIndirectRefKind(ref);
555 Object* result;
556 switch (kind) {
557 case kLocal:
558 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700559 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700560 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700561 break;
562 }
563 case kGlobal:
564 {
565 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
566 IndirectReferenceTable& globals = vm->globals;
567 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700568 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700569 break;
570 }
571 case kWeakGlobal:
572 {
573 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
574 IndirectReferenceTable& weak_globals = vm->weak_globals;
575 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700576 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700577 if (result == kClearedJniWeakGlobal) {
578 // This is a special case where it's okay to return NULL.
579 return NULL;
580 }
581 break;
582 }
583 case kSirtOrInvalid:
584 default:
585 // TODO: make stack indirect reference table lookup more efficient
586 // Check if this is a local reference in the SIRT
587 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700588 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700589 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700590 // Assume an invalid local reference is actually a direct pointer.
591 result = reinterpret_cast<Object*>(obj);
592 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700593 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700594 }
595 }
596
597 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700598 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
599 JniAbort(NULL);
600 } else {
601 if (result != kInvalidIndirectRefObject) {
602 Heap::VerifyObject(result);
603 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700604 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700605 return result;
606}
607
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700608class CountStackDepthVisitor : public Thread::StackVisitor {
609 public:
610 CountStackDepthVisitor() : depth(0) {}
611 virtual bool VisitFrame(const Frame&) {
612 ++depth;
613 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700614 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700615
616 int GetDepth() const {
617 return depth;
618 }
619
620 private:
621 uint32_t depth;
622};
623
624class BuildStackTraceVisitor : public Thread::StackVisitor {
625 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700626 explicit BuildStackTraceVisitor(int depth) : count(0) {
627 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700628 pc_trace = IntArray::Alloc(depth);
629 }
630
631 virtual ~BuildStackTraceVisitor() {}
632
633 virtual bool VisitFrame(const Frame& frame) {
634 method_trace->Set(count, frame.GetMethod());
635 pc_trace->Set(count, frame.GetPC());
636 ++count;
637 return true;
638 }
639
640 const Method* GetMethod(uint32_t i) {
641 DCHECK(i < count);
642 return method_trace->Get(i);
643 }
644
645 uintptr_t GetPC(uint32_t i) {
646 DCHECK(i < count);
647 return pc_trace->Get(i);
648 }
649
650 private:
651 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700652 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700653 IntArray* pc_trace;
654};
655
656void Thread::WalkStack(StackVisitor* visitor) {
657 Frame frame = Thread::Current()->GetTopOfStack();
658 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
659 // CHECK(native_to_managed_record_ != NULL);
660 NativeToManagedRecord* record = native_to_managed_record_;
661
662 while (frame.GetSP()) {
663 for ( ; frame.GetMethod() != 0; frame.Next()) {
664 visitor->VisitFrame(frame);
665 }
666 if (record == NULL) {
667 break;
668 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700669 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 -0700670 record = record->link;
671 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700672}
673
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700674ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700675 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700676
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700677 CountStackDepthVisitor count_visitor;
678 WalkStack(&count_visitor);
679 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700680
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700681 BuildStackTraceVisitor build_trace_visitor(depth);
682 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700683
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700684 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700685
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700686 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700687 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700688 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700689 const Class* klass = method->GetDeclaringClass();
690 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700691 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700692 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700693
694 StackTraceElement* obj =
695 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700696 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700697 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700698 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700699 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700700 java_traces->Set(i, obj);
701 }
702 return java_traces;
703}
704
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700705void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700706 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700707 va_list args;
708 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700709 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700710 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700711
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700712 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700713 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700714 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700715 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700716 descriptor.erase(descriptor.length() - 1);
717
718 JNIEnv* env = GetJniEnv();
719 jclass exception_class = env->FindClass(descriptor.c_str());
720 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
721 int rc = env->ThrowNew(exception_class, msg.c_str());
722 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700723}
724
Elliott Hughes79082e32011-08-25 12:07:32 -0700725void Thread::ThrowOutOfMemoryError() {
726 UNIMPLEMENTED(FATAL);
727}
728
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700729Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
730 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
731 DCHECK(class_linker != NULL);
732
733 Frame cur_frame = GetTopOfStack();
734 for (int unwind_depth = 0; ; unwind_depth++) {
735 const Method* cur_method = cur_frame.GetMethod();
736 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
737 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
738
739 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
740 throw_pc,
741 dex_file,
742 class_linker);
743 if (handler_addr) {
744 *handler_pc = handler_addr;
745 return cur_frame;
746 } else {
747 // Check if we are at the last frame
748 if (cur_frame.HasNext()) {
749 cur_frame.Next();
750 } else {
751 // Either at the top of stack or next frame is native.
752 break;
753 }
754 }
755 }
756 *handler_pc = NULL;
757 return Frame();
758}
759
760void* Thread::FindExceptionHandlerInMethod(const Method* method,
761 void* throw_pc,
762 const DexFile& dex_file,
763 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700764 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700765 exception_ = NULL;
766
767 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700768 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700769 DexFile::CatchHandlerIterator iter;
770 for (iter = dex_file.dexFindCatchHandler(*code_item,
771 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
772 !iter.HasNext();
773 iter.Next()) {
774 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
775 DCHECK(klass != NULL);
776 if (exception_obj->InstanceOf(klass)) {
777 dex_pc = iter.Get().address_;
778 break;
779 }
780 }
781
782 exception_ = exception_obj;
783 if (iter.HasNext()) {
784 return NULL;
785 } else {
786 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
787 }
788}
789
Elliott Hughes410c0c82011-09-01 17:58:25 -0700790void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
791 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
792 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
793 jni_env_->locals.VisitRoots(visitor, arg);
794 jni_env_->monitors.VisitRoots(visitor, arg);
795 // visitThreadStack(visitor, thread, arg);
796 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
797}
798
Ian Rogersb033c752011-07-20 12:22:35 -0700799static const char* kStateNames[] = {
800 "New",
801 "Runnable",
802 "Blocked",
803 "Waiting",
804 "TimedWaiting",
805 "Native",
806 "Terminated",
807};
808std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
809 if (state >= Thread::kNew && state <= Thread::kTerminated) {
810 os << kStateNames[state-Thread::kNew];
811 } else {
812 os << "State[" << static_cast<int>(state) << "]";
813 }
814 return os;
815}
816
Elliott Hughes330304d2011-08-12 14:28:05 -0700817std::ostream& operator<<(std::ostream& os, const Thread& thread) {
818 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700819 << ",pthread_t=" << thread.GetImpl()
820 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700821 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -0700822 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700823 return os;
824}
825
Carl Shapiro61e019d2011-07-14 16:53:09 -0700826ThreadList* ThreadList::Create() {
827 return new ThreadList;
828}
829
Carl Shapirob5573532011-07-12 18:22:59 -0700830ThreadList::ThreadList() {
831 lock_ = Mutex::Create("ThreadList::Lock");
832}
833
834ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700835 if (Contains(Thread::Current())) {
836 Runtime::Current()->DetachCurrentThread();
837 }
838
839 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700840 // reach this point. This means that all daemon threads had been
841 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700842 // TODO: dump ThreadList if non-empty.
843 CHECK_EQ(list_.size(), 0U);
844
Carl Shapirob5573532011-07-12 18:22:59 -0700845 delete lock_;
846 lock_ = NULL;
847}
848
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700849bool ThreadList::Contains(Thread* thread) {
850 return find(list_.begin(), list_.end(), thread) != list_.end();
851}
852
Elliott Hughesd92bec42011-09-02 17:04:36 -0700853void ThreadList::Dump(std::ostream& os) {
854 MutexLock mu(lock_);
855 os << "DALVIK THREADS (" << list_.size() << "):\n";
856 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
857 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
858 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700859 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700860 }
861}
862
Carl Shapirob5573532011-07-12 18:22:59 -0700863void ThreadList::Register(Thread* thread) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700864 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -0700865 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700866 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700867 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -0700868}
869
Elliott Hughes02b48d12011-09-07 17:15:51 -0700870void ThreadList::Unregister() {
871 //LOG(INFO) << "ThreadList::Unregister() " << *Thread::Current();
Carl Shapirob5573532011-07-12 18:22:59 -0700872 MutexLock mu(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700873 Thread* self = Thread::Current();
874 CHECK(Contains(self));
875 list_.remove(self);
876 uint32_t thin_lock_id = self->thin_lock_id_;
877 delete self;
878 ReleaseThreadId(thin_lock_id);
Carl Shapirob5573532011-07-12 18:22:59 -0700879}
880
Elliott Hughes410c0c82011-09-01 17:58:25 -0700881void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
882 MutexLock mu(lock_);
883 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
884 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
885 (*it)->VisitRoots(visitor, arg);
886 }
887}
888
Elliott Hughes02b48d12011-09-07 17:15:51 -0700889uint32_t ThreadList::AllocThreadId() {
890 DCHECK(lock_->HaveLock());
891 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
892 if (!allocated_ids_[i]) {
893 allocated_ids_.set(i);
894 return i + 1; // Zero is reserved to mean "invalid".
895 }
896 }
897 LOG(FATAL) << "Out of internal thread ids";
898 return 0;
899}
900
901void ThreadList::ReleaseThreadId(uint32_t id) {
902 DCHECK(lock_->HaveLock());
903 --id; // Zero is reserved to mean "invalid".
904 DCHECK(allocated_ids_[id]) << id;
905 allocated_ids_.reset(id);
906}
907
Carl Shapirob5573532011-07-12 18:22:59 -0700908} // namespace