blob: 2e7b6a9a303f895e7775bd446f1f3cf42b935cac [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>
Carl Shapirob5573532011-07-12 18:22:59 -07007#include <algorithm>
Elliott Hugheseb4f6142011-07-15 17:43:51 -07008#include <cerrno>
Carl Shapirob5573532011-07-12 18:22:59 -07009#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070010
Elliott Hughesa5b897e2011-08-16 11:33:06 -070011#include "class_linker.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070012#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070013#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070014#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070015#include "runtime.h"
16#include "utils.h"
buzbee54330722011-08-23 16:46:55 -070017#include "runtime_support.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
19namespace art {
20
Elliott Hughese27955c2011-08-26 15:21:24 -070021/* desktop Linux needs a little help with gettid() */
22#if !defined(HAVE_ANDROID_OS)
23#define __KERNEL__
24# include <linux/unistd.h>
25#ifdef _syscall0
26_syscall0(pid_t, gettid)
27#else
28pid_t gettid() { return syscall(__NR_gettid);}
29#endif
30#undef __KERNEL__
31#endif
32
Carl Shapirob5573532011-07-12 18:22:59 -070033pthread_key_t Thread::pthread_key_self_;
34
buzbee3ea4ec52011-08-22 17:37:19 -070035void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -070036#if defined(__arm__)
37 pShlLong = art_shl_long;
38 pShrLong = art_shr_long;
39 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -070040 pIdiv = __aeabi_idiv;
41 pIdivmod = __aeabi_idivmod;
42 pI2f = __aeabi_i2f;
43 pF2iz = __aeabi_f2iz;
44 pD2f = __aeabi_d2f;
45 pF2d = __aeabi_f2d;
46 pD2iz = __aeabi_d2iz;
47 pL2f = __aeabi_l2f;
48 pL2d = __aeabi_l2d;
49 pFadd = __aeabi_fadd;
50 pFsub = __aeabi_fsub;
51 pFdiv = __aeabi_fdiv;
52 pFmul = __aeabi_fmul;
53 pFmodf = fmodf;
54 pDadd = __aeabi_dadd;
55 pDsub = __aeabi_dsub;
56 pDdiv = __aeabi_ddiv;
57 pDmul = __aeabi_dmul;
58 pFmod = fmod;
59 pArtF2l = artF2L;
60 pArtD2l = artD2L;
61 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -070062 pLmul = __aeabi_lmul;
buzbee54330722011-08-23 16:46:55 -070063#endif
buzbeedfd3d702011-08-28 12:56:51 -070064 pAllocFromCode = Array::AllocFromCode;
65 pNewInstanceFromCode = Class::NewInstanceFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -070066 pMemcpy = memcpy;
buzbeee6d61962011-08-27 11:58:19 -070067 pArtHandleFillArrayDataNoThrow = artHandleFillArrayDataNoThrow;
buzbeee1931742011-08-28 21:15:53 -070068 pGet32Static = Field::Get32StaticFromCode;
69 pSet32Static = Field::Set32StaticFromCode;
70 pGet64Static = Field::Get64StaticFromCode;
71 pSet64Static = Field::Set64StaticFromCode;
72 pGetObjStatic = Field::GetObjStaticFromCode;
73 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -070074#if 0
buzbee3ea4ec52011-08-22 17:37:19 -070075bool (Thread::*pArtUnlockObject)(struct Thread*, struct Object*);
76bool (Thread::*pArtCanPutArrayElementNoThrow)(const struct ClassObject*,
77 const struct ClassObject*);
78int (Thread::*pArtInstanceofNonTrivialNoThrow)
79 (const struct ClassObject*, const struct ClassObject*);
80int (Thread::*pArtInstanceofNonTrivial) (const struct ClassObject*,
81 const struct ClassObject*);
82struct Method* (Thread::*pArtFindInterfaceMethodInCache)(ClassObject*, uint32_t,
83 const struct Method*, struct DvmDex*);
84bool (Thread::*pArtUnlockObjectNoThrow)(struct Thread*, struct Object*);
85void (Thread::*pArtLockObjectNoThrow)(struct Thread*, struct Object*);
86struct Object* (Thread::*pArtAllocObjectNoThrow)(struct ClassObject*, int);
87void (Thread::*pArtThrowException)(struct Thread*, struct Object*);
88bool (Thread::*pArtHandleFillArrayDataNoThrow)(struct ArrayObject*, const uint16_t*);
89#endif
90}
91
Carl Shapirob5573532011-07-12 18:22:59 -070092Mutex* Mutex::Create(const char* name) {
93 Mutex* mu = new Mutex(name);
94 int result = pthread_mutex_init(&mu->lock_impl_, NULL);
Ian Rogersb033c752011-07-20 12:22:35 -070095 CHECK_EQ(0, result);
Carl Shapirob5573532011-07-12 18:22:59 -070096 return mu;
97}
98
99void Mutex::Lock() {
100 int result = pthread_mutex_lock(&lock_impl_);
101 CHECK_EQ(result, 0);
102 SetOwner(Thread::Current());
103}
104
105bool Mutex::TryLock() {
106 int result = pthread_mutex_lock(&lock_impl_);
107 if (result == EBUSY) {
108 return false;
109 } else {
110 CHECK_EQ(result, 0);
111 SetOwner(Thread::Current());
112 return true;
113 }
114}
115
116void Mutex::Unlock() {
117 CHECK(GetOwner() == Thread::Current());
118 int result = pthread_mutex_unlock(&lock_impl_);
119 CHECK_EQ(result, 0);
Elliott Hughesf4c21c92011-08-19 17:31:31 -0700120 SetOwner(NULL);
Carl Shapirob5573532011-07-12 18:22:59 -0700121}
122
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700123void Frame::Next() {
124 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700125 GetMethod()->GetFrameSizeInBytes();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700126 sp_ = reinterpret_cast<const Method**>(next_sp);
127}
128
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700129uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700130 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700131 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700132 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700133}
134
135const Method* Frame::NextMethod() const {
136 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700137 GetMethod()->GetFrameSizeInBytes();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700138 return reinterpret_cast<const Method*>(next_sp);
139}
140
Carl Shapiro61e019d2011-07-14 16:53:09 -0700141void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700142 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700143 return NULL;
144}
145
Brian Carlstromb765be02011-08-17 23:54:10 -0700146Thread* Thread::Create(const Runtime* runtime) {
147 size_t stack_size = runtime->GetStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700148
149 Thread* new_thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700150 new_thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700151
152 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700153 errno = pthread_attr_init(&attr);
154 if (errno != 0) {
155 PLOG(FATAL) << "pthread_attr_init failed";
156 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700157
Elliott Hughese27955c2011-08-26 15:21:24 -0700158 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
159 if (errno != 0) {
160 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
161 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700162
Elliott Hughese27955c2011-08-26 15:21:24 -0700163 errno = pthread_attr_setstacksize(&attr, stack_size);
164 if (errno != 0) {
165 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
166 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700167
Elliott Hughese27955c2011-08-26 15:21:24 -0700168 errno = pthread_create(&new_thread->handle_, &attr, ThreadStart, new_thread);
169 if (errno != 0) {
170 PLOG(FATAL) << "pthread_create failed";
171 }
172
173 errno = pthread_attr_destroy(&attr);
174 if (errno != 0) {
175 PLOG(FATAL) << "pthread_attr_destroy failed";
176 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700177
178 return new_thread;
179}
180
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700181Thread* Thread::Attach(const Runtime* runtime) {
Carl Shapiro61e019d2011-07-14 16:53:09 -0700182 Thread* thread = new Thread;
Ian Rogers176f59c2011-07-20 13:14:11 -0700183 thread->InitCpu();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700184
185 thread->handle_ = pthread_self();
186
187 thread->state_ = kRunnable;
188
Elliott Hughesa5780da2011-07-17 11:39:39 -0700189 errno = pthread_setspecific(Thread::pthread_key_self_, thread);
190 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700191 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700192 }
193
Elliott Hughes75770752011-08-24 17:52:38 -0700194 thread->jni_env_ = new JNIEnvExt(thread, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700195
Carl Shapiro61e019d2011-07-14 16:53:09 -0700196 return thread;
197}
198
Elliott Hughese27955c2011-08-26 15:21:24 -0700199pid_t Thread::GetTid() const {
200 return gettid();
201}
202
Carl Shapirob5573532011-07-12 18:22:59 -0700203static void ThreadExitCheck(void* arg) {
204 LG << "Thread exit check";
205}
206
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700207bool Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700208 // Allocate a TLS slot.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700209 errno = pthread_key_create(&Thread::pthread_key_self_, ThreadExitCheck);
210 if (errno != 0) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700211 PLOG(WARNING) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700212 return false;
213 }
214
215 // Double-check the TLS slot allocation.
216 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hugheseb4f6142011-07-15 17:43:51 -0700217 LOG(WARNING) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700218 return false;
219 }
220
221 // TODO: initialize other locks and condition variables
222
223 return true;
224}
225
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700226void Thread::Shutdown() {
227 errno = pthread_key_delete(Thread::pthread_key_self_);
228 if (errno != 0) {
229 PLOG(WARNING) << "pthread_key_delete failed";
230 }
231}
232
233Thread::~Thread() {
234 delete jni_env_;
235}
236
Ian Rogers408f79a2011-08-23 18:22:33 -0700237size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700238 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700239 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700240 count += cur->NumberOfReferences();
241 }
242 return count;
243}
244
Ian Rogers408f79a2011-08-23 18:22:33 -0700245bool Thread::SirtContains(jobject obj) {
246 Object** sirt_entry = reinterpret_cast<Object**>(obj);
247 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700248 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700249 // A SIRT should always have a jobject/jclass as a native method is passed
250 // in a this pointer or a class
251 DCHECK_GT(num_refs, 0u);
252 if ((&cur->References()[0] >= sirt_entry) &&
253 (sirt_entry <= (&cur->References()[num_refs-1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700254 return true;
255 }
256 }
257 return false;
258}
259
Ian Rogers408f79a2011-08-23 18:22:33 -0700260Object* Thread::DecodeJObject(jobject obj) {
261 // TODO: Only allowed to hold Object* when in the runnable state
262 // DCHECK(state_ == kRunnable);
263 if (obj == NULL) {
264 return NULL;
265 }
266 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
267 IndirectRefKind kind = GetIndirectRefKind(ref);
268 Object* result;
269 switch (kind) {
270 case kLocal:
271 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700272 IndirectReferenceTable& locals = jni_env_->locals;
Ian Rogers408f79a2011-08-23 18:22:33 -0700273 result = locals.Get(ref);
274 break;
275 }
276 case kGlobal:
277 {
278 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
279 IndirectReferenceTable& globals = vm->globals;
280 MutexLock mu(vm->globals_lock);
281 result = globals.Get(ref);
282 break;
283 }
284 case kWeakGlobal:
285 {
286 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
287 IndirectReferenceTable& weak_globals = vm->weak_globals;
288 MutexLock mu(vm->weak_globals_lock);
289 result = weak_globals.Get(ref);
290 if (result == kClearedJniWeakGlobal) {
291 // This is a special case where it's okay to return NULL.
292 return NULL;
293 }
294 break;
295 }
296 case kSirtOrInvalid:
297 default:
298 // TODO: make stack indirect reference table lookup more efficient
299 // Check if this is a local reference in the SIRT
300 if (SirtContains(obj)) {
301 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
302 } else if (false /*gDvmJni.workAroundAppJniBugs*/) { // TODO
303 // Assume an invalid local reference is actually a direct pointer.
304 result = reinterpret_cast<Object*>(obj);
305 } else {
306 LOG(FATAL) << "Invalid indirect reference " << obj;
307 result = reinterpret_cast<Object*>(kInvalidIndirectRefObject);
308 }
309 }
310
311 if (result == NULL) {
312 LOG(FATAL) << "JNI ERROR (app bug): use of deleted " << kind << ": "
313 << obj;
314 }
315 Heap::VerifyObject(result);
316 return result;
317}
318
Shih-wei Liao44175362011-08-28 16:59:17 -0700319// TODO: Compute length
320bool Thread::WalkStack(uint16_t length,
321 ObjectArray<Method>* method_trace,
322 IntArray* pc_trace) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700323 Frame frame = Thread::Current()->GetTopOfStack();
Shih-wei Liao44175362011-08-28 16:59:17 -0700324
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700325 for (uint16_t i = 0; i < length && frame.HasNext(); ++i, frame.Next()) {
Shih-wei Liao44175362011-08-28 16:59:17 -0700326 method_trace->Set(i, (Method*) frame.GetMethod());
327 pc_trace->Set(i, frame.GetPC());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700328 }
Shih-wei Liao44175362011-08-28 16:59:17 -0700329 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700330}
331
Shih-wei Liao44175362011-08-28 16:59:17 -0700332ObjectArray<StackTraceElement>* Thread::AllocStackTrace(uint16_t length) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700333 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700334
335 ObjectArray<Method>* method_trace = class_linker->AllocObjectArray<Method>(length);
336 IntArray* pc_trace = IntArray::Alloc(length);
337
338 WalkStack(length, method_trace, pc_trace);
339
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700340 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(length);
341
342 for (uint16_t i = 0; i < length; ++i) {
343 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao44175362011-08-28 16:59:17 -0700344 const Method* method = method_trace->Get(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700345 const Class* klass = method->GetDeclaringClass();
346 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700347 String* readable_descriptor = String::AllocFromModifiedUtf8(
348 PrettyDescriptor(klass->GetDescriptor()).c_str()
349 );
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700350
351 StackTraceElement* obj =
352 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700353 method->GetName(),
354 String::AllocFromModifiedUtf8(klass->source_file_),
355 dex_file.GetLineNumFromPC(method,
356 method->ToDexPC(pc_trace->Get(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700357 java_traces->Set(i, obj);
358 }
359 return java_traces;
360}
361
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700362void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700363 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700364 va_list args;
365 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700366 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700367 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700368
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700369 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
370 CHECK(exception_class_descriptor[0] == 'L');
371 std::string descriptor(exception_class_descriptor + 1);
372 CHECK(descriptor[descriptor.length() - 1] == ';');
373 descriptor.erase(descriptor.length() - 1);
374
375 JNIEnv* env = GetJniEnv();
376 jclass exception_class = env->FindClass(descriptor.c_str());
377 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
378 int rc = env->ThrowNew(exception_class, msg.c_str());
379 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700380}
381
Elliott Hughes79082e32011-08-25 12:07:32 -0700382void Thread::ThrowOutOfMemoryError() {
383 UNIMPLEMENTED(FATAL);
384}
385
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700386Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
387 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
388 DCHECK(class_linker != NULL);
389
390 Frame cur_frame = GetTopOfStack();
391 for (int unwind_depth = 0; ; unwind_depth++) {
392 const Method* cur_method = cur_frame.GetMethod();
393 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
394 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
395
396 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
397 throw_pc,
398 dex_file,
399 class_linker);
400 if (handler_addr) {
401 *handler_pc = handler_addr;
402 return cur_frame;
403 } else {
404 // Check if we are at the last frame
405 if (cur_frame.HasNext()) {
406 cur_frame.Next();
407 } else {
408 // Either at the top of stack or next frame is native.
409 break;
410 }
411 }
412 }
413 *handler_pc = NULL;
414 return Frame();
415}
416
417void* Thread::FindExceptionHandlerInMethod(const Method* method,
418 void* throw_pc,
419 const DexFile& dex_file,
420 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700421 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700422 exception_ = NULL;
423
424 intptr_t dex_pc = -1;
425 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->code_off_);
426 DexFile::CatchHandlerIterator iter;
427 for (iter = dex_file.dexFindCatchHandler(*code_item,
428 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
429 !iter.HasNext();
430 iter.Next()) {
431 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
432 DCHECK(klass != NULL);
433 if (exception_obj->InstanceOf(klass)) {
434 dex_pc = iter.Get().address_;
435 break;
436 }
437 }
438
439 exception_ = exception_obj;
440 if (iter.HasNext()) {
441 return NULL;
442 } else {
443 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
444 }
445}
446
Ian Rogersb033c752011-07-20 12:22:35 -0700447static const char* kStateNames[] = {
448 "New",
449 "Runnable",
450 "Blocked",
451 "Waiting",
452 "TimedWaiting",
453 "Native",
454 "Terminated",
455};
456std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
457 if (state >= Thread::kNew && state <= Thread::kTerminated) {
458 os << kStateNames[state-Thread::kNew];
459 } else {
460 os << "State[" << static_cast<int>(state) << "]";
461 }
462 return os;
463}
464
Elliott Hughes330304d2011-08-12 14:28:05 -0700465std::ostream& operator<<(std::ostream& os, const Thread& thread) {
466 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700467 << ",pthread_t=" << thread.GetImpl()
468 << ",tid=" << thread.GetTid()
469 << ",id=" << thread.GetId()
470 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700471 return os;
472}
473
Carl Shapiro61e019d2011-07-14 16:53:09 -0700474ThreadList* ThreadList::Create() {
475 return new ThreadList;
476}
477
Carl Shapirob5573532011-07-12 18:22:59 -0700478ThreadList::ThreadList() {
479 lock_ = Mutex::Create("ThreadList::Lock");
480}
481
482ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700483 if (Contains(Thread::Current())) {
484 Runtime::Current()->DetachCurrentThread();
485 }
486
487 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -0700488 // reach this point. This means that all daemon threads had been
489 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700490 // TODO: dump ThreadList if non-empty.
491 CHECK_EQ(list_.size(), 0U);
492
Carl Shapirob5573532011-07-12 18:22:59 -0700493 delete lock_;
494 lock_ = NULL;
495}
496
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700497bool ThreadList::Contains(Thread* thread) {
498 return find(list_.begin(), list_.end(), thread) != list_.end();
499}
500
Carl Shapirob5573532011-07-12 18:22:59 -0700501void ThreadList::Register(Thread* thread) {
502 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700503 CHECK(!Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700504 list_.push_front(thread);
505}
506
507void ThreadList::Unregister(Thread* thread) {
508 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700509 CHECK(Contains(thread));
Carl Shapirob5573532011-07-12 18:22:59 -0700510 list_.remove(thread);
511}
512
Carl Shapirob5573532011-07-12 18:22:59 -0700513} // namespace