blob: 4b477b8b81165363e9c389c9ad17fc6788cf1a2d [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 Hughes8daa0922011-09-11 13:46:25 -070020#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070021#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070022
23namespace art {
24
25pthread_key_t Thread::pthread_key_self_;
26
buzbee4a3164f2011-09-03 11:25:10 -070027// Temporary debugging hook for compiler.
28static void DebugMe(Method* method, uint32_t info) {
29 LOG(INFO) << "DebugMe";
30 if (method != NULL)
31 LOG(INFO) << PrettyMethod(method);
32 LOG(INFO) << "Info: " << info;
33}
34
35/*
36 * TODO: placeholder for a method that can be called by the
37 * invoke-interface trampoline to unwind and handle exception. The
38 * trampoline will arrange it so that the caller appears to be the
39 * callsite of the failed invoke-interface. See comments in
40 * compiler/runtime_support.S
41 */
42extern "C" void artFailedInvokeInterface()
43{
44 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
45}
46
47// TODO: placeholder. See comments in compiler/runtime_support.S
48extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
49 Object* this_object , Method* caller_method)
50{
51 /*
52 * Note: this_object has not yet been null-checked. To match
53 * the old-world state, nullcheck this_object and load
54 * Class* this_class = this_object->GetClass().
55 * See comments and possible thrown exceptions in old-world
56 * Interp.cpp:dvmInterpFindInterfaceMethod, and complete with
57 * new-world FindVirtualMethodForInterface.
58 */
59 UNIMPLEMENTED(FATAL) << "Unimplemented invoke interface";
60 return 0LL;
61}
62
buzbee1b4c8592011-08-31 10:43:51 -070063// TODO: placeholder. This is what generated code will call to throw
64static void ThrowException(Thread* thread, Throwable* exception) {
65 /*
66 * exception may be NULL, in which case this routine should
67 * throw NPE. NOTE: this is a convenience for generated code,
68 * which previuosly did the null check inline and constructed
69 * and threw a NPE if NULL. This routine responsible for setting
70 * exception_ in thread.
71 */
72 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
73}
74
75// TODO: placeholder. Helper function to type
76static Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
77 /*
78 * Should initialize & fix up method->dex_cache_resolved_types_[].
79 * Returns initialized type. Does not return normally if an exception
80 * is thrown, but instead initiates the catch. Should be similar to
81 * ClassLinker::InitializeStaticStorageFromCode.
82 */
83 UNIMPLEMENTED(FATAL);
84 return NULL;
85}
86
buzbee561227c2011-09-02 15:28:19 -070087// TODO: placeholder. Helper function to resolve virtual method
88static void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
89 /*
90 * Slow-path handler on invoke virtual method path in which
91 * base method is unresolved at compile-time. Doesn't need to
92 * return anything - just either ensure that
93 * method->dex_cache_resolved_methods_(method_idx) != NULL or
94 * throw and unwind. The caller will restart call sequence
95 * from the beginning.
96 */
97}
98
buzbee1da522d2011-09-04 11:22:20 -070099// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
100static Array* CheckAndAllocFromCode(uint32_t type_index, Method* method,
101 int32_t component_count)
102{
103 /*
104 * Just a wrapper around Array::AllocFromCode() that additionally
105 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
106 */
107 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
108 return Array::AllocFromCode(type_index, method, component_count);
109}
110
buzbee2a475e72011-09-07 17:19:17 -0700111// TODO: placeholder (throw on failure)
112static void CheckCastFromCode(const Class* a, const Class* b) {
113 if (a->IsAssignableFrom(b)) {
114 return;
115 }
116 UNIMPLEMENTED(FATAL);
117}
118
119// TODO: placeholder
120static void UnlockObjectFromCode(Thread* thread, Object* obj) {
121 // TODO: throw and unwind if lock not held
122 // TODO: throw and unwind on NPE
buzbee4ef76522011-09-08 10:00:32 -0700123 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700124}
125
126// TODO: placeholder
127static void LockObjectFromCode(Thread* thread, Object* obj) {
buzbee4ef76522011-09-08 10:00:32 -0700128 obj->MonitorEnter(thread);
buzbee2a475e72011-09-07 17:19:17 -0700129}
130
buzbee0d966cf2011-09-08 17:34:58 -0700131// TODO: placeholder
132static void CheckSuspendFromCode(Thread* thread) {
133 /*
134 * Code is at a safe point, suspend if needed.
135 * Also, this is where a pending safepoint callback
136 * would be fired.
137 */
138}
139
buzbeecefd1872011-09-09 09:59:52 -0700140// TODO: placeholder
141static void StackOverflowFromCode(Method* method) {
142 //NOTE: to save code space, this handler needs to look up its own Thread*
143 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
144}
145
buzbee5ade1d22011-09-09 14:44:52 -0700146// TODO: placeholder
147static void ThrowNullPointerFromCode() {
148 //NOTE: to save code space, this handler must look up caller's Method*
149 UNIMPLEMENTED(FATAL) << "Null pointer exception";
150}
151
152// TODO: placeholder
153static void ThrowDivZeroFromCode() {
154 UNIMPLEMENTED(FATAL) << "Divide by zero";
155}
156
157// TODO: placeholder
158static void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
159 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index <<
160 ", limit: " << limit;
161}
162
163// TODO: placeholder
164static void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
165 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
166 " ref: " << ref;
167}
168
169// TODO: placeholder
170static void ThrowNegArraySizeFromCode(int32_t index) {
171 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
172}
173
174// TODO: placeholder
175static void ThrowInternalErrorFromCode(int32_t errnum) {
176 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
177}
178
179// TODO: placeholder
180static void ThrowRuntimeExceptionFromCode(int32_t errnum) {
181 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
182}
183
184// TODO: placeholder
185static void ThrowNoSuchMethodFromCode(int32_t method_idx) {
186 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
187}
188
189/*
190 * Temporary placeholder. Should include run-time checks for size
191 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
192 * As with other new "FromCode" routines, this should return to the caller
193 * only if no exception has been thrown.
194 *
195 * NOTE: When dealing with a raw dex file, the data to be copied uses
196 * little-endian ordering. Require that oat2dex do any required swapping
197 * so this routine can get by with a memcpy().
198 *
199 * Format of the data:
200 * ushort ident = 0x0300 magic value
201 * ushort width width of each element in the table
202 * uint size number of elements in the table
203 * ubyte data[size*width] table of data values (may contain a single-byte
204 * padding at the end)
205 */
206static void HandleFillArrayDataFromCode(Array* array, const uint16_t* table)
207{
208 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
209 uint32_t size_in_bytes = size * table[1];
210 if (static_cast<int32_t>(size) > array->GetLength()) {
211 ThrowArrayBoundsFromCode(array->GetLength(), size);
212 }
213 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
214 (char*)&table[4], size_in_bytes);
215}
216
217// TODO: move to more appropriate location
218/*
219 * Float/double conversion requires clamping to min and max of integer form. If
220 * target doesn't support this normally, use these.
221 */
222static int64_t D2L(double d)
223{
224 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
225 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
226 if (d >= kMaxLong)
227 return (int64_t)0x7fffffffffffffffULL;
228 else if (d <= kMinLong)
229 return (int64_t)0x8000000000000000ULL;
230 else if (d != d) // NaN case
231 return 0;
232 else
233 return (int64_t)d;
234}
235
236static int64_t F2L(float f)
237{
238 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
239 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
240 if (f >= kMaxLong)
241 return (int64_t)0x7fffffffffffffffULL;
242 else if (f <= kMinLong)
243 return (int64_t)0x8000000000000000ULL;
244 else if (f != f) // NaN case
245 return 0;
246 else
247 return (int64_t)f;
248}
249
buzbee3ea4ec52011-08-22 17:37:19 -0700250void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700251#if defined(__arm__)
252 pShlLong = art_shl_long;
253 pShrLong = art_shr_long;
254 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700255 pIdiv = __aeabi_idiv;
256 pIdivmod = __aeabi_idivmod;
257 pI2f = __aeabi_i2f;
258 pF2iz = __aeabi_f2iz;
259 pD2f = __aeabi_d2f;
260 pF2d = __aeabi_f2d;
261 pD2iz = __aeabi_d2iz;
262 pL2f = __aeabi_l2f;
263 pL2d = __aeabi_l2d;
264 pFadd = __aeabi_fadd;
265 pFsub = __aeabi_fsub;
266 pFdiv = __aeabi_fdiv;
267 pFmul = __aeabi_fmul;
268 pFmodf = fmodf;
269 pDadd = __aeabi_dadd;
270 pDsub = __aeabi_dsub;
271 pDdiv = __aeabi_ddiv;
272 pDmul = __aeabi_dmul;
273 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700274 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700275 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700276 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700277#endif
buzbeec396efc2011-09-11 09:36:41 -0700278 pF2l = F2L;
279 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700280 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700281 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700282 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700283 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700284 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700285 pGet32Static = Field::Get32StaticFromCode;
286 pSet32Static = Field::Set32StaticFromCode;
287 pGet64Static = Field::Get64StaticFromCode;
288 pSet64Static = Field::Set64StaticFromCode;
289 pGetObjStatic = Field::GetObjStaticFromCode;
290 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700291 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
292 pThrowException = ThrowException;
293 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700294 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700295 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700296 pInstanceofNonTrivialFromCode = Object::InstanceOf;
297 pCheckCastFromCode = CheckCastFromCode;
298 pLockObjectFromCode = LockObjectFromCode;
299 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700300 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700301 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700302 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700303 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
304 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
305 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
306 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
307 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
308 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
309 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
310 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700311 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700312}
313
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700314void Frame::Next() {
315 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700316 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700317 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700318}
319
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700320uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700321 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700322 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700323 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700324}
325
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700326Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700327 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700328 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700329 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700330}
331
Carl Shapiro61e019d2011-07-14 16:53:09 -0700332void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700333 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700334 return NULL;
335}
336
Brian Carlstromb765be02011-08-17 23:54:10 -0700337Thread* Thread::Create(const Runtime* runtime) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700338 UNIMPLEMENTED(FATAL) << "need to pass in a java.lang.Thread";
339
Elliott Hughesbe759c62011-09-08 19:38:21 -0700340 size_t stack_size = runtime->GetDefaultStackSize();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700341
342 Thread* new_thread = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700343
344 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700345 errno = pthread_attr_init(&attr);
346 if (errno != 0) {
347 PLOG(FATAL) << "pthread_attr_init failed";
348 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700349
Elliott Hughese27955c2011-08-26 15:21:24 -0700350 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
351 if (errno != 0) {
352 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
353 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700354
Elliott Hughese27955c2011-08-26 15:21:24 -0700355 errno = pthread_attr_setstacksize(&attr, stack_size);
356 if (errno != 0) {
357 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
358 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700359
Elliott Hughesbe759c62011-09-08 19:38:21 -0700360 errno = pthread_create(&new_thread->pthread_, &attr, ThreadStart, new_thread);
Elliott Hughese27955c2011-08-26 15:21:24 -0700361 if (errno != 0) {
362 PLOG(FATAL) << "pthread_create failed";
363 }
364
365 errno = pthread_attr_destroy(&attr);
366 if (errno != 0) {
367 PLOG(FATAL) << "pthread_attr_destroy failed";
368 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700369
Elliott Hughesdcc24742011-09-07 14:02:44 -0700370 // TODO: get the "daemon" field from the java.lang.Thread.
371 // new_thread->is_daemon_ = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon);
372
Carl Shapiro61e019d2011-07-14 16:53:09 -0700373 return new_thread;
374}
375
Elliott Hughesdcc24742011-09-07 14:02:44 -0700376Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700377 Thread* self = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700378
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700379 self->tid_ = ::art::GetTid();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700380 self->pthread_ = pthread_self();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700381 self->is_daemon_ = as_daemon;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700382
Elliott Hughesbe759c62011-09-08 19:38:21 -0700383 self->InitStackHwm();
384
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700385 self->state_ = kRunnable;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700386
Elliott Hughesdcc24742011-09-07 14:02:44 -0700387 SetThreadName(name);
388
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700389 errno = pthread_setspecific(Thread::pthread_key_self_, self);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700390 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700391 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700392 }
393
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700394 self->jni_env_ = new JNIEnvExt(self, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700395
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700396 runtime->GetThreadList()->Register(self);
397
398 // If we're the main thread, ClassLinker won't be created until after we're attached,
399 // so that thread needs a two-stage attach. Regular threads don't need this hack.
400 if (self->thin_lock_id_ != ThreadList::kMainId) {
401 self->CreatePeer(name, as_daemon);
402 }
403
404 return self;
405}
406
407void Thread::CreatePeer(const char* name, bool as_daemon) {
408 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
409
410 JNIEnv* env = jni_env_;
411
412 jobject thread_group = NULL;
413 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700414 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700415 jboolean thread_is_daemon = as_daemon;
416
417 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700418 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700419
Elliott Hughes8daa0922011-09-11 13:46:25 -0700420 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
421 peer_ = env->NewGlobalRef(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700422}
423
Elliott Hughesbe759c62011-09-08 19:38:21 -0700424void Thread::InitStackHwm() {
425 pthread_attr_t attributes;
426 errno = pthread_getattr_np(pthread_, &attributes);
427 if (errno != 0) {
428 PLOG(FATAL) << "pthread_getattr_np failed";
429 }
430
Elliott Hughesbe759c62011-09-08 19:38:21 -0700431 void* stack_base;
432 size_t stack_size;
433 errno = pthread_attr_getstack(&attributes, &stack_base, &stack_size);
434 if (errno != 0) {
435 PLOG(FATAL) << "pthread_attr_getstack failed";
436 }
437
Elliott Hughesbe759c62011-09-08 19:38:21 -0700438 if (stack_size <= kStackOverflowReservedBytes) {
439 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
440 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700441
442 // stack_base is the "lowest addressable byte" of the stack.
443 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
444 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700445 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700446
447 // Sanity check.
448 int stack_variable;
449 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700450
451 errno = pthread_attr_destroy(&attributes);
452 if (errno != 0) {
453 PLOG(FATAL) << "pthread_attr_destroy failed";
454 }
455}
456
Elliott Hughesa0957642011-09-02 14:27:33 -0700457void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700458 /*
459 * Get the java.lang.Thread object. This function gets called from
460 * some weird debug contexts, so it's possible that there's a GC in
461 * progress on some other thread. To decrease the chances of the
462 * thread object being moved out from under us, we add the reference
463 * to the tracked allocation list, which pins it in place.
464 *
465 * If threadObj is NULL, the thread is still in the process of being
466 * attached to the VM, and there's really nothing interesting to
467 * say about it yet.
468 */
469 os << "TODO: pin Thread before dumping\n";
470#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700471 // TODO: dalvikvm had this limitation, but we probably still want to do our best.
472 if (peer_ == NULL) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700473 LOGI("Can't dump thread %d: threadObj not set", threadId);
474 return;
475 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700476 dvmAddTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700477#endif
478
479 DumpState(os);
480 DumpStack(os);
481
482#if 0
Elliott Hughesdcc24742011-09-07 14:02:44 -0700483 dvmReleaseTrackedAlloc(peer_, NULL);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700484#endif
Elliott Hughesa0957642011-09-02 14:27:33 -0700485}
486
Elliott Hughesd92bec42011-09-02 17:04:36 -0700487std::string GetSchedulerGroup(pid_t tid) {
488 // /proc/<pid>/group looks like this:
489 // 2:devices:/
490 // 1:cpuacct,cpu:/
491 // We want the third field from the line whose second field contains the "cpu" token.
492 std::string cgroup_file;
493 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
494 return "";
495 }
496 std::vector<std::string> cgroup_lines;
497 Split(cgroup_file, '\n', cgroup_lines);
498 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
499 std::vector<std::string> cgroup_fields;
500 Split(cgroup_lines[i], ':', cgroup_fields);
501 std::vector<std::string> cgroups;
502 Split(cgroup_fields[1], ',', cgroups);
503 for (size_t i = 0; i < cgroups.size(); ++i) {
504 if (cgroups[i] == "cpu") {
505 return cgroup_fields[2].substr(1); // Skip the leading slash.
506 }
507 }
508 }
509 return "";
510}
511
512void Thread::DumpState(std::ostream& os) const {
513 std::string thread_name("unknown");
514 int priority = -1;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700515
Elliott Hughesd92bec42011-09-02 17:04:36 -0700516#if 0 // TODO
517 nameStr = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name);
518 threadName = dvmCreateCstrFromString(nameStr);
519 priority = dvmGetFieldInt(threadObj, gDvm.offJavaLangThread_priority);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700520#else
Elliott Hughesdcc24742011-09-07 14:02:44 -0700521 {
522 // TODO: this may be truncated; we should use the java.lang.Thread 'name' field instead.
523 std::string stats;
524 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
525 size_t start = stats.find('(') + 1;
526 size_t end = stats.find(')') - start;
527 thread_name = stats.substr(start, end);
528 }
529 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700530 priority = -1;
Elliott Hughesd92bec42011-09-02 17:04:36 -0700531#endif
532
533 int policy;
534 sched_param sp;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700535 errno = pthread_getschedparam(pthread_, &policy, &sp);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700536 if (errno != 0) {
537 PLOG(FATAL) << "pthread_getschedparam failed";
538 }
539
540 std::string scheduler_group(GetSchedulerGroup(GetTid()));
541 if (scheduler_group.empty()) {
542 scheduler_group = "default";
543 }
544
545 std::string group_name("(null; initializing?)");
546#if 0
547 groupObj = (Object*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_group);
548 if (groupObj != NULL) {
549 nameStr = (StringObject*) dvmGetFieldObject(groupObj, gDvm.offJavaLangThreadGroup_name);
550 groupName = dvmCreateCstrFromString(nameStr);
551 }
552#else
553 group_name = "TODO";
554#endif
555
556 os << '"' << thread_name << '"';
Elliott Hughesdcc24742011-09-07 14:02:44 -0700557 if (is_daemon_) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700558 os << " daemon";
559 }
560 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700561 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700562 << " " << state_ << "\n";
563
564 int suspend_count = 0; // TODO
565 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700566 os << " | group=\"" << group_name << "\""
567 << " sCount=" << suspend_count
568 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700569 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700570 << " self=" << reinterpret_cast<const void*>(this) << "\n";
571 os << " | sysTid=" << GetTid()
572 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
573 << " sched=" << policy << "/" << sp.sched_priority
574 << " cgrp=" << scheduler_group
575 << " handle=" << GetImpl() << "\n";
576
577 // Grab the scheduler stats for this thread.
578 std::string scheduler_stats;
579 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
580 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
581 } else {
582 scheduler_stats = "0 0 0";
583 }
584
585 int utime = 0;
586 int stime = 0;
587 int task_cpu = 0;
588 std::string stats;
589 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
590 // Skip the command, which may contain spaces.
591 stats = stats.substr(stats.find(')') + 2);
592 // Extract the three fields we care about.
593 std::vector<std::string> fields;
594 Split(stats, ' ', fields);
595 utime = strtoull(fields[11].c_str(), NULL, 10);
596 stime = strtoull(fields[12].c_str(), NULL, 10);
597 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
598 }
599
600 os << " | schedstat=( " << scheduler_stats << " )"
601 << " utm=" << utime
602 << " stm=" << stime
603 << " core=" << task_cpu
604 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
605}
606
607void Thread::DumpStack(std::ostream& os) const {
608 os << "UNIMPLEMENTED: Thread::DumpStack\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700609}
610
Elliott Hughesbe759c62011-09-08 19:38:21 -0700611void Thread::ThreadExitCallback(void* arg) {
612 Thread* self = reinterpret_cast<Thread*>(arg);
613 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700614}
615
Elliott Hughesbe759c62011-09-08 19:38:21 -0700616void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700617 // Allocate a TLS slot.
Elliott Hughesbe759c62011-09-08 19:38:21 -0700618 errno = pthread_key_create(&Thread::pthread_key_self_, Thread::ThreadExitCallback);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700619 if (errno != 0) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700620 PLOG(FATAL) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700621 }
622
623 // Double-check the TLS slot allocation.
624 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700625 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700626 }
627
628 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700629}
630
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700631void Thread::Shutdown() {
632 errno = pthread_key_delete(Thread::pthread_key_self_);
633 if (errno != 0) {
634 PLOG(WARNING) << "pthread_key_delete failed";
635 }
636}
637
Elliott Hughesdcc24742011-09-07 14:02:44 -0700638Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700639 : peer_(NULL),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700640 wait_mutex_("Thread wait mutex"),
641 wait_monitor_(NULL),
642 interrupted_(false),
643 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700644 top_of_managed_stack_(),
645 native_to_managed_record_(NULL),
646 top_sirt_(NULL),
647 jni_env_(NULL),
648 exception_(NULL),
649 suspend_count_(0),
650 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700651 InitCpu();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700652 InitFunctionPointers();
Elliott Hughes8daa0922011-09-11 13:46:25 -0700653 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700654}
655
Elliott Hughes02b48d12011-09-07 17:15:51 -0700656void MonitorExitVisitor(const Object* object, void*) {
657 Object* entered_monitor = const_cast<Object*>(object);
658 entered_monitor->MonitorExit();;
659}
660
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700661Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700662 // TODO: check we're not calling the JNI DetachCurrentThread function from
663 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
664
665 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
666 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
667
668 if (IsExceptionPending()) {
669 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
670 }
671
672 // TODO: ThreadGroup.removeThread(this);
673
674 // TODO: this.vmData = 0;
675
676 // TODO: say "bye" to the debugger.
677 //if (gDvm.debuggerConnected) {
678 // dvmDbgPostThreadDeath(self);
679 //}
680
681 // Thread.join() is implemented as an Object.wait() on the Thread.lock
682 // object. Signal anyone who is waiting.
683 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
684 //dvmLockObject(self, lock);
685 //dvmObjectNotifyAll(self, lock);
686 //dvmUnlockObject(self, lock);
687 //lock = NULL;
688
Elliott Hughes8daa0922011-09-11 13:46:25 -0700689 // Delete our global reference to the java.lang.Thread.
690 jni_env_->DeleteGlobalRef(peer_);
691 peer_ = NULL;
692
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700693 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700694 jni_env_ = NULL;
695
696 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700697}
698
Ian Rogers408f79a2011-08-23 18:22:33 -0700699size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700700 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700701 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700702 count += cur->NumberOfReferences();
703 }
704 return count;
705}
706
Ian Rogers408f79a2011-08-23 18:22:33 -0700707bool Thread::SirtContains(jobject obj) {
708 Object** sirt_entry = reinterpret_cast<Object**>(obj);
709 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700710 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700711 // A SIRT should always have a jobject/jclass as a native method is passed
712 // in a this pointer or a class
713 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700714 if ((&cur->References()[0] <= sirt_entry) &&
715 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700716 return true;
717 }
718 }
719 return false;
720}
721
Ian Rogers408f79a2011-08-23 18:22:33 -0700722Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700723 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700724 if (obj == NULL) {
725 return NULL;
726 }
727 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
728 IndirectRefKind kind = GetIndirectRefKind(ref);
729 Object* result;
730 switch (kind) {
731 case kLocal:
732 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700733 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700734 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700735 break;
736 }
737 case kGlobal:
738 {
739 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
740 IndirectReferenceTable& globals = vm->globals;
741 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700742 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700743 break;
744 }
745 case kWeakGlobal:
746 {
747 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
748 IndirectReferenceTable& weak_globals = vm->weak_globals;
749 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700750 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700751 if (result == kClearedJniWeakGlobal) {
752 // This is a special case where it's okay to return NULL.
753 return NULL;
754 }
755 break;
756 }
757 case kSirtOrInvalid:
758 default:
759 // TODO: make stack indirect reference table lookup more efficient
760 // Check if this is a local reference in the SIRT
761 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700762 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700763 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700764 // Assume an invalid local reference is actually a direct pointer.
765 result = reinterpret_cast<Object*>(obj);
766 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700767 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700768 }
769 }
770
771 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700772 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
773 JniAbort(NULL);
774 } else {
775 if (result != kInvalidIndirectRefObject) {
776 Heap::VerifyObject(result);
777 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700778 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700779 return result;
780}
781
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700782class CountStackDepthVisitor : public Thread::StackVisitor {
783 public:
784 CountStackDepthVisitor() : depth(0) {}
785 virtual bool VisitFrame(const Frame&) {
786 ++depth;
787 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700788 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700789
790 int GetDepth() const {
791 return depth;
792 }
793
794 private:
795 uint32_t depth;
796};
797
798class BuildStackTraceVisitor : public Thread::StackVisitor {
799 public:
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700800 explicit BuildStackTraceVisitor(int depth) : count(0) {
801 method_trace = Runtime::Current()->GetClassLinker()->AllocObjectArray<Method>(depth);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700802 pc_trace = IntArray::Alloc(depth);
803 }
804
805 virtual ~BuildStackTraceVisitor() {}
806
807 virtual bool VisitFrame(const Frame& frame) {
808 method_trace->Set(count, frame.GetMethod());
809 pc_trace->Set(count, frame.GetPC());
810 ++count;
811 return true;
812 }
813
814 const Method* GetMethod(uint32_t i) {
815 DCHECK(i < count);
816 return method_trace->Get(i);
817 }
818
819 uintptr_t GetPC(uint32_t i) {
820 DCHECK(i < count);
821 return pc_trace->Get(i);
822 }
823
824 private:
825 uint32_t count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700826 ObjectArray<Method>* method_trace;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700827 IntArray* pc_trace;
828};
829
830void Thread::WalkStack(StackVisitor* visitor) {
831 Frame frame = Thread::Current()->GetTopOfStack();
832 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
833 // CHECK(native_to_managed_record_ != NULL);
834 NativeToManagedRecord* record = native_to_managed_record_;
835
836 while (frame.GetSP()) {
837 for ( ; frame.GetMethod() != 0; frame.Next()) {
838 visitor->VisitFrame(frame);
839 }
840 if (record == NULL) {
841 break;
842 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700843 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 -0700844 record = record->link;
845 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700846}
847
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700848ObjectArray<StackTraceElement>* Thread::AllocStackTrace() {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700849 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Shih-wei Liao44175362011-08-28 16:59:17 -0700850
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700851 CountStackDepthVisitor count_visitor;
852 WalkStack(&count_visitor);
853 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700854
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700855 BuildStackTraceVisitor build_trace_visitor(depth);
856 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700857
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700858 ObjectArray<StackTraceElement>* java_traces = class_linker->AllocStackTraceElementArray(depth);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700859
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700860 for (int32_t i = 0; i < depth; ++i) {
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700861 // Prepare parameter for StackTraceElement(String cls, String method, String file, int line)
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700862 const Method* method = build_trace_visitor.GetMethod(i);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700863 const Class* klass = method->GetDeclaringClass();
864 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700865 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700866 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700867
868 StackTraceElement* obj =
869 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700870 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700871 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -0700872 dex_file.GetLineNumFromPC(method,
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700873 method->ToDexPC(build_trace_visitor.GetPC(i))));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700874 java_traces->Set(i, obj);
875 }
876 return java_traces;
877}
878
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700879void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700880 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700881 va_list args;
882 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700883 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700884 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700885
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700886 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700887 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700888 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700889 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700890 descriptor.erase(descriptor.length() - 1);
891
892 JNIEnv* env = GetJniEnv();
893 jclass exception_class = env->FindClass(descriptor.c_str());
894 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
895 int rc = env->ThrowNew(exception_class, msg.c_str());
896 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700897}
898
Elliott Hughes79082e32011-08-25 12:07:32 -0700899void Thread::ThrowOutOfMemoryError() {
900 UNIMPLEMENTED(FATAL);
901}
902
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700903Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
904 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
905 DCHECK(class_linker != NULL);
906
907 Frame cur_frame = GetTopOfStack();
908 for (int unwind_depth = 0; ; unwind_depth++) {
909 const Method* cur_method = cur_frame.GetMethod();
910 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
911 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
912
913 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
914 throw_pc,
915 dex_file,
916 class_linker);
917 if (handler_addr) {
918 *handler_pc = handler_addr;
919 return cur_frame;
920 } else {
921 // Check if we are at the last frame
922 if (cur_frame.HasNext()) {
923 cur_frame.Next();
924 } else {
925 // Either at the top of stack or next frame is native.
926 break;
927 }
928 }
929 }
930 *handler_pc = NULL;
931 return Frame();
932}
933
934void* Thread::FindExceptionHandlerInMethod(const Method* method,
935 void* throw_pc,
936 const DexFile& dex_file,
937 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700938 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700939 exception_ = NULL;
940
941 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700942 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700943 DexFile::CatchHandlerIterator iter;
944 for (iter = dex_file.dexFindCatchHandler(*code_item,
945 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
946 !iter.HasNext();
947 iter.Next()) {
948 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
949 DCHECK(klass != NULL);
950 if (exception_obj->InstanceOf(klass)) {
951 dex_pc = iter.Get().address_;
952 break;
953 }
954 }
955
956 exception_ = exception_obj;
957 if (iter.HasNext()) {
958 return NULL;
959 } else {
960 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
961 }
962}
963
Elliott Hughes410c0c82011-09-01 17:58:25 -0700964void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
965 //(*visitor)(&thread->threadObj, threadId, ROOT_THREAD_OBJECT, arg);
966 //(*visitor)(&thread->exception, threadId, ROOT_NATIVE_STACK, arg);
967 jni_env_->locals.VisitRoots(visitor, arg);
968 jni_env_->monitors.VisitRoots(visitor, arg);
969 // visitThreadStack(visitor, thread, arg);
970 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
971}
972
Ian Rogersb033c752011-07-20 12:22:35 -0700973static const char* kStateNames[] = {
974 "New",
975 "Runnable",
976 "Blocked",
977 "Waiting",
978 "TimedWaiting",
979 "Native",
980 "Terminated",
981};
982std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
983 if (state >= Thread::kNew && state <= Thread::kTerminated) {
984 os << kStateNames[state-Thread::kNew];
985 } else {
986 os << "State[" << static_cast<int>(state) << "]";
987 }
988 return os;
989}
990
Elliott Hughes330304d2011-08-12 14:28:05 -0700991std::ostream& operator<<(std::ostream& os, const Thread& thread) {
992 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -0700993 << ",pthread_t=" << thread.GetImpl()
994 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -0700995 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -0700996 << ",state=" << thread.GetState()
997 << ",peer=" << thread.GetPeer()
998 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -0700999 return os;
1000}
1001
Elliott Hughes8daa0922011-09-11 13:46:25 -07001002} // namespace art