blob: 05b4b9ba6ed4350676b3a600e7d9d8fd3c159d59 [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"
Ian Rogersaaa20802011-09-11 21:47:37 -070020#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070021#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070022#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070023
24namespace art {
25
26pthread_key_t Thread::pthread_key_self_;
27
buzbee4a3164f2011-09-03 11:25:10 -070028// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070029void DebugMe(Method* method, uint32_t info) {
buzbee4a3164f2011-09-03 11:25:10 -070030 LOG(INFO) << "DebugMe";
31 if (method != NULL)
32 LOG(INFO) << PrettyMethod(method);
33 LOG(INFO) << "Info: " << info;
34}
35
36/*
37 * TODO: placeholder for a method that can be called by the
38 * invoke-interface trampoline to unwind and handle exception. The
39 * trampoline will arrange it so that the caller appears to be the
40 * callsite of the failed invoke-interface. See comments in
41 * compiler/runtime_support.S
42 */
Elliott Hughesd369bb72011-09-12 14:41:14 -070043extern "C" void artFailedInvokeInterface() {
buzbee4a3164f2011-09-03 11:25:10 -070044 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
Elliott Hughesd369bb72011-09-12 14:41:14 -070064void 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 previously 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: " << PrettyType(exception);
buzbee1b4c8592011-08-31 10:43:51 -070073}
74
75// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -070076Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -070077 /*
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
Elliott Hughesd369bb72011-09-12 14:41:14 -070088void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -070089 /*
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
Elliott Hughesd369bb72011-09-12 14:41:14 -0700100Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -0700101 /*
102 * Just a wrapper around Array::AllocFromCode() that additionally
103 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
104 */
105 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
106 return Array::AllocFromCode(type_index, method, component_count);
107}
108
buzbee2a475e72011-09-07 17:19:17 -0700109// TODO: placeholder (throw on failure)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700110void CheckCastFromCode(const Class* a, const Class* b) {
buzbee2a475e72011-09-07 17:19:17 -0700111 if (a->IsAssignableFrom(b)) {
112 return;
113 }
114 UNIMPLEMENTED(FATAL);
115}
116
117// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700118void UnlockObjectFromCode(Thread* thread, Object* obj) {
buzbee2a475e72011-09-07 17:19:17 -0700119 // TODO: throw and unwind if lock not held
120 // TODO: throw and unwind on NPE
buzbee4ef76522011-09-08 10:00:32 -0700121 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700122}
123
124// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700125void LockObjectFromCode(Thread* thread, Object* obj) {
buzbee4ef76522011-09-08 10:00:32 -0700126 obj->MonitorEnter(thread);
buzbee2a475e72011-09-07 17:19:17 -0700127}
128
buzbee0d966cf2011-09-08 17:34:58 -0700129// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700130void CheckSuspendFromCode(Thread* thread) {
buzbee0d966cf2011-09-08 17:34:58 -0700131 /*
132 * Code is at a safe point, suspend if needed.
133 * Also, this is where a pending safepoint callback
134 * would be fired.
135 */
136}
137
buzbeecefd1872011-09-09 09:59:52 -0700138// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700139void StackOverflowFromCode(Method* method) {
140 //NOTE: to save code space, this handler needs to look up its own Thread*
141 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700142}
143
buzbee5ade1d22011-09-09 14:44:52 -0700144// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700145void ThrowNullPointerFromCode() {
146 Thread::Current()->Dump(std::cerr);
147 //NOTE: to save code space, this handler must look up caller's Method*
148 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700149}
150
151// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700152void ThrowDivZeroFromCode() {
153 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700154}
155
156// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700157void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
158 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700159}
160
161// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700162void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700163 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
164 " ref: " << ref;
165}
166
167// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700168void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700169 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
170}
171
172// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700173void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700174 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
175}
176
177// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700178void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700179 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
180}
181
182// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700183void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700184 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
185}
186
187/*
188 * Temporary placeholder. Should include run-time checks for size
189 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
190 * As with other new "FromCode" routines, this should return to the caller
191 * only if no exception has been thrown.
192 *
193 * NOTE: When dealing with a raw dex file, the data to be copied uses
194 * little-endian ordering. Require that oat2dex do any required swapping
195 * so this routine can get by with a memcpy().
196 *
197 * Format of the data:
198 * ushort ident = 0x0300 magic value
199 * ushort width width of each element in the table
200 * uint size number of elements in the table
201 * ubyte data[size*width] table of data values (may contain a single-byte
202 * padding at the end)
203 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700204void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700205 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
206 uint32_t size_in_bytes = size * table[1];
207 if (static_cast<int32_t>(size) > array->GetLength()) {
208 ThrowArrayBoundsFromCode(array->GetLength(), size);
209 }
210 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
211 (char*)&table[4], size_in_bytes);
212}
213
214// TODO: move to more appropriate location
215/*
216 * Float/double conversion requires clamping to min and max of integer form. If
217 * target doesn't support this normally, use these.
218 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700219int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700220 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
221 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
222 if (d >= kMaxLong)
223 return (int64_t)0x7fffffffffffffffULL;
224 else if (d <= kMinLong)
225 return (int64_t)0x8000000000000000ULL;
226 else if (d != d) // NaN case
227 return 0;
228 else
229 return (int64_t)d;
230}
231
Elliott Hughesd369bb72011-09-12 14:41:14 -0700232int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700233 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
234 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
235 if (f >= kMaxLong)
236 return (int64_t)0x7fffffffffffffffULL;
237 else if (f <= kMinLong)
238 return (int64_t)0x8000000000000000ULL;
239 else if (f != f) // NaN case
240 return 0;
241 else
242 return (int64_t)f;
243}
244
buzbee3ea4ec52011-08-22 17:37:19 -0700245void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700246#if defined(__arm__)
247 pShlLong = art_shl_long;
248 pShrLong = art_shr_long;
249 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700250 pIdiv = __aeabi_idiv;
251 pIdivmod = __aeabi_idivmod;
252 pI2f = __aeabi_i2f;
253 pF2iz = __aeabi_f2iz;
254 pD2f = __aeabi_d2f;
255 pF2d = __aeabi_f2d;
256 pD2iz = __aeabi_d2iz;
257 pL2f = __aeabi_l2f;
258 pL2d = __aeabi_l2d;
259 pFadd = __aeabi_fadd;
260 pFsub = __aeabi_fsub;
261 pFdiv = __aeabi_fdiv;
262 pFmul = __aeabi_fmul;
263 pFmodf = fmodf;
264 pDadd = __aeabi_dadd;
265 pDsub = __aeabi_dsub;
266 pDdiv = __aeabi_ddiv;
267 pDmul = __aeabi_dmul;
268 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700269 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700270 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700271 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700272#endif
buzbeec396efc2011-09-11 09:36:41 -0700273 pF2l = F2L;
274 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700275 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700276 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700277 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700278 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700279 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700280 pGet32Static = Field::Get32StaticFromCode;
281 pSet32Static = Field::Set32StaticFromCode;
282 pGet64Static = Field::Get64StaticFromCode;
283 pSet64Static = Field::Set64StaticFromCode;
284 pGetObjStatic = Field::GetObjStaticFromCode;
285 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700286 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
287 pThrowException = ThrowException;
288 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700289 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700290 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700291 pInstanceofNonTrivialFromCode = Object::InstanceOf;
292 pCheckCastFromCode = CheckCastFromCode;
293 pLockObjectFromCode = LockObjectFromCode;
294 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700295 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700296 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700297 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700298 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
299 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
300 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
301 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
302 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
303 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
304 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
305 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700306 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700307}
308
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700309void Frame::Next() {
310 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700311 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700312 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700313}
314
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700315uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700316 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700317 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700318 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700319}
320
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700321Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700322 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700323 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700324 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700325}
326
Carl Shapiro61e019d2011-07-14 16:53:09 -0700327void* ThreadStart(void *arg) {
Elliott Hughes53b61312011-08-12 18:28:20 -0700328 UNIMPLEMENTED(FATAL);
Carl Shapirob5573532011-07-12 18:22:59 -0700329 return NULL;
330}
331
Elliott Hughesd369bb72011-09-12 14:41:14 -0700332void Thread::Create(Object* peer, size_t stack_size) {
333 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700334
Elliott Hughesd369bb72011-09-12 14:41:14 -0700335 if (stack_size == 0) {
336 stack_size = Runtime::Current()->GetDefaultStackSize();
337 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700338
Elliott Hughesd369bb72011-09-12 14:41:14 -0700339 Thread* self = new Thread;
340 self->peer_ = peer;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700341
342 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700343 errno = pthread_attr_init(&attr);
344 if (errno != 0) {
345 PLOG(FATAL) << "pthread_attr_init failed";
346 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700347
Elliott Hughese27955c2011-08-26 15:21:24 -0700348 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
349 if (errno != 0) {
350 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
351 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700352
Elliott Hughese27955c2011-08-26 15:21:24 -0700353 errno = pthread_attr_setstacksize(&attr, stack_size);
354 if (errno != 0) {
355 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
356 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700357
Elliott Hughesd369bb72011-09-12 14:41:14 -0700358 errno = pthread_create(&self->pthread_, &attr, ThreadStart, self);
Elliott Hughese27955c2011-08-26 15:21:24 -0700359 if (errno != 0) {
360 PLOG(FATAL) << "pthread_create failed";
361 }
362
363 errno = pthread_attr_destroy(&attr);
364 if (errno != 0) {
365 PLOG(FATAL) << "pthread_attr_destroy failed";
366 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700367}
368
Elliott Hughesdcc24742011-09-07 14:02:44 -0700369Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700370 Thread* self = new Thread;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700371
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700372 self->tid_ = ::art::GetTid();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700373 self->pthread_ = pthread_self();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700374
Elliott Hughesbe759c62011-09-08 19:38:21 -0700375 self->InitStackHwm();
376
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700377 self->state_ = kRunnable;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700378
Elliott Hughesdcc24742011-09-07 14:02:44 -0700379 SetThreadName(name);
380
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700381 errno = pthread_setspecific(Thread::pthread_key_self_, self);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700382 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700383 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700384 }
385
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700386 self->jni_env_ = new JNIEnvExt(self, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700387
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700388 runtime->GetThreadList()->Register(self);
389
390 // If we're the main thread, ClassLinker won't be created until after we're attached,
391 // so that thread needs a two-stage attach. Regular threads don't need this hack.
392 if (self->thin_lock_id_ != ThreadList::kMainId) {
393 self->CreatePeer(name, as_daemon);
394 }
395
396 return self;
397}
398
Elliott Hughesd369bb72011-09-12 14:41:14 -0700399jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
400 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
401 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
402 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
403 // This will be null in the compiler (and tests), but never in a running system.
404 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
405 return thread_group;
406}
407
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700408void Thread::CreatePeer(const char* name, bool as_daemon) {
409 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
410
411 JNIEnv* env = jni_env_;
412
Elliott Hughesd369bb72011-09-12 14:41:14 -0700413 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
414 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700415 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700416 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700417 jboolean thread_is_daemon = as_daemon;
418
419 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700420 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700421
Elliott Hughes8daa0922011-09-11 13:46:25 -0700422 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700423
424 // Because we mostly run without code available (in the compiler, in tests), we
425 // manually assign the fields the constructor should have set.
426 // TODO: lose this.
427 jfieldID fid;
428 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
429 env->SetObjectField(peer, fid, thread_group);
430 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
431 env->SetObjectField(peer, fid, thread_name);
432 fid = env->GetFieldID(c, "priority", "I");
433 env->SetIntField(peer, fid, thread_priority);
434 fid = env->GetFieldID(c, "daemon", "Z");
435 env->SetBooleanField(peer, fid, thread_is_daemon);
436
437 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700438}
439
Elliott Hughesbe759c62011-09-08 19:38:21 -0700440void Thread::InitStackHwm() {
441 pthread_attr_t attributes;
442 errno = pthread_getattr_np(pthread_, &attributes);
443 if (errno != 0) {
444 PLOG(FATAL) << "pthread_getattr_np failed";
445 }
446
Elliott Hughesbe759c62011-09-08 19:38:21 -0700447 void* stack_base;
448 size_t stack_size;
449 errno = pthread_attr_getstack(&attributes, &stack_base, &stack_size);
450 if (errno != 0) {
451 PLOG(FATAL) << "pthread_attr_getstack failed";
452 }
453
Elliott Hughesbe759c62011-09-08 19:38:21 -0700454 if (stack_size <= kStackOverflowReservedBytes) {
455 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
456 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700457
458 // stack_base is the "lowest addressable byte" of the stack.
459 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
460 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700461 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700462
463 // Sanity check.
464 int stack_variable;
465 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700466
467 errno = pthread_attr_destroy(&attributes);
468 if (errno != 0) {
469 PLOG(FATAL) << "pthread_attr_destroy failed";
470 }
471}
472
Elliott Hughesa0957642011-09-02 14:27:33 -0700473void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700474 DumpState(os);
475 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700476}
477
Elliott Hughesd92bec42011-09-02 17:04:36 -0700478std::string GetSchedulerGroup(pid_t tid) {
479 // /proc/<pid>/group looks like this:
480 // 2:devices:/
481 // 1:cpuacct,cpu:/
482 // We want the third field from the line whose second field contains the "cpu" token.
483 std::string cgroup_file;
484 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
485 return "";
486 }
487 std::vector<std::string> cgroup_lines;
488 Split(cgroup_file, '\n', cgroup_lines);
489 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
490 std::vector<std::string> cgroup_fields;
491 Split(cgroup_lines[i], ':', cgroup_fields);
492 std::vector<std::string> cgroups;
493 Split(cgroup_fields[1], ',', cgroups);
494 for (size_t i = 0; i < cgroups.size(); ++i) {
495 if (cgroups[i] == "cpu") {
496 return cgroup_fields[2].substr(1); // Skip the leading slash.
497 }
498 }
499 }
500 return "";
501}
502
503void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700504 std::string thread_name("<native thread without managed peer>");
505 std::string group_name;
506 int priority;
507 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700508
Elliott Hughesd369bb72011-09-12 14:41:14 -0700509 if (peer_ != NULL) {
510 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
511
512 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
513 Class* int_class = class_linker->FindPrimitiveClass('I');
514 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
515 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
516 Class* thread_group_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
517
518 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
519 Field* priority_field = thread_class->FindDeclaredInstanceField("priority", int_class);
520 Field* daemon_field = thread_class->FindDeclaredInstanceField("daemon", boolean_class);
521 Field* thread_group_field = thread_class->FindDeclaredInstanceField("group", thread_group_class);
522
523 String* thread_name_string = reinterpret_cast<String*>(name_field->GetObject(peer_));
524 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
525 priority = priority_field->GetInt(peer_);
526 is_daemon = daemon_field->GetBoolean(peer_);
527
528 Object* thread_group = thread_group_field->GetObject(peer_);
529 if (thread_group != NULL) {
530 Field* name_field = thread_group_class->FindDeclaredInstanceField("name", string_class);
531 String* group_name_string = reinterpret_cast<String*>(name_field->GetObject(thread_group));
532 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
533 }
534 } else {
535 // This name may be truncated, but it's the best we can do in the absence of a managed peer.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700536 std::string stats;
537 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
538 size_t start = stats.find('(') + 1;
539 size_t end = stats.find(')') - start;
540 thread_name = stats.substr(start, end);
541 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700542 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700543 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700544
545 int policy;
546 sched_param sp;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700547 errno = pthread_getschedparam(pthread_, &policy, &sp);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700548 if (errno != 0) {
549 PLOG(FATAL) << "pthread_getschedparam failed";
550 }
551
552 std::string scheduler_group(GetSchedulerGroup(GetTid()));
553 if (scheduler_group.empty()) {
554 scheduler_group = "default";
555 }
556
Elliott Hughesd92bec42011-09-02 17:04:36 -0700557 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700558 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700559 os << " daemon";
560 }
561 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700562 << " tid=" << GetThinLockId()
Elliott Hughesd92bec42011-09-02 17:04:36 -0700563 << " " << state_ << "\n";
564
565 int suspend_count = 0; // TODO
566 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700567 os << " | group=\"" << group_name << "\""
568 << " sCount=" << suspend_count
569 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700570 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700571 << " self=" << reinterpret_cast<const void*>(this) << "\n";
572 os << " | sysTid=" << GetTid()
573 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
574 << " sched=" << policy << "/" << sp.sched_priority
575 << " cgrp=" << scheduler_group
576 << " handle=" << GetImpl() << "\n";
577
578 // Grab the scheduler stats for this thread.
579 std::string scheduler_stats;
580 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
581 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
582 } else {
583 scheduler_stats = "0 0 0";
584 }
585
586 int utime = 0;
587 int stime = 0;
588 int task_cpu = 0;
589 std::string stats;
590 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
591 // Skip the command, which may contain spaces.
592 stats = stats.substr(stats.find(')') + 2);
593 // Extract the three fields we care about.
594 std::vector<std::string> fields;
595 Split(stats, ' ', fields);
596 utime = strtoull(fields[11].c_str(), NULL, 10);
597 stime = strtoull(fields[12].c_str(), NULL, 10);
598 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
599 }
600
601 os << " | schedstat=( " << scheduler_stats << " )"
602 << " utm=" << utime
603 << " stm=" << stime
604 << " core=" << task_cpu
605 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
606}
607
Elliott Hughesd369bb72011-09-12 14:41:14 -0700608struct StackDumpVisitor : public Thread::StackVisitor {
609 StackDumpVisitor(std::ostream& os) : os(os) {
610 }
611
612 ~StackDumpVisitor() {
613 }
614
615 void VisitFrame(const Frame& frame) {
616 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
617
618 Method* m = frame.GetMethod();
619 Class* c = m->GetDeclaringClass();
620 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
621
622 os << " at " << PrettyMethod(m, false);
623 if (m->IsNative()) {
624 os << "(Native method)";
625 } else {
626 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(frame.GetPC()));
627 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
628 }
629 os << "\n";
630 }
631
632 std::ostream& os;
633};
634
Elliott Hughesd92bec42011-09-02 17:04:36 -0700635void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700636 StackDumpVisitor dumper(os);
637 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700638}
639
Elliott Hughesbe759c62011-09-08 19:38:21 -0700640void Thread::ThreadExitCallback(void* arg) {
641 Thread* self = reinterpret_cast<Thread*>(arg);
642 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700643}
644
Elliott Hughesbe759c62011-09-08 19:38:21 -0700645void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700646 // Allocate a TLS slot.
Elliott Hughesbe759c62011-09-08 19:38:21 -0700647 errno = pthread_key_create(&Thread::pthread_key_self_, Thread::ThreadExitCallback);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700648 if (errno != 0) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700649 PLOG(FATAL) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700650 }
651
652 // Double-check the TLS slot allocation.
653 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700654 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700655 }
656
657 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700658}
659
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700660void Thread::Shutdown() {
661 errno = pthread_key_delete(Thread::pthread_key_self_);
662 if (errno != 0) {
663 PLOG(WARNING) << "pthread_key_delete failed";
664 }
665}
666
Elliott Hughesdcc24742011-09-07 14:02:44 -0700667Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700668 : peer_(NULL),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700669 wait_mutex_("Thread wait mutex"),
670 wait_monitor_(NULL),
671 interrupted_(false),
672 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700673 top_of_managed_stack_(),
674 native_to_managed_record_(NULL),
675 top_sirt_(NULL),
676 jni_env_(NULL),
677 exception_(NULL),
678 suspend_count_(0),
679 class_loader_override_(NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700680 InitCpu();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700681 InitFunctionPointers();
Elliott Hughes8daa0922011-09-11 13:46:25 -0700682 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700683}
684
Elliott Hughes02b48d12011-09-07 17:15:51 -0700685void MonitorExitVisitor(const Object* object, void*) {
686 Object* entered_monitor = const_cast<Object*>(object);
687 entered_monitor->MonitorExit();;
688}
689
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700690Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700691 // TODO: check we're not calling the JNI DetachCurrentThread function from
692 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
693
694 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
695 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
696
697 if (IsExceptionPending()) {
698 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
699 }
700
701 // TODO: ThreadGroup.removeThread(this);
702
703 // TODO: this.vmData = 0;
704
705 // TODO: say "bye" to the debugger.
706 //if (gDvm.debuggerConnected) {
707 // dvmDbgPostThreadDeath(self);
708 //}
709
710 // Thread.join() is implemented as an Object.wait() on the Thread.lock
711 // object. Signal anyone who is waiting.
712 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
713 //dvmLockObject(self, lock);
714 //dvmObjectNotifyAll(self, lock);
715 //dvmUnlockObject(self, lock);
716 //lock = NULL;
717
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700718 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700719 jni_env_ = NULL;
720
721 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700722}
723
Ian Rogers408f79a2011-08-23 18:22:33 -0700724size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700725 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700726 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700727 count += cur->NumberOfReferences();
728 }
729 return count;
730}
731
Ian Rogers408f79a2011-08-23 18:22:33 -0700732bool Thread::SirtContains(jobject obj) {
733 Object** sirt_entry = reinterpret_cast<Object**>(obj);
734 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700735 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700736 // A SIRT should always have a jobject/jclass as a native method is passed
737 // in a this pointer or a class
738 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700739 if ((&cur->References()[0] <= sirt_entry) &&
740 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700741 return true;
742 }
743 }
744 return false;
745}
746
Ian Rogers408f79a2011-08-23 18:22:33 -0700747Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700748 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700749 if (obj == NULL) {
750 return NULL;
751 }
752 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
753 IndirectRefKind kind = GetIndirectRefKind(ref);
754 Object* result;
755 switch (kind) {
756 case kLocal:
757 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700758 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700759 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700760 break;
761 }
762 case kGlobal:
763 {
764 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
765 IndirectReferenceTable& globals = vm->globals;
766 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700767 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700768 break;
769 }
770 case kWeakGlobal:
771 {
772 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
773 IndirectReferenceTable& weak_globals = vm->weak_globals;
774 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700775 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700776 if (result == kClearedJniWeakGlobal) {
777 // This is a special case where it's okay to return NULL.
778 return NULL;
779 }
780 break;
781 }
782 case kSirtOrInvalid:
783 default:
784 // TODO: make stack indirect reference table lookup more efficient
785 // Check if this is a local reference in the SIRT
786 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700787 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700788 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700789 // Assume an invalid local reference is actually a direct pointer.
790 result = reinterpret_cast<Object*>(obj);
791 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700792 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700793 }
794 }
795
796 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700797 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
798 JniAbort(NULL);
799 } else {
800 if (result != kInvalidIndirectRefObject) {
801 Heap::VerifyObject(result);
802 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700803 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700804 return result;
805}
806
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700807class CountStackDepthVisitor : public Thread::StackVisitor {
808 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700809 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -0700810
811 virtual void VisitFrame(const Frame&) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700812 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700813 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700814
815 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -0700816 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700817 }
818
819 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700820 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700821};
822
Ian Rogersaaa20802011-09-11 21:47:37 -0700823//
824class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700825 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700826 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
827 // Allocate method trace with an extra slot that will hold the PC trace
828 method_trace_ = Runtime::Current()->GetClassLinker()->
829 AllocObjectArray<Object>(depth + 1);
830 // Register a local reference as IntArray::Alloc may trigger GC
831 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
832 pc_trace_ = IntArray::Alloc(depth);
833#ifdef MOVING_GARBAGE_COLLECTOR
834 // Re-read after potential GC
835 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
836#endif
837 // Save PC trace in last element of method trace, also places it into the
838 // object graph.
839 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700840 }
841
Ian Rogersaaa20802011-09-11 21:47:37 -0700842 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700843
Elliott Hughesd369bb72011-09-12 14:41:14 -0700844 virtual void VisitFrame(const Frame& frame) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700845 method_trace_->Set(count_, frame.GetMethod());
846 pc_trace_->Set(count_, frame.GetPC());
847 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700848 }
849
Ian Rogersaaa20802011-09-11 21:47:37 -0700850 jobject GetInternalStackTrace() const {
851 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700852 }
853
854 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700855 // Current position down stack trace
856 uint32_t count_;
857 // Array of return PC values
858 IntArray* pc_trace_;
859 // An array of the methods on the stack, the last entry is a reference to the
860 // PC trace
861 ObjectArray<Object>* method_trace_;
862 // Local indirect reference table entry for method trace
863 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700864};
865
Ian Rogersaaa20802011-09-11 21:47:37 -0700866void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700867 Frame frame = GetTopOfStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700868 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
869 // CHECK(native_to_managed_record_ != NULL);
870 NativeToManagedRecord* record = native_to_managed_record_;
871
872 while (frame.GetSP()) {
873 for ( ; frame.GetMethod() != 0; frame.Next()) {
874 visitor->VisitFrame(frame);
875 }
876 if (record == NULL) {
877 break;
878 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700879 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 -0700880 record = record->link;
881 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700882}
883
Ian Rogersaaa20802011-09-11 21:47:37 -0700884jobject Thread::CreateInternalStackTrace() const {
885 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700886 CountStackDepthVisitor count_visitor;
887 WalkStack(&count_visitor);
888 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700889
Ian Rogersaaa20802011-09-11 21:47:37 -0700890 // Transition into runnable state to work on Object*/Array*
891 ScopedJniThreadState ts(jni_env_);
892
893 // Build internal stack trace
894 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700895 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700896
Ian Rogersaaa20802011-09-11 21:47:37 -0700897 return build_trace_visitor.GetInternalStackTrace();
898}
899
900jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
901 JNIEnv* env) {
902 // Transition into runnable state to work on Object*/Array*
903 ScopedJniThreadState ts(env);
904
905 // Decode the internal stack trace into the depth, method trace and PC trace
906 ObjectArray<Object>* method_trace =
907 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
908 int32_t depth = method_trace->GetLength()-1;
909 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
910
911 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
912
913 // Create java_trace array and place in local reference table
914 ObjectArray<StackTraceElement>* java_traces =
915 class_linker->AllocStackTraceElementArray(depth);
916 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700917
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700918 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700919 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
920 Method* method = down_cast<Method*>(method_trace->Get(i));
921 uint32_t native_pc = pc_trace->Get(i);
922 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700923 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700924 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700925 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700926
Ian Rogersaaa20802011-09-11 21:47:37 -0700927 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700928 StackTraceElement* obj =
929 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700930 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700931 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -0700932 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -0700933 method->ToDexPC(native_pc)));
934#ifdef MOVING_GARBAGE_COLLECTOR
935 // Re-read after potential GC
936 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
937 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
938 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
939#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700940 java_traces->Set(i, obj);
941 }
Ian Rogersaaa20802011-09-11 21:47:37 -0700942 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700943}
944
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700945void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -0700946 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700947 va_list args;
948 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700949 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700950 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -0700951
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700952 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700953 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700954 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700955 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -0700956 descriptor.erase(descriptor.length() - 1);
957
958 JNIEnv* env = GetJniEnv();
959 jclass exception_class = env->FindClass(descriptor.c_str());
960 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
961 int rc = env->ThrowNew(exception_class, msg.c_str());
962 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -0700963}
964
Elliott Hughes79082e32011-08-25 12:07:32 -0700965void Thread::ThrowOutOfMemoryError() {
966 UNIMPLEMENTED(FATAL);
967}
968
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700969Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
970 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
971 DCHECK(class_linker != NULL);
972
973 Frame cur_frame = GetTopOfStack();
974 for (int unwind_depth = 0; ; unwind_depth++) {
975 const Method* cur_method = cur_frame.GetMethod();
976 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
977 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
978
979 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
980 throw_pc,
981 dex_file,
982 class_linker);
983 if (handler_addr) {
984 *handler_pc = handler_addr;
985 return cur_frame;
986 } else {
987 // Check if we are at the last frame
988 if (cur_frame.HasNext()) {
989 cur_frame.Next();
990 } else {
991 // Either at the top of stack or next frame is native.
992 break;
993 }
994 }
995 }
996 *handler_pc = NULL;
997 return Frame();
998}
999
1000void* Thread::FindExceptionHandlerInMethod(const Method* method,
1001 void* throw_pc,
1002 const DexFile& dex_file,
1003 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001004 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001005 exception_ = NULL;
1006
1007 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001008 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001009 DexFile::CatchHandlerIterator iter;
1010 for (iter = dex_file.dexFindCatchHandler(*code_item,
1011 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
1012 !iter.HasNext();
1013 iter.Next()) {
1014 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
1015 DCHECK(klass != NULL);
1016 if (exception_obj->InstanceOf(klass)) {
1017 dex_pc = iter.Get().address_;
1018 break;
1019 }
1020 }
1021
1022 exception_ = exception_obj;
1023 if (iter.HasNext()) {
1024 return NULL;
1025 } else {
1026 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
1027 }
1028}
1029
Elliott Hughes410c0c82011-09-01 17:58:25 -07001030void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001031 if (exception_ != NULL) {
1032 visitor(exception_, arg);
1033 }
1034 if (peer_ != NULL) {
1035 visitor(peer_, arg);
1036 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001037 jni_env_->locals.VisitRoots(visitor, arg);
1038 jni_env_->monitors.VisitRoots(visitor, arg);
1039 // visitThreadStack(visitor, thread, arg);
1040 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1041}
1042
Ian Rogersb033c752011-07-20 12:22:35 -07001043static const char* kStateNames[] = {
1044 "New",
1045 "Runnable",
1046 "Blocked",
1047 "Waiting",
1048 "TimedWaiting",
1049 "Native",
1050 "Terminated",
1051};
1052std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
1053 if (state >= Thread::kNew && state <= Thread::kTerminated) {
1054 os << kStateNames[state-Thread::kNew];
1055 } else {
1056 os << "State[" << static_cast<int>(state) << "]";
1057 }
1058 return os;
1059}
1060
Elliott Hughes330304d2011-08-12 14:28:05 -07001061std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1062 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001063 << ",pthread_t=" << thread.GetImpl()
1064 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001065 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001066 << ",state=" << thread.GetState()
1067 << ",peer=" << thread.GetPeer()
1068 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001069 return os;
1070}
1071
Elliott Hughes8daa0922011-09-11 13:46:25 -07001072} // namespace art