blob: 9361d004fb2e98ebff3bbf148be762a50b751aff [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 }
328 errno = pthread_mutexattr_settype(&debug_attributes, PTHREAD_MUTEX_ERRORCHECK);
329 if (errno != 0) {
330 PLOG(FATAL) << "pthread_mutexattr_settype failed";
331 }
Elliott Hughesbe759c62011-09-08 19:38:21 -0700332 errno = pthread_mutex_init(&mu->mutex_, &debug_attributes);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700333 if (errno != 0) {
334 PLOG(FATAL) << "pthread_mutex_init failed";
335 }
336 errno = pthread_mutexattr_destroy(&debug_attributes);
337 if (errno != 0) {
338 PLOG(FATAL) << "pthread_mutexattr_destroy failed";
339 }
340#else
Elliott Hughesbe759c62011-09-08 19:38:21 -0700341 errno = pthread_mutex_init(&mu->mutex_, NULL);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700342 if (errno != 0) {
343 PLOG(FATAL) << "pthread_mutex_init failed";
344 }
345#endif
Carl Shapirob5573532011-07-12 18:22:59 -0700346 return mu;
347}
348
349void Mutex::Lock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700350 int result = pthread_mutex_lock(&mutex_);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700351 if (result != 0) {
352 errno = result;
353 PLOG(FATAL) << "pthread_mutex_lock failed";
354 }
Carl Shapirob5573532011-07-12 18:22:59 -0700355}
356
357bool Mutex::TryLock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700358 int result = pthread_mutex_trylock(&mutex_);
Carl Shapirob5573532011-07-12 18:22:59 -0700359 if (result == EBUSY) {
360 return false;
Carl Shapirob5573532011-07-12 18:22:59 -0700361 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700362 if (result != 0) {
363 errno = result;
364 PLOG(FATAL) << "pthread_mutex_trylock failed";
365 }
366 return true;
Carl Shapirob5573532011-07-12 18:22:59 -0700367}
368
369void Mutex::Unlock() {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700370 int result = pthread_mutex_unlock(&mutex_);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700371 if (result != 0) {
372 errno = result;
373 PLOG(FATAL) << "pthread_mutex_unlock failed";
374 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700375}
376
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700377void Frame::Next() {
378 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700379 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700380 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700381}
382
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700383uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700384 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700385 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700386 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700387}
388
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700390 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700391 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700393}
394
Carl Shapiro61e019d2011-07-14 16:53:09 -0700395void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700396 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700397 return NULL;
398}
399
Brian Carlstromb765be02011-08-17 23:54:10 -0700400Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700401 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
402
Elliott Hughesbe759c62011-09-08 19:38:21 -0700403 size_t stack_size = runtime->GetDefaultStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700404
405 Thread* new_thread = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700406
407 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700408 errno = pthread_attr_init(&attr);
409 if (errno != 0) {
410 PLOG(FATAL) << "pthread_attr_init failed";
411 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700412
Elliott Hughese27955c2011-08-26 15:21:24 -0700413 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
414 if (errno != 0) {
415 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
416 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700417
Elliott Hughese27955c2011-08-26 15:21:24 -0700418 errno = pthread_attr_setstacksize(&attr, stack_size);
419 if (errno != 0) {
420 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
421 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700422
Elliott Hughesbe759c62011-09-08 19:38:21 -0700423 errno = pthread_create(&new_thread->pthread_, &attr, ThreadStart, new_thread);
Elliott Hughese27955c2011-08-26 15:21:24 -0700424 if (errno != 0) {
425 PLOG(FATAL) << "pthread_create failed";
426 }
427
428 errno = pthread_attr_destroy(&attr);
429 if (errno != 0) {
430 PLOG(FATAL) << "pthread_attr_destroy failed";
431 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700432
Elliott Hughesdcc24742011-09-07 14:02:44 -0700433 // TODO: get the "daemon" field from the java.lang.Thread.
434 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
435
Carl Shapiro61e019d2011-07-14 16:53:09 -0700436 return new_thread;
437}
438
Elliott Hughesdcc24742011-09-07 14:02:44 -0700439Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700440 Thread* self = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700441
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700442 self->tid_ = ::art::GetTid();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700443 self->pthread_ = pthread_self();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700444 self->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700445
Elliott Hughesbe759c62011-09-08 19:38:21 -0700446 self->InitStackHwm();
447
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700448 self->state_ = kRunnable;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700449
Elliott Hughesdcc24742011-09-07 14:02:44 -0700450 SetThreadName(name);
451
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700452 errno = pthread_setspecific(Thread::pthread_key_self_, self);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700453 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700454 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700455 }
456
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700457 self->jni_env_ = new JNIEnvExt(self, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700458
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700459 runtime->GetThreadList()->Register(self);
460
461 // If we're the main thread, ClassLinker won't be created until after we're attached,
462 // so that thread needs a two-stage attach. Regular threads don't need this hack.
463 if (self->thin_lock_id_ != ThreadList::kMainId) {
464 self->CreatePeer(name, as_daemon);
465 }
466
467 return self;
468}
469
470void Thread::CreatePeer(const char* name, bool as_daemon) {
471 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
472
473 JNIEnv* env = jni_env_;
474
475 jobject thread_group = NULL;
476 jobject thread_name = env->NewStringUTF(name);
477 jint thread_priority = 123;
478 jboolean thread_is_daemon = as_daemon;
479
480 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700481 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700482 jobject o = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
483 LOG(INFO) << "Created new java.lang.Thread " << (void*) o << " decoded=" << (void*) DecodeJObject(o);
484
485 peer_ = DecodeJObject(o);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700486}
487
Elliott Hughesbe759c62011-09-08 19:38:21 -0700488void Thread::InitStackHwm() {
489 pthread_attr_t attributes;
490 errno = pthread_getattr_np(pthread_, &attributes);
491 if (errno != 0) {
492 PLOG(FATAL) << "pthread_getattr_np failed";
493 }
494
Elliott Hughesbe759c62011-09-08 19:38:21 -0700495 void* stack_base;
496 size_t stack_size;
497 errno = pthread_attr_getstack(&attributes, &stack_base, &stack_size);
498 if (errno != 0) {
499 PLOG(FATAL) << "pthread_attr_getstack failed";
500 }
501
Elliott Hughesbe759c62011-09-08 19:38:21 -0700502 if (stack_size <= kStackOverflowReservedBytes) {
503 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
504 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700505
506 // stack_base is the "lowest addressable byte" of the stack.
507 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
508 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700509 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700510
511 // Sanity check.
512 int stack_variable;
513 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700514
515 errno = pthread_attr_destroy(&attributes);
516 if (errno != 0) {
517 PLOG(FATAL) << "pthread_attr_destroy failed";
518 }
519}
520
Elliott Hughesa0957642011-09-02 14:27:33 -0700521void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700522 /*
523 * Get the java.lang.Thread object. This function gets called from
524 * some weird debug contexts, so it's possible that there's a GC in
525 * progress on some other thread. To decrease the chances of the
526 * thread object being moved out from under us, we add the reference
527 * to the tracked allocation list, which pins it in place.
528 *
529 * If threadObj is NULL, the thread is still in the process of being
530 * attached to the VM, and there's really nothing interesting to
531 * say about it yet.
532 */
533 os << "TODO: pin Thread before dumping\n";
534#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700535 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
536 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700537 LOGI("Can't dump thread %d: threadObj not set", threadId);
538 return;
539 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700540 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700541#endif
542
543 DumpState(os);
544 DumpStack(os);
545
546#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700547 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700548#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700549}
550
Elliott Hughesd92bec42011-09-02 17:04:36 -0700551std::string GetSchedulerGroup(pid_t tid) {
552 // /proc/<pid>/group looks like this:
553 // 2:devices:/
554 // 1:cpuacct,cpu:/
555 // We want the third field from the line whose second field contains the "cpu" token.
556 std::string cgroup_file;
557 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
558 return "";
559 }
560 std::vector<std::string> cgroup_lines;
561 Split(cgroup_file, '\n', cgroup_lines);
562 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
563 std::vector<std::string> cgroup_fields;
564 Split(cgroup_lines[i], ':', cgroup_fields);
565 std::vector<std::string> cgroups;
566 Split(cgroup_fields[1], ',', cgroups);
567 for (size_t i = 0; i < cgroups.size(); ++i) {
568 if (cgroups[i] == "cpu") {
569 return cgroup_fields[2].substr(1); // Skip the leading slash.
570 }
571 }
572 }
573 return "";
574}
575
576void Thread::DumpState(std::ostream& os) const {
577 std::string thread_name("unknown");
578 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700579
Elliott Hughesd92bec42011-09-02 17:04:36 -0700580#if 0 // TODO
581 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
582 threadName = dvmCreateCstrFromString(nameStr);
583 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700584#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700585 {
586 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
587 std::string stats;
588 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
589 size_t start = stats.find('(') + 1;
590 size_t end = stats.find(')') - start;
591 thread_name = stats.substr(start, end);
592 }
593 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700594 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700595#endif
596
597 int policy;
598 sched_param sp;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700599 errno = pthread_getschedparam(pthread_, &policy, &sp);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700600 if (errno != 0) {
601 PLOG(FATAL) << "pthread_getschedparam failed";
602 }
603
604 std::string scheduler_group(GetSchedulerGroup(GetTid()));
605 if (scheduler_group.empty()) {
606 scheduler_group = "default";
607 }
608
609 std::string group_name("(null; initializing?)");
610#if 0
611 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
612 if (groupObj != NULL) {
613 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
614 groupName = dvmCreateCstrFromString(nameStr);
615 }
616#else
617 group_name = "TODO";
618#endif
619
620 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700621 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700622 os << " daemon";
623 }
624 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700625 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700626 << " " << state_ << "\n";
627
628 int suspend_count = 0; // TODO
629 int debug_suspend_count = 0; // TODO
Elliott Hughesdcc24742011-09-07 14:02:44 -0700630 void* peer_ = NULL; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700631 os << " | group=\"" << group_name << "\""
632 << " sCount=" << suspend_count
633 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700634 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700635 << " self=" << reinterpret_cast<const void*>(this) << "\n";
636 os << " | sysTid=" << GetTid()
637 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
638 << " sched=" << policy << "/" << sp.sched_priority
639 << " cgrp=" << scheduler_group
640 << " handle=" << GetImpl() << "\n";
641
642 // Grab the scheduler stats for this thread.
643 std::string scheduler_stats;
644 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
645 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
646 } else {
647 scheduler_stats = "0 0 0";
648 }
649
650 int utime = 0;
651 int stime = 0;
652 int task_cpu = 0;
653 std::string stats;
654 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
655 // Skip the command, which may contain spaces.
656 stats = stats.substr(stats.find(')') + 2);
657 // Extract the three fields we care about.
658 std::vector<std::string> fields;
659 Split(stats, ' ', fields);
660 utime = strtoull(fields[11].c_str(), NULL, 10);
661 stime = strtoull(fields[12].c_str(), NULL, 10);
662 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
663 }
664
665 os << " | schedstat=( " << scheduler_stats << " )"
666 << " utm=" << utime
667 << " stm=" << stime
668 << " core=" << task_cpu
669 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
670}
671
672void Thread::DumpStack(std::ostream& os) const {
673 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700674}
675
Elliott Hughesbe759c62011-09-08 19:38:21 -0700676void Thread::ThreadExitCallback(void* arg) {
677 Thread* self = reinterpret_cast<Thread*>(arg);
678 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700679}
680
Elliott Hughesbe759c62011-09-08 19:38:21 -0700681void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700682 // Allocate a TLS slot.
Elliott Hughesbe759c62011-09-08 19:38:21 -0700683 errno = pthread_key_create(&Thread::pthread_key_self_, Thread::ThreadExitCallback);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700684 if (errno != 0) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700685 PLOG(FATAL) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700686 }
687
688 // Double-check the TLS slot allocation.
689 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700690 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700691 }
692
693 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700694}
695
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700696void Thread::Shutdown() {
697 errno = pthread_key_delete(Thread::pthread_key_self_);
698 if (errno != 0) {
699 PLOG(WARNING) << "pthread_key_delete failed";
700 }
701}
702
Elliott Hughesdcc24742011-09-07 14:02:44 -0700703Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700704 : peer_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700705 top_of_managed_stack_(),
706 native_to_managed_record_(NULL),
707 top_sirt_(NULL),
708 jni_env_(NULL),
709 exception_(NULL),
710 suspend_count_(0),
711 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700712 InitCpu();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700713 {
714 ThreadListLock mu;
715 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
716 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700717 InitFunctionPointers();
718}
719
Elliott Hughes02b48d12011-09-07 17:15:51 -0700720void MonitorExitVisitor(const Object* object, void*) {
721 Object* entered_monitor = const_cast<Object*>(object);
722 entered_monitor->MonitorExit();;
723}
724
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700725Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700726 // TODO: check we're not calling the JNI DetachCurrentThread function from
727 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
728
729 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
730 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
731
732 if (IsExceptionPending()) {
733 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
734 }
735
736 // TODO: ThreadGroup.removeThread(this);
737
738 // TODO: this.vmData = 0;
739
740 // TODO: say "bye" to the debugger.
741 //if (gDvm.debuggerConnected) {
742 // dvmDbgPostThreadDeath(self);
743 //}
744
745 // Thread.join() is implemented as an Object.wait() on the Thread.lock
746 // object. Signal anyone who is waiting.
747 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
748 //dvmLockObject(self, lock);
749 //dvmObjectNotifyAll(self, lock);
750 //dvmUnlockObject(self, lock);
751 //lock = NULL;
752
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700753 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700754 jni_env_ = NULL;
755
756 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700757}
758
Ian Rogers408f79a2011-08-23 18:22:33 -0700759size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700760 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700761 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700762 count += cur->NumberOfReferences();
763 }
764 return count;
765}
766
Ian Rogers408f79a2011-08-23 18:22:33 -0700767bool Thread::SirtContains(jobject obj) {
768 Object** sirt_entry = reinterpret_cast<Object**>(obj);
769 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700770 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700771 // A SIRT should always have a jobject/jclass as a native method is passed
772 // in a this pointer or a class
773 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700774 if ((&cur->References()[0] <= sirt_entry) &&
775 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700776 return true;
777 }
778 }
779 return false;
780}
781
Ian Rogers408f79a2011-08-23 18:22:33 -0700782Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700783 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700784 if (obj == NULL) {
785 return NULL;
786 }
787 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
788 IndirectRefKind kind = GetIndirectRefKind(ref);
789 Object* result;
790 switch (kind) {
791 case kLocal:
792 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700793 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700794 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700795 break;
796 }
797 case kGlobal:
798 {
799 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
800 IndirectReferenceTable& globals = vm->globals;
801 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700802 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700803 break;
804 }
805 case kWeakGlobal:
806 {
807 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
808 IndirectReferenceTable& weak_globals = vm->weak_globals;
809 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700810 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700811 if (result == kClearedJniWeakGlobal) {
812 // This is a special case where it's okay to return NULL.
813 return NULL;
814 }
815 break;
816 }
817 case kSirtOrInvalid:
818 default:
819 // TODO: make stack indirect reference table lookup more efficient
820 // Check if this is a local reference in the SIRT
821 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700822 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700823 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700824 // Assume an invalid local reference is actually a direct pointer.
825 result = reinterpret_cast<Object*>(obj);
826 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700827 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700828 }
829 }
830
831 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700832 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
833 JniAbort(NULL);
834 } else {
835 if (result != kInvalidIndirectRefObject) {
836 Heap::VerifyObject(result);
837 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700838 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700839 return result;
840}
841
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700842class CountStackDepthVisitor : public Thread::StackVisitor {
843 public:
844 CountStackDepthVisitor() : depth(0) {}
845 virtual bool VisitFrame(const Frame&) {
846 ++depth;
847 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700848 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700849
850 int GetDepth() const {
851 return depth;
852 }
853
854 private:
855 uint32_t depth;
856};
857
858class BuildStackTraceVisitor : public Thread::StackVisitor {
859 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700860 explicit BuildStackTraceVisitor(int depth) : count(0) {
861 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700862 pc_trace = IntArray::Alloc(depth);
863 }
864
865 virtual ~BuildStackTraceVisitor() {}
866
867 virtual bool VisitFrame(const Frame& frame) {
868 method_trace->Set(count, frame.GetMethod());
869 pc_trace->Set(count, frame.GetPC());
870 ++count;
871 return true;
872 }
873
874 const Method* GetMethod(uint32_t i) {
875 DCHECK(i < count);
876 return method_trace->Get(i);
877 }
878
879 uintptr_t GetPC(uint32_t i) {
880 DCHECK(i < count);
881 return pc_trace->Get(i);
882 }
883
884 private:
885 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700886 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700887 IntArray* pc_trace;
888};
889
890void Thread::WalkStack(StackVisitor* visitor) {
891 Frame frame = Thread::Current()->GetTopOfStack();
892 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
893 // CHECK(native_to_managed_record_ != NULL);
894 NativeToManagedRecord* record = native_to_managed_record_;
895
896 while (frame.GetSP()) {
897 for ( ; frame.GetMethod() != 0; frame.Next()) {
898 visitor->VisitFrame(frame);
899 }
900 if (record == NULL) {
901 break;
902 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700903 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 -0700904 record = record->link;
905 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700906}
907
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700908ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700909 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700910
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700911 CountStackDepthVisitor count_visitor;
912 WalkStack(&count_visitor);
913 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700914
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700915 BuildStackTraceVisitor build_trace_visitor(depth);
916 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700917
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700918 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700919
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700920 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700921 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700922 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700923 const Class* klass = method->GetDeclaringClass();
924 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700925 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700926 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700927
928 StackTraceElement* obj =
929 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700930 method->GetName(),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700931 String::AllocFromModifiedUtf8(klass->GetSourceFile()),
Shih-wei Liao44175362011-08-28 16:59:17 -0700932 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700933 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700934 java_traces->Set(i, obj);
935 }
936 return java_traces;
937}
938
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700939void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700940 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700941 va_list args;
942 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700943 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700944 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700945
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700946 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700947 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700948 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700949 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700950 descriptor.erase(descriptor.length() - 1);
951
952 JNIEnv* env = GetJniEnv();
953 jclass exception_class = env->FindClass(descriptor.c_str());
954 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
955 int rc = env->ThrowNew(exception_class, msg.c_str());
956 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700957}
958
Elliott Hughes79082e32011-08-25 12:07:32 -0700959void Thread::ThrowOutOfMemoryError() {
960 UNIMPLEMENTED(FATAL);
961}
962
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700963Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
964 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
965 DCHECK(class_linker != NULL);
966
967 Frame cur_frame = GetTopOfStack();
968 for (int unwind_depth = 0; ; unwind_depth++) {
969 const Method* cur_method = cur_frame.GetMethod();
970 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
971 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
972
973 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
974 throw_pc,
975 dex_file,
976 class_linker);
977 if (handler_addr) {
978 *handler_pc = handler_addr;
979 return cur_frame;
980 } else {
981 // Check if we are at the last frame
982 if (cur_frame.HasNext()) {
983 cur_frame.Next();
984 } else {
985 // Either at the top of stack or next frame is native.
986 break;
987 }
988 }
989 }
990 *handler_pc = NULL;
991 return Frame();
992}
993
994void* Thread::FindExceptionHandlerInMethod(const Method* method,
995 void* throw_pc,
996 const DexFile& dex_file,
997 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700998 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700999 exception_ = NULL;
1000
1001 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001002 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001003 DexFile::CatchHandlerIterator iter;
1004 for (iter = dex_file.dexFindCatchHandler(*code_item,
1005 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
1006 !iter.HasNext();
1007 iter.Next()) {
1008 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
1009 DCHECK(klass != NULL);
1010 if (exception_obj->InstanceOf(klass)) {
1011 dex_pc = iter.Get().address_;
1012 break;
1013 }
1014 }
1015
1016 exception_ = exception_obj;
1017 if (iter.HasNext()) {
1018 return NULL;
1019 } else {
1020 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
1021 }
1022}
1023
Elliott Hughes410c0c82011-09-01 17:58:25 -07001024void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
1025 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
1026 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
1027 jni_env_->locals.VisitRoots(visitor, arg);
1028 jni_env_->monitors.VisitRoots(visitor, arg);
1029 // visitThreadStack(visitor, thread, arg);
1030 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1031}
1032
Ian Rogersb033c752011-07-20 12:22:35 -07001033static const char* kStateNames[] = {
1034 "New",
1035 "Runnable",
1036 "Blocked",
1037 "Waiting",
1038 "TimedWaiting",
1039 "Native",
1040 "Terminated",
1041};
1042std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
1043 if (state >= Thread::kNew && state <= Thread::kTerminated) {
1044 os << kStateNames[state-Thread::kNew];
1045 } else {
1046 os << "State[" << static_cast<int>(state) << "]";
1047 }
1048 return os;
1049}
1050
Elliott Hughes330304d2011-08-12 14:28:05 -07001051std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1052 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001053 << ",pthread_t=" << thread.GetImpl()
1054 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001055 << ",id=" << thread.GetThinLockId()
Elliott Hughese27955c2011-08-26 15:21:24 -07001056 << ",state=" << thread.GetState() << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001057 return os;
1058}
1059
Carl Shapiro61e019d2011-07-14 16:53:09 -07001060ThreadList* ThreadList::Create() {
1061 return new ThreadList;
1062}
1063
Carl Shapirob5573532011-07-12 18:22:59 -07001064ThreadList::ThreadList() {
1065 lock_ = Mutex::Create("ThreadList::Lock");
1066}
1067
1068ThreadList::~ThreadList() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001069 if (Contains(Thread::Current())) {
1070 Runtime::Current()->DetachCurrentThread();
1071 }
1072
1073 // All threads should have exited and unregistered when we
Carl Shapirob5573532011-07-12 18:22:59 -07001074 // reach this point. This means that all daemon threads had been
1075 // shutdown cleanly.
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001076 // TODO: dump ThreadList if non-empty.
1077 CHECK_EQ(list_.size(), 0U);
1078
Carl Shapirob5573532011-07-12 18:22:59 -07001079 delete lock_;
1080 lock_ = NULL;
1081}
1082
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001083bool ThreadList::Contains(Thread* thread) {
1084 return find(list_.begin(), list_.end(), thread) != list_.end();
1085}
1086
Elliott Hughesd92bec42011-09-02 17:04:36 -07001087void ThreadList::Dump(std::ostream& os) {
1088 MutexLock mu(lock_);
1089 os << "DALVIK THREADS (" << list_.size() << "):\n";
1090 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
1091 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
1092 (*it)->Dump(os);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001093 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -07001094 }
1095}
1096
Carl Shapirob5573532011-07-12 18:22:59 -07001097void ThreadList::Register(Thread* thread) {
Elliott Hughesbe759c62011-09-08 19:38:21 -07001098 //LOG(INFO) << "ThreadList::Register() " << *thread;
Carl Shapirob5573532011-07-12 18:22:59 -07001099 MutexLock mu(lock_);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001100 CHECK(!Contains(thread));
Elliott Hughesdcc24742011-09-07 14:02:44 -07001101 list_.push_back(thread);
Carl Shapirob5573532011-07-12 18:22:59 -07001102}
1103
Elliott Hughes02b48d12011-09-07 17:15:51 -07001104void ThreadList::Unregister() {
Elliott Hughes02b48d12011-09-07 17:15:51 -07001105 Thread* self = Thread::Current();
Elliott Hughesbe759c62011-09-08 19:38:21 -07001106
1107 //LOG(INFO) << "ThreadList::Unregister() " << self;
1108 MutexLock mu(lock_);
1109
1110 // Remove this thread from the list.
Elliott Hughes02b48d12011-09-07 17:15:51 -07001111 CHECK(Contains(self));
1112 list_.remove(self);
Elliott Hughesbe759c62011-09-08 19:38:21 -07001113
1114 // Delete the Thread* and release the thin lock id.
Elliott Hughes02b48d12011-09-07 17:15:51 -07001115 uint32_t thin_lock_id = self->thin_lock_id_;
1116 delete self;
1117 ReleaseThreadId(thin_lock_id);
Elliott Hughesbe759c62011-09-08 19:38:21 -07001118
1119 // Clear the TLS data, so that thread is recognizably detached.
1120 // (It may wish to reattach later.)
1121 errno = pthread_setspecific(Thread::pthread_key_self_, NULL);
1122 if (errno != 0) {
1123 PLOG(FATAL) << "pthread_setspecific failed";
1124 }
Carl Shapirob5573532011-07-12 18:22:59 -07001125}
1126
Elliott Hughes410c0c82011-09-01 17:58:25 -07001127void ThreadList::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
1128 MutexLock mu(lock_);
1129 typedef std::list<Thread*>::const_iterator It; // TODO: C++0x auto
1130 for (It it = list_.begin(), end = list_.end(); it != end; ++it) {
1131 (*it)->VisitRoots(visitor, arg);
1132 }
1133}
1134
Elliott Hughes02b48d12011-09-07 17:15:51 -07001135uint32_t ThreadList::AllocThreadId() {
Elliott Hughes92b3b562011-09-08 16:32:26 -07001136 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001137 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1138 if (!allocated_ids_[i]) {
1139 allocated_ids_.set(i);
1140 return i + 1; // Zero is reserved to mean "invalid".
1141 }
1142 }
1143 LOG(FATAL) << "Out of internal thread ids";
1144 return 0;
1145}
1146
1147void ThreadList::ReleaseThreadId(uint32_t id) {
Elliott Hughes92b3b562011-09-08 16:32:26 -07001148 DCHECK_LOCK_HELD(lock_);
Elliott Hughes02b48d12011-09-07 17:15:51 -07001149 --id; // Zero is reserved to mean "invalid".
1150 DCHECK(allocated_ids_[id]) << id;
1151 allocated_ids_.reset(id);
1152}
1153
Carl Shapirob5573532011-07-12 18:22:59 -07001154} // namespace