blob: 0a0f6f59fef615ad396d0a5b91be1ac5d455de82 [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
Elliott Hughes93e74e82011-09-13 11:07:03 -0700327void* Thread::CreateCallback(void *arg) {
328 Thread* self = reinterpret_cast<Thread*>(arg);
329 Runtime* runtime = Runtime::Current();
330
331 self->Attach(runtime);
332
333 ClassLinker* class_linker = runtime->GetClassLinker();
334
335 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
336 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
337
338 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
339 String* thread_name = reinterpret_cast<String*>(name_field->GetObject(self->peer_));
340 if (thread_name != NULL) {
341 SetThreadName(thread_name->ToModifiedUtf8().c_str());
342 }
343
344 // Wait until it's safe to start running code. (There may have been a suspend-all
345 // in progress while we were starting up.)
346 runtime->GetThreadList()->WaitForGo();
347
348 // TODO: say "hi" to the debugger.
349 //if (gDvm.debuggerConnected) {
350 // dvmDbgPostThreadStart(self);
351 //}
352
353 // Invoke the 'run' method of our java.lang.Thread.
354 CHECK(self->peer_ != NULL);
355 Object* receiver = self->peer_;
356 Method* Thread_run = thread_class->FindVirtualMethod("run", "()V");
357 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(Thread_run);
358 m->Invoke(self, receiver, NULL, NULL);
359
360 // Detach.
361 runtime->GetThreadList()->Unregister();
362
Carl Shapirob5573532011-07-12 18:22:59 -0700363 return NULL;
364}
365
Elliott Hughes93e74e82011-09-13 11:07:03 -0700366void SetVmData(Object* managed_thread, Thread* native_thread) {
367 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
368
369 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
370 Class* int_class = class_linker->FindPrimitiveClass('I');
371
372 Field* vmData_field = thread_class->FindDeclaredInstanceField("vmData", int_class);
373
374 vmData_field->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
375}
376
Elliott Hughesd369bb72011-09-12 14:41:14 -0700377void Thread::Create(Object* peer, size_t stack_size) {
378 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700379
Elliott Hughesd369bb72011-09-12 14:41:14 -0700380 if (stack_size == 0) {
381 stack_size = Runtime::Current()->GetDefaultStackSize();
382 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700383
Elliott Hughes93e74e82011-09-13 11:07:03 -0700384 Thread* native_thread = new Thread;
385 native_thread->peer_ = peer;
386
387 // Thread.start is synchronized, so we know that vmData is 0,
388 // and know that we're not racing to assign it.
389 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700390
391 pthread_attr_t attr;
Elliott Hughese27955c2011-08-26 15:21:24 -0700392 errno = pthread_attr_init(&attr);
393 if (errno != 0) {
394 PLOG(FATAL) << "pthread_attr_init failed";
395 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700396
Elliott Hughese27955c2011-08-26 15:21:24 -0700397 errno = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
398 if (errno != 0) {
399 PLOG(FATAL) << "pthread_attr_setdetachstate(PTHREAD_CREATE_DETACHED) failed";
400 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700401
Elliott Hughese27955c2011-08-26 15:21:24 -0700402 errno = pthread_attr_setstacksize(&attr, stack_size);
403 if (errno != 0) {
404 PLOG(FATAL) << "pthread_attr_setstacksize(" << stack_size << ") failed";
405 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700406
Elliott Hughes93e74e82011-09-13 11:07:03 -0700407 errno = pthread_create(&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread);
Elliott Hughese27955c2011-08-26 15:21:24 -0700408 if (errno != 0) {
409 PLOG(FATAL) << "pthread_create failed";
410 }
411
412 errno = pthread_attr_destroy(&attr);
413 if (errno != 0) {
414 PLOG(FATAL) << "pthread_attr_destroy failed";
415 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700416
417 // Let the child know when it's safe to start running.
418 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700419}
420
Elliott Hughes93e74e82011-09-13 11:07:03 -0700421void Thread::Attach(const Runtime* runtime) {
422 InitCpu();
423 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700424
Elliott Hughes93e74e82011-09-13 11:07:03 -0700425 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700426
Elliott Hughes93e74e82011-09-13 11:07:03 -0700427 tid_ = ::art::GetTid();
428 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700429
Elliott Hughes93e74e82011-09-13 11:07:03 -0700430 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700431
Elliott Hughes93e74e82011-09-13 11:07:03 -0700432 errno = pthread_setspecific(Thread::pthread_key_self_, this);
Elliott Hughesa5780da2011-07-17 11:39:39 -0700433 if (errno != 0) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700434 PLOG(FATAL) << "pthread_setspecific failed";
Elliott Hughesa5780da2011-07-17 11:39:39 -0700435 }
436
Elliott Hughes93e74e82011-09-13 11:07:03 -0700437 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700438
Elliott Hughes93e74e82011-09-13 11:07:03 -0700439 runtime->GetThreadList()->Register(this);
440}
441
442Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
443 Thread* self = new Thread;
444 self->Attach(runtime);
445
446 self->SetState(Thread::kRunnable);
447
448 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700449
450 // If we're the main thread, ClassLinker won't be created until after we're attached,
451 // so that thread needs a two-stage attach. Regular threads don't need this hack.
452 if (self->thin_lock_id_ != ThreadList::kMainId) {
453 self->CreatePeer(name, as_daemon);
454 }
455
456 return self;
457}
458
Elliott Hughesd369bb72011-09-12 14:41:14 -0700459jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
460 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
461 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
462 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
463 // This will be null in the compiler (and tests), but never in a running system.
464 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
465 return thread_group;
466}
467
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700468void Thread::CreatePeer(const char* name, bool as_daemon) {
469 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
470
471 JNIEnv* env = jni_env_;
472
Elliott Hughesd369bb72011-09-12 14:41:14 -0700473 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
474 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700475 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700476 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700477 jboolean thread_is_daemon = as_daemon;
478
479 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700480 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700481
Elliott Hughes8daa0922011-09-11 13:46:25 -0700482 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700483
484 // Because we mostly run without code available (in the compiler, in tests), we
485 // manually assign the fields the constructor should have set.
486 // TODO: lose this.
487 jfieldID fid;
488 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
489 env->SetObjectField(peer, fid, thread_group);
490 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
491 env->SetObjectField(peer, fid, thread_name);
492 fid = env->GetFieldID(c, "priority", "I");
493 env->SetIntField(peer, fid, thread_priority);
494 fid = env->GetFieldID(c, "daemon", "Z");
495 env->SetBooleanField(peer, fid, thread_is_daemon);
496
497 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700498}
499
Elliott Hughesbe759c62011-09-08 19:38:21 -0700500void Thread::InitStackHwm() {
501 pthread_attr_t attributes;
502 errno = pthread_getattr_np(pthread_, &attributes);
503 if (errno != 0) {
504 PLOG(FATAL) << "pthread_getattr_np failed";
505 }
506
Elliott Hughesbe759c62011-09-08 19:38:21 -0700507 void* stack_base;
508 size_t stack_size;
509 errno = pthread_attr_getstack(&attributes, &stack_base, &stack_size);
510 if (errno != 0) {
511 PLOG(FATAL) << "pthread_attr_getstack failed";
512 }
513
Elliott Hughesbe759c62011-09-08 19:38:21 -0700514 if (stack_size <= kStackOverflowReservedBytes) {
515 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
516 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700517
518 // stack_base is the "lowest addressable byte" of the stack.
519 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
520 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700521 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700522
523 // Sanity check.
524 int stack_variable;
525 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700526
527 errno = pthread_attr_destroy(&attributes);
528 if (errno != 0) {
529 PLOG(FATAL) << "pthread_attr_destroy failed";
530 }
531}
532
Elliott Hughesa0957642011-09-02 14:27:33 -0700533void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700534 DumpState(os);
535 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700536}
537
Elliott Hughesd92bec42011-09-02 17:04:36 -0700538std::string GetSchedulerGroup(pid_t tid) {
539 // /proc/<pid>/group looks like this:
540 // 2:devices:/
541 // 1:cpuacct,cpu:/
542 // We want the third field from the line whose second field contains the "cpu" token.
543 std::string cgroup_file;
544 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
545 return "";
546 }
547 std::vector<std::string> cgroup_lines;
548 Split(cgroup_file, '\n', cgroup_lines);
549 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
550 std::vector<std::string> cgroup_fields;
551 Split(cgroup_lines[i], ':', cgroup_fields);
552 std::vector<std::string> cgroups;
553 Split(cgroup_fields[1], ',', cgroups);
554 for (size_t i = 0; i < cgroups.size(); ++i) {
555 if (cgroups[i] == "cpu") {
556 return cgroup_fields[2].substr(1); // Skip the leading slash.
557 }
558 }
559 }
560 return "";
561}
562
563void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700564 std::string thread_name("<native thread without managed peer>");
565 std::string group_name;
566 int priority;
567 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700568
Elliott Hughesd369bb72011-09-12 14:41:14 -0700569 if (peer_ != NULL) {
570 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
571
572 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
573 Class* int_class = class_linker->FindPrimitiveClass('I');
574 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
575 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
576 Class* thread_group_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
577
578 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
579 Field* priority_field = thread_class->FindDeclaredInstanceField("priority", int_class);
580 Field* daemon_field = thread_class->FindDeclaredInstanceField("daemon", boolean_class);
581 Field* thread_group_field = thread_class->FindDeclaredInstanceField("group", thread_group_class);
582
583 String* thread_name_string = reinterpret_cast<String*>(name_field->GetObject(peer_));
584 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
585 priority = priority_field->GetInt(peer_);
586 is_daemon = daemon_field->GetBoolean(peer_);
587
588 Object* thread_group = thread_group_field->GetObject(peer_);
589 if (thread_group != NULL) {
590 Field* name_field = thread_group_class->FindDeclaredInstanceField("name", string_class);
591 String* group_name_string = reinterpret_cast<String*>(name_field->GetObject(thread_group));
592 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
593 }
594 } else {
595 // 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 -0700596 std::string stats;
597 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
598 size_t start = stats.find('(') + 1;
599 size_t end = stats.find(')') - start;
600 thread_name = stats.substr(start, end);
601 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700602 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700603 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700604
605 int policy;
606 sched_param sp;
Elliott Hughesbe759c62011-09-08 19:38:21 -0700607 errno = pthread_getschedparam(pthread_, &policy, &sp);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700608 if (errno != 0) {
609 PLOG(FATAL) << "pthread_getschedparam failed";
610 }
611
612 std::string scheduler_group(GetSchedulerGroup(GetTid()));
613 if (scheduler_group.empty()) {
614 scheduler_group = "default";
615 }
616
Elliott Hughesd92bec42011-09-02 17:04:36 -0700617 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700618 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700619 os << " daemon";
620 }
621 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700622 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700623 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700624
625 int suspend_count = 0; // TODO
626 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700627 os << " | group=\"" << group_name << "\""
628 << " sCount=" << suspend_count
629 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700630 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700631 << " self=" << reinterpret_cast<const void*>(this) << "\n";
632 os << " | sysTid=" << GetTid()
633 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
634 << " sched=" << policy << "/" << sp.sched_priority
635 << " cgrp=" << scheduler_group
636 << " handle=" << GetImpl() << "\n";
637
638 // Grab the scheduler stats for this thread.
639 std::string scheduler_stats;
640 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
641 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
642 } else {
643 scheduler_stats = "0 0 0";
644 }
645
646 int utime = 0;
647 int stime = 0;
648 int task_cpu = 0;
649 std::string stats;
650 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
651 // Skip the command, which may contain spaces.
652 stats = stats.substr(stats.find(')') + 2);
653 // Extract the three fields we care about.
654 std::vector<std::string> fields;
655 Split(stats, ' ', fields);
656 utime = strtoull(fields[11].c_str(), NULL, 10);
657 stime = strtoull(fields[12].c_str(), NULL, 10);
658 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
659 }
660
661 os << " | schedstat=( " << scheduler_stats << " )"
662 << " utm=" << utime
663 << " stm=" << stime
664 << " core=" << task_cpu
665 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
666}
667
Elliott Hughesd369bb72011-09-12 14:41:14 -0700668struct StackDumpVisitor : public Thread::StackVisitor {
669 StackDumpVisitor(std::ostream& os) : os(os) {
670 }
671
672 ~StackDumpVisitor() {
673 }
674
675 void VisitFrame(const Frame& frame) {
676 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
677
678 Method* m = frame.GetMethod();
679 Class* c = m->GetDeclaringClass();
680 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
681
682 os << " at " << PrettyMethod(m, false);
683 if (m->IsNative()) {
684 os << "(Native method)";
685 } else {
686 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(frame.GetPC()));
687 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
688 }
689 os << "\n";
690 }
691
692 std::ostream& os;
693};
694
Elliott Hughesd92bec42011-09-02 17:04:36 -0700695void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700696 StackDumpVisitor dumper(os);
697 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700698}
699
Elliott Hughesbe759c62011-09-08 19:38:21 -0700700void Thread::ThreadExitCallback(void* arg) {
701 Thread* self = reinterpret_cast<Thread*>(arg);
702 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700703}
704
Elliott Hughesbe759c62011-09-08 19:38:21 -0700705void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700706 // Allocate a TLS slot.
Elliott Hughesbe759c62011-09-08 19:38:21 -0700707 errno = pthread_key_create(&Thread::pthread_key_self_, Thread::ThreadExitCallback);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700708 if (errno != 0) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700709 PLOG(FATAL) << "pthread_key_create failed";
Carl Shapirob5573532011-07-12 18:22:59 -0700710 }
711
712 // Double-check the TLS slot allocation.
713 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700714 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700715 }
716
717 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700718}
719
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700720void Thread::Shutdown() {
721 errno = pthread_key_delete(Thread::pthread_key_self_);
722 if (errno != 0) {
723 PLOG(WARNING) << "pthread_key_delete failed";
724 }
725}
726
Elliott Hughesdcc24742011-09-07 14:02:44 -0700727Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700728 : peer_(NULL),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700729 wait_mutex_("Thread wait mutex"),
730 wait_monitor_(NULL),
731 interrupted_(false),
732 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700733 top_of_managed_stack_(),
734 native_to_managed_record_(NULL),
735 top_sirt_(NULL),
736 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700737 state_(Thread::kUnknown),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700738 exception_(NULL),
739 suspend_count_(0),
740 class_loader_override_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700741}
742
Elliott Hughes02b48d12011-09-07 17:15:51 -0700743void MonitorExitVisitor(const Object* object, void*) {
744 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700745 entered_monitor->MonitorExit();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700746}
747
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700748Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700749 // TODO: check we're not calling the JNI DetachCurrentThread function from
750 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
751
752 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700753 if (jni_env_ != NULL) {
754 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
755 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700756
757 if (IsExceptionPending()) {
758 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
759 }
760
761 // TODO: ThreadGroup.removeThread(this);
762
Elliott Hughes93e74e82011-09-13 11:07:03 -0700763 if (peer_ != NULL) {
764 SetVmData(peer_, NULL);
765 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700766
767 // TODO: say "bye" to the debugger.
768 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700769 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700770 //}
771
772 // Thread.join() is implemented as an Object.wait() on the Thread.lock
773 // object. Signal anyone who is waiting.
774 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
775 //dvmLockObject(self, lock);
776 //dvmObjectNotifyAll(self, lock);
777 //dvmUnlockObject(self, lock);
778 //lock = NULL;
779
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700780 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700781 jni_env_ = NULL;
782
783 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700784}
785
Ian Rogers408f79a2011-08-23 18:22:33 -0700786size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700787 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700788 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700789 count += cur->NumberOfReferences();
790 }
791 return count;
792}
793
Ian Rogers408f79a2011-08-23 18:22:33 -0700794bool Thread::SirtContains(jobject obj) {
795 Object** sirt_entry = reinterpret_cast<Object**>(obj);
796 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700797 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700798 // A SIRT should always have a jobject/jclass as a native method is passed
799 // in a this pointer or a class
800 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700801 if ((&cur->References()[0] <= sirt_entry) &&
802 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700803 return true;
804 }
805 }
806 return false;
807}
808
Ian Rogers408f79a2011-08-23 18:22:33 -0700809Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700810 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700811 if (obj == NULL) {
812 return NULL;
813 }
814 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
815 IndirectRefKind kind = GetIndirectRefKind(ref);
816 Object* result;
817 switch (kind) {
818 case kLocal:
819 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700820 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700821 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700822 break;
823 }
824 case kGlobal:
825 {
826 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
827 IndirectReferenceTable& globals = vm->globals;
828 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700829 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700830 break;
831 }
832 case kWeakGlobal:
833 {
834 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
835 IndirectReferenceTable& weak_globals = vm->weak_globals;
836 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700837 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700838 if (result == kClearedJniWeakGlobal) {
839 // This is a special case where it's okay to return NULL.
840 return NULL;
841 }
842 break;
843 }
844 case kSirtOrInvalid:
845 default:
846 // TODO: make stack indirect reference table lookup more efficient
847 // Check if this is a local reference in the SIRT
848 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700849 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700850 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700851 // Assume an invalid local reference is actually a direct pointer.
852 result = reinterpret_cast<Object*>(obj);
853 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700854 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700855 }
856 }
857
858 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700859 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
860 JniAbort(NULL);
861 } else {
862 if (result != kInvalidIndirectRefObject) {
863 Heap::VerifyObject(result);
864 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700865 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700866 return result;
867}
868
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700869class CountStackDepthVisitor : public Thread::StackVisitor {
870 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700871 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -0700872
873 virtual void VisitFrame(const Frame&) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700874 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700875 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700876
877 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -0700878 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700879 }
880
881 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700882 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700883};
884
Ian Rogersaaa20802011-09-11 21:47:37 -0700885//
886class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700887 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700888 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
889 // Allocate method trace with an extra slot that will hold the PC trace
890 method_trace_ = Runtime::Current()->GetClassLinker()->
891 AllocObjectArray<Object>(depth + 1);
892 // Register a local reference as IntArray::Alloc may trigger GC
893 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
894 pc_trace_ = IntArray::Alloc(depth);
895#ifdef MOVING_GARBAGE_COLLECTOR
896 // Re-read after potential GC
897 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
898#endif
899 // Save PC trace in last element of method trace, also places it into the
900 // object graph.
901 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700902 }
903
Ian Rogersaaa20802011-09-11 21:47:37 -0700904 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700905
Elliott Hughesd369bb72011-09-12 14:41:14 -0700906 virtual void VisitFrame(const Frame& frame) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700907 method_trace_->Set(count_, frame.GetMethod());
908 pc_trace_->Set(count_, frame.GetPC());
909 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700910 }
911
Ian Rogersaaa20802011-09-11 21:47:37 -0700912 jobject GetInternalStackTrace() const {
913 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700914 }
915
916 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700917 // Current position down stack trace
918 uint32_t count_;
919 // Array of return PC values
920 IntArray* pc_trace_;
921 // An array of the methods on the stack, the last entry is a reference to the
922 // PC trace
923 ObjectArray<Object>* method_trace_;
924 // Local indirect reference table entry for method trace
925 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700926};
927
Ian Rogersaaa20802011-09-11 21:47:37 -0700928void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700929 Frame frame = GetTopOfStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700930 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
931 // CHECK(native_to_managed_record_ != NULL);
932 NativeToManagedRecord* record = native_to_managed_record_;
933
934 while (frame.GetSP()) {
935 for ( ; frame.GetMethod() != 0; frame.Next()) {
936 visitor->VisitFrame(frame);
937 }
938 if (record == NULL) {
939 break;
940 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700941 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 -0700942 record = record->link;
943 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700944}
945
Ian Rogersaaa20802011-09-11 21:47:37 -0700946jobject Thread::CreateInternalStackTrace() const {
947 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700948 CountStackDepthVisitor count_visitor;
949 WalkStack(&count_visitor);
950 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -0700951
Ian Rogersaaa20802011-09-11 21:47:37 -0700952 // Transition into runnable state to work on Object*/Array*
953 ScopedJniThreadState ts(jni_env_);
954
955 // Build internal stack trace
956 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700957 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -0700958
Ian Rogersaaa20802011-09-11 21:47:37 -0700959 return build_trace_visitor.GetInternalStackTrace();
960}
961
962jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
963 JNIEnv* env) {
964 // Transition into runnable state to work on Object*/Array*
965 ScopedJniThreadState ts(env);
966
967 // Decode the internal stack trace into the depth, method trace and PC trace
968 ObjectArray<Object>* method_trace =
969 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
970 int32_t depth = method_trace->GetLength()-1;
971 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
972
973 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
974
975 // Create java_trace array and place in local reference table
976 ObjectArray<StackTraceElement>* java_traces =
977 class_linker->AllocStackTraceElementArray(depth);
978 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700979
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700980 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700981 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
982 Method* method = down_cast<Method*>(method_trace->Get(i));
983 uint32_t native_pc = pc_trace->Get(i);
984 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700985 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -0700986 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700987 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700988
Ian Rogersaaa20802011-09-11 21:47:37 -0700989 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700990 StackTraceElement* obj =
991 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -0700992 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700993 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -0700994 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -0700995 method->ToDexPC(native_pc)));
996#ifdef MOVING_GARBAGE_COLLECTOR
997 // Re-read after potential GC
998 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
999 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1000 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1001#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001002 java_traces->Set(i, obj);
1003 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001004 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001005}
1006
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001007void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001008 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001009 va_list args;
1010 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001011 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001012 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001013
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001014 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001015 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001016 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001017 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001018 descriptor.erase(descriptor.length() - 1);
1019
1020 JNIEnv* env = GetJniEnv();
1021 jclass exception_class = env->FindClass(descriptor.c_str());
1022 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1023 int rc = env->ThrowNew(exception_class, msg.c_str());
1024 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001025}
1026
Elliott Hughes79082e32011-08-25 12:07:32 -07001027void Thread::ThrowOutOfMemoryError() {
1028 UNIMPLEMENTED(FATAL);
1029}
1030
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001031Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
1032 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1033 DCHECK(class_linker != NULL);
1034
1035 Frame cur_frame = GetTopOfStack();
1036 for (int unwind_depth = 0; ; unwind_depth++) {
1037 const Method* cur_method = cur_frame.GetMethod();
1038 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
1039 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
1040
1041 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
1042 throw_pc,
1043 dex_file,
1044 class_linker);
1045 if (handler_addr) {
1046 *handler_pc = handler_addr;
1047 return cur_frame;
1048 } else {
1049 // Check if we are at the last frame
1050 if (cur_frame.HasNext()) {
1051 cur_frame.Next();
1052 } else {
1053 // Either at the top of stack or next frame is native.
1054 break;
1055 }
1056 }
1057 }
1058 *handler_pc = NULL;
1059 return Frame();
1060}
1061
1062void* Thread::FindExceptionHandlerInMethod(const Method* method,
1063 void* throw_pc,
1064 const DexFile& dex_file,
1065 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001066 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001067 exception_ = NULL;
1068
1069 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001070 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001071 DexFile::CatchHandlerIterator iter;
1072 for (iter = dex_file.dexFindCatchHandler(*code_item,
1073 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
1074 !iter.HasNext();
1075 iter.Next()) {
1076 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
1077 DCHECK(klass != NULL);
1078 if (exception_obj->InstanceOf(klass)) {
1079 dex_pc = iter.Get().address_;
1080 break;
1081 }
1082 }
1083
1084 exception_ = exception_obj;
1085 if (iter.HasNext()) {
1086 return NULL;
1087 } else {
1088 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
1089 }
1090}
1091
Elliott Hughes410c0c82011-09-01 17:58:25 -07001092void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001093 if (exception_ != NULL) {
1094 visitor(exception_, arg);
1095 }
1096 if (peer_ != NULL) {
1097 visitor(peer_, arg);
1098 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001099 jni_env_->locals.VisitRoots(visitor, arg);
1100 jni_env_->monitors.VisitRoots(visitor, arg);
1101 // visitThreadStack(visitor, thread, arg);
1102 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1103}
1104
Ian Rogersb033c752011-07-20 12:22:35 -07001105static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001106 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001107 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001108 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001109 "Blocked",
1110 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001111 "Initializing",
1112 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001113 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001114 "VmWait",
1115 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001116};
1117std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001118 int int_state = static_cast<int>(state);
1119 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1120 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001121 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001122 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001123 }
1124 return os;
1125}
1126
Elliott Hughes330304d2011-08-12 14:28:05 -07001127std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1128 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001129 << ",pthread_t=" << thread.GetImpl()
1130 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001131 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001132 << ",state=" << thread.GetState()
1133 << ",peer=" << thread.GetPeer()
1134 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001135 return os;
1136}
1137
Elliott Hughes8daa0922011-09-11 13:46:25 -07001138} // namespace art