blob: 232c1150ab9edfd71a006a72b654bd59478d4454 [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 Rogersbdb03912011-09-14 00:55:44 -070030#include "context.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070031#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070032#include "jni_internal.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070033#include "object.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070035#include "runtime_support.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070036#include "scoped_jni_thread_state.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070037#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070038#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070039
40namespace art {
41
42pthread_key_t Thread::pthread_key_self_;
43
Elliott Hughes29f27422011-09-18 16:02:18 -070044static Class* gThrowable = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070045static Field* gThread_daemon = NULL;
46static Field* gThread_group = NULL;
47static Field* gThread_lock = NULL;
48static Field* gThread_name = NULL;
49static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070050static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070051static Field* gThread_vmData = NULL;
52static Field* gThreadGroup_name = NULL;
53static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070054static Method* gThreadGroup_removeThread = NULL;
55static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070056
buzbee4a3164f2011-09-03 11:25:10 -070057// Temporary debugging hook for compiler.
Elliott Hughesd369bb72011-09-12 14:41:14 -070058void DebugMe(Method* method, uint32_t info) {
Elliott Hughes01158d72011-09-19 19:47:10 -070059 LOG(INFO) << "DebugMe";
60 if (method != NULL) {
61 LOG(INFO) << PrettyMethod(method);
62 }
63 LOG(INFO) << "Info: " << info;
buzbee4a3164f2011-09-03 11:25:10 -070064}
65
Ian Rogersbdb03912011-09-14 00:55:44 -070066// Called by generated call to throw an exception
Ian Rogersff1ed472011-09-20 13:46:24 -070067extern "C" void artDeliverExceptionFromCode(Throwable* exception, Thread* thread, Method** sp) {
Elliott Hughesd369bb72011-09-12 14:41:14 -070068 /*
69 * exception may be NULL, in which case this routine should
70 * throw NPE. NOTE: this is a convenience for generated code,
71 * which previously did the null check inline and constructed
72 * and threw a NPE if NULL. This routine responsible for setting
Ian Rogersbdb03912011-09-14 00:55:44 -070073 * exception_ in thread and delivering the exception.
Elliott Hughesd369bb72011-09-12 14:41:14 -070074 */
Ian Rogers67375ac2011-09-14 00:55:44 -070075 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -070076 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogersbdb03912011-09-14 00:55:44 -070077 thread->SetTopOfStack(sp, 0);
Ian Rogers93dd9662011-09-17 23:21:22 -070078 if (exception == NULL) {
79 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
Ian Rogersff1ed472011-09-20 13:46:24 -070080 } else {
81 thread->SetException(exception);
Ian Rogers93dd9662011-09-17 23:21:22 -070082 }
Ian Rogersff1ed472011-09-20 13:46:24 -070083 thread->DeliverException();
84}
85
86// Deliver an exception that's pending on thread helping set up a callee save frame on the way
87extern "C" void artDeliverPendingExceptionFromCode(Thread* thread, Method** sp) {
88 *sp = Runtime::Current()->GetCalleeSaveMethod();
89 thread->SetTopOfStack(sp, 0);
90 thread->DeliverException();
buzbee1b4c8592011-08-31 10:43:51 -070091}
92
Ian Rogers9651f422011-09-19 20:26:07 -070093// Called by generated call to throw a NPE exception
Ian Rogersff1ed472011-09-20 13:46:24 -070094extern "C" void artThrowNullPointerExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -070095 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -070096 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -070097 thread->SetTopOfStack(sp, 0);
98 thread->ThrowNewException("Ljava/lang/NullPointerException;", "unexpected null reference");
Ian Rogersff1ed472011-09-20 13:46:24 -070099 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700100}
101
102// Called by generated call to throw an arithmetic divide by zero exception
Ian Rogersff1ed472011-09-20 13:46:24 -0700103extern "C" void artThrowDivZeroFromCode(Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700104 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700105 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700106 thread->SetTopOfStack(sp, 0);
107 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
Ian Rogersff1ed472011-09-20 13:46:24 -0700108 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700109}
110
111// Called by generated call to throw an arithmetic divide by zero exception
Ian Rogersff1ed472011-09-20 13:46:24 -0700112extern "C" void artThrowArrayBoundsFromCode(int index, int limit, Thread* thread, Method** sp) {
Ian Rogers9651f422011-09-19 20:26:07 -0700113 // Place a special frame at the TOS that will save all callee saves
Ian Rogersff1ed472011-09-20 13:46:24 -0700114 *sp = Runtime::Current()->GetCalleeSaveMethod();
Ian Rogers9651f422011-09-19 20:26:07 -0700115 thread->SetTopOfStack(sp, 0);
116 thread->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
117 "length=%d; index=%d", limit, index);
Ian Rogersff1ed472011-09-20 13:46:24 -0700118 thread->DeliverException();
Ian Rogers9651f422011-09-19 20:26:07 -0700119}
120
Ian Rogersff1ed472011-09-20 13:46:24 -0700121// Called by the AbstractMethodError stub (not runtime support)
122void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread, Method** sp) {
123 *sp = Runtime::Current()->GetCalleeSaveMethod();
124 thread->SetTopOfStack(sp, 0);
Ian Rogersa0841a82011-09-22 14:16:31 -0700125 thread->ThrowNewException("Ljava/lang/AbstractMethodError;",
Ian Rogersff1ed472011-09-20 13:46:24 -0700126 "abstract method \"%s\"",
127 PrettyMethod(method).c_str());
128 thread->DeliverException();
129}
130
Ian Rogers932746a2011-09-22 18:57:50 -0700131extern "C" void artThrowStackOverflowFromCode(Method* method, Thread* thread, Method** sp) {
132 // Place a special frame at the TOS that will save all callee saves
133 Runtime* runtime = Runtime::Current();
134 *sp = runtime->GetCalleeSaveMethod();
135 thread->SetTopOfStack(sp, 0);
136 thread->SetStackEndForStackOverflow();
137 thread->ThrowNewException("Ljava/lang/StackOverflowError;",
138 "stack size %zdkb; default stack size: %zdkb",
139 thread->GetStackSize() / KB, runtime->GetDefaultStackSize() / KB);
140 thread->ResetDefaultStackEnd();
141 thread->DeliverException();
Ian Rogersff1ed472011-09-20 13:46:24 -0700142}
143
144// TODO: placeholder
145void ThrowVerificationErrorFromCode(int32_t src1, int32_t ref) {
146 UNIMPLEMENTED(FATAL) << "Verification error, src1: " << src1 <<
147 " ref: " << ref;
148}
149
150// TODO: placeholder
151void ThrowNegArraySizeFromCode(int32_t index) {
152 UNIMPLEMENTED(FATAL) << "Negative array size: " << index;
153}
154
155// TODO: placeholder
156void ThrowInternalErrorFromCode(int32_t errnum) {
157 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
158}
159
160// TODO: placeholder
161void ThrowRuntimeExceptionFromCode(int32_t errnum) {
162 UNIMPLEMENTED(FATAL) << "Internal error: " << errnum;
163}
164
165// TODO: placeholder
166void ThrowNoSuchMethodFromCode(int32_t method_idx) {
167 UNIMPLEMENTED(FATAL) << "No such method, idx: " << method_idx;
168}
Ian Rogersbdb03912011-09-14 00:55:44 -0700169
buzbee1b4c8592011-08-31 10:43:51 -0700170// TODO: placeholder. Helper function to type
Elliott Hughesd369bb72011-09-12 14:41:14 -0700171Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
buzbee1b4c8592011-08-31 10:43:51 -0700172 /*
173 * Should initialize & fix up method->dex_cache_resolved_types_[].
174 * Returns initialized type. Does not return normally if an exception
175 * is thrown, but instead initiates the catch. Should be similar to
176 * ClassLinker::InitializeStaticStorageFromCode.
177 */
178 UNIMPLEMENTED(FATAL);
179 return NULL;
180}
181
buzbee561227c2011-09-02 15:28:19 -0700182// TODO: placeholder. Helper function to resolve virtual method
Elliott Hughesd369bb72011-09-12 14:41:14 -0700183void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
buzbee561227c2011-09-02 15:28:19 -0700184 /*
185 * Slow-path handler on invoke virtual method path in which
186 * base method is unresolved at compile-time. Doesn't need to
187 * return anything - just either ensure that
188 * method->dex_cache_resolved_methods_(method_idx) != NULL or
189 * throw and unwind. The caller will restart call sequence
190 * from the beginning.
191 */
192}
193
buzbee1da522d2011-09-04 11:22:20 -0700194// TODO: placeholder. Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesd369bb72011-09-12 14:41:14 -0700195Array* CheckAndAllocFromCode(uint32_t type_index, Method* method, int32_t component_count) {
buzbee1da522d2011-09-04 11:22:20 -0700196 /*
197 * Just a wrapper around Array::AllocFromCode() that additionally
198 * throws a runtime exception "bad Filled array req" for 'D' and 'J'.
199 */
200 UNIMPLEMENTED(WARNING) << "Need check that not 'D' or 'J'";
201 return Array::AllocFromCode(type_index, method, component_count);
202}
203
buzbee2a475e72011-09-07 17:19:17 -0700204// TODO: placeholder (throw on failure)
Ian Rogersff1ed472011-09-20 13:46:24 -0700205extern "C" int artCheckCastFromCode(const Class* a, const Class* b) {
Brian Carlstromc2282522011-09-17 10:33:14 -0700206 DCHECK(a->IsClass());
207 DCHECK(b->IsClass());
208 if (b->IsAssignableFrom(a)) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700209 return 0; // Success
210 } else {
211 Thread::Current()->ThrowNewException("Ljava/lang/ClassCastException;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700212 "%s cannot be cast to %s",
213 PrettyDescriptor(a->GetDescriptor()).c_str(),
214 PrettyDescriptor(b->GetDescriptor()).c_str());
Ian Rogersff1ed472011-09-20 13:46:24 -0700215 return -1; // Failure
Brian Carlstromc2282522011-09-17 10:33:14 -0700216 }
buzbee2a475e72011-09-07 17:19:17 -0700217}
218
Ian Rogersff1ed472011-09-20 13:46:24 -0700219extern "C" int artUnlockObjectFromCode(Thread* thread, Object* obj) {
220 DCHECK(obj != NULL); // Assumed to have been checked before entry
221 return obj->MonitorExit(thread) ? 0 /* Success */ : -1 /* Failure */;
buzbee2a475e72011-09-07 17:19:17 -0700222}
223
Elliott Hughesd369bb72011-09-12 14:41:14 -0700224void LockObjectFromCode(Thread* thread, Object* obj) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700225 DCHECK(obj != NULL); // Assumed to have been checked before entry
Elliott Hughes8d768a92011-09-14 16:35:25 -0700226 obj->MonitorEnter(thread);
Ian Rogersff1ed472011-09-20 13:46:24 -0700227 DCHECK(thread->HoldsLock(obj));
228 // Only possible exception is NPE and is handled before entry
229 DCHECK(thread->GetException() == NULL);
buzbee2a475e72011-09-07 17:19:17 -0700230}
231
buzbeec1f45042011-09-21 16:03:19 -0700232extern "C" void artCheckSuspendFromCode(Thread* thread) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700233 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
buzbee0d966cf2011-09-08 17:34:58 -0700234}
235
buzbee5ade1d22011-09-09 14:44:52 -0700236/*
Ian Rogersff1ed472011-09-20 13:46:24 -0700237 * Fill the array with predefined constant values, throwing exceptions if the array is null or
238 * not of sufficient length.
buzbee5ade1d22011-09-09 14:44:52 -0700239 *
240 * NOTE: When dealing with a raw dex file, the data to be copied uses
241 * little-endian ordering. Require that oat2dex do any required swapping
242 * so this routine can get by with a memcpy().
243 *
244 * Format of the data:
245 * ushort ident = 0x0300 magic value
246 * ushort width width of each element in the table
247 * uint size number of elements in the table
248 * ubyte data[size*width] table of data values (may contain a single-byte
249 * padding at the end)
250 */
Ian Rogersff1ed472011-09-20 13:46:24 -0700251extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
252 DCHECK_EQ(table[0], 0x0300);
253 if (array == NULL) {
254 Thread::Current()->ThrowNewException("Ljava/lang/NullPointerException;",
255 "null array in fill array");
256 return -1; // Error
257 }
258 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
259 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
260 if (static_cast<int32_t>(size) > array->GetLength()) {
261 Thread::Current()->ThrowNewException("Ljava/lang/ArrayIndexOutOfBoundsException;",
262 "failed array fill. length=%d; index=%d",
263 array->GetLength(), size);
264 return -1; // Error
265 }
266 uint16_t width = table[1];
267 uint32_t size_in_bytes = size * width;
268 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
269 return 0; // Success
Brian Carlstrom16192862011-09-12 17:50:06 -0700270}
271
272// See comments in runtime_support.S
Ian Rogersff1ed472011-09-20 13:46:24 -0700273extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
274 Object* this_object ,
275 Method* caller_method) {
276 Thread* thread = Thread::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700277 if (this_object == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700278 thread->ThrowNewException("Ljava/lang/NullPointerException;",
279 "null receiver during interface dispatch");
280 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700281 }
282 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
283 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
284 if (interface_method == NULL) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700285 // Could not resolve interface method. Throw error and unwind
286 CHECK(thread->GetException() != NULL);
287 return 0;
Brian Carlstrom16192862011-09-12 17:50:06 -0700288 }
289 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
290 const void* code = method->GetCode();
291
292 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
293 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
294 uint64_t result = ((code_uint << 32) | method_uint);
295 return result;
296}
297
buzbee5ade1d22011-09-09 14:44:52 -0700298// TODO: move to more appropriate location
299/*
300 * Float/double conversion requires clamping to min and max of integer form. If
301 * target doesn't support this normally, use these.
302 */
Elliott Hughesd369bb72011-09-12 14:41:14 -0700303int64_t D2L(double d) {
buzbee5ade1d22011-09-09 14:44:52 -0700304 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
305 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
306 if (d >= kMaxLong)
307 return (int64_t)0x7fffffffffffffffULL;
308 else if (d <= kMinLong)
309 return (int64_t)0x8000000000000000ULL;
310 else if (d != d) // NaN case
311 return 0;
312 else
313 return (int64_t)d;
314}
315
Elliott Hughesd369bb72011-09-12 14:41:14 -0700316int64_t F2L(float f) {
buzbee5ade1d22011-09-09 14:44:52 -0700317 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
318 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
319 if (f >= kMaxLong)
320 return (int64_t)0x7fffffffffffffffULL;
321 else if (f <= kMinLong)
322 return (int64_t)0x8000000000000000ULL;
323 else if (f != f) // NaN case
324 return 0;
325 else
326 return (int64_t)f;
327}
328
Brian Carlstrom16192862011-09-12 17:50:06 -0700329// Return value helper for jobject return types
330static Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
331 return thread->DecodeJObject(obj);
332}
333
buzbee3ea4ec52011-08-22 17:37:19 -0700334void Thread::InitFunctionPointers() {
buzbee54330722011-08-23 16:46:55 -0700335#if defined(__arm__)
336 pShlLong = art_shl_long;
337 pShrLong = art_shr_long;
338 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700339 pIdiv = __aeabi_idiv;
340 pIdivmod = __aeabi_idivmod;
341 pI2f = __aeabi_i2f;
342 pF2iz = __aeabi_f2iz;
343 pD2f = __aeabi_d2f;
344 pF2d = __aeabi_f2d;
345 pD2iz = __aeabi_d2iz;
346 pL2f = __aeabi_l2f;
347 pL2d = __aeabi_l2d;
348 pFadd = __aeabi_fadd;
349 pFsub = __aeabi_fsub;
350 pFdiv = __aeabi_fdiv;
351 pFmul = __aeabi_fmul;
352 pFmodf = fmodf;
353 pDadd = __aeabi_dadd;
354 pDsub = __aeabi_dsub;
355 pDdiv = __aeabi_ddiv;
356 pDmul = __aeabi_dmul;
357 pFmod = fmod;
buzbee7b1b86d2011-08-26 18:59:10 -0700358 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700359 pLmul = __aeabi_lmul;
Ian Rogersff1ed472011-09-20 13:46:24 -0700360 pCheckCastFromCode = art_check_cast_from_code;
361 pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
Ian Rogerscbba6ac2011-09-22 16:28:37 -0700362 pInitializeStaticStorage = art_initialize_static_storage_from_code;
buzbee4a3164f2011-09-03 11:25:10 -0700363 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
buzbeec1f45042011-09-21 16:03:19 -0700364 pTestSuspendFromCode = art_test_suspend;
Ian Rogersff1ed472011-09-20 13:46:24 -0700365 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
366 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
367 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
Ian Rogers932746a2011-09-22 18:57:50 -0700368 pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700369 pUnlockObjectFromCode = art_unlock_object_from_code;
Ian Rogers67375ac2011-09-14 00:55:44 -0700370#endif
Ian Rogersff1ed472011-09-20 13:46:24 -0700371 pDeliverException = art_deliver_exception_from_code;
buzbeec396efc2011-09-11 09:36:41 -0700372 pF2l = F2L;
373 pD2l = D2L;
buzbeedfd3d702011-08-28 12:56:51 -0700374 pAllocFromCode = Array::AllocFromCode;
buzbee1da522d2011-09-04 11:22:20 -0700375 pCheckAndAllocFromCode = CheckAndAllocFromCode;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700376 pAllocObjectFromCode = Class::AllocObjectFromCode;
buzbee3ea4ec52011-08-22 17:37:19 -0700377 pMemcpy = memcpy;
buzbeee1931742011-08-28 21:15:53 -0700378 pGet32Static = Field::Get32StaticFromCode;
379 pSet32Static = Field::Set32StaticFromCode;
380 pGet64Static = Field::Get64StaticFromCode;
381 pSet64Static = Field::Set64StaticFromCode;
382 pGetObjStatic = Field::GetObjStaticFromCode;
383 pSetObjStatic = Field::SetObjStaticFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700384 pCanPutArrayElementFromCode = Class::CanPutArrayElementFromCode;
buzbee1b4c8592011-08-31 10:43:51 -0700385 pInitializeTypeFromCode = InitializeTypeFromCode;
buzbee561227c2011-09-02 15:28:19 -0700386 pResolveMethodFromCode = ResolveMethodFromCode;
buzbee2a475e72011-09-07 17:19:17 -0700387 pInstanceofNonTrivialFromCode = Object::InstanceOf;
buzbee2a475e72011-09-07 17:19:17 -0700388 pLockObjectFromCode = LockObjectFromCode;
Brian Carlstrom845490b2011-09-19 15:56:53 -0700389 pFindInstanceFieldFromCode = Field::FindInstanceFieldFromCode;
buzbeec1f45042011-09-21 16:03:19 -0700390 pCheckSuspendFromCode = artCheckSuspendFromCode;
buzbee5ade1d22011-09-09 14:44:52 -0700391 pThrowVerificationErrorFromCode = ThrowVerificationErrorFromCode;
392 pThrowNegArraySizeFromCode = ThrowNegArraySizeFromCode;
393 pThrowRuntimeExceptionFromCode = ThrowRuntimeExceptionFromCode;
394 pThrowInternalErrorFromCode = ThrowInternalErrorFromCode;
395 pThrowNoSuchMethodFromCode = ThrowNoSuchMethodFromCode;
Ian Rogersbdb03912011-09-14 00:55:44 -0700396 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
Brian Carlstrom16192862011-09-12 17:50:06 -0700397 pFindNativeMethod = FindNativeMethod;
398 pDecodeJObjectInThread = DecodeJObjectInThread;
buzbee4a3164f2011-09-03 11:25:10 -0700399 pDebugMe = DebugMe;
buzbee3ea4ec52011-08-22 17:37:19 -0700400}
401
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700402void Frame::Next() {
Ian Rogers67375ac2011-09-14 00:55:44 -0700403 size_t frame_size = GetMethod()->GetFrameSizeInBytes();
404 DCHECK_NE(frame_size, 0u);
405 DCHECK_LT(frame_size, 1024u);
Ian Rogersff1ed472011-09-20 13:46:24 -0700406 byte* next_sp = reinterpret_cast<byte*>(sp_) + frame_size;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700407 sp_ = reinterpret_cast<Method**>(next_sp);
Ian Rogersff1ed472011-09-20 13:46:24 -0700408 if(*sp_ != NULL) {
409 DCHECK_EQ((*sp_)->GetClass(), Method::GetMethodClass());
410 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700411}
412
Ian Rogers90865722011-09-19 11:11:44 -0700413bool Frame::HasMethod() const {
414 return GetMethod() != NULL && (!GetMethod()->IsPhony());
415}
416
Ian Rogersbdb03912011-09-14 00:55:44 -0700417uintptr_t Frame::GetReturnPC() const {
Ian Rogersff1ed472011-09-20 13:46:24 -0700418 byte* pc_addr = reinterpret_cast<byte*>(sp_) + GetMethod()->GetReturnPcOffsetInBytes();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700419 return *reinterpret_cast<uintptr_t*>(pc_addr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700420}
421
Ian Rogersbdb03912011-09-14 00:55:44 -0700422uintptr_t Frame::LoadCalleeSave(int num) const {
423 // Callee saves are held at the top of the frame
424 Method* method = GetMethod();
425 DCHECK(method != NULL);
426 size_t frame_size = method->GetFrameSizeInBytes();
Ian Rogersff1ed472011-09-20 13:46:24 -0700427 byte* save_addr = reinterpret_cast<byte*>(sp_) + frame_size - ((num + 1) * kPointerSize);
Ian Rogers67375ac2011-09-14 00:55:44 -0700428#if defined(__i386__)
429 save_addr -= kPointerSize; // account for return address
430#endif
Ian Rogersbdb03912011-09-14 00:55:44 -0700431 return *reinterpret_cast<uintptr_t*>(save_addr);
432}
433
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700434Method* Frame::NextMethod() const {
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700435 byte* next_sp = reinterpret_cast<byte*>(sp_) +
Shih-wei Liaod11af152011-08-23 16:02:11 -0700436 GetMethod()->GetFrameSizeInBytes();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700437 return *reinterpret_cast<Method**>(next_sp);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -0700438}
439
Brian Carlstrom78128a62011-09-15 17:21:19 -0700440void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700441 Thread* self = reinterpret_cast<Thread*>(arg);
442 Runtime* runtime = Runtime::Current();
443
444 self->Attach(runtime);
445
Elliott Hughes038a8062011-09-18 14:12:41 -0700446 String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700447 if (thread_name != NULL) {
448 SetThreadName(thread_name->ToModifiedUtf8().c_str());
449 }
450
451 // Wait until it's safe to start running code. (There may have been a suspend-all
452 // in progress while we were starting up.)
453 runtime->GetThreadList()->WaitForGo();
454
455 // TODO: say "hi" to the debugger.
456 //if (gDvm.debuggerConnected) {
457 // dvmDbgPostThreadStart(self);
458 //}
459
460 // Invoke the 'run' method of our java.lang.Thread.
461 CHECK(self->peer_ != NULL);
462 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700463 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700464 m->Invoke(self, receiver, NULL, NULL);
465
466 // Detach.
467 runtime->GetThreadList()->Unregister();
468
Carl Shapirob5573532011-07-12 18:22:59 -0700469 return NULL;
470}
471
Elliott Hughes93e74e82011-09-13 11:07:03 -0700472void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700473 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700474}
475
Elliott Hughes01158d72011-09-19 19:47:10 -0700476Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
477 Object* thread = Decode<Object*>(env, java_thread);
478 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
479}
480
Elliott Hughesd369bb72011-09-12 14:41:14 -0700481void Thread::Create(Object* peer, size_t stack_size) {
482 CHECK(peer != NULL);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700483
Elliott Hughesd369bb72011-09-12 14:41:14 -0700484 if (stack_size == 0) {
485 stack_size = Runtime::Current()->GetDefaultStackSize();
486 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700487
Elliott Hughes93e74e82011-09-13 11:07:03 -0700488 Thread* native_thread = new Thread;
489 native_thread->peer_ = peer;
490
491 // Thread.start is synchronized, so we know that vmData is 0,
492 // and know that we're not racing to assign it.
493 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700494
495 pthread_attr_t attr;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700496 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
497 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
498 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
499 CHECK_PTHREAD_CALL(pthread_create, (&native_thread->pthread_, &attr, Thread::CreateCallback, native_thread), "new thread");
500 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
Elliott Hughes93e74e82011-09-13 11:07:03 -0700501
502 // Let the child know when it's safe to start running.
503 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700504}
505
Elliott Hughes93e74e82011-09-13 11:07:03 -0700506void Thread::Attach(const Runtime* runtime) {
507 InitCpu();
508 InitFunctionPointers();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700509
Elliott Hughes93e74e82011-09-13 11:07:03 -0700510 thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700511
Elliott Hughes93e74e82011-09-13 11:07:03 -0700512 tid_ = ::art::GetTid();
513 pthread_ = pthread_self();
Elliott Hughesbe759c62011-09-08 19:38:21 -0700514
Elliott Hughes93e74e82011-09-13 11:07:03 -0700515 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700516
Elliott Hughes8d768a92011-09-14 16:35:25 -0700517 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700518
Elliott Hughes93e74e82011-09-13 11:07:03 -0700519 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700520
Elliott Hughes93e74e82011-09-13 11:07:03 -0700521 runtime->GetThreadList()->Register(this);
522}
523
524Thread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
525 Thread* self = new Thread;
526 self->Attach(runtime);
527
528 self->SetState(Thread::kRunnable);
529
530 SetThreadName(name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700531
532 // If we're the main thread, ClassLinker won't be created until after we're attached,
533 // so that thread needs a two-stage attach. Regular threads don't need this hack.
534 if (self->thin_lock_id_ != ThreadList::kMainId) {
535 self->CreatePeer(name, as_daemon);
536 }
537
538 return self;
539}
540
Elliott Hughesd369bb72011-09-12 14:41:14 -0700541jobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
542 jclass thread_group_class = env->FindClass("java/lang/ThreadGroup");
543 jfieldID fid = env->GetStaticFieldID(thread_group_class, field_name, "Ljava/lang/ThreadGroup;");
544 jobject thread_group = env->GetStaticObjectField(thread_group_class, fid);
545 // This will be null in the compiler (and tests), but never in a running system.
546 //CHECK(thread_group != NULL) << "java.lang.ThreadGroup." << field_name << " not initialized";
547 return thread_group;
548}
549
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700550void Thread::CreatePeer(const char* name, bool as_daemon) {
Elliott Hughes01158d72011-09-19 19:47:10 -0700551 Thread* self = Thread::Current();
552 ScopedThreadStateChange tsc(self, Thread::kNative);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700553
554 JNIEnv* env = jni_env_;
555
Elliott Hughesd369bb72011-09-12 14:41:14 -0700556 const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
557 jobject thread_group = GetWellKnownThreadGroup(env, field_name);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700558 jobject thread_name = env->NewStringUTF(name);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700559 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700560 jboolean thread_is_daemon = as_daemon;
561
562 jclass c = env->FindClass("java/lang/Thread");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700563 jmethodID mid = env->GetMethodID(c, "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700564
Elliott Hughes8daa0922011-09-11 13:46:25 -0700565 jobject peer = env->NewObject(c, mid, thread_group, thread_name, thread_priority, thread_is_daemon);
Elliott Hughes01158d72011-09-19 19:47:10 -0700566 peer_ = DecodeJObject(peer);
567 SetVmData(peer_, self);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700568
569 // Because we mostly run without code available (in the compiler, in tests), we
570 // manually assign the fields the constructor should have set.
571 // TODO: lose this.
Elliott Hughes01158d72011-09-19 19:47:10 -0700572 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
573 gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group));
574 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name));
575 gThread_priority->SetInt(peer_, thread_priority);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700576}
577
Elliott Hughesbe759c62011-09-08 19:38:21 -0700578void Thread::InitStackHwm() {
579 pthread_attr_t attributes;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700580 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_, &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700581
Ian Rogers932746a2011-09-22 18:57:50 -0700582 void* temp_stack_base;
583 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
584 __FUNCTION__);
585 stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700586
Ian Rogers932746a2011-09-22 18:57:50 -0700587 if (stack_size_ <= kStackOverflowReservedBytes) {
588 LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700589 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700590
Ian Rogers932746a2011-09-22 18:57:50 -0700591 // Set stack_end_ to the bottom of the stack saving space of stack overflows
592 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700593
594 // Sanity check.
595 int stack_variable;
596 CHECK_GT(&stack_variable, (void*) stack_end_);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700597
Elliott Hughes8d768a92011-09-14 16:35:25 -0700598 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700599}
600
Elliott Hughesa0957642011-09-02 14:27:33 -0700601void Thread::Dump(std::ostream& os) const {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700602 DumpState(os);
603 DumpStack(os);
Elliott Hughesa0957642011-09-02 14:27:33 -0700604}
605
Elliott Hughesd92bec42011-09-02 17:04:36 -0700606std::string GetSchedulerGroup(pid_t tid) {
607 // /proc/<pid>/group looks like this:
608 // 2:devices:/
609 // 1:cpuacct,cpu:/
610 // We want the third field from the line whose second field contains the "cpu" token.
611 std::string cgroup_file;
612 if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
613 return "";
614 }
615 std::vector<std::string> cgroup_lines;
616 Split(cgroup_file, '\n', cgroup_lines);
617 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
618 std::vector<std::string> cgroup_fields;
619 Split(cgroup_lines[i], ':', cgroup_fields);
620 std::vector<std::string> cgroups;
621 Split(cgroup_fields[1], ',', cgroups);
622 for (size_t i = 0; i < cgroups.size(); ++i) {
623 if (cgroups[i] == "cpu") {
624 return cgroup_fields[2].substr(1); // Skip the leading slash.
625 }
626 }
627 }
628 return "";
629}
630
631void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700632 std::string thread_name("<native thread without managed peer>");
633 std::string group_name;
634 int priority;
635 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700636
Elliott Hughesd369bb72011-09-12 14:41:14 -0700637 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700638 String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700639 thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughes038a8062011-09-18 14:12:41 -0700640 priority = gThread_priority->GetInt(peer_);
641 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700642
Elliott Hughes038a8062011-09-18 14:12:41 -0700643 Object* thread_group = gThread_group->GetObject(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700644 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700645 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700646 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
647 }
648 } else {
649 // 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 -0700650 std::string stats;
651 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
652 size_t start = stats.find('(') + 1;
653 size_t end = stats.find(')') - start;
654 thread_name = stats.substr(start, end);
655 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700656 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700657 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700658
659 int policy;
660 sched_param sp;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700661 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_, &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700662
663 std::string scheduler_group(GetSchedulerGroup(GetTid()));
664 if (scheduler_group.empty()) {
665 scheduler_group = "default";
666 }
667
Elliott Hughesd92bec42011-09-02 17:04:36 -0700668 os << '"' << thread_name << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700669 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700670 os << " daemon";
671 }
672 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700673 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700674 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700675
Elliott Hughesd92bec42011-09-02 17:04:36 -0700676 int debug_suspend_count = 0; // TODO
Elliott Hughesd92bec42011-09-02 17:04:36 -0700677 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700678 << " sCount=" << suspend_count_
Elliott Hughesd92bec42011-09-02 17:04:36 -0700679 << " dsCount=" << debug_suspend_count
Elliott Hughesdcc24742011-09-07 14:02:44 -0700680 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700681 << " self=" << reinterpret_cast<const void*>(this) << "\n";
682 os << " | sysTid=" << GetTid()
683 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
684 << " sched=" << policy << "/" << sp.sched_priority
685 << " cgrp=" << scheduler_group
686 << " handle=" << GetImpl() << "\n";
687
688 // Grab the scheduler stats for this thread.
689 std::string scheduler_stats;
690 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
691 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
692 } else {
693 scheduler_stats = "0 0 0";
694 }
695
696 int utime = 0;
697 int stime = 0;
698 int task_cpu = 0;
699 std::string stats;
700 if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
701 // Skip the command, which may contain spaces.
702 stats = stats.substr(stats.find(')') + 2);
703 // Extract the three fields we care about.
704 std::vector<std::string> fields;
705 Split(stats, ' ', fields);
706 utime = strtoull(fields[11].c_str(), NULL, 10);
707 stime = strtoull(fields[12].c_str(), NULL, 10);
708 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
709 }
710
711 os << " | schedstat=( " << scheduler_stats << " )"
712 << " utm=" << utime
713 << " stm=" << stime
714 << " core=" << task_cpu
715 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
716}
717
Elliott Hughesd369bb72011-09-12 14:41:14 -0700718struct StackDumpVisitor : public Thread::StackVisitor {
719 StackDumpVisitor(std::ostream& os) : os(os) {
720 }
721
Ian Rogersbdb03912011-09-14 00:55:44 -0700722 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700723 }
724
Ian Rogersbdb03912011-09-14 00:55:44 -0700725 void VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700726 if (!frame.HasMethod()) {
727 return;
728 }
Elliott Hughesd369bb72011-09-12 14:41:14 -0700729 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
730
731 Method* m = frame.GetMethod();
732 Class* c = m->GetDeclaringClass();
733 const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
734
735 os << " at " << PrettyMethod(m, false);
736 if (m->IsNative()) {
737 os << "(Native method)";
738 } else {
Ian Rogersbdb03912011-09-14 00:55:44 -0700739 int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700740 os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
741 }
742 os << "\n";
743 }
744
745 std::ostream& os;
746};
747
Elliott Hughesd92bec42011-09-02 17:04:36 -0700748void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700749 StackDumpVisitor dumper(os);
750 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700751}
752
Elliott Hughes8d768a92011-09-14 16:35:25 -0700753Thread::State Thread::SetState(Thread::State new_state) {
754 Thread::State old_state = state_;
755 if (old_state == new_state) {
756 return old_state;
757 }
758
759 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
760 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
761
762 if (new_state == Thread::kRunnable) {
763 /*
764 * Change our status to Thread::kRunnable. The transition requires
765 * that we check for pending suspension, because the VM considers
766 * us to be "asleep" in all other states, and another thread could
767 * be performing a GC now.
768 *
769 * The order of operations is very significant here. One way to
770 * do this wrong is:
771 *
772 * GCing thread Our thread (in kNative)
773 * ------------ ----------------------
774 * check suspend count (== 0)
775 * SuspendAllThreads()
776 * grab suspend-count lock
777 * increment all suspend counts
778 * release suspend-count lock
779 * check thread state (== kNative)
780 * all are suspended, begin GC
781 * set state to kRunnable
782 * (continue executing)
783 *
784 * We can correct this by grabbing the suspend-count lock and
785 * performing both of our operations (check suspend count, set
786 * state) while holding it, now we need to grab a mutex on every
787 * transition to kRunnable.
788 *
789 * What we do instead is change the order of operations so that
790 * the transition to kRunnable happens first. If we then detect
791 * that the suspend count is nonzero, we switch to kSuspended.
792 *
793 * Appropriate compiler and memory barriers are required to ensure
794 * that the operations are observed in the expected order.
795 *
796 * This does create a small window of opportunity where a GC in
797 * progress could observe what appears to be a running thread (if
798 * it happens to look between when we set to kRunnable and when we
799 * switch to kSuspended). At worst this only affects assertions
800 * and thread logging. (We could work around it with some sort
801 * of intermediate "pre-running" state that is generally treated
802 * as equivalent to running, but that doesn't seem worthwhile.)
803 *
804 * We can also solve this by combining the "status" and "suspend
805 * count" fields into a single 32-bit value. This trades the
806 * store/load barrier on transition to kRunnable for an atomic RMW
807 * op on all transitions and all suspend count updates (also, all
808 * accesses to status or the thread count require bit-fiddling).
809 * It also eliminates the brief transition through kRunnable when
810 * the thread is supposed to be suspended. This is possibly faster
811 * on SMP and slightly more correct, but less convenient.
812 */
813 android_atomic_acquire_store(new_state, addr);
814 if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
815 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
816 }
817 } else {
818 /*
819 * Not changing to Thread::kRunnable. No additional work required.
820 *
821 * We use a releasing store to ensure that, if we were runnable,
822 * any updates we previously made to objects on the managed heap
823 * will be observed before the state change.
824 */
825 android_atomic_release_store(new_state, addr);
826 }
827
828 return old_state;
829}
830
831void Thread::WaitUntilSuspended() {
832 // TODO: dalvik dropped the waiting thread's priority after a while.
833 // TODO: dalvik timed out and aborted.
834 useconds_t delay = 0;
835 while (GetState() == Thread::kRunnable) {
836 useconds_t new_delay = delay * 2;
837 CHECK_GE(new_delay, delay);
838 delay = new_delay;
839 if (delay == 0) {
840 sched_yield();
841 delay = 10000;
842 } else {
843 usleep(delay);
844 }
845 }
846}
847
Elliott Hughesbe759c62011-09-08 19:38:21 -0700848void Thread::ThreadExitCallback(void* arg) {
849 Thread* self = reinterpret_cast<Thread*>(arg);
850 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700851}
852
Elliott Hughesbe759c62011-09-08 19:38:21 -0700853void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700854 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700855 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700856
857 // Double-check the TLS slot allocation.
858 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700859 LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700860 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700861}
Carl Shapirob5573532011-07-12 18:22:59 -0700862
Elliott Hughes038a8062011-09-18 14:12:41 -0700863void Thread::FinishStartup() {
Elliott Hughes038a8062011-09-18 14:12:41 -0700864 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
865 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
866 Class* boolean_class = class_linker->FindPrimitiveClass('Z');
867 Class* int_class = class_linker->FindPrimitiveClass('I');
868 Class* String_class = class_linker->FindSystemClass("Ljava/lang/String;");
869 Class* Thread_class = class_linker->FindSystemClass("Ljava/lang/Thread;");
870 Class* ThreadGroup_class = class_linker->FindSystemClass("Ljava/lang/ThreadGroup;");
871 Class* ThreadLock_class = class_linker->FindSystemClass("Ljava/lang/ThreadLock;");
Elliott Hughes29f27422011-09-18 16:02:18 -0700872 Class* UncaughtExceptionHandler_class = class_linker->FindSystemClass("Ljava/lang/Thread$UncaughtExceptionHandler;");
873 gThrowable = class_linker->FindSystemClass("Ljava/lang/Throwable;");
Elliott Hughes038a8062011-09-18 14:12:41 -0700874 gThread_daemon = Thread_class->FindDeclaredInstanceField("daemon", boolean_class);
875 gThread_group = Thread_class->FindDeclaredInstanceField("group", ThreadGroup_class);
876 gThread_lock = Thread_class->FindDeclaredInstanceField("lock", ThreadLock_class);
877 gThread_name = Thread_class->FindDeclaredInstanceField("name", String_class);
878 gThread_priority = Thread_class->FindDeclaredInstanceField("priority", int_class);
879 gThread_run = Thread_class->FindVirtualMethod("run", "()V");
Elliott Hughes29f27422011-09-18 16:02:18 -0700880 gThread_uncaughtHandler = Thread_class->FindDeclaredInstanceField("uncaughtHandler", UncaughtExceptionHandler_class);
Elliott Hughes038a8062011-09-18 14:12:41 -0700881 gThread_vmData = Thread_class->FindDeclaredInstanceField("vmData", int_class);
882 gThreadGroup_name = ThreadGroup_class->FindDeclaredInstanceField("name", String_class);
Elliott Hughes29f27422011-09-18 16:02:18 -0700883 gThreadGroup_removeThread = ThreadGroup_class->FindVirtualMethod("removeThread", "(Ljava/lang/Thread;)V");
884 gUncaughtExceptionHandler_uncaughtException =
885 UncaughtExceptionHandler_class->FindVirtualMethod("uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700886
887 // Finish attaching the main thread.
888 Thread::Current()->CreatePeer("main", false);
Carl Shapirob5573532011-07-12 18:22:59 -0700889}
890
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700891void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700892 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700893}
894
Elliott Hughesdcc24742011-09-07 14:02:44 -0700895Thread::Thread()
Elliott Hughes02b48d12011-09-07 17:15:51 -0700896 : peer_(NULL),
Elliott Hughes85d15452011-09-16 17:33:01 -0700897 wait_mutex_(new Mutex("Thread wait mutex")),
898 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700899 wait_monitor_(NULL),
900 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700901 wait_next_(NULL),
902 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700903 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700904 top_of_managed_stack_(),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700905 top_of_managed_stack_pc_(0),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700906 native_to_managed_record_(NULL),
907 top_sirt_(NULL),
908 jni_env_(NULL),
Elliott Hughes93e74e82011-09-13 11:07:03 -0700909 state_(Thread::kUnknown),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700910 self_(NULL),
911 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700912 exception_(NULL),
913 suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700914 class_loader_override_(NULL),
915 long_jump_context_(NULL) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700916}
917
Elliott Hughes02b48d12011-09-07 17:15:51 -0700918void MonitorExitVisitor(const Object* object, void*) {
919 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughes5f791332011-09-15 17:45:30 -0700920 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700921}
922
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700923Thread::~Thread() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700924 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700925 if (jni_env_ != NULL) {
926 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
927 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700928
Elliott Hughes93e74e82011-09-13 11:07:03 -0700929 if (peer_ != NULL) {
Elliott Hughes29f27422011-09-18 16:02:18 -0700930 Object* group = gThread_group->GetObject(peer_);
931
932 // Handle any pending exception.
933 if (IsExceptionPending()) {
934 // Get and clear the exception.
935 Object* exception = GetException();
936 ClearException();
937
938 // If the thread has its own handler, use that.
939 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
940 if (handler == NULL) {
941 // Otherwise use the thread group's default handler.
942 handler = group;
943 }
944
945 // Call the handler.
946 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
947 Object* args[2];
948 args[0] = peer_;
949 args[1] = exception;
950 m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
951
952 // If the handler threw, clear that exception too.
953 ClearException();
954 }
955
956 // this.group.removeThread(this);
Elliott Hughes081be7f2011-09-18 16:50:26 -0700957 // group can be null if we're in the compiler or a test.
958 if (group != NULL) {
959 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
960 Object* args = peer_;
961 m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
962 }
Elliott Hughes29f27422011-09-18 16:02:18 -0700963
964 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700965 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700966
Elliott Hughes29f27422011-09-18 16:02:18 -0700967 // TODO: say "bye" to the debugger.
968 //if (gDvm.debuggerConnected) {
969 // dvmDbgPostThreadDeath(self);
970 //}
Elliott Hughes02b48d12011-09-07 17:15:51 -0700971
Elliott Hughes29f27422011-09-18 16:02:18 -0700972 // Thread.join() is implemented as an Object.wait() on the Thread.lock
973 // object. Signal anyone who is waiting.
Elliott Hughes5f791332011-09-15 17:45:30 -0700974 Thread* self = Thread::Current();
Elliott Hughes038a8062011-09-18 14:12:41 -0700975 Object* lock = gThread_lock->GetObject(peer_);
976 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700977 if (lock != NULL) {
978 lock->MonitorEnter(self);
979 lock->NotifyAll();
980 lock->MonitorExit(self);
981 }
982 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700983
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700984 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -0700985 jni_env_ = NULL;
986
987 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -0700988
989 delete wait_cond_;
990 delete wait_mutex_;
991
992 delete long_jump_context_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700993}
994
Ian Rogers408f79a2011-08-23 18:22:33 -0700995size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700996 size_t count = 0;
Ian Rogers408f79a2011-08-23 18:22:33 -0700997 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -0700998 count += cur->NumberOfReferences();
999 }
1000 return count;
1001}
1002
Ian Rogers408f79a2011-08-23 18:22:33 -07001003bool Thread::SirtContains(jobject obj) {
1004 Object** sirt_entry = reinterpret_cast<Object**>(obj);
1005 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->Link()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001006 size_t num_refs = cur->NumberOfReferences();
Ian Rogers408f79a2011-08-23 18:22:33 -07001007 // A SIRT should always have a jobject/jclass as a native method is passed
1008 // in a this pointer or a class
1009 DCHECK_GT(num_refs, 0u);
Shih-wei Liao2f0ce9d2011-09-01 02:07:58 -07001010 if ((&cur->References()[0] <= sirt_entry) &&
1011 (sirt_entry <= (&cur->References()[num_refs - 1]))) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001012 return true;
1013 }
1014 }
1015 return false;
1016}
1017
Ian Rogers67375ac2011-09-14 00:55:44 -07001018void Thread::PopSirt() {
1019 CHECK(top_sirt_ != NULL);
1020 top_sirt_ = top_sirt_->Link();
1021}
1022
Ian Rogers408f79a2011-08-23 18:22:33 -07001023Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001024 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001025 if (obj == NULL) {
1026 return NULL;
1027 }
1028 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1029 IndirectRefKind kind = GetIndirectRefKind(ref);
1030 Object* result;
1031 switch (kind) {
1032 case kLocal:
1033 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001034 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001035 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001036 break;
1037 }
1038 case kGlobal:
1039 {
1040 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1041 IndirectReferenceTable& globals = vm->globals;
1042 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001043 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001044 break;
1045 }
1046 case kWeakGlobal:
1047 {
1048 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1049 IndirectReferenceTable& weak_globals = vm->weak_globals;
1050 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001051 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001052 if (result == kClearedJniWeakGlobal) {
1053 // This is a special case where it's okay to return NULL.
1054 return NULL;
1055 }
1056 break;
1057 }
1058 case kSirtOrInvalid:
1059 default:
1060 // TODO: make stack indirect reference table lookup more efficient
1061 // Check if this is a local reference in the SIRT
1062 if (SirtContains(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001063 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001064 } else if (jni_env_->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001065 // Assume an invalid local reference is actually a direct pointer.
1066 result = reinterpret_cast<Object*>(obj);
1067 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001068 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001069 }
1070 }
1071
1072 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001073 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1074 JniAbort(NULL);
1075 } else {
1076 if (result != kInvalidIndirectRefObject) {
1077 Heap::VerifyObject(result);
1078 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001079 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001080 return result;
1081}
1082
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001083class CountStackDepthVisitor : public Thread::StackVisitor {
1084 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001085 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001086
Elliott Hughes29f27422011-09-18 16:02:18 -07001087 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1088 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001089 // Note we also skip the frame if it doesn't have a method (namely the callee
1090 // save frame)
Brian Carlstrom25c33252011-09-18 15:58:35 -07001091 DCHECK(gThrowable != NULL);
Ian Rogers90865722011-09-19 11:11:44 -07001092 if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001093 skipping_ = false;
1094 }
1095 if (!skipping_) {
1096 ++depth_;
1097 } else {
1098 ++skip_depth_;
1099 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001100 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001101
1102 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001103 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001104 }
1105
Elliott Hughes29f27422011-09-18 16:02:18 -07001106 int GetSkipDepth() const {
1107 return skip_depth_;
1108 }
1109
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001110 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001111 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001112 uint32_t skip_depth_;
1113 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001114};
1115
Ian Rogersaaa20802011-09-11 21:47:37 -07001116class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001117 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001118 explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
1119 : skip_depth_(skip_depth), count_(0) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001120 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001121 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Ian Rogersaaa20802011-09-11 21:47:37 -07001122 // Register a local reference as IntArray::Alloc may trigger GC
1123 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1124 pc_trace_ = IntArray::Alloc(depth);
1125#ifdef MOVING_GARBAGE_COLLECTOR
1126 // Re-read after potential GC
1127 method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1128#endif
1129 // Save PC trace in last element of method trace, also places it into the
1130 // object graph.
1131 method_trace_->Set(depth, pc_trace_);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001132 }
1133
Ian Rogersaaa20802011-09-11 21:47:37 -07001134 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001135
Ian Rogersbdb03912011-09-14 00:55:44 -07001136 virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001137 if (skip_depth_ > 0) {
1138 skip_depth_--;
1139 return;
1140 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001141 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001142 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001143 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001144 }
1145
Ian Rogersaaa20802011-09-11 21:47:37 -07001146 jobject GetInternalStackTrace() const {
1147 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001148 }
1149
1150 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001151 // How many more frames to skip.
1152 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001153 // Current position down stack trace
1154 uint32_t count_;
1155 // Array of return PC values
1156 IntArray* pc_trace_;
1157 // An array of the methods on the stack, the last entry is a reference to the
1158 // PC trace
1159 ObjectArray<Object>* method_trace_;
1160 // Local indirect reference table entry for method trace
1161 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001162};
1163
Ian Rogersaaa20802011-09-11 21:47:37 -07001164void Thread::WalkStack(StackVisitor* visitor) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001165 Frame frame = GetTopOfStack();
Ian Rogersbdb03912011-09-14 00:55:44 -07001166 uintptr_t pc = top_of_managed_stack_pc_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001167 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1168 // CHECK(native_to_managed_record_ != NULL);
1169 NativeToManagedRecord* record = native_to_managed_record_;
1170
Ian Rogersbdb03912011-09-14 00:55:44 -07001171 while (frame.GetSP() != 0) {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001172 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001173 DCHECK(frame.GetMethod()->IsWithinCode(pc));
1174 visitor->VisitFrame(frame, pc);
1175 pc = frame.GetReturnPC();
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001176 }
1177 if (record == NULL) {
1178 break;
1179 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001180 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001181 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Ian Rogersbdb03912011-09-14 00:55:44 -07001182 pc = record->last_top_of_managed_stack_pc_;
1183 record = record->link_;
1184 }
1185}
1186
Ian Rogers67375ac2011-09-14 00:55:44 -07001187void Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
Ian Rogersbdb03912011-09-14 00:55:44 -07001188 Frame frame = GetTopOfStack();
1189 uintptr_t pc = top_of_managed_stack_pc_;
1190
1191 if (frame.GetSP() != 0) {
1192 for ( ; frame.GetMethod() != 0; frame.Next()) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001193 DCHECK(frame.GetMethod()->IsWithinCode(pc));
Ian Rogersbdb03912011-09-14 00:55:44 -07001194 visitor->VisitFrame(frame, pc);
1195 pc = frame.GetReturnPC();
1196 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001197 if (include_upcall) {
1198 visitor->VisitFrame(frame, pc);
1199 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001200 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001201}
1202
Elliott Hughes01158d72011-09-19 19:47:10 -07001203jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001204 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001205 CountStackDepthVisitor count_visitor;
1206 WalkStack(&count_visitor);
1207 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001208 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001209
Ian Rogersaaa20802011-09-11 21:47:37 -07001210 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001211 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001212
1213 // Build internal stack trace
Elliott Hughes29f27422011-09-18 16:02:18 -07001214 BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001215 WalkStack(&build_trace_visitor);
Shih-wei Liao44175362011-08-28 16:59:17 -07001216
Ian Rogersaaa20802011-09-11 21:47:37 -07001217 return build_trace_visitor.GetInternalStackTrace();
1218}
1219
Elliott Hughes01158d72011-09-19 19:47:10 -07001220jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1221 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001222 // Transition into runnable state to work on Object*/Array*
1223 ScopedJniThreadState ts(env);
1224
1225 // Decode the internal stack trace into the depth, method trace and PC trace
1226 ObjectArray<Object>* method_trace =
1227 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1228 int32_t depth = method_trace->GetLength()-1;
1229 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1230
1231 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1232
Elliott Hughes01158d72011-09-19 19:47:10 -07001233 jobjectArray result;
1234 ObjectArray<StackTraceElement>* java_traces;
1235 if (output_array != NULL) {
1236 // Reuse the array we were given.
1237 result = output_array;
1238 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1239 output_array));
1240 // ...adjusting the number of frames we'll write to not exceed the array length.
1241 depth = std::min(depth, java_traces->GetLength());
1242 } else {
1243 // Create java_trace array and place in local reference table
1244 java_traces = class_linker->AllocStackTraceElementArray(depth);
1245 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1246 }
1247
1248 if (stack_depth != NULL) {
1249 *stack_depth = depth;
1250 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001251
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001252 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001253 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1254 Method* method = down_cast<Method*>(method_trace->Get(i));
1255 uint32_t native_pc = pc_trace->Get(i);
1256 Class* klass = method->GetDeclaringClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001257 const DexFile& dex_file = class_linker->FindDexFile(klass->GetDexCache());
Elliott Hughes38933572011-09-16 12:29:03 -07001258 std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001259
Ian Rogersaaa20802011-09-11 21:47:37 -07001260 // Allocate element, potentially triggering GC
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001261 StackTraceElement* obj =
Elliott Hughes38933572011-09-16 12:29:03 -07001262 StackTraceElement::Alloc(String::AllocFromModifiedUtf8(class_name.c_str()),
Shih-wei Liao44175362011-08-28 16:59:17 -07001263 method->GetName(),
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001264 klass->GetSourceFile(),
Shih-wei Liao44175362011-08-28 16:59:17 -07001265 dex_file.GetLineNumFromPC(method,
Ian Rogersaaa20802011-09-11 21:47:37 -07001266 method->ToDexPC(native_pc)));
1267#ifdef MOVING_GARBAGE_COLLECTOR
1268 // Re-read after potential GC
1269 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1270 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1271 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1272#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001273 java_traces->Set(i, obj);
1274 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001275 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001276}
1277
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001278void Thread::ThrowNewException(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001279 va_list args;
1280 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001281 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001282 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001283}
1284
1285void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1286 std::string msg;
1287 StringAppendV(&msg, fmt, ap);
Elliott Hughes37f7a402011-08-22 18:56:01 -07001288
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001289 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001290 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001291 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001292 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001293 descriptor.erase(descriptor.length() - 1);
1294
1295 JNIEnv* env = GetJniEnv();
1296 jclass exception_class = env->FindClass(descriptor.c_str());
1297 CHECK(exception_class != NULL) << "descriptor=\"" << descriptor << "\"";
1298 int rc = env->ThrowNew(exception_class, msg.c_str());
1299 CHECK_EQ(rc, JNI_OK);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001300}
1301
Elliott Hughes79082e32011-08-25 12:07:32 -07001302void Thread::ThrowOutOfMemoryError() {
1303 UNIMPLEMENTED(FATAL);
1304}
1305
Ian Rogersbdb03912011-09-14 00:55:44 -07001306class CatchBlockStackVisitor : public Thread::StackVisitor {
1307 public:
1308 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Ian Rogers67375ac2011-09-14 00:55:44 -07001309 : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
1310#ifndef NDEBUG
1311 handler_pc_ = 0xEBADC0DE;
1312 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1313#endif
1314 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001315
Ian Rogersbdb03912011-09-14 00:55:44 -07001316 virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1317 if (!found_) {
Ian Rogersbdb03912011-09-14 00:55:44 -07001318 Method* method = fr.GetMethod();
Ian Rogers67375ac2011-09-14 00:55:44 -07001319 if (method == NULL) {
1320 // This is the upcall, we remember the frame and last_pc so that we may
1321 // long jump to them
1322 handler_pc_ = pc;
1323 handler_frame_ = fr;
1324 return;
Ian Rogersbdb03912011-09-14 00:55:44 -07001325 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001326 uint32_t dex_pc = DexFile::kDexNoIndex;
Ian Rogers90865722011-09-19 11:11:44 -07001327 if (method->IsPhony()) {
1328 // ignore callee save method
1329 } else if (method->IsNative()) {
1330 native_method_count_++;
1331 } else {
1332 // Move the PC back 2 bytes as a call will frequently terminate the
1333 // decoding of a particular instruction and we want to make sure we
1334 // get the Dex PC of the instruction with the call and not the
1335 // instruction following.
1336 pc -= 2;
1337 dex_pc = method->ToDexPC(pc);
Ian Rogers67375ac2011-09-14 00:55:44 -07001338 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001339 if (dex_pc != DexFile::kDexNoIndex) {
1340 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1341 if (found_dex_pc != DexFile::kDexNoIndex) {
1342 found_ = true;
Ian Rogers67375ac2011-09-14 00:55:44 -07001343 handler_pc_ = method->ToNativePC(found_dex_pc);
1344 handler_frame_ = fr;
Ian Rogersbdb03912011-09-14 00:55:44 -07001345 }
1346 }
1347 if (!found_) {
1348 // Caller may be handler, fill in callee saves in context
1349 long_jump_context_->FillCalleeSaves(fr);
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001350 }
1351 }
1352 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001353
1354 // Did we find a catch block yet?
1355 bool found_;
1356 // The type of the exception catch block to find
1357 Class* to_find_;
1358 // Frame with found handler or last frame if no handler found
1359 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001360 // PC to branch to for the handler
1361 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001362 // Context that will be the target of the long jump
1363 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001364 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1365 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001366};
1367
Ian Rogersff1ed472011-09-20 13:46:24 -07001368void Thread::DeliverException() {
1369 Throwable *exception = GetException(); // Set exception on thread
1370 CHECK(exception != NULL);
Ian Rogersbdb03912011-09-14 00:55:44 -07001371
1372 Context* long_jump_context = GetLongJumpContext();
1373 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Ian Rogers67375ac2011-09-14 00:55:44 -07001374 WalkStackUntilUpCall(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001375
Ian Rogers67375ac2011-09-14 00:55:44 -07001376 // Pop any SIRT
1377 if (catch_finder.native_method_count_ == 1) {
1378 PopSirt();
Ian Rogersbdb03912011-09-14 00:55:44 -07001379 } else {
Ian Rogersad42e132011-09-17 20:23:33 -07001380 // We only expect the stack crawl to have passed 1 native method as it's terminated
1381 // by an up call
Ian Rogers67375ac2011-09-14 00:55:44 -07001382 DCHECK_EQ(catch_finder.native_method_count_, 0u);
Ian Rogersbdb03912011-09-14 00:55:44 -07001383 }
Ian Rogers67375ac2011-09-14 00:55:44 -07001384 long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
1385 long_jump_context->SetPC(catch_finder.handler_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001386 long_jump_context->DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001387}
1388
Ian Rogersbdb03912011-09-14 00:55:44 -07001389Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001390 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001391 if (result == NULL) {
1392 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001393 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001394 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001395 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001396}
1397
Elliott Hughes5f791332011-09-15 17:45:30 -07001398bool Thread::HoldsLock(Object* object) {
1399 if (object == NULL) {
1400 return false;
1401 }
1402 return object->GetLockOwner() == thin_lock_id_;
1403}
1404
Elliott Hughes038a8062011-09-18 14:12:41 -07001405bool Thread::IsDaemon() {
1406 return gThread_daemon->GetBoolean(peer_);
1407}
1408
Elliott Hughes410c0c82011-09-01 17:58:25 -07001409void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001410 if (exception_ != NULL) {
1411 visitor(exception_, arg);
1412 }
1413 if (peer_ != NULL) {
1414 visitor(peer_, arg);
1415 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001416 jni_env_->locals.VisitRoots(visitor, arg);
1417 jni_env_->monitors.VisitRoots(visitor, arg);
1418 // visitThreadStack(visitor, thread, arg);
1419 UNIMPLEMENTED(WARNING) << "some per-Thread roots not visited";
1420}
1421
Ian Rogersb033c752011-07-20 12:22:35 -07001422static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001423 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001424 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001425 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001426 "Blocked",
1427 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001428 "Initializing",
1429 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001430 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001431 "VmWait",
1432 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001433};
1434std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001435 int int_state = static_cast<int>(state);
1436 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1437 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001438 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001439 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001440 }
1441 return os;
1442}
1443
Elliott Hughes330304d2011-08-12 14:28:05 -07001444std::ostream& operator<<(std::ostream& os, const Thread& thread) {
1445 os << "Thread[" << &thread
Elliott Hughese27955c2011-08-26 15:21:24 -07001446 << ",pthread_t=" << thread.GetImpl()
1447 << ",tid=" << thread.GetTid()
Elliott Hughesdcc24742011-09-07 14:02:44 -07001448 << ",id=" << thread.GetThinLockId()
Elliott Hughes8daa0922011-09-11 13:46:25 -07001449 << ",state=" << thread.GetState()
1450 << ",peer=" << thread.GetPeer()
1451 << "]";
Elliott Hughes330304d2011-08-12 14:28:05 -07001452 return os;
1453}
1454
Elliott Hughes8daa0922011-09-11 13:46:25 -07001455} // namespace art