blob: 78cb1c628fbe92d0a70d4b069d4c07b8ed9b4169 [file] [log] [blame]
Carl Shapirob5573532011-07-12 18:22:59 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -07004
Ian Rogersb033c752011-07-20 12:22:35 -07005#include <pthread.h>
6#include <sys/mman.h>
Elliott Hughesa0957642011-09-02 14:27:33 -07007
Carl Shapirob5573532011-07-12 18:22:59 -07008#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -07009#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070010#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070011#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070012#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070013
Elliott Hughesa5b897e2011-08-16 11:33:06 -070014#include "class_linker.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070015#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070016#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070017#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070018#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070019#include "runtime_support.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070020#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070021
22namespace art {
23
24pthread_key_t Thread::pthread_key_self_;
25
buzbee4a3164f2011-09-03 11:25:10 -070026// Temporary debugging hook for compiler.
27static void DebugMe(Method* method, uint32_t info) {
28 LOG(INFO) << "DebugMe";
29 if (method != NULL)
30 LOG(INFO) << PrettyMethod(method);
31 LOG(INFO) << "Info: " << info;
32}
33
34/*
35 * TODO: placeholder for a method that can be called by the
36 * invoke-interface trampoline to unwind and handle exception. The
37 * trampoline will arrange it so that the caller appears to be the
38 * callsite of the failed invoke-interface. See comments in
39 * compiler/runtime_support.S
40 */
41extern "C" void artFailedInvokeInterface()
42{
43 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
44}
45
46// TODO: placeholder. See comments in compiler/runtime_support.S
47extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
48 Object* this_object , Method* caller_method)
49{
50 /*
51 * Note: this_object has not yet been null-checked. To match
52 * the old-world state, nullcheck this_object and load
53 * Class* this_class = this_object->GetClass().
54 * See comments and possible thrown exceptions in old-world
55 * Interp.cpp:dvmInterpFindInterfaceMethod, and complete with
56 * new-world FindVirtualMethodForInterface.
57 */
58 UNIMPLEMENTED(FATAL) << "Unimplemented invoke interface";
59 return 0LL;
60}
61
buzbee1b4c8592011-08-31 10:43:51 -070062// TODO: placeholder. This is what generated code will call to throw
63static void ThrowException(Thread* thread, Throwable* exception) {
64 /*
65 * exception may be NULL, in which case this routine should
66 * throw NPE. NOTE: this is a convenience for generated code,
67 * which previuosly did the null check inline and constructed
68 * and threw a NPE if NULL. This routine responsible for setting
69 * exception_ in thread.
70 */
71 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
72}
73
74// TODO: placeholder. Helper function to type
75static Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
76 /*
77 * Should initialize & fix up method->dex_cache_resolved_types_[].
78 * Returns initialized type. Does not return normally if an exception
79 * is thrown, but instead initiates the catch. Should be similar to
80 * ClassLinker::InitializeStaticStorageFromCode.
81 */
82 UNIMPLEMENTED(FATAL);
83 return NULL;
84}
85
buzbee561227c2011-09-02 15:28:19 -070086// TODO: placeholder. Helper function to resolve virtual method
87static void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
88 /*
89 * Slow-path handler on invoke virtual method path in which
90 * base method is unresolved at compile-time. Doesn't need to
91 * return anything - just either ensure that
92 * method->dex_cache_resolved_methods_(method_idx) != NULL or
93 * throw and unwind. The caller will restart call sequence
94 * from the beginning.
95 */
96}
97
buzbee1da522d2011-09-04 11:22:20 -070098// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
99static Array* CheckAndAllocFromCode(uint32_t type_index, Method* method,
100 int32_t component_count)
101{
102 /*
103 * Just a wrapper around Array::AllocFromCode() that additionally
104 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
105 */
106 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
107 return Array::AllocFromCode(type_index, method, component_count);
108}
109
buzbee2a475e72011-09-07 17:19:17 -0700110// TODO: placeholder (throw on failure)
111static void CheckCastFromCode(const Class* a, const Class* b) {
112 if (a->IsAssignableFrom(b)) {
113 return;
114 }
115 UNIMPLEMENTED(FATAL);
116}
117
118// TODO: placeholder
119static void UnlockObjectFromCode(Thread* thread, Object* obj) {
120 // TODO: throw and unwind if lock not held
121 // TODO: throw and unwind on NPE
buzbee4ef76522011-09-08 10:00:32 -0700122 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700123}
124
125// TODO: placeholder
126static void LockObjectFromCode(Thread* thread, Object* obj) {
buzbee4ef76522011-09-08 10:00:32 -0700127 obj->MonitorEnter(thread);
buzbee2a475e72011-09-07 17:19:17 -0700128}
129
buzbee0d966cf2011-09-08 17:34:58 -0700130// TODO: placeholder
131static void CheckSuspendFromCode(Thread* thread) {
132 /*
133 * Code is at a safe point, suspend if needed.
134 * Also, this is where a pending safepoint callback
135 * would be fired.
136 */
137}
138
buzbeecefd1872011-09-09 09:59:52 -0700139// TODO: placeholder
140static void StackOverflowFromCode(Method* method) {
141 //NOTE: to save code space, this handler needs to look up its own Thread*
142 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
143}
144
buzbee5ade1d22011-09-09 14:44:52 -0700145// TODO: placeholder
146static void ThrowNullPointerFromCode() {
147 //NOTE: to save code space, this handler must look up caller's Method*
148 UNIMPLEMENTED(FATAL) << "Null pointer exception";
149}
150
151// TODO: placeholder
152static void ThrowDivZeroFromCode() {
153 UNIMPLEMENTED(FATAL) << "Divide by zero";
154}
155
156// TODO: placeholder
157static void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
158 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index <<
159 ", limit: " << limit;
160}
161
162// TODO: placeholder
163static void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
164 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
165 " ref: " << ref;
166}
167
168// TODO: placeholder
169static void ThrowNegArraySizeFromCode(int32_t index) {
170 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
171}
172
173// TODO: placeholder
174static void ThrowInternalErrorFromCode(int32_t errnum) {
175 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
176}
177
178// TODO: placeholder
179static void ThrowRuntimeExceptionFromCode(int32_t errnum) {
180 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
181}
182
183// TODO: placeholder
184static void ThrowNoSuchMethodFromCode(int32_t method_idx) {
185 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
186}
187
188/*
189 * Temporary placeholder. Should include run-time checks for size
190 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
191 * As with other new "FromCode" routines, this should return to the caller
192 * only if no exception has been thrown.
193 *
194 * NOTE: When dealing with a raw dex file, the data to be copied uses
195 * little-endian ordering. Require that oat2dex do any required swapping
196 * so this routine can get by with a memcpy().
197 *
198 * Format of the data:
199 * ushort ident = 0x0300 magic value
200 * ushort width width of each element in the table
201 * uint size number of elements in the table
202 * ubyte data[size*width] table of data values (may contain a single-byte
203 * padding at the end)
204 */
205static void HandleFillArrayDataFromCode(Array* array, const uint16_t* table)
206{
207 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
208 uint32_t size_in_bytes = size * table[1];
209 if (static_cast<int32_t>(size) > array->GetLength()) {
210 ThrowArrayBoundsFromCode(array->GetLength(), size);
211 }
212 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
213 (char*)&table[4], size_in_bytes);
214}
215
216// TODO: move to more appropriate location
217/*
218 * Float/double conversion requires clamping to min and max of integer form. If
219 * target doesn't support this normally, use these.
220 */
221static int64_t D2L(double d)
222{
223 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
224 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
225 if (d >= kMaxLong)
226 return (int64_t)0x7fffffffffffffffULL;
227 else if (d <= kMinLong)
228 return (int64_t)0x8000000000000000ULL;
229 else if (d != d) // NaN case
230 return 0;
231 else
232 return (int64_t)d;
233}
234
235static int64_t F2L(float f)
236{
237 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
238 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
239 if (f >= kMaxLong)
240 return (int64_t)0x7fffffffffffffffULL;
241 else if (f <= kMinLong)
242 return (int64_t)0x8000000000000000ULL;
243 else if (f != f) // NaN case
244 return 0;
245 else
246 return (int64_t)f;
247}
248
buzbee3ea4ec52011-08-22 17:37:19 -0700249void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700250#if defined(__arm__)
251 pShlLong = art_shl_long;
252 pShrLong = art_shr_long;
253 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700254 pIdiv = __aeabi_idiv;
255 pIdivmod = __aeabi_idivmod;
256 pI2f = __aeabi_i2f;
257 pF2iz = __aeabi_f2iz;
258 pD2f = __aeabi_d2f;
259 pF2d = __aeabi_f2d;
260 pD2iz = __aeabi_d2iz;
261 pL2f = __aeabi_l2f;
262 pL2d = __aeabi_l2d;
263 pFadd = __aeabi_fadd;
264 pFsub = __aeabi_fsub;
265 pFdiv = __aeabi_fdiv;
266 pFmul = __aeabi_fmul;
267 pFmodf = fmodf;
268 pDadd = __aeabi_dadd;
269 pDsub = __aeabi_dsub;
270 pDdiv = __aeabi_ddiv;
271 pDmul = __aeabi_dmul;
272 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700273 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700274 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700275 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700276#endif
buzbeec396efc2011-09-11 09:36:41 -0700277 pF2l = F2L;
278 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700279 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700280 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700281 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700282 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700283 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700284 pGet32Static = Field::Get32StaticFromCode;
285 pSet32Static = Field::Set32StaticFromCode;
286 pGet64Static = Field::Get64StaticFromCode;
287 pSet64Static = Field::Set64StaticFromCode;
288 pGetObjStatic = Field::GetObjStaticFromCode;
289 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700290 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
291 pThrowException = ThrowException;
292 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700293 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700294 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700295 pInstanceofNonTrivialFromCode = Object::InstanceOf;
296 pCheckCastFromCode = CheckCastFromCode;
297 pLockObjectFromCode = LockObjectFromCode;
298 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700299 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700300 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700301 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700302 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
303 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
304 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
305 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
306 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
307 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
308 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
309 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700310 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700311}
312
Elliott Hughesbe759c62011-09-08 19:38:21 -0700313Mutex::~Mutex() {
314 errno = pthread_mutex_destroy(&mutex_);
315 if (errno != 0) {
316 PLOG(FATAL) << "pthread_mutex_destroy failed";
317 }
318}
319
Carl Shapirob5573532011-07-12 18:22:59 -0700320Mutex* Mutex::Create(const char* name) {
321 Mutex* mu = new Mutex(name);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700322#ifndef NDEBUG
323 pthread_mutexattr_t debug_attributes;
324 errno = pthread_mutexattr_init(&debug_attributes);
325 if (errno != 0) {
326 PLOG(FATAL) << "pthread_mutexattr_init failed";
327 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700328#if VERIFY_OBJECT_ENABLED
329 errno = pthread_mutexattr_settype(&debug_attributes, PTHREAD_MUTEX_RECURSIVE);
330#else
Elliott Hughes92b3b562011-09-08 16:32:26 -0700331 errno = pthread_mutexattr_settype(&debug_attributes, PTHREAD_MUTEX_ERRORCHECK);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700332#endif
Elliott Hughes92b3b562011-09-08 16:32:26 -0700333 if (errno != 0) {
334 PLOG(FATAL) << "pthread_mutexattr_settype failed";
335 }
Elliott Hughesbe759c62011-09-08 19:38:21 -0700336 errno = pthread_mutex_init(&mu->mutex_, &debug_attributes);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700337 if (errno != 0) {
338 PLOG(FATAL) << "pthread_mutex_init failed";
339 }
340 errno = pthread_mutexattr_destroy(&debug_attributes);
341 if (errno != 0) {
342 PLOG(FATAL) << "pthread_mutexattr_destroy failed";
343 }
344#else
Elliott Hughesbe759c62011-09-08 19:38:21 -0700345 errno = pthread_mutex_init(&mu->mutex_, NULL);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700346 if (errno != 0) {
347 PLOG(FATAL) << "pthread_mutex_init failed";
348 }
349#endif
Carl Shapirob5573532011-07-12 18:22:59 -0700350 return mu;
351}
352
353void Mutex::Lock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700354 int result = pthread_mutex_lock(&mutex_);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700355 if (result != 0) {
356 errno = result;
357 PLOG(FATAL) << "pthread_mutex_lock failed";
358 }
Carl Shapirob5573532011-07-12 18:22:59 -0700359}
360
361bool Mutex::TryLock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700362 int result = pthread_mutex_trylock(&mutex_);
Carl Shapirob5573532011-07-12 18:22:59 -0700363 if (result == EBUSY) {
364 return false;
Carl Shapirob5573532011-07-12 18:22:59 -0700365 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700366 if (result != 0) {
367 errno = result;
368 PLOG(FATAL) << "pthread_mutex_trylock failed";
369 }
370 return true;
Carl Shapirob5573532011-07-12 18:22:59 -0700371}
372
373void Mutex::Unlock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700374 int result = pthread_mutex_unlock(&mutex_);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700375 if (result != 0) {
376 errno = result;
377 PLOG(FATAL) << "pthread_mutex_unlock failed";
378 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700379}
380
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700381void Frame::Next() {
382 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700383 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700385}
386
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700387uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700388 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700389 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700390 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700391}
392
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700393Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700394 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700395 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700396 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700397}
398
Carl Shapiro61e019d2011-07-14 16:53:09 -0700399void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700400 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700401 return NULL;
402}
403
Brian Carlstromb765be02011-08-17 23:54:10 -0700404Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700405 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
406
Elliott Hughesbe759c62011-09-08 19:38:21 -0700407 size_t stack_size = runtime->GetDefaultStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700408
409 Thread* new_thread = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700410
411 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700412 errno = pthread_attr_init(&attr);
413 if (errno != 0) {
414 PLOG(FATAL) << "pthread_attr_init failed";
415 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700416
Elliott Hughese27955c2011-08-26 15:21:24 -0700417 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
418 if (errno != 0) {
419 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
420 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700421
Elliott Hughese27955c2011-08-26 15:21:24 -0700422 errno = pthread_attr_setstacksize(&attr, stack_size);
423 if (errno != 0) {
424 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
425 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700426
Elliott Hughesbe759c62011-09-08 19:38:21 -0700427 errno = pthread_create(&new_thread->pthread_, &attr, ThreadStart, new_thread);
Elliott Hughese27955c2011-08-26 15:21:24 -0700428 if (errno != 0) {
429 PLOG(FATAL) << "pthread_create failed";
430 }
431
432 errno = pthread_attr_destroy(&attr);
433 if (errno != 0) {
434 PLOG(FATAL) << "pthread_attr_destroy failed";
435 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700436
Elliott Hughesdcc24742011-09-07 14:02:44 -0700437 // TODO: get the "daemon" field from the java.lang.Thread.
438 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
439
Carl Shapiro61e019d2011-07-14 16:53:09 -0700440 return new_thread;
441}
442
Elliott Hughesdcc24742011-09-07 14:02:44 -0700443Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700444 Thread* self = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700445
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700446 self->tid_ = ::art::GetTid();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700447 self->pthread_ = pthread_self();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700448 self->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700449
Elliott Hughesbe759c62011-09-08 19:38:21 -0700450 self->InitStackHwm();
451
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700452 self->state_ = kRunnable;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700453
Elliott Hughesdcc24742011-09-07 14:02:44 -0700454 SetThreadName(name);
455
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700456 errno = pthread_setspecific(Thread::pthread_key_self_, self);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700457 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700458 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700459 }
460
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700461 self->jni_env_ = new JNIEnvExt(self, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700462
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700463 runtime->GetThreadList()->Register(self);
464
465 // If we're the main thread, ClassLinker won't be created until after we're attached,
466 // so that thread needs a two-stage attach. Regular threads don't need this hack.
467 if (self->thin_lock_id_ != ThreadList::kMainId) {
468 self->CreatePeer(name, as_daemon);
469 }
470
471 return self;
472}
473
474void Thread::CreatePeer(const char* name, bool as_daemon) {
475 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
476
477 JNIEnv* env = jni_env_;
478
479 jobject thread_group = NULL;
480 jobject thread_name = env->NewStringUTF(name);
481 jint thread_priority = 123;
482 jboolean thread_is_daemon = as_daemon;
483
484 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700485 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700486 jobject o = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
487 LOG(INFO) << "Created new java.lang.Thread " << (void*) o << " decoded=" << (void*) DecodeJObject(o);
488
489 peer_ = DecodeJObject(o);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700490}
491
Elliott Hughesbe759c62011-09-08 19:38:21 -0700492void Thread::InitStackHwm() {
493 pthread_attr_t attributes;
494 errno = pthread_getattr_np(pthread_, &attributes);
495 if (errno != 0) {
496 PLOG(FATAL) << "pthread_getattr_np failed";
497 }
498
Elliott Hughesbe759c62011-09-08 19:38:21 -0700499 void* stack_base;
500 size_t stack_size;
501 errno = pthread_attr_getstack(&attributes, &stack_base, &stack_size);
502 if (errno != 0) {
503 PLOG(FATAL) << "pthread_attr_getstack failed";
504 }
505
Elliott Hughesbe759c62011-09-08 19:38:21 -0700506 if (stack_size <= kStackOverflowReservedBytes) {
507 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
508 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700509
510 // stack_base is the "lowest addressable byte" of the stack.
511 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
512 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700513 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700514
515 // Sanity check.
516 int stack_variable;
517 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700518
519 errno = pthread_attr_destroy(&attributes);
520 if (errno != 0) {
521 PLOG(FATAL) << "pthread_attr_destroy failed";
522 }
523}
524
Elliott Hughesa0957642011-09-02 14:27:33 -0700525void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700526 /*
527 * Get the java.lang.Thread object. This function gets called from
528 * some weird debug contexts, so it's possible that there's a GC in
529 * progress on some other thread. To decrease the chances of the
530 * thread object being moved out from under us, we add the reference
531 * to the tracked allocation list, which pins it in place.
532 *
533 * If threadObj is NULL, the thread is still in the process of being
534 * attached to the VM, and there's really nothing interesting to
535 * say about it yet.
536 */
537 os << "TODO: pin Thread before dumping\n";
538#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700539 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
540 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700541 LOGI("Can't dump thread %d: threadObj not set", threadId);
542 return;
543 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700544 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700545#endif
546
547 DumpState(os);
548 DumpStack(os);
549
550#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700551 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700552#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700553}
554
Elliott Hughesd92bec42011-09-02 17:04:36 -0700555std::string GetSchedulerGroup(pid_t tid) {
556 // /proc/<pid>/group looks like this:
557 // 2:devices:/
558 // 1:cpuacct,cpu:/
559 // We want the third field from the line whose second field contains the "cpu" token.
560 std::string cgroup_file;
561 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
562 return "";
563 }
564 std::vector<std::string> cgroup_lines;
565 Split(cgroup_file, '\n', cgroup_lines);
566 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
567 std::vector<std::string> cgroup_fields;
568 Split(cgroup_lines[i], ':', cgroup_fields);
569 std::vector<std::string> cgroups;
570 Split(cgroup_fields[1], ',', cgroups);
571 for (size_t i = 0; i < cgroups.size(); ++i) {
572 if (cgroups[i] == "cpu") {
573 return cgroup_fields[2].substr(1); // Skip the leading slash.
574 }
575 }
576 }
577 return "";
578}
579
580void Thread::DumpState(std::ostream& os) const {
581 std::string thread_name("unknown");
582 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700583
Elliott Hughesd92bec42011-09-02 17:04:36 -0700584#if 0 // TODO
585 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
586 threadName = dvmCreateCstrFromString(nameStr);
587 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700588#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700589 {
590 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
591 std::string stats;
592 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
593 size_t start = stats.find('(') + 1;
594 size_t end = stats.find(')') - start;
595 thread_name = stats.substr(start, end);
596 }
597 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700598 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700599#endif
600
601 int policy;
602 sched_param sp;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700603 errno = pthread_getschedparam(pthread_, &policy, &sp);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700604 if (errno != 0) {
605 PLOG(FATAL) << "pthread_getschedparam failed";
606 }
607
608 std::string scheduler_group(GetSchedulerGroup(GetTid()));
609 if (scheduler_group.empty()) {
610 scheduler_group = "default";
611 }
612
613 std::string group_name("(null; initializing?)");
614#if 0
615 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
616 if (groupObj != NULL) {
617 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
618 groupName = dvmCreateCstrFromString(nameStr);
619 }
620#else
621 group_name = "TODO";
622#endif
623
624 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700625 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700626 os << " daemon";
627 }
628 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700629 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700630 << " " << state_ << "\n";
631
632 int suspend_count = 0; // TODO
633 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700634 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700635 os << " | group=\"" << group_name << "\""
636 << " sCount=" << suspend_count
637 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700638 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700639 << " self=" << reinterpret_cast<const void*>(this) << "\n";
640 os << " | sysTid=" << GetTid()
641 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
642 << " sched=" << policy << "/" << sp.sched_priority
643 << " cgrp=" << scheduler_group
644 << " handle=" << GetImpl() << "\n";
645
646 // Grab the scheduler stats for this thread.
647 std::string scheduler_stats;
648 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
649 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
650 } else {
651 scheduler_stats = "0 0 0";
652 }
653
654 int utime = 0;
655 int stime = 0;
656 int task_cpu = 0;
657 std::string stats;
658 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
659 // Skip the command, which may contain spaces.
660 stats = stats.substr(stats.find(')') + 2);
661 // Extract the three fields we care about.
662 std::vector<std::string> fields;
663 Split(stats, ' ', fields);
664 utime = strtoull(fields[11].c_str(), NULL, 10);
665 stime = strtoull(fields[12].c_str(), NULL, 10);
666 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
667 }
668
669 os << " | schedstat=( " << scheduler_stats << " )"
670 << " utm=" << utime
671 << " stm=" << stime
672 << " core=" << task_cpu
673 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
674}
675
676void Thread::DumpStack(std::ostream& os) const {
677 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700678}
679
Elliott Hughesbe759c62011-09-08 19:38:21 -0700680void Thread::ThreadExitCallback(void* arg) {
681 Thread* self = reinterpret_cast<Thread*>(arg);
682 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700683}
684
Elliott Hughesbe759c62011-09-08 19:38:21 -0700685void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700686 // Allocate a TLS slot.
Elliott Hughesbe759c62011-09-08 19:38:21 -0700687 errno = pthread_key_create(&Thread::pthread_key_self_, Thread::ThreadExitCallback);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700688 if (errno != 0) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700689 PLOG(FATAL) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700690 }
691
692 // Double-check the TLS slot allocation.
693 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700694 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700695 }
696
697 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700698}
699
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700700void Thread::Shutdown() {
701 errno = pthread_key_delete(Thread::pthread_key_self_);
702 if (errno != 0) {
703 PLOG(WARNING) << "pthread_key_delete failed";
704 }
705}
706
Elliott Hughesdcc24742011-09-07 14:02:44 -0700707Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700708 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700709 top_of_managed_stack_(),
710 native_to_managed_record_(NULL),
711 top_sirt_(NULL),
712 jni_env_(NULL),
713 exception_(NULL),
714 suspend_count_(0),
715 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700716 InitCpu();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700717 {
718 ThreadListLock mu;
719 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
720 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700721 InitFunctionPointers();
722}
723
Elliott Hughes02b48d12011-09-07 17:15:51 -0700724void MonitorExitVisitor(const Object* object, void*) {
725 Object* entered_monitor = const_cast<Object*>(object);
726 entered_monitor->MonitorExit();;
727}
728
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700729Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700730 // TODO: check we're not calling the JNI DetachCurrentThread function from
731 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
732
733 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
734 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
735
736 if (IsExceptionPending()) {
737 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
738 }
739
740 // TODO: ThreadGroup.removeThread(this);
741
742 // TODO: this.vmData = 0;
743
744 // TODO: say "bye" to the debugger.
745 //if (gDvm.debuggerConnected) {
746 // dvmDbgPostThreadDeath(self);
747 //}
748
749 // Thread.join() is implemented as an Object.wait() on the Thread.lock
750 // object. Signal anyone who is waiting.
751 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
752 //dvmLockObject(self, lock);
753 //dvmObjectNotifyAll(self, lock);
754 //dvmUnlockObject(self, lock);
755 //lock = NULL;
756
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700757 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700758 jni_env_ = NULL;
759
760 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700761}
762
Ian Rogers408f79a2011-08-23 18:22:33 -0700763size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700764 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700765 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700766 count += cur->NumberOfReferences();
767 }
768 return count;
769}
770
Ian Rogers408f79a2011-08-23 18:22:33 -0700771bool Thread::SirtContains(jobject obj) {
772 Object** sirt_entry = reinterpret_cast<Object**>(obj);
773 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700774 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700775 // A SIRT should always have a jobject/jclass as a native method is passed
776 // in a this pointer or a class
777 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700778 if ((&cur->References()[0] <= sirt_entry) &&
779 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700780 return true;
781 }
782 }
783 return false;
784}
785
Ian Rogers408f79a2011-08-23 18:22:33 -0700786Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700787 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700788 if (obj == NULL) {
789 return NULL;
790 }
791 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
792 IndirectRefKind kind = GetIndirectRefKind(ref);
793 Object* result;
794 switch (kind) {
795 case kLocal:
796 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700797 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700798 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700799 break;
800 }
801 case kGlobal:
802 {
803 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
804 IndirectReferenceTable& globals = vm->globals;
805 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700806 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700807 break;
808 }
809 case kWeakGlobal:
810 {
811 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
812 IndirectReferenceTable& weak_globals = vm->weak_globals;
813 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700814 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700815 if (result == kClearedJniWeakGlobal) {
816 // This is a special case where it's okay to return NULL.
817 return NULL;
818 }
819 break;
820 }
821 case kSirtOrInvalid:
822 default:
823 // TODO: make stack indirect reference table lookup more efficient
824 // Check if this is a local reference in the SIRT
825 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700826 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700827 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700828 // Assume an invalid local reference is actually a direct pointer.
829 result = reinterpret_cast<Object*>(obj);
830 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700831 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700832 }
833 }
834
835 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700836 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
837 JniAbort(NULL);
838 } else {
839 if (result != kInvalidIndirectRefObject) {
840 Heap::VerifyObject(result);
841 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700842 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700843 return result;
844}
845
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700846class CountStackDepthVisitor : public Thread::StackVisitor {
847 public:
848 CountStackDepthVisitor() : depth(0) {}
849 virtual bool VisitFrame(const Frame&) {
850 ++depth;
851 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700852 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700853
854 int GetDepth() const {
855 return depth;
856 }
857
858 private:
859 uint32_t depth;
860};
861
862class BuildStackTraceVisitor : public Thread::StackVisitor {
863 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700864 explicit BuildStackTraceVisitor(int depth) : count(0) {
865 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700866 pc_trace = IntArray::Alloc(depth);
867 }
868
869 virtual ~BuildStackTraceVisitor() {}
870
871 virtual bool VisitFrame(const Frame& frame) {
872 method_trace->Set(count, frame.GetMethod());
873 pc_trace->Set(count, frame.GetPC());
874 ++count;
875 return true;
876 }
877
878 const Method* GetMethod(uint32_t i) {
879 DCHECK(i < count);
880 return method_trace->Get(i);
881 }
882
883 uintptr_t GetPC(uint32_t i) {
884 DCHECK(i < count);
885 return pc_trace->Get(i);
886 }
887
888 private:
889 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700890 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700891 IntArray* pc_trace;
892};
893
894void Thread::WalkStack(StackVisitor* visitor) {
895 Frame frame = Thread::Current()->GetTopOfStack();
896 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
897 // CHECK(native_to_managed_record_ != NULL);
898 NativeToManagedRecord* record = native_to_managed_record_;
899
900 while (frame.GetSP()) {
901 for ( ; frame.GetMethod() != 0; frame.Next()) {
902 visitor->VisitFrame(frame);
903 }
904 if (record == NULL) {
905 break;
906 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700907 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 -0700908 record = record->link;
909 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700910}
911
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700912ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700913 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700914
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700915 CountStackDepthVisitor count_visitor;
916 WalkStack(&count_visitor);
917 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700918
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700919 BuildStackTraceVisitor build_trace_visitor(depth);
920 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700921
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700922 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700923
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700924 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700925 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700926 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700927 const Class* klass = method->GetDeclaringClass();
928 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700929 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700930 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700931
932 StackTraceElement* obj =
933 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700934 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700935 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -0700936 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700937 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700938 java_traces->Set(i, obj);
939 }
940 return java_traces;
941}
942
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700943void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700944 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700945 va_list args;
946 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700947 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700948 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700949
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700950 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700951 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700952 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700953 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700954 descriptor.erase(descriptor.length() - 1);
955
956 JNIEnv* env = GetJniEnv();
957 jclass exception_class = env->FindClass(descriptor.c_str());
958 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
959 int rc = env->ThrowNew(exception_class, msg.c_str());
960 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700961}
962
Elliott Hughes79082e32011-08-25 12:07:32 -0700963void Thread::ThrowOutOfMemoryError() {
964 UNIMPLEMENTED(FATAL);
965}
966
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700967Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
968 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
969 DCHECK(class_linker != NULL);
970
971 Frame cur_frame = GetTopOfStack();
972 for (int unwind_depth = 0; ; unwind_depth++) {
973 const Method* cur_method = cur_frame.GetMethod();
974 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
975 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
976
977 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
978 throw_pc,
979 dex_file,
980 class_linker);
981 if (handler_addr) {
982 *handler_pc = handler_addr;
983 return cur_frame;
984 } else {
985 // Check if we are at the last frame
986 if (cur_frame.HasNext()) {
987 cur_frame.Next();
988 } else {
989 // Either at the top of stack or next frame is native.
990 break;
991 }
992 }
993 }
994 *handler_pc = NULL;
995 return Frame();
996}
997
998void* Thread::FindExceptionHandlerInMethod(const Method* method,
999 void* throw_pc,
1000 const DexFile& dex_file,
1001 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001002 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001003 exception_ = NULL;
1004
1005 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001006 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001007 DexFile::CatchHandlerIterator iter;
1008 for (iter = dex_file.dexFindCatchHandler(*code_item,
1009 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
1010 !iter.HasNext();
1011 iter.Next()) {
1012 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
1013 DCHECK(klass != NULL);
1014 if (exception_obj->InstanceOf(klass)) {
1015 dex_pc = iter.Get().address_;
1016 break;
1017 }
1018 }
1019
1020 exception_ = exception_obj;
1021 if (iter.HasNext()) {
1022 return NULL;
1023 } else {
1024 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
1025 }
1026}
1027
Elliott Hughes410c0c82011-09-01 17:58:25 -07001028void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
1029 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
1030 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
1031 jni_env_->locals.VisitRoots(visitor, arg);
1032 jni_env_->monitors.VisitRoots(visitor, arg);
1033 // visitThreadStack(visitor, thread, arg);
1034 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1035}
1036
Ian Rogersb033c752011-07-20 12:22:35 -07001037static const char* kStateNames[] = {
1038 "New",
1039 "Runnable",
1040 "Blocked",
1041 "Waiting",
1042 "TimedWaiting",
1043 "Native",
1044 "Terminated",
1045};
1046std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
1047 if (state >= Thread::kNew && state <= Thread::kTerminated) {
1048 os << kStateNames[state-Thread::kNew];
1049 } else {
1050 os << "State[" << static_cast<int>(state) << "]";
1051 }
1052 return os;
1053}
1054
Elliott Hughes330304d2011-08-12 14:28:05 -07001055std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1056 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001057 << ",pthread_t=" << thread.GetImpl()
1058 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001059 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -07001060 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001061 return os;
1062}
1063
Carl Shapiro61e019d2011-07-14 16:53:09 -07001064ThreadList* ThreadList::Create() {
1065 return new ThreadList;
1066}
1067
Carl Shapirob5573532011-07-12 18:22:59 -07001068ThreadList::ThreadList() {
1069 lock_ = Mutex::Create("ThreadList::Lock");
1070}
1071
1072ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001073 if (Contains(Thread::Current())) {
1074 Runtime::Current()->DetachCurrentThread();
1075 }
1076
1077 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -07001078 // reach this point. This means that all daemon threads had been
1079 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001080 // TODO: dump ThreadList if non-empty.
1081 CHECK_EQ(list_.size(), 0U);
1082
Carl Shapirob5573532011-07-12 18:22:59 -07001083 delete lock_;
1084 lock_ = NULL;
1085}
1086
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001087bool ThreadList::Contains(Thread* thread) {
1088 return find(list_.begin(), list_.end(), thread) != list_.end();
1089}
1090
Elliott Hughesd92bec42011-09-02 17:04:36 -07001091void ThreadList::Dump(std::ostream& os) {
1092 MutexLock mu(lock_);
1093 os << "DALVIK THREADS (" << list_.size() << "):\n";
1094 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
1095 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
1096 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001097 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -07001098 }
1099}
1100
Carl Shapirob5573532011-07-12 18:22:59 -07001101void ThreadList::Register(Thread* thread) {
Elliott Hughesbe759c62011-09-08 19:38:21 -07001102 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -07001103 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001104 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -07001105 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -07001106}
1107
Elliott Hughes02b48d12011-09-07 17:15:51 -07001108void ThreadList::Unregister() {
Elliott Hughes02b48d12011-09-07 17:15:51 -07001109 Thread* self = Thread::Current();
Elliott Hughesbe759c62011-09-08 19:38:21 -07001110
1111 //LOG(INFO) << "ThreadList::Unregister() " << self;
1112 MutexLock mu(lock_);
1113
1114 // Remove this thread from the list.
Elliott Hughes02b48d12011-09-07 17:15:51 -07001115 CHECK(Contains(self));
1116 list_.remove(self);
Elliott Hughesbe759c62011-09-08 19:38:21 -07001117
1118 // Delete the Thread* and release the thin lock id.
Elliott Hughes02b48d12011-09-07 17:15:51 -07001119 uint32_t thin_lock_id = self->thin_lock_id_;
1120 delete self;
1121 ReleaseThreadId(thin_lock_id);
Elliott Hughesbe759c62011-09-08 19:38:21 -07001122
1123 // Clear the TLS data, so that thread is recognizably detached.
1124 // (It may wish to reattach later.)
1125 errno = pthread_setspecific(Thread::pthread_key_self_, NULL);
1126 if (errno != 0) {
1127 PLOG(FATAL) << "pthread_setspecific failed";
1128 }
Carl Shapirob5573532011-07-12 18:22:59 -07001129}
1130
Elliott Hughes410c0c82011-09-01 17:58:25 -07001131void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
1132 MutexLock mu(lock_);
1133 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
1134 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
1135 (*it)->VisitRoots(visitor, arg);
1136 }
1137}
1138
Elliott Hughes02b48d12011-09-07 17:15:51 -07001139uint32_t ThreadList::AllocThreadId() {
Elliott Hughes92b3b562011-09-08 16:32:26 -07001140 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001141 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1142 if (!allocated_ids_[i]) {
1143 allocated_ids_.set(i);
1144 return i + 1; // Zero is reserved to mean "invalid".
1145 }
1146 }
1147 LOG(FATAL) << "Out of internal thread ids";
1148 return 0;
1149}
1150
1151void ThreadList::ReleaseThreadId(uint32_t id) {
Elliott Hughes92b3b562011-09-08 16:32:26 -07001152 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001153 --id; // Zero is reserved to mean "invalid".
1154 DCHECK(allocated_ids_[id]) << id;
1155 allocated_ids_.reset(id);
1156}
1157
Carl Shapirob5573532011-07-12 18:22:59 -07001158} // namespace