blob: 426677e0669e6526b68008c15a19d4c1388c6d6d [file] [log] [blame]
Elliott Hughes8d768a92011-09-14 16:35:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapirob5573532011-07-12 18:22:59 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
Elliott Hughes8d768a92011-09-14 16:35:25 -070019#include <dynamic_annotations.h>
Ian Rogersb033c752011-07-20 12:22:35 -070020#include <pthread.h>
21#include <sys/mman.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070022
Carl Shapirob5573532011-07-12 18:22:59 -070023#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070024#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070025#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070026#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070027#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070028
Elliott Hughesa5b897e2011-08-16 11:33:06 -070029#include "class_linker.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070030#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070031#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070032#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070033#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070034#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070035#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070036#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070037#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070038
39namespace art {
40
41pthread_key_t Thread::pthread_key_self_;
42
buzbee4a3164f2011-09-03 11:25:10 -070043// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070044void DebugMe(Method* method, uint32_t info) {
buzbee4a3164f2011-09-03 11:25:10 -070045 LOG(INFO) << "DebugMe";
46 if (method != NULL)
47 LOG(INFO) << PrettyMethod(method);
48 LOG(INFO) << "Info: " << info;
49}
50
51/*
52 * TODO: placeholder for a method that can be called by the
53 * invoke-interface trampoline to unwind and handle exception. The
54 * trampoline will arrange it so that the caller appears to be the
55 * callsite of the failed invoke-interface. See comments in
56 * compiler/runtime_support.S
57 */
Elliott Hughesd369bb72011-09-12 14:41:14 -070058extern "C" void artFailedInvokeInterface() {
buzbee4a3164f2011-09-03 11:25:10 -070059 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw";
60}
61
62// TODO: placeholder. See comments in compiler/runtime_support.S
63extern "C" uint64_t artFindInterfaceMethodInCache(uint32_t method_idx,
64 Object* this_object , Method* caller_method)
65{
66 /*
67 * Note: this_object has not yet been null-checked. To match
68 * the old-world state, nullcheck this_object and load
69 * Class* this_class = this_object->GetClass().
70 * See comments and possible thrown exceptions in old-world
71 * Interp.cpp:dvmInterpFindInterfaceMethod, and complete with
72 * new-world FindVirtualMethodForInterface.
73 */
74 UNIMPLEMENTED(FATAL) << "Unimplemented invoke interface";
75 return 0LL;
76}
77
buzbee1b4c8592011-08-31 10:43:51 -070078// TODO: placeholder. This is what generated code will call to throw
Elliott Hughesd369bb72011-09-12 14:41:14 -070079void ThrowException(Thread* thread, Throwable* exception) {
80 /*
81 * exception may be NULL, in which case this routine should
82 * throw NPE. NOTE: this is a convenience for generated code,
83 * which previously did the null check inline and constructed
84 * and threw a NPE if NULL. This routine responsible for setting
85 * exception_ in thread.
86 */
87 UNIMPLEMENTED(FATAL) << "Unimplemented exception throw: " << PrettyType(exception);
buzbee1b4c8592011-08-31 10:43:51 -070088}
89
90// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -070091Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -070092 /*
93 * Should initialize & fix up method->dex_cache_resolved_types_[].
94 * Returns initialized type. Does not return normally if an exception
95 * is thrown, but instead initiates the catch. Should be similar to
96 * ClassLinker::InitializeStaticStorageFromCode.
97 */
98 UNIMPLEMENTED(FATAL);
99 return NULL;
100}
101
buzbee561227c2011-09-02 15:28:19 -0700102// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -0700103void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -0700104 /*
105 * Slow-path handler on invoke virtual method path in which
106 * base method is unresolved at compile-time. Doesn't need to
107 * return anything - just either ensure that
108 * method->dex_cache_resolved_methods_(method_idx) != NULL or
109 * throw and unwind. The caller will restart call sequence
110 * from the beginning.
111 */
112}
113
buzbee1da522d2011-09-04 11:22:20 -0700114// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesd369bb72011-09-12 14:41:14 -0700115Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -0700116 /*
117 * Just a wrapper around Array::AllocFromCode() that additionally
118 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
119 */
120 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
121 return Array::AllocFromCode(type_index, method, component_count);
122}
123
buzbee2a475e72011-09-07 17:19:17 -0700124// TODO: placeholder (throw on failure)
Elliott Hughesd369bb72011-09-12 14:41:14 -0700125void CheckCastFromCode(const Class* a, const Class* b) {
buzbee2a475e72011-09-07 17:19:17 -0700126 if (a->IsAssignableFrom(b)) {
127 return;
128 }
129 UNIMPLEMENTED(FATAL);
130}
131
Elliott Hughesd369bb72011-09-12 14:41:14 -0700132void UnlockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700133 // TODO: throw and unwind if lock not held
134 // TODO: throw and unwind on NPE
135 obj->MonitorExit(thread);
buzbee2a475e72011-09-07 17:19:17 -0700136}
137
Elliott Hughesd369bb72011-09-12 14:41:14 -0700138void LockObjectFromCode(Thread* thread, Object* obj) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700139 obj->MonitorEnter(thread);
140 // TODO: throw and unwind on failure.
buzbee2a475e72011-09-07 17:19:17 -0700141}
142
Elliott Hughesd369bb72011-09-12 14:41:14 -0700143void CheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700144 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700145}
146
buzbeecefd1872011-09-09 09:59:52 -0700147// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700148void StackOverflowFromCode(Method* method) {
149 //NOTE: to save code space, this handler needs to look up its own Thread*
150 UNIMPLEMENTED(FATAL) << "Stack overflow: " << PrettyMethod(method);
buzbeecefd1872011-09-09 09:59:52 -0700151}
152
buzbee5ade1d22011-09-09 14:44:52 -0700153// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700154void ThrowNullPointerFromCode() {
155 Thread::Current()->Dump(std::cerr);
156 //NOTE: to save code space, this handler must look up caller's Method*
157 UNIMPLEMENTED(FATAL) << "Null pointer exception";
buzbee5ade1d22011-09-09 14:44:52 -0700158}
159
160// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700161void ThrowDivZeroFromCode() {
162 UNIMPLEMENTED(FATAL) << "Divide by zero";
buzbee5ade1d22011-09-09 14:44:52 -0700163}
164
165// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700166void ThrowArrayBoundsFromCode(int32_t index, int32_t limit) {
167 UNIMPLEMENTED(FATAL) << "Bound check exception, idx: " << index << ", limit: " << limit;
buzbee5ade1d22011-09-09 14:44:52 -0700168}
169
170// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700171void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
buzbee5ade1d22011-09-09 14:44:52 -0700172 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
173 " ref: " << ref;
174}
175
176// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700177void ThrowNegArraySizeFromCode(int32_t index) {
buzbee5ade1d22011-09-09 14:44:52 -0700178 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
179}
180
181// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700182void ThrowInternalErrorFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700183 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
184}
185
186// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700187void ThrowRuntimeExceptionFromCode(int32_t errnum) {
buzbee5ade1d22011-09-09 14:44:52 -0700188 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
189}
190
191// TODO: placeholder
Elliott Hughesd369bb72011-09-12 14:41:14 -0700192void ThrowNoSuchMethodFromCode(int32_t method_idx) {
buzbee5ade1d22011-09-09 14:44:52 -0700193 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
194}
195
196/*
197 * Temporary placeholder. Should include run-time checks for size
198 * of fill data <= size of array. If not, throw arrayOutOfBoundsException.
199 * As with other new "FromCode" routines, this should return to the caller
200 * only if no exception has been thrown.
201 *
202 * NOTE: When dealing with a raw dex file, the data to be copied uses
203 * little-endian ordering. Require that oat2dex do any required swapping
204 * so this routine can get by with a memcpy().
205 *
206 * Format of the data:
207 * ushort ident = 0x0300 magic value
208 * ushort width width of each element in the table
209 * uint size number of elements in the table
210 * ubyte data[size*width] table of data values (may contain a single-byte
211 * padding at the end)
212 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700213void HandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
buzbee5ade1d22011-09-09 14:44:52 -0700214 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
215 uint32_t size_in_bytes = size * table[1];
216 if (static_cast<int32_t>(size) > array->GetLength()) {
217 ThrowArrayBoundsFromCode(array->GetLength(), size);
218 }
219 memcpy((char*)array + art::Array::DataOffset().Int32Value(),
220 (char*)&table[4], size_in_bytes);
221}
222
223// TODO: move to more appropriate location
224/*
225 * Float/double conversion requires clamping to min and max of integer form. If
226 * target doesn't support this normally, use these.
227 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700228int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700229 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
230 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
231 if (d >= kMaxLong)
232 return (int64_t)0x7fffffffffffffffULL;
233 else if (d <= kMinLong)
234 return (int64_t)0x8000000000000000ULL;
235 else if (d != d) // NaN case
236 return 0;
237 else
238 return (int64_t)d;
239}
240
Elliott Hughesd369bb72011-09-12 14:41:14 -0700241int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700242 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
243 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
244 if (f >= kMaxLong)
245 return (int64_t)0x7fffffffffffffffULL;
246 else if (f <= kMinLong)
247 return (int64_t)0x8000000000000000ULL;
248 else if (f != f) // NaN case
249 return 0;
250 else
251 return (int64_t)f;
252}
253
buzbee3ea4ec52011-08-22 17:37:19 -0700254void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700255#if defined(__arm__)
256 pShlLong = art_shl_long;
257 pShrLong = art_shr_long;
258 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700259 pIdiv = __aeabi_idiv;
260 pIdivmod = __aeabi_idivmod;
261 pI2f = __aeabi_i2f;
262 pF2iz = __aeabi_f2iz;
263 pD2f = __aeabi_d2f;
264 pF2d = __aeabi_f2d;
265 pD2iz = __aeabi_d2iz;
266 pL2f = __aeabi_l2f;
267 pL2d = __aeabi_l2d;
268 pFadd = __aeabi_fadd;
269 pFsub = __aeabi_fsub;
270 pFdiv = __aeabi_fdiv;
271 pFmul = __aeabi_fmul;
272 pFmodf = fmodf;
273 pDadd = __aeabi_dadd;
274 pDsub = __aeabi_dsub;
275 pDdiv = __aeabi_ddiv;
276 pDmul = __aeabi_dmul;
277 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700278 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700279 pLmul = __aeabi_lmul;
buzbee4a3164f2011-09-03 11:25:10 -0700280 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbee54330722011-08-23 16:46:55 -0700281#endif
buzbeec396efc2011-09-11 09:36:41 -0700282 pF2l = F2L;
283 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700284 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700285 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700286 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700287 pMemcpy = memcpy;
buzbee1b4c8592011-08-31 10:43:51 -0700288 pHandleFillArrayDataFromCode = HandleFillArrayDataFromCode;
buzbeee1931742011-08-28 21:15:53 -0700289 pGet32Static = Field::Get32StaticFromCode;
290 pSet32Static = Field::Set32StaticFromCode;
291 pGet64Static = Field::Get64StaticFromCode;
292 pSet64Static = Field::Set64StaticFromCode;
293 pGetObjStatic = Field::GetObjStaticFromCode;
294 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700295 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
296 pThrowException = ThrowException;
297 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700298 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700299 pInitializeStaticStorage = ClassLinker::InitializeStaticStorageFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700300 pInstanceofNonTrivialFromCode = Object::InstanceOf;
301 pCheckCastFromCode = CheckCastFromCode;
302 pLockObjectFromCode = LockObjectFromCode;
303 pUnlockObjectFromCode = UnlockObjectFromCode;
buzbee34cd9e52011-09-08 14:31:52 -0700304 pFindFieldFromCode = Field::FindFieldFromCode;
buzbee0d966cf2011-09-08 17:34:58 -0700305 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbeecefd1872011-09-09 09:59:52 -0700306 pStackOverflowFromCode = StackOverflowFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700307 pThrowNullPointerFromCode = ThrowNullPointerFromCode;
308 pThrowArrayBoundsFromCode = ThrowArrayBoundsFromCode;
309 pThrowDivZeroFromCode = ThrowDivZeroFromCode;
310 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
311 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
312 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
313 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
314 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700315 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700316}
317
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700318void Frame::Next() {
319 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700320 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700321 sp_ = reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700322}
323
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700324uintptr_t Frame::GetPC() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700325 byte* pc_addr = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700326 GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700327 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700328}
329
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700330Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700331 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700332 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700333 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700334}
335
Elliott Hughes93e74e82011-09-13 11:07:03 -0700336void* Thread::CreateCallback(void *arg) {
337 Thread* self = reinterpret_cast<Thread*>(arg);
338 Runtime* runtime = Runtime::Current();
339
340 self->Attach(runtime);
341
342 ClassLinker* class_linker = runtime->GetClassLinker();
343
344 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
345 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
346
347 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
348 String* thread_name = reinterpret_cast<String*>(name_field->GetObject(self->peer_));
349 if (thread_name != NULL) {
350 SetThreadName(thread_name->ToModifiedUtf8().c_str());
351 }
352
353 // Wait until it's safe to start running code. (There may have been a suspend-all
354 // in progress while we were starting up.)
355 runtime->GetThreadList()->WaitForGo();
356
357 // TODO: say "hi" to the debugger.
358 //if (gDvm.debuggerConnected) {
359 // dvmDbgPostThreadStart(self);
360 //}
361
362 // Invoke the 'run' method of our java.lang.Thread.
363 CHECK(self->peer_ != NULL);
364 Object* receiver = self->peer_;
365 Method* Thread_run = thread_class->FindVirtualMethod("run", "()V");
366 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(Thread_run);
367 m->Invoke(self, receiver, NULL, NULL);
368
369 // Detach.
370 runtime->GetThreadList()->Unregister();
371
Carl Shapirob5573532011-07-12 18:22:59 -0700372 return NULL;
373}
374
Elliott Hughes93e74e82011-09-13 11:07:03 -0700375void SetVmData(Object* managed_thread, Thread* native_thread) {
376 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
377
378 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
379 Class* int_class = class_linker->FindPrimitiveClass('I');
380
381 Field* vmData_field = thread_class->FindDeclaredInstanceField("vmData", int_class);
382
383 vmData_field->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
384}
385
Elliott Hughesd369bb72011-09-12 14:41:14 -0700386void Thread::Create(Object* peer, size_t stack_size) {
387 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700388
Elliott Hughesd369bb72011-09-12 14:41:14 -0700389 if (stack_size == 0) {
390 stack_size = Runtime::Current()->GetDefaultStackSize();
391 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700392
Elliott Hughes93e74e82011-09-13 11:07:03 -0700393 Thread* native_thread = new Thread;
394 native_thread->peer_ = peer;
395
396 // Thread.start is synchronized, so we know that vmData is 0,
397 // and know that we're not racing to assign it.
398 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700399
400 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700401 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
402 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
403 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
404 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
405 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700406
407 // Let the child know when it's safe to start running.
408 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700409}
410
Elliott Hughes93e74e82011-09-13 11:07:03 -0700411void Thread::Attach(const Runtime* runtime) {
412 InitCpu();
413 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700414
Elliott Hughes93e74e82011-09-13 11:07:03 -0700415 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700416
Elliott Hughes93e74e82011-09-13 11:07:03 -0700417 tid_ = ::art::GetTid();
418 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700419
Elliott Hughes93e74e82011-09-13 11:07:03 -0700420 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700421
Elliott Hughes8d768a92011-09-14 16:35:25 -0700422 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700423
Elliott Hughes93e74e82011-09-13 11:07:03 -0700424 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700425
Elliott Hughes93e74e82011-09-13 11:07:03 -0700426 runtime->GetThreadList()->Register(this);
427}
428
429Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
430 Thread* self = new Thread;
431 self->Attach(runtime);
432
433 self->SetState(Thread::kRunnable);
434
435 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700436
437 // If we're the main thread, ClassLinker won't be created until after we're attached,
438 // so that thread needs a two-stage attach. Regular threads don't need this hack.
439 if (self->thin_lock_id_ != ThreadList::kMainId) {
440 self->CreatePeer(name, as_daemon);
441 }
442
443 return self;
444}
445
Elliott Hughesd369bb72011-09-12 14:41:14 -0700446jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
447 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
448 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
449 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
450 // This will be null in the compiler (and tests), but never in a running system.
451 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
452 return thread_group;
453}
454
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700455void Thread::CreatePeer(const char* name, bool as_daemon) {
456 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
457
458 JNIEnv* env = jni_env_;
459
Elliott Hughesd369bb72011-09-12 14:41:14 -0700460 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
461 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700462 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700463 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700464 jboolean thread_is_daemon = as_daemon;
465
466 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700467 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700468
Elliott Hughes8daa0922011-09-11 13:46:25 -0700469 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700470
471 // Because we mostly run without code available (in the compiler, in tests), we
472 // manually assign the fields the constructor should have set.
473 // TODO: lose this.
474 jfieldID fid;
475 fid = env->GetFieldID(c, "group", "Ljava/lang/ThreadGroup;");
476 env->SetObjectField(peer, fid, thread_group);
477 fid = env->GetFieldID(c, "name", "Ljava/lang/String;");
478 env->SetObjectField(peer, fid, thread_name);
479 fid = env->GetFieldID(c, "priority", "I");
480 env->SetIntField(peer, fid, thread_priority);
481 fid = env->GetFieldID(c, "daemon", "Z");
482 env->SetBooleanField(peer, fid, thread_is_daemon);
483
484 peer_ = DecodeJObject(peer);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700485}
486
Elliott Hughesbe759c62011-09-08 19:38:21 -0700487void Thread::InitStackHwm() {
488 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700489 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700490
Elliott Hughesbe759c62011-09-08 19:38:21 -0700491 void* stack_base;
492 size_t stack_size;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700493 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700494
Elliott Hughesbe759c62011-09-08 19:38:21 -0700495 if (stack_size <= kStackOverflowReservedBytes) {
496 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size << " bytes)";
497 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700498
499 // stack_base is the "lowest addressable byte" of the stack.
500 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
501 // to throw a StackOverflowError.
buzbeecefd1872011-09-09 09:59:52 -0700502 stack_end_ = reinterpret_cast<byte*>(stack_base) + kStackOverflowReservedBytes;
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700503
504 // Sanity check.
505 int stack_variable;
506 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700507
Elliott Hughes8d768a92011-09-14 16:35:25 -0700508 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700509}
510
Elliott Hughesa0957642011-09-02 14:27:33 -0700511void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700512 DumpState(os);
513 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700514}
515
Elliott Hughesd92bec42011-09-02 17:04:36 -0700516std::string GetSchedulerGroup(pid_t tid) {
517 // /proc/<pid>/group looks like this:
518 // 2:devices:/
519 // 1:cpuacct,cpu:/
520 // We want the third field from the line whose second field contains the "cpu" token.
521 std::string cgroup_file;
522 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
523 return "";
524 }
525 std::vector<std::string> cgroup_lines;
526 Split(cgroup_file, '\n', cgroup_lines);
527 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
528 std::vector<std::string> cgroup_fields;
529 Split(cgroup_lines[i], ':', cgroup_fields);
530 std::vector<std::string> cgroups;
531 Split(cgroup_fields[1], ',', cgroups);
532 for (size_t i = 0; i < cgroups.size(); ++i) {
533 if (cgroups[i] == "cpu") {
534 return cgroup_fields[2].substr(1); // Skip the leading slash.
535 }
536 }
537 }
538 return "";
539}
540
541void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700542 std::string thread_name("<native thread without managed peer>");
543 std::string group_name;
544 int priority;
545 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700546
Elliott Hughesd369bb72011-09-12 14:41:14 -0700547 if (peer_ != NULL) {
548 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
549
550 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
551 Class* int_class = class_linker->FindPrimitiveClass('I');
552 Class* string_class = class_linker->FindSystemClass("Ljava/lang/String;");
553 Class* thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
554 Class* thread_group_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
555
556 Field* name_field = thread_class->FindDeclaredInstanceField("name", string_class);
557 Field* priority_field = thread_class->FindDeclaredInstanceField("priority", int_class);
558 Field* daemon_field = thread_class->FindDeclaredInstanceField("daemon", boolean_class);
559 Field* thread_group_field = thread_class->FindDeclaredInstanceField("group", thread_group_class);
560
561 String* thread_name_string = reinterpret_cast<String*>(name_field->GetObject(peer_));
562 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
563 priority = priority_field->GetInt(peer_);
564 is_daemon = daemon_field->GetBoolean(peer_);
565
566 Object* thread_group = thread_group_field->GetObject(peer_);
567 if (thread_group != NULL) {
568 Field* name_field = thread_group_class->FindDeclaredInstanceField("name", string_class);
569 String* group_name_string = reinterpret_cast<String*>(name_field->GetObject(thread_group));
570 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
571 }
572 } else {
573 // 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 -0700574 std::string stats;
575 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
576 size_t start = stats.find('(') + 1;
577 size_t end = stats.find(')') - start;
578 thread_name = stats.substr(start, end);
579 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700580 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700581 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700582
583 int policy;
584 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700585 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700586
587 std::string scheduler_group(GetSchedulerGroup(GetTid()));
588 if (scheduler_group.empty()) {
589 scheduler_group = "default";
590 }
591
Elliott Hughesd92bec42011-09-02 17:04:36 -0700592 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700593 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700594 os << " daemon";
595 }
596 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700597 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700598 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700599
Elliott Hughesd92bec42011-09-02 17:04:36 -0700600 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700601 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700602 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700603 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700604 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700605 << " self=" << reinterpret_cast<const void*>(this) << "\n";
606 os << " | sysTid=" << GetTid()
607 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
608 << " sched=" << policy << "/" << sp.sched_priority
609 << " cgrp=" << scheduler_group
610 << " handle=" << GetImpl() << "\n";
611
612 // Grab the scheduler stats for this thread.
613 std::string scheduler_stats;
614 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
615 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
616 } else {
617 scheduler_stats = "0 0 0";
618 }
619
620 int utime = 0;
621 int stime = 0;
622 int task_cpu = 0;
623 std::string stats;
624 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
625 // Skip the command, which may contain spaces.
626 stats = stats.substr(stats.find(')') + 2);
627 // Extract the three fields we care about.
628 std::vector<std::string> fields;
629 Split(stats, ' ', fields);
630 utime = strtoull(fields[11].c_str(), NULL, 10);
631 stime = strtoull(fields[12].c_str(), NULL, 10);
632 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
633 }
634
635 os << " | schedstat=( " << scheduler_stats << " )"
636 << " utm=" << utime
637 << " stm=" << stime
638 << " core=" << task_cpu
639 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
640}
641
Elliott Hughesd369bb72011-09-12 14:41:14 -0700642struct StackDumpVisitor : public Thread::StackVisitor {
643 StackDumpVisitor(std::ostream& os) : os(os) {
644 }
645
646 ~StackDumpVisitor() {
647 }
648
649 void VisitFrame(const Frame& frame) {
650 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
651
652 Method* m = frame.GetMethod();
653 Class* c = m->GetDeclaringClass();
654 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
655
656 os << " at " << PrettyMethod(m, false);
657 if (m->IsNative()) {
658 os << "(Native method)";
659 } else {
660 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(frame.GetPC()));
661 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
662 }
663 os << "\n";
664 }
665
666 std::ostream& os;
667};
668
Elliott Hughesd92bec42011-09-02 17:04:36 -0700669void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700670 StackDumpVisitor dumper(os);
671 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700672}
673
Elliott Hughes8d768a92011-09-14 16:35:25 -0700674Thread::State Thread::SetState(Thread::State new_state) {
675 Thread::State old_state = state_;
676 if (old_state == new_state) {
677 return old_state;
678 }
679
680 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
681 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
682
683 if (new_state == Thread::kRunnable) {
684 /*
685 * Change our status to Thread::kRunnable. The transition requires
686 * that we check for pending suspension, because the VM considers
687 * us to be "asleep" in all other states, and another thread could
688 * be performing a GC now.
689 *
690 * The order of operations is very significant here. One way to
691 * do this wrong is:
692 *
693 * GCing thread Our thread (in kNative)
694 * ------------ ----------------------
695 * check suspend count (== 0)
696 * SuspendAllThreads()
697 * grab suspend-count lock
698 * increment all suspend counts
699 * release suspend-count lock
700 * check thread state (== kNative)
701 * all are suspended, begin GC
702 * set state to kRunnable
703 * (continue executing)
704 *
705 * We can correct this by grabbing the suspend-count lock and
706 * performing both of our operations (check suspend count, set
707 * state) while holding it, now we need to grab a mutex on every
708 * transition to kRunnable.
709 *
710 * What we do instead is change the order of operations so that
711 * the transition to kRunnable happens first. If we then detect
712 * that the suspend count is nonzero, we switch to kSuspended.
713 *
714 * Appropriate compiler and memory barriers are required to ensure
715 * that the operations are observed in the expected order.
716 *
717 * This does create a small window of opportunity where a GC in
718 * progress could observe what appears to be a running thread (if
719 * it happens to look between when we set to kRunnable and when we
720 * switch to kSuspended). At worst this only affects assertions
721 * and thread logging. (We could work around it with some sort
722 * of intermediate "pre-running" state that is generally treated
723 * as equivalent to running, but that doesn't seem worthwhile.)
724 *
725 * We can also solve this by combining the "status" and "suspend
726 * count" fields into a single 32-bit value. This trades the
727 * store/load barrier on transition to kRunnable for an atomic RMW
728 * op on all transitions and all suspend count updates (also, all
729 * accesses to status or the thread count require bit-fiddling).
730 * It also eliminates the brief transition through kRunnable when
731 * the thread is supposed to be suspended. This is possibly faster
732 * on SMP and slightly more correct, but less convenient.
733 */
734 android_atomic_acquire_store(new_state, addr);
735 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
736 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
737 }
738 } else {
739 /*
740 * Not changing to Thread::kRunnable. No additional work required.
741 *
742 * We use a releasing store to ensure that, if we were runnable,
743 * any updates we previously made to objects on the managed heap
744 * will be observed before the state change.
745 */
746 android_atomic_release_store(new_state, addr);
747 }
748
749 return old_state;
750}
751
752void Thread::WaitUntilSuspended() {
753 // TODO: dalvik dropped the waiting thread's priority after a while.
754 // TODO: dalvik timed out and aborted.
755 useconds_t delay = 0;
756 while (GetState() == Thread::kRunnable) {
757 useconds_t new_delay = delay * 2;
758 CHECK_GE(new_delay, delay);
759 delay = new_delay;
760 if (delay == 0) {
761 sched_yield();
762 delay = 10000;
763 } else {
764 usleep(delay);
765 }
766 }
767}
768
Elliott Hughesbe759c62011-09-08 19:38:21 -0700769void Thread::ThreadExitCallback(void* arg) {
770 Thread* self = reinterpret_cast<Thread*>(arg);
771 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700772}
773
Elliott Hughesbe759c62011-09-08 19:38:21 -0700774void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700775 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700776 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700777
778 // Double-check the TLS slot allocation.
779 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700780 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700781 }
782
783 // TODO: initialize other locks and condition variables
Carl Shapirob5573532011-07-12 18:22:59 -0700784}
785
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700786void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700787 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700788}
789
Elliott Hughesdcc24742011-09-07 14:02:44 -0700790Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700791 : peer_(NULL),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700792 wait_mutex_("Thread wait mutex"),
793 wait_monitor_(NULL),
794 interrupted_(false),
795 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700796 top_of_managed_stack_(),
797 native_to_managed_record_(NULL),
798 top_sirt_(NULL),
799 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700800 state_(Thread::kUnknown),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700801 exception_(NULL),
802 suspend_count_(0),
803 class_loader_override_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700804}
805
Elliott Hughes02b48d12011-09-07 17:15:51 -0700806void MonitorExitVisitor(const Object* object, void*) {
807 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700808 entered_monitor->MonitorExit();
Elliott Hughes02b48d12011-09-07 17:15:51 -0700809}
810
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700811Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700812 // TODO: check we're not calling the JNI DetachCurrentThread function from
813 // a call stack that includes managed frames. (It's only valid if the stack is all-native.)
814
815 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700816 if (jni_env_ != NULL) {
817 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
818 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700819
820 if (IsExceptionPending()) {
821 UNIMPLEMENTED(FATAL) << "threadExitUncaughtException()";
822 }
823
824 // TODO: ThreadGroup.removeThread(this);
825
Elliott Hughes93e74e82011-09-13 11:07:03 -0700826 if (peer_ != NULL) {
827 SetVmData(peer_, NULL);
828 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700829
830 // TODO: say "bye" to the debugger.
831 //if (gDvm.debuggerConnected) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700832 // dvmDbgPostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700833 //}
834
835 // Thread.join() is implemented as an Object.wait() on the Thread.lock
836 // object. Signal anyone who is waiting.
837 //Object* lock = dvmGetFieldObject(self->threadObj, gDvm.offJavaLangThread_lock);
838 //dvmLockObject(self, lock);
839 //dvmObjectNotifyAll(self, lock);
840 //dvmUnlockObject(self, lock);
841 //lock = NULL;
842
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700843 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700844 jni_env_ = NULL;
845
846 SetState(Thread::kTerminated);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700847}
848
Ian Rogers408f79a2011-08-23 18:22:33 -0700849size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700850 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700851 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700852 count += cur->NumberOfReferences();
853 }
854 return count;
855}
856
Ian Rogers408f79a2011-08-23 18:22:33 -0700857bool Thread::SirtContains(jobject obj) {
858 Object** sirt_entry = reinterpret_cast<Object**>(obj);
859 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700860 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -0700861 // A SIRT should always have a jobject/jclass as a native method is passed
862 // in a this pointer or a class
863 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -0700864 if ((&cur->References()[0] <= sirt_entry) &&
865 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700866 return true;
867 }
868 }
869 return false;
870}
871
Ian Rogers408f79a2011-08-23 18:22:33 -0700872Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700873 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -0700874 if (obj == NULL) {
875 return NULL;
876 }
877 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
878 IndirectRefKind kind = GetIndirectRefKind(ref);
879 Object* result;
880 switch (kind) {
881 case kLocal:
882 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -0700883 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700884 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700885 break;
886 }
887 case kGlobal:
888 {
889 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
890 IndirectReferenceTable& globals = vm->globals;
891 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700892 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700893 break;
894 }
895 case kWeakGlobal:
896 {
897 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
898 IndirectReferenceTable& weak_globals = vm->weak_globals;
899 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700900 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -0700901 if (result == kClearedJniWeakGlobal) {
902 // This is a special case where it's okay to return NULL.
903 return NULL;
904 }
905 break;
906 }
907 case kSirtOrInvalid:
908 default:
909 // TODO: make stack indirect reference table lookup more efficient
910 // Check if this is a local reference in the SIRT
911 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700912 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -0700913 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -0700914 // Assume an invalid local reference is actually a direct pointer.
915 result = reinterpret_cast<Object*>(obj);
916 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -0700917 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -0700918 }
919 }
920
921 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700922 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
923 JniAbort(NULL);
924 } else {
925 if (result != kInvalidIndirectRefObject) {
926 Heap::VerifyObject(result);
927 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700928 }
Ian Rogers408f79a2011-08-23 18:22:33 -0700929 return result;
930}
931
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700932class CountStackDepthVisitor : public Thread::StackVisitor {
933 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700934 CountStackDepthVisitor() : depth_(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -0700935
936 virtual void VisitFrame(const Frame&) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700937 ++depth_;
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700938 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700939
940 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -0700941 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700942 }
943
944 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700945 uint32_t depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700946};
947
Ian Rogersaaa20802011-09-11 21:47:37 -0700948//
949class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700950 public:
Ian Rogersaaa20802011-09-11 21:47:37 -0700951 explicit BuildInternalStackTraceVisitor(int depth, ScopedJniThreadState& ts) : count_(0) {
952 // Allocate method trace with an extra slot that will hold the PC trace
953 method_trace_ = Runtime::Current()->GetClassLinker()->
954 AllocObjectArray<Object>(depth + 1);
955 // Register a local reference as IntArray::Alloc may trigger GC
956 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
957 pc_trace_ = IntArray::Alloc(depth);
958#ifdef MOVING_GARBAGE_COLLECTOR
959 // Re-read after potential GC
960 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
961#endif
962 // Save PC trace in last element of method trace, also places it into the
963 // object graph.
964 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700965 }
966
Ian Rogersaaa20802011-09-11 21:47:37 -0700967 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700968
Elliott Hughesd369bb72011-09-12 14:41:14 -0700969 virtual void VisitFrame(const Frame& frame) {
Ian Rogersaaa20802011-09-11 21:47:37 -0700970 method_trace_->Set(count_, frame.GetMethod());
971 pc_trace_->Set(count_, frame.GetPC());
972 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700973 }
974
Ian Rogersaaa20802011-09-11 21:47:37 -0700975 jobject GetInternalStackTrace() const {
976 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700977 }
978
979 private:
Ian Rogersaaa20802011-09-11 21:47:37 -0700980 // Current position down stack trace
981 uint32_t count_;
982 // Array of return PC values
983 IntArray* pc_trace_;
984 // An array of the methods on the stack, the last entry is a reference to the
985 // PC trace
986 ObjectArray<Object>* method_trace_;
987 // Local indirect reference table entry for method trace
988 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700989};
990
Ian Rogersaaa20802011-09-11 21:47:37 -0700991void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700992 Frame frame = GetTopOfStack();
Shih-wei Liao9b576b42011-08-29 01:45:07 -0700993 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
994 // CHECK(native_to_managed_record_ != NULL);
995 NativeToManagedRecord* record = native_to_managed_record_;
996
997 while (frame.GetSP()) {
998 for ( ; frame.GetMethod() != 0; frame.Next()) {
999 visitor->VisitFrame(frame);
1000 }
1001 if (record == NULL) {
1002 break;
1003 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001004 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 -07001005 record = record->link;
1006 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001007}
1008
Ian Rogersaaa20802011-09-11 21:47:37 -07001009jobject Thread::CreateInternalStackTrace() const {
1010 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001011 CountStackDepthVisitor count_visitor;
1012 WalkStack(&count_visitor);
1013 int32_t depth = count_visitor.GetDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001014
Ian Rogersaaa20802011-09-11 21:47:37 -07001015 // Transition into runnable state to work on Object*/Array*
1016 ScopedJniThreadState ts(jni_env_);
1017
1018 // Build internal stack trace
1019 BuildInternalStackTraceVisitor build_trace_visitor(depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001020 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001021
Ian Rogersaaa20802011-09-11 21:47:37 -07001022 return build_trace_visitor.GetInternalStackTrace();
1023}
1024
1025jobjectArray Thread::InternalStackTraceToStackTraceElementArray(jobject internal,
1026 JNIEnv* env) {
1027 // Transition into runnable state to work on Object*/Array*
1028 ScopedJniThreadState ts(env);
1029
1030 // Decode the internal stack trace into the depth, method trace and PC trace
1031 ObjectArray<Object>* method_trace =
1032 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1033 int32_t depth = method_trace->GetLength()-1;
1034 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1035
1036 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1037
1038 // Create java_trace array and place in local reference table
1039 ObjectArray<StackTraceElement>* java_traces =
1040 class_linker->AllocStackTraceElementArray(depth);
1041 jobjectArray result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001042
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001043 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001044 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1045 Method* method = down_cast<Method*>(method_trace->Get(i));
1046 uint32_t native_pc = pc_trace->Get(i);
1047 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001048 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Shih-wei Liao44175362011-08-28 16:59:17 -07001049 String* readable_descriptor = String::AllocFromModifiedUtf8(
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001050 PrettyDescriptor(klass->GetDescriptor()).c_str());
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001051
Ian Rogersaaa20802011-09-11 21:47:37 -07001052 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001053 StackTraceElement* obj =
1054 StackTraceElement::Alloc(readable_descriptor,
Shih-wei Liao44175362011-08-28 16:59:17 -07001055 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001056 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001057 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001058 method->ToDexPC(native_pc)));
1059#ifdef MOVING_GARBAGE_COLLECTOR
1060 // Re-read after potential GC
1061 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1062 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1063 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1064#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001065 java_traces->Set(i, obj);
1066 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001067 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001068}
1069
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001070void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughes37f7a402011-08-22 18:56:01 -07001071 std::string msg;
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001072 va_list args;
1073 va_start(args, fmt);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001074 StringAppendV(&msg, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001075 va_end(args);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001076
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001077 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001078 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001079 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001080 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001081 descriptor.erase(descriptor.length() - 1);
1082
1083 JNIEnv* env = GetJniEnv();
1084 jclass exception_class = env->FindClass(descriptor.c_str());
1085 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1086 int rc = env->ThrowNew(exception_class, msg.c_str());
1087 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001088}
1089
Elliott Hughes79082e32011-08-25 12:07:32 -07001090void Thread::ThrowOutOfMemoryError() {
1091 UNIMPLEMENTED(FATAL);
1092}
1093
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001094Frame Thread::FindExceptionHandler(void* throw_pc, void** handler_pc) {
1095 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1096 DCHECK(class_linker != NULL);
1097
1098 Frame cur_frame = GetTopOfStack();
1099 for (int unwind_depth = 0; ; unwind_depth++) {
1100 const Method* cur_method = cur_frame.GetMethod();
1101 DexCache* dex_cache = cur_method->GetDeclaringClass()->GetDexCache();
1102 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
1103
1104 void* handler_addr = FindExceptionHandlerInMethod(cur_method,
1105 throw_pc,
1106 dex_file,
1107 class_linker);
1108 if (handler_addr) {
1109 *handler_pc = handler_addr;
1110 return cur_frame;
1111 } else {
1112 // Check if we are at the last frame
1113 if (cur_frame.HasNext()) {
1114 cur_frame.Next();
1115 } else {
1116 // Either at the top of stack or next frame is native.
1117 break;
1118 }
1119 }
1120 }
1121 *handler_pc = NULL;
1122 return Frame();
1123}
1124
1125void* Thread::FindExceptionHandlerInMethod(const Method* method,
1126 void* throw_pc,
1127 const DexFile& dex_file,
1128 ClassLinker* class_linker) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001129 Throwable* exception_obj = exception_;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001130 exception_ = NULL;
1131
1132 intptr_t dex_pc = -1;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001133 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001134 DexFile::CatchHandlerIterator iter;
1135 for (iter = dex_file.dexFindCatchHandler(*code_item,
1136 method->ToDexPC(reinterpret_cast<intptr_t>(throw_pc)));
1137 !iter.HasNext();
1138 iter.Next()) {
1139 Class* klass = class_linker->FindSystemClass(dex_file.dexStringByTypeIdx(iter.Get().type_idx_));
1140 DCHECK(klass != NULL);
1141 if (exception_obj->InstanceOf(klass)) {
1142 dex_pc = iter.Get().address_;
1143 break;
1144 }
1145 }
1146
1147 exception_ = exception_obj;
1148 if (iter.HasNext()) {
1149 return NULL;
1150 } else {
1151 return reinterpret_cast<void*>( method->ToNativePC(dex_pc) );
1152 }
1153}
1154
Elliott Hughes410c0c82011-09-01 17:58:25 -07001155void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001156 if (exception_ != NULL) {
1157 visitor(exception_, arg);
1158 }
1159 if (peer_ != NULL) {
1160 visitor(peer_, arg);
1161 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001162 jni_env_->locals.VisitRoots(visitor, arg);
1163 jni_env_->monitors.VisitRoots(visitor, arg);
1164 // visitThreadStack(visitor, thread, arg);
1165 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1166}
1167
Ian Rogersb033c752011-07-20 12:22:35 -07001168static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001169 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001170 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001171 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001172 "Blocked",
1173 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001174 "Initializing",
1175 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001176 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001177 "VmWait",
1178 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001179};
1180std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001181 int int_state = static_cast<int>(state);
1182 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1183 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001184 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001185 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001186 }
1187 return os;
1188}
1189
Elliott Hughes330304d2011-08-12 14:28:05 -07001190std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1191 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001192 << ",pthread_t=" << thread.GetImpl()
1193 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001194 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001195 << ",state=" << thread.GetState()
1196 << ",peer=" << thread.GetPeer()
1197 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001198 return os;
1199}
1200
Elliott Hughes8daa0922011-09-11 13:46:25 -07001201} // namespace art