blob: 8bd7bc20a4ff191ae9120262b33f025caa790938 [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>
Brian Carlstromdbf05b72011-12-15 00:55:24 -080022#include <sys/resource.h>
23#include <sys/time.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070024
Carl Shapirob5573532011-07-12 18:22:59 -070025#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070026#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070027#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070028#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070029#include <list>
Carl Shapirob5573532011-07-12 18:22:59 -070030
Elliott Hughes872d4ec2011-10-21 17:07:15 -070031#include "debugger.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070032#include "class_linker.h"
Brian Carlstromdf143242011-10-10 18:05:34 -070033#include "class_loader.h"
Ian Rogersbdb03912011-09-14 00:55:44 -070034#include "context.h"
Ian Rogersd6b1f612011-09-27 13:38:14 -070035#include "dex_verifier.h"
Ian Rogers408f79a2011-08-23 18:22:33 -070036#include "heap.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070037#include "jni_internal.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070038#include "monitor.h"
Elliott Hughesa5b897e2011-08-16 11:33:06 -070039#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080040#include "object_utils.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -050041#include "reflection.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070042#include "runtime.h"
buzbee54330722011-08-23 16:46:55 -070043#include "runtime_support.h"
Elliott Hughes726079d2011-10-07 18:43:44 -070044#include "ScopedLocalRef.h"
Ian Rogersaaa20802011-09-11 21:47:37 -070045#include "scoped_jni_thread_state.h"
Logan Chienf7ad17e2012-03-15 03:10:03 +080046#include "shadow_frame.h"
Ian Rogers30fab402012-01-23 15:43:46 -080047#include "space.h"
Elliott Hughes68e76522011-10-05 13:22:16 -070048#include "stack.h"
49#include "stack_indirect_reference_table.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070050#include "thread_list.h"
Elliott Hughesa0957642011-09-02 14:27:33 -070051#include "utils.h"
Carl Shapirob5573532011-07-12 18:22:59 -070052
53namespace art {
54
55pthread_key_t Thread::pthread_key_self_;
56
Elliott Hughes462c9442012-03-23 18:47:50 -070057static Class* gThreadGroup = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -070058static Class* gThreadLock = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070059static Field* gThread_daemon = NULL;
60static Field* gThread_group = NULL;
61static Field* gThread_lock = NULL;
62static Field* gThread_name = NULL;
63static Field* gThread_priority = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070064static Field* gThread_uncaughtHandler = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070065static Field* gThread_vmData = NULL;
Elliott Hughes462c9442012-03-23 18:47:50 -070066static Field* gThreadGroup_mMain = NULL;
67static Field* gThreadGroup_mSystem = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070068static Field* gThreadGroup_name = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -070069static Field* gThreadLock_thread = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070070static Method* gThread_run = NULL;
Elliott Hughes29f27422011-09-18 16:02:18 -070071static Method* gThreadGroup_removeThread = NULL;
72static Method* gUncaughtExceptionHandler_uncaughtException = NULL;
Elliott Hughes038a8062011-09-18 14:12:41 -070073
Ian Rogers5d76c432011-10-31 21:42:49 -070074void Thread::InitCardTable() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080075 card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -070076}
77
buzbee3ea4ec52011-08-22 17:37:19 -070078void Thread::InitFunctionPointers() {
Bill Buzbee11f9d212012-03-03 20:03:18 -080079#if defined(__mips)
80 pShlLong = art_shl_long;
81 pShrLong = art_shr_long;
82 pUshrLong = art_ushr_long;
83 pI2f = __floatsisf;
84 pF2iz = __fixsfi;
85 pD2f = __truncdfsf2;
86 pF2d = __extendsfdfs;
87 pD2iz = __fixdfsi;
88 pL2f = __floatdisf;
89 pL2d = __floatdidf;
90 pFadd = __addsf3;
91 pFsub = __subsf3;
92 pFdiv = divsf3;
93 pFmul = __mulsf3;
94 pFmodf = fmodf;
95 pDadd = __adddf3;
96 pDsub = __subdf3;
97 pDdiv = __divdf3;
98 pDmul = muldf3;
99 pFmod = fmod;
Elliott Hughes0ece7b92012-03-09 18:14:40 -0800100 pCmpgFloat = CmpgFloat;
101 pCmplFloat = CmplFloat;
102 pCmpgDouble = CmpgDouble;
103 pCmplDouble = CmplDouble;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700104#elif defined(__arm__)
buzbeefc9e6fa2012-03-23 15:14:29 -0700105 pMemcmp16 = __memcmp16;
106 pIndexOf = art_indexof;
107 pStringCompareTo = art_string_compareto;
buzbee54330722011-08-23 16:46:55 -0700108 pShlLong = art_shl_long;
109 pShrLong = art_shr_long;
110 pUshrLong = art_ushr_long;
buzbee7b1b86d2011-08-26 18:59:10 -0700111 pIdiv = __aeabi_idiv;
112 pIdivmod = __aeabi_idivmod;
113 pI2f = __aeabi_i2f;
114 pF2iz = __aeabi_f2iz;
115 pD2f = __aeabi_d2f;
116 pF2d = __aeabi_f2d;
117 pD2iz = __aeabi_d2iz;
118 pL2f = __aeabi_l2f;
119 pL2d = __aeabi_l2d;
120 pFadd = __aeabi_fadd;
121 pFsub = __aeabi_fsub;
122 pFdiv = __aeabi_fdiv;
123 pFmul = __aeabi_fmul;
124 pFmodf = fmodf;
125 pDadd = __aeabi_dadd;
126 pDsub = __aeabi_dsub;
127 pDdiv = __aeabi_ddiv;
128 pDmul = __aeabi_dmul;
129 pFmod = fmod;
Ian Rogersc6f3bb82012-03-21 20:40:33 -0700130 pLadd = NULL;
131 pLsub = NULL;
132 pLand = NULL;
133 pLor = NULL;
134 pLxor = NULL;
buzbee7b1b86d2011-08-26 18:59:10 -0700135 pLdivmod = __aeabi_ldivmod;
buzbee439c4fa2011-08-27 15:59:07 -0700136 pLmul = __aeabi_lmul;
Elliott Hughesb408de72011-10-04 14:35:05 -0700137 pAllocArrayFromCode = art_alloc_array_from_code;
Ian Rogers0eb7d7e2012-01-31 21:12:32 -0800138 pAllocArrayFromCodeWithAccessCheck = art_alloc_array_from_code_with_access_check;
Brian Carlstrom6fd03fb2011-10-17 16:11:00 -0700139 pAllocObjectFromCode = art_alloc_object_from_code;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700140 pAllocObjectFromCodeWithAccessCheck = art_alloc_object_from_code_with_access_check;
Ian Rogerse51a5112011-09-23 14:16:35 -0700141 pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
Elliott Hughesb408de72011-10-04 14:35:05 -0700142 pCheckAndAllocArrayFromCode = art_check_and_alloc_array_from_code;
Ian Rogers0eb7d7e2012-01-31 21:12:32 -0800143 pCheckAndAllocArrayFromCodeWithAccessCheck = art_check_and_alloc_array_from_code_with_access_check;
Ian Rogersff1ed472011-09-20 13:46:24 -0700144 pCheckCastFromCode = art_check_cast_from_code;
Ian Rogers1bddec32012-02-04 12:27:34 -0800145 pGet32Instance = art_get32_instance_from_code;
146 pGet64Instance = art_get64_instance_from_code;
147 pGetObjInstance = art_get_obj_instance_from_code;
Ian Rogersce9eca62011-10-07 17:11:03 -0700148 pGet32Static = art_get32_static_from_code;
149 pGet64Static = art_get64_static_from_code;
150 pGetObjStatic = art_get_obj_static_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700151 pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
Ian Rogerscbba6ac2011-09-22 16:28:37 -0700152 pInitializeStaticStorage = art_initialize_static_storage_from_code;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700153 pInitializeTypeFromCode = art_initialize_type_from_code;
Ian Rogersb093c6b2011-10-31 16:19:55 -0700154 pInitializeTypeAndVerifyAccessFromCode = art_initialize_type_and_verify_access_from_code;
Ian Rogersc8b306f2012-02-17 21:34:44 -0800155 pInvokeDirectTrampolineWithAccessCheck = art_invoke_direct_trampoline_with_access_check;
buzbee4a3164f2011-09-03 11:25:10 -0700156 pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800157 pInvokeInterfaceTrampolineWithAccessCheck = art_invoke_interface_trampoline_with_access_check;
Ian Rogersc8b306f2012-02-17 21:34:44 -0800158 pInvokeStaticTrampolineWithAccessCheck = art_invoke_static_trampoline_with_access_check;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800159 pInvokeSuperTrampolineWithAccessCheck = art_invoke_super_trampoline_with_access_check;
160 pInvokeVirtualTrampolineWithAccessCheck = art_invoke_virtual_trampoline_with_access_check;
Brian Carlstrom6fd03fb2011-10-17 16:11:00 -0700161 pLockObjectFromCode = art_lock_object_from_code;
Brian Carlstrom6fd03fb2011-10-17 16:11:00 -0700162 pResolveStringFromCode = art_resolve_string_from_code;
Ian Rogers1bddec32012-02-04 12:27:34 -0800163 pSet32Instance = art_set32_instance_from_code;
164 pSet64Instance = art_set64_instance_from_code;
165 pSetObjInstance = art_set_obj_instance_from_code;
Ian Rogersce9eca62011-10-07 17:11:03 -0700166 pSet32Static = art_set32_static_from_code;
167 pSet64Static = art_set64_static_from_code;
168 pSetObjStatic = art_set_obj_static_from_code;
Brian Carlstrom6fd03fb2011-10-17 16:11:00 -0700169 pTestSuspendFromCode = art_test_suspend;
Ian Rogersff1ed472011-09-20 13:46:24 -0700170 pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
171 pThrowDivZeroFromCode = art_throw_div_zero_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700172 pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
173 pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700174 pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
Ian Rogers932746a2011-09-22 18:57:50 -0700175 pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
Ian Rogersc0c8dc82011-09-24 18:15:59 -0700176 pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
Ian Rogersff1ed472011-09-20 13:46:24 -0700177 pUnlockObjectFromCode = art_unlock_object_from_code;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700178#elif defined(__i386__)
Ian Rogersb3ab25b2012-03-19 01:12:01 -0700179 pShlLong = NULL;
180 pShrLong = NULL;
181 pUshrLong = NULL;
182 pIdiv = NULL;
183 pIdivmod = NULL;
184 pI2f = NULL;
185 pF2iz = NULL;
186 pD2f = NULL;
187 pF2d = NULL;
188 pD2iz = NULL;
189 pL2f = NULL;
190 pL2d = NULL;
191 pFadd = NULL;
192 pFsub = NULL;
193 pFdiv = NULL;
194 pFmul = NULL;
195 pFmodf = NULL;
196 pDadd = NULL;
197 pDsub = NULL;
198 pDdiv = NULL;
199 pDmul = NULL;
200 pFmod = NULL;
Ian Rogersc6f3bb82012-03-21 20:40:33 -0700201 pLadd = NULL;
202 pLsub = NULL;
203 pLand = NULL;
204 pLor = NULL;
205 pLxor = NULL;
Ian Rogersb3ab25b2012-03-19 01:12:01 -0700206 pLdivmod = NULL;
207 pLmul = NULL;
208 pAllocArrayFromCode = NULL;
209 pAllocArrayFromCodeWithAccessCheck = NULL;
210 pAllocObjectFromCode = NULL;
211 pAllocObjectFromCodeWithAccessCheck = NULL;
212 pCanPutArrayElementFromCode = NULL;
213 pCheckAndAllocArrayFromCode = NULL;
214 pCheckAndAllocArrayFromCodeWithAccessCheck = NULL;
215 pCheckCastFromCode = NULL;
216 pGet32Instance = NULL;
217 pGet64Instance = NULL;
218 pGetObjInstance = NULL;
219 pGet32Static = NULL;
220 pGet64Static = NULL;
221 pGetObjStatic = NULL;
222 pHandleFillArrayDataFromCode = NULL;
223 pInitializeStaticStorage = NULL;
224 pInitializeTypeFromCode = NULL;
225 pInitializeTypeAndVerifyAccessFromCode = NULL;
226 pInvokeDirectTrampolineWithAccessCheck = NULL;
227 pInvokeInterfaceTrampoline = NULL;
228 pInvokeInterfaceTrampolineWithAccessCheck = NULL;
229 pInvokeStaticTrampolineWithAccessCheck = NULL;
230 pInvokeSuperTrampolineWithAccessCheck = NULL;
231 pInvokeVirtualTrampolineWithAccessCheck = NULL;
232 pLockObjectFromCode = NULL;
233 pResolveStringFromCode = NULL;
234 pSet32Instance = NULL;
235 pSet64Instance = NULL;
236 pSetObjInstance = NULL;
237 pSet32Static = NULL;
238 pSet64Static = NULL;
239 pSetObjStatic = NULL;
240 pTestSuspendFromCode = NULL;
241 pThrowArrayBoundsFromCode = NULL;
242 pThrowDivZeroFromCode = NULL;
243 pThrowNegArraySizeFromCode = NULL;
244 pThrowNoSuchMethodFromCode = NULL;
245 pThrowNullPointerFromCode = NULL;
246 pThrowStackOverflowFromCode = NULL;
247 pThrowVerificationErrorFromCode = NULL;
248 pUnlockObjectFromCode = NULL;
Ian Rogersb3ab25b2012-03-19 01:12:01 -0700249#endif
buzbeec396efc2011-09-11 09:36:41 -0700250 pF2l = F2L;
251 pD2l = D2L;
buzbee3ea4ec52011-08-22 17:37:19 -0700252 pMemcpy = memcpy;
Ian Rogers4a510d82011-10-09 14:30:24 -0700253 pCheckSuspendFromCode = CheckSuspendFromCode;
buzbee4a3164f2011-09-03 11:25:10 -0700254 pDebugMe = DebugMe;
Ian Rogers4a510d82011-10-09 14:30:24 -0700255 pDecodeJObjectInThread = DecodeJObjectInThread;
256 pDeliverException = art_deliver_exception_from_code;
257 pFindNativeMethod = FindNativeMethod;
Ian Rogerscaab8c42011-10-12 12:11:18 -0700258 pInstanceofNonTrivialFromCode = IsAssignableFromCode;
Ian Rogers4a510d82011-10-09 14:30:24 -0700259 pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
260 pUnresolvedDirectMethodTrampolineFromCode = UnresolvedDirectMethodTrampolineFromCode;
Elliott Hughesc0f09332012-03-26 13:27:06 -0700261 pUpdateDebuggerFromCode = NULL; // Controlled by SetDebuggerUpdatesEnabled.
262}
263
264void Thread::SetDebuggerUpdatesEnabled(bool enabled) {
265 LOG(INFO) << "Turning debugger updates " << (enabled ? "on" : "off") << " for " << *this;
266 pUpdateDebuggerFromCode = (enabled ? art_update_debugger : NULL);
buzbee3ea4ec52011-08-22 17:37:19 -0700267}
268
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700269void Thread::InitTid() {
270 tid_ = ::art::GetTid();
271}
272
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700273void Thread::InitAfterFork() {
274 InitTid();
Elliott Hughes3147a232011-10-12 15:55:07 -0700275#if defined(__BIONIC__)
276 // Work around a bionic bug.
277 struct bionic_pthread_internal_t {
278 void* next;
279 void** pref;
280 pthread_attr_t attr;
281 pid_t kernel_id;
282 // et cetera. we just need 'kernel_id' so we can stop here.
283 };
284 reinterpret_cast<bionic_pthread_internal_t*>(pthread_self())->kernel_id = tid_;
285#endif
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700286}
287
Brian Carlstrom78128a62011-09-15 17:21:19 -0700288void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700289 Thread* self = reinterpret_cast<Thread*>(arg);
Elliott Hughes462c9442012-03-23 18:47:50 -0700290 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700291
Elliott Hughes93e74e82011-09-13 11:07:03 -0700292 // Wait until it's safe to start running code. (There may have been a suspend-all
293 // in progress while we were starting up.)
Elliott Hughes462c9442012-03-23 18:47:50 -0700294 Runtime* runtime = Runtime::Current();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700295 runtime->GetThreadList()->WaitForGo();
296
Elliott Hughes47179f72011-10-27 16:44:39 -0700297 {
298 CHECK_EQ(self->GetState(), Thread::kRunnable);
Elliott Hughes899e7892012-01-24 14:57:32 -0800299 SirtRef<String> thread_name(self->GetThreadName());
300 self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
Elliott Hughes47179f72011-10-27 16:44:39 -0700301 }
302
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700303 Dbg::PostThreadStart(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700304
305 // Invoke the 'run' method of our java.lang.Thread.
306 CHECK(self->peer_ != NULL);
307 Object* receiver = self->peer_;
Elliott Hughes038a8062011-09-18 14:12:41 -0700308 Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700309 m->Invoke(self, receiver, NULL, NULL);
310
311 // Detach.
312 runtime->GetThreadList()->Unregister();
313
Carl Shapirob5573532011-07-12 18:22:59 -0700314 return NULL;
315}
316
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700317static void SetVmData(Object* managed_thread, Thread* native_thread) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700318 gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
Elliott Hughes93e74e82011-09-13 11:07:03 -0700319}
320
Elliott Hughes761928d2011-11-16 18:33:03 -0800321Thread* Thread::FromManagedThread(Object* thread_peer) {
322 return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread_peer)));
323}
324
Elliott Hughes01158d72011-09-19 19:47:10 -0700325Thread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
Elliott Hughes761928d2011-11-16 18:33:03 -0800326 return FromManagedThread(Decode<Object*>(env, java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700327}
328
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700329static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700330 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700331 if (stack_size == 0) {
332 stack_size = Runtime::Current()->GetDefaultStackSize();
333 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700334
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700335 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
336 if (stack_size < PTHREAD_STACK_MIN) {
337 stack_size = PTHREAD_STACK_MIN;
338 }
339
340 // It's likely that callers are trying to ensure they have at least a certain amount of
341 // stack space, so we should add our reserved space on top of what they requested, rather
342 // than implicitly take it away from them.
343 stack_size += Thread::kStackOverflowReservedBytes;
344
345 // Some systems require the stack size to be a multiple of the system page size, so round up.
346 stack_size = RoundUp(stack_size, kPageSize);
347
348 return stack_size;
349}
350
351void Thread::Create(Object* peer, size_t stack_size) {
352 CHECK(peer != NULL);
353
354 stack_size = FixStackSize(stack_size);
355
Elliott Hughes93e74e82011-09-13 11:07:03 -0700356 Thread* native_thread = new Thread;
357 native_thread->peer_ = peer;
358
359 // Thread.start is synchronized, so we know that vmData is 0,
360 // and know that we're not racing to assign it.
361 SetVmData(peer, native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700362
Elliott Hughes47179f72011-10-27 16:44:39 -0700363 {
364 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
365 pthread_t new_pthread;
366 pthread_attr_t attr;
367 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
368 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
369 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
370 CHECK_PTHREAD_CALL(pthread_create, (&new_pthread, &attr, Thread::CreateCallback, native_thread), "new thread");
371 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
372 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700373
374 // Let the child know when it's safe to start running.
375 Runtime::Current()->GetThreadList()->SignalGo(native_thread);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700376}
377
Elliott Hughes462c9442012-03-23 18:47:50 -0700378void Thread::Init() {
379 // This function does all the initialization that must be run by the native thread it applies to.
380 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
381 // we can handshake with the corresponding native thread when it's ready.) Check this native
382 // thread hasn't been through here already...
Elliott Hughescac6cc72011-11-03 20:31:21 -0700383 CHECK(Thread::Current() == NULL);
384
Elliott Hughes93e74e82011-09-13 11:07:03 -0700385 InitCpu();
386 InitFunctionPointers();
Ian Rogers5d76c432011-10-31 21:42:49 -0700387 InitCardTable();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700388
Elliott Hughes462c9442012-03-23 18:47:50 -0700389 Runtime* runtime = Runtime::Current();
390 CHECK(runtime != NULL);
391
392 thin_lock_id_ = runtime->GetThreadList()->AllocThreadId();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700393
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700394 InitTid();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700395 InitStackHwm();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700396
Elliott Hughes3147a232011-10-12 15:55:07 -0700397 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
Elliott Hughesa5780da2011-07-17 11:39:39 -0700398
Elliott Hughes93e74e82011-09-13 11:07:03 -0700399 jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
Elliott Hughes330304d2011-08-12 14:28:05 -0700400
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700401 runtime->GetThreadList()->Register();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700402}
403
Elliott Hughes462c9442012-03-23 18:47:50 -0700404Thread* Thread::Attach(const char* thread_name, bool as_daemon, Object* thread_group) {
Elliott Hughescac6cc72011-11-03 20:31:21 -0700405 Thread* self = new Thread;
Elliott Hughes462c9442012-03-23 18:47:50 -0700406 self->Init();
Elliott Hughes93e74e82011-09-13 11:07:03 -0700407
Elliott Hughescac6cc72011-11-03 20:31:21 -0700408 self->SetState(Thread::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700409
Elliott Hughescac6cc72011-11-03 20:31:21 -0700410 // If we're the main thread, ClassLinker won't be created until after we're attached,
411 // so that thread needs a two-stage attach. Regular threads don't need this hack.
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800412 // In the compiler, all threads need this hack, because no-one's going to be getting
413 // a native peer!
414 if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700415 self->CreatePeer(thread_name, as_daemon, thread_group);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800416 } else {
417 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
Elliott Hughes22869a92012-03-27 14:08:24 -0700418 if (thread_name != NULL) {
419 self->name_->assign(thread_name);
420 ::art::SetThreadName(thread_name);
421 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700422 }
Elliott Hughescac6cc72011-11-03 20:31:21 -0700423
424 self->GetJniEnv()->locals.AssertEmpty();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700425 return self;
426}
427
Elliott Hughes462c9442012-03-23 18:47:50 -0700428Object* Thread::GetMainThreadGroup() {
429 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(gThreadGroup, true)) {
430 return NULL;
431 }
432 return gThreadGroup_mMain->GetObject(NULL);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700433}
434
Elliott Hughes462c9442012-03-23 18:47:50 -0700435Object* Thread::GetSystemThreadGroup() {
436 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(gThreadGroup, true)) {
437 return NULL;
438 }
439 return gThreadGroup_mSystem->GetObject(NULL);
440}
441
442void Thread::CreatePeer(const char* name, bool as_daemon, Object* thread_group) {
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500443 CHECK(Runtime::Current()->IsStarted());
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700444 JNIEnv* env = jni_env_;
445
Elliott Hughes462c9442012-03-23 18:47:50 -0700446 if (thread_group == NULL) {
447 thread_group = Thread::GetMainThreadGroup();
448 }
449 ScopedLocalRef<jobject> java_thread_group(env, AddLocalReference<jobject>(env, thread_group));
Elliott Hughes726079d2011-10-07 18:43:44 -0700450 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Elliott Hughes8daa0922011-09-11 13:46:25 -0700451 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700452 jboolean thread_is_daemon = as_daemon;
453
Elliott Hughes726079d2011-10-07 18:43:44 -0700454 ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/Thread"));
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700455 ScopedLocalRef<jobject> peer(env, env->AllocObject(c.get()));
Elliott Hughes726079d2011-10-07 18:43:44 -0700456 peer_ = DecodeJObject(peer.get());
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700457 if (peer_ == NULL) {
458 CHECK(IsExceptionPending());
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700459 return;
460 }
461 jmethodID mid = env->GetMethodID(c.get(), "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
Elliott Hughes462c9442012-03-23 18:47:50 -0700462 env->CallNonvirtualVoidMethod(peer.get(), c.get(), mid, java_thread_group.get(), thread_name.get(), thread_priority, thread_is_daemon);
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500463 CHECK(!IsExceptionPending()) << " " << PrettyTypeOf(GetException());
Elliott Hughes7a3aeb42011-09-25 17:39:47 -0700464 SetVmData(peer_, Thread::Current());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700465
Elliott Hughes899e7892012-01-24 14:57:32 -0800466 SirtRef<String> peer_thread_name(GetThreadName());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700467 if (peer_thread_name.get() == NULL) {
468 // The Thread constructor should have set the Thread.name to a
469 // non-null value. However, because we can run without code
470 // available (in the compiler, in tests), we manually assign the
471 // fields the constructor should have set.
472 gThread_daemon->SetBoolean(peer_, thread_is_daemon);
Elliott Hughes462c9442012-03-23 18:47:50 -0700473 gThread_group->SetObject(peer_, thread_group);
Brian Carlstrom00fae582011-10-28 01:16:28 -0700474 gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name.get()));
475 gThread_priority->SetInt(peer_, thread_priority);
Elliott Hughes899e7892012-01-24 14:57:32 -0800476 peer_thread_name.reset(GetThreadName());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700477 }
478 // thread_name may have been null, so don't trust this to be non-null
479 if (peer_thread_name.get() != NULL) {
Elliott Hughes899e7892012-01-24 14:57:32 -0800480 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -0700481 }
Elliott Hughes726079d2011-10-07 18:43:44 -0700482
483 // Pre-allocate an OutOfMemoryError for the double-OOME case.
484 ThrowNewException("Ljava/lang/OutOfMemoryError;",
485 "OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available");
486 ScopedLocalRef<jthrowable> exception(env, env->ExceptionOccurred());
487 env->ExceptionClear();
488 pre_allocated_OutOfMemoryError_ = Decode<Throwable*>(env, exception.get());
Carl Shapiro61e019d2011-07-14 16:53:09 -0700489}
490
Elliott Hughes899e7892012-01-24 14:57:32 -0800491void Thread::SetThreadName(const char* name) {
492 name_->assign(name);
493 ::art::SetThreadName(name);
494 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
495}
496
Elliott Hughesbe759c62011-09-08 19:38:21 -0700497void Thread::InitStackHwm() {
Elliott Hughes215f3142012-01-19 00:22:47 -0800498#if defined(__APPLE__)
Elliott Hughes6cc332e2012-01-20 22:59:20 -0800499 // Only needed to run code. Try implementing this with pthread_get_stacksize_np and pthread_get_stackaddr_np.
500 UNIMPLEMENTED(WARNING);
Elliott Hughes215f3142012-01-19 00:22:47 -0800501#else
Elliott Hughesbe759c62011-09-08 19:38:21 -0700502 pthread_attr_t attributes;
Elliott Hughes3147a232011-10-12 15:55:07 -0700503 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700504
Ian Rogers932746a2011-09-22 18:57:50 -0700505 void* temp_stack_base;
506 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
507 __FUNCTION__);
Ian Rogers30fab402012-01-23 15:43:46 -0800508 stack_begin_ = reinterpret_cast<byte*>(temp_stack_base);
Elliott Hughesbe759c62011-09-08 19:38:21 -0700509
Ian Rogers932746a2011-09-22 18:57:50 -0700510 if (stack_size_ <= kStackOverflowReservedBytes) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800511 LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
Elliott Hughesbe759c62011-09-08 19:38:21 -0700512 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700513
Ian Rogers932746a2011-09-22 18:57:50 -0700514 // Set stack_end_ to the bottom of the stack saving space of stack overflows
515 ResetDefaultStackEnd();
Elliott Hughes449b4bd2011-09-09 12:01:38 -0700516
517 // Sanity check.
518 int stack_variable;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700519 CHECK_GT(&stack_variable, reinterpret_cast<void*>(stack_end_));
Elliott Hughesbe759c62011-09-08 19:38:21 -0700520
Elliott Hughes8d768a92011-09-14 16:35:25 -0700521 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes215f3142012-01-19 00:22:47 -0800522#endif
Elliott Hughesbe759c62011-09-08 19:38:21 -0700523}
524
Elliott Hughes899e7892012-01-24 14:57:32 -0800525void Thread::Dump(std::ostream& os, bool full) const {
526 if (full) {
527 DumpState(os);
528 DumpStack(os);
529 } else {
530 os << "Thread[";
531 if (GetThinLockId() != 0) {
532 // If we're in kStarting, we won't have a thin lock id or tid yet.
533 os << GetThinLockId()
534 << ",tid=" << GetTid() << ',';
535 }
536 os << GetState()
537 << ",Thread*=" << this
Elliott Hughesffb465f2012-03-01 18:46:05 -0800538 << ",peer=" << peer_
Elliott Hughes899e7892012-01-24 14:57:32 -0800539 << ",\"" << *name_ << "\""
540 << "]";
Elliott Hughese0918552011-10-28 17:18:29 -0700541 }
Elliott Hughesa0957642011-09-02 14:27:33 -0700542}
543
Elliott Hughes899e7892012-01-24 14:57:32 -0800544String* Thread::GetThreadName() const {
Elliott Hughesfc861622011-10-17 17:57:47 -0700545 return (peer_ != NULL) ? reinterpret_cast<String*>(gThread_name->GetObject(peer_)) : NULL;
546}
547
Elliott Hughesffb465f2012-03-01 18:46:05 -0800548void Thread::GetThreadName(std::string& name) const {
549 name.assign(*name_);
550}
551
Elliott Hughesd92bec42011-09-02 17:04:36 -0700552void Thread::DumpState(std::ostream& os) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700553 std::string group_name;
554 int priority;
555 bool is_daemon = false;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700556
Elliott Hughesd369bb72011-09-12 14:41:14 -0700557 if (peer_ != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700558 priority = gThread_priority->GetInt(peer_);
559 is_daemon = gThread_daemon->GetBoolean(peer_);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700560
Elliott Hughesa2155262011-11-16 16:26:58 -0800561 Object* thread_group = GetThreadGroup();
Elliott Hughesd369bb72011-09-12 14:41:14 -0700562 if (thread_group != NULL) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700563 String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
Elliott Hughesd369bb72011-09-12 14:41:14 -0700564 group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
565 }
566 } else {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700567 priority = GetNativePriority();
Elliott Hughesdcc24742011-09-07 14:02:44 -0700568 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700569
570 int policy;
571 sched_param sp;
Elliott Hughes3147a232011-10-12 15:55:07 -0700572 CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_self(), &policy, &sp), __FUNCTION__);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700573
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700574 std::string scheduler_group_name(GetSchedulerGroupName(GetTid()));
575 if (scheduler_group_name.empty()) {
576 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700577 }
578
Elliott Hughes899e7892012-01-24 14:57:32 -0800579 os << '"' << *name_ << '"';
Elliott Hughesd369bb72011-09-12 14:41:14 -0700580 if (is_daemon) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700581 os << " daemon";
582 }
583 os << " prio=" << priority
Elliott Hughesdcc24742011-09-07 14:02:44 -0700584 << " tid=" << GetThinLockId()
Elliott Hughes93e74e82011-09-13 11:07:03 -0700585 << " " << GetState() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700586
Elliott Hughesd92bec42011-09-02 17:04:36 -0700587 os << " | group=\"" << group_name << "\""
Elliott Hughes8d768a92011-09-14 16:35:25 -0700588 << " sCount=" << suspend_count_
Elliott Hughes234ab152011-10-26 14:02:26 -0700589 << " dsCount=" << debug_suspend_count_
Elliott Hughesdcc24742011-09-07 14:02:44 -0700590 << " obj=" << reinterpret_cast<void*>(peer_)
Elliott Hughesd92bec42011-09-02 17:04:36 -0700591 << " self=" << reinterpret_cast<const void*>(this) << "\n";
592 os << " | sysTid=" << GetTid()
593 << " nice=" << getpriority(PRIO_PROCESS, GetTid())
594 << " sched=" << policy << "/" << sp.sched_priority
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700595 << " cgrp=" << scheduler_group_name
Elliott Hughes3147a232011-10-12 15:55:07 -0700596 << " handle=" << pthread_self() << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -0700597
598 // Grab the scheduler stats for this thread.
599 std::string scheduler_stats;
600 if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
601 scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
602 } else {
603 scheduler_stats = "0 0 0";
604 }
605
606 int utime = 0;
607 int stime = 0;
608 int task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700609 GetTaskStats(GetTid(), utime, stime, task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -0700610
611 os << " | schedstat=( " << scheduler_stats << " )"
612 << " utm=" << utime
613 << " stm=" << stime
614 << " core=" << task_cpu
615 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
616}
617
Ian Rogersb04f69f2011-10-17 00:40:54 -0700618void Thread::PushNativeToManagedRecord(NativeToManagedRecord* record) {
619 Method **sp = top_of_managed_stack_.GetSP();
620#ifndef NDEBUG
621 if (sp != NULL) {
622 Method* m = *sp;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800623 Runtime::Current()->GetHeap()->VerifyObject(m);
Ian Rogersb04f69f2011-10-17 00:40:54 -0700624 DCHECK((m == NULL) || m->IsMethod());
625 }
626#endif
627 record->last_top_of_managed_stack_ = reinterpret_cast<void*>(sp);
628 record->last_top_of_managed_stack_pc_ = top_of_managed_stack_pc_;
629 record->link_ = native_to_managed_record_;
630 native_to_managed_record_ = record;
631 top_of_managed_stack_.SetSP(NULL);
632}
633
634void Thread::PopNativeToManagedRecord(const NativeToManagedRecord& record) {
635 native_to_managed_record_ = record.link_;
636 top_of_managed_stack_.SetSP(reinterpret_cast<Method**>(record.last_top_of_managed_stack_));
637 top_of_managed_stack_pc_ = record.last_top_of_managed_stack_pc_;
638}
639
Elliott Hughesd369bb72011-09-12 14:41:14 -0700640struct StackDumpVisitor : public Thread::StackVisitor {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700641 StackDumpVisitor(std::ostream& os, const Thread* thread)
Ian Rogers28ad40d2011-10-27 15:19:26 -0700642 : last_method(NULL), last_line_number(0), repetition_count(0), os(os), thread(thread),
643 frame_count(0) {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700644 }
645
Ian Rogersbdb03912011-09-14 00:55:44 -0700646 virtual ~StackDumpVisitor() {
Elliott Hughesd369bb72011-09-12 14:41:14 -0700647 }
648
Elliott Hughes530fa002012-03-12 11:44:49 -0700649 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogers90865722011-09-19 11:11:44 -0700650 if (!frame.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -0700651 return true;
Ian Rogers90865722011-09-19 11:11:44 -0700652 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700653 const int kMaxRepetition = 3;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700654 Method* m = frame.GetMethod();
655 Class* c = m->GetDeclaringClass();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700656 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersb861dc02011-11-14 17:00:05 -0800657 const DexCache* dex_cache = c->GetDexCache();
658 int line_number = -1;
659 if (dex_cache != NULL) { // be tolerant of bad input
660 const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
661 line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
662 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700663 if (line_number == last_line_number && last_method == m) {
664 repetition_count++;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700665 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700666 if (repetition_count >= kMaxRepetition) {
667 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
668 }
669 repetition_count = 0;
670 last_line_number = line_number;
671 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700672 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700673 if (repetition_count < kMaxRepetition) {
674 os << " at " << PrettyMethod(m, false);
675 if (m->IsNative()) {
676 os << "(Native method)";
677 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800678 mh.ChangeMethod(m);
679 const char* source_file(mh.GetDeclaringClassSourceFile());
680 os << "(" << (source_file != NULL ? source_file : "unavailable")
Ian Rogers28ad40d2011-10-27 15:19:26 -0700681 << ":" << line_number << ")";
682 }
683 os << "\n";
684 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700685
686 if (frame_count++ == 0) {
687 Monitor::DescribeWait(os, thread);
688 }
Elliott Hughes530fa002012-03-12 11:44:49 -0700689 return true;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700690 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800691 MethodHelper mh;
Ian Rogers28ad40d2011-10-27 15:19:26 -0700692 Method* last_method;
693 int last_line_number;
694 int repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700695 std::ostream& os;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700696 const Thread* thread;
697 int frame_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -0700698};
699
Elliott Hughesd92bec42011-09-02 17:04:36 -0700700void Thread::DumpStack(std::ostream& os) const {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800701 // If we're currently in native code, dump that stack before dumping the managed stack.
702 if (GetState() == Thread::kNative || GetState() == Thread::kVmWait) {
703 DumpNativeStack(os);
704 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700705 StackDumpVisitor dumper(os, this);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700706 WalkStack(&dumper);
Elliott Hughese27955c2011-08-26 15:21:24 -0700707}
708
Elliott Hughesa4060e52012-03-02 16:51:35 -0800709void Thread::SetStateWithoutSuspendCheck(Thread::State new_state) {
710 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
711 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
712 android_atomic_release_store(new_state, addr);
713}
714
Elliott Hughes8d768a92011-09-14 16:35:25 -0700715Thread::State Thread::SetState(Thread::State new_state) {
716 Thread::State old_state = state_;
717 if (old_state == new_state) {
718 return old_state;
719 }
720
721 volatile void* raw = reinterpret_cast<volatile void*>(&state_);
722 volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
723
724 if (new_state == Thread::kRunnable) {
725 /*
726 * Change our status to Thread::kRunnable. The transition requires
Elliott Hughes81ff3182012-03-23 20:35:56 -0700727 * that we check for pending suspension, because the runtime considers
Elliott Hughes8d768a92011-09-14 16:35:25 -0700728 * us to be "asleep" in all other states, and another thread could
729 * be performing a GC now.
730 *
731 * The order of operations is very significant here. One way to
732 * do this wrong is:
733 *
734 * GCing thread Our thread (in kNative)
735 * ------------ ----------------------
736 * check suspend count (== 0)
737 * SuspendAllThreads()
738 * grab suspend-count lock
739 * increment all suspend counts
740 * release suspend-count lock
741 * check thread state (== kNative)
742 * all are suspended, begin GC
743 * set state to kRunnable
744 * (continue executing)
745 *
746 * We can correct this by grabbing the suspend-count lock and
747 * performing both of our operations (check suspend count, set
748 * state) while holding it, now we need to grab a mutex on every
749 * transition to kRunnable.
750 *
751 * What we do instead is change the order of operations so that
752 * the transition to kRunnable happens first. If we then detect
753 * that the suspend count is nonzero, we switch to kSuspended.
754 *
755 * Appropriate compiler and memory barriers are required to ensure
756 * that the operations are observed in the expected order.
757 *
758 * This does create a small window of opportunity where a GC in
759 * progress could observe what appears to be a running thread (if
760 * it happens to look between when we set to kRunnable and when we
761 * switch to kSuspended). At worst this only affects assertions
762 * and thread logging. (We could work around it with some sort
763 * of intermediate "pre-running" state that is generally treated
764 * as equivalent to running, but that doesn't seem worthwhile.)
765 *
766 * We can also solve this by combining the "status" and "suspend
767 * count" fields into a single 32-bit value. This trades the
768 * store/load barrier on transition to kRunnable for an atomic RMW
769 * op on all transitions and all suspend count updates (also, all
770 * accesses to status or the thread count require bit-fiddling).
771 * It also eliminates the brief transition through kRunnable when
772 * the thread is supposed to be suspended. This is possibly faster
773 * on SMP and slightly more correct, but less convenient.
774 */
775 android_atomic_acquire_store(new_state, addr);
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800776 ANNOTATE_IGNORE_READS_BEGIN();
777 int suspend_count = suspend_count_;
778 ANNOTATE_IGNORE_READS_END();
779 if (suspend_count != 0) {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700780 Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
781 }
782 } else {
783 /*
784 * Not changing to Thread::kRunnable. No additional work required.
785 *
786 * We use a releasing store to ensure that, if we were runnable,
787 * any updates we previously made to objects on the managed heap
788 * will be observed before the state change.
789 */
790 android_atomic_release_store(new_state, addr);
791 }
792
793 return old_state;
794}
795
Elliott Hughes761928d2011-11-16 18:33:03 -0800796bool Thread::IsSuspended() {
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800797 ANNOTATE_IGNORE_READS_BEGIN();
798 int suspend_count = suspend_count_;
799 ANNOTATE_IGNORE_READS_END();
800 return suspend_count != 0 && GetState() != Thread::kRunnable;
Elliott Hughes761928d2011-11-16 18:33:03 -0800801}
802
Elliott Hughesff738062012-02-03 15:00:42 -0800803static void ReportThreadSuspendTimeout(Thread* waiting_thread) {
804 Runtime* runtime = Runtime::Current();
805 std::ostringstream ss;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800806 ss << "Thread suspend timeout waiting for thread " << *waiting_thread << "\n";
Elliott Hughesff738062012-02-03 15:00:42 -0800807 runtime->DumpLockHolders(ss);
808 ss << "\n";
809 runtime->GetThreadList()->DumpLocked(ss);
810 LOG(FATAL) << ss.str();
811}
812
Elliott Hughes8d768a92011-09-14 16:35:25 -0700813void Thread::WaitUntilSuspended() {
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800814 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
815
816 useconds_t total_delay = 0;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700817 useconds_t delay = 0;
818 while (GetState() == Thread::kRunnable) {
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800819 if (total_delay >= kTimeoutUs) {
Elliott Hughesff738062012-02-03 15:00:42 -0800820 ReportThreadSuspendTimeout(this);
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800821 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700822 useconds_t new_delay = delay * 2;
823 CHECK_GE(new_delay, delay);
824 delay = new_delay;
825 if (delay == 0) {
826 sched_yield();
827 delay = 10000;
828 } else {
829 usleep(delay);
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800830 total_delay += delay;
Elliott Hughes8d768a92011-09-14 16:35:25 -0700831 }
832 }
833}
834
Elliott Hughesbe759c62011-09-08 19:38:21 -0700835void Thread::ThreadExitCallback(void* arg) {
836 Thread* self = reinterpret_cast<Thread*>(arg);
837 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
Carl Shapirob5573532011-07-12 18:22:59 -0700838}
839
Elliott Hughesbe759c62011-09-08 19:38:21 -0700840void Thread::Startup() {
Carl Shapirob5573532011-07-12 18:22:59 -0700841 // Allocate a TLS slot.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700842 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
Carl Shapirob5573532011-07-12 18:22:59 -0700843
844 // Double-check the TLS slot allocation.
845 if (pthread_getspecific(pthread_key_self_) != NULL) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800846 LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
Carl Shapirob5573532011-07-12 18:22:59 -0700847 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700848}
Carl Shapirob5573532011-07-12 18:22:59 -0700849
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700850// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700851static Class* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700852 Class* c = class_linker->FindSystemClass(descriptor);
853 CHECK(c != NULL) << descriptor;
854 return c;
855}
856
857// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700858static Field* FindFieldOrDie(Class* c, const char* name, const char* descriptor) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700859 Field* f = c->FindDeclaredInstanceField(name, descriptor);
860 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700861 return f;
862}
863
864// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700865static Method* FindMethodOrDie(Class* c, const char* name, const char* signature) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700866 Method* m = c->FindVirtualMethod(name, signature);
867 CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
868 return m;
869}
870
Elliott Hughes462c9442012-03-23 18:47:50 -0700871// TODO: make more accessible?
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700872static Field* FindStaticFieldOrDie(Class* c, const char* name, const char* descriptor) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700873 Field* f = c->FindDeclaredStaticField(name, descriptor);
874 CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
875 return f;
876}
877
Elliott Hughes038a8062011-09-18 14:12:41 -0700878void Thread::FinishStartup() {
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500879 CHECK(Runtime::Current()->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -0700880 Thread* self = Thread::Current();
881
882 // Need to be kRunnable for FindClass
883 ScopedThreadStateChange tsc(self, Thread::kRunnable);
884
Elliott Hughes038a8062011-09-18 14:12:41 -0700885 // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
886 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700887
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700888 Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700889 Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
Elliott Hughes462c9442012-03-23 18:47:50 -0700890 gThreadGroup = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700891 gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700892
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700893 gThread_daemon = FindFieldOrDie(Thread_class, "daemon", "Z");
894 gThread_group = FindFieldOrDie(Thread_class, "group", "Ljava/lang/ThreadGroup;");
895 gThread_lock = FindFieldOrDie(Thread_class, "lock", "Ljava/lang/ThreadLock;");
896 gThread_name = FindFieldOrDie(Thread_class, "name", "Ljava/lang/String;");
897 gThread_priority = FindFieldOrDie(Thread_class, "priority", "I");
898 gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
899 gThread_vmData = FindFieldOrDie(Thread_class, "vmData", "I");
Elliott Hughes462c9442012-03-23 18:47:50 -0700900 gThreadGroup_name = FindFieldOrDie(gThreadGroup, "name", "Ljava/lang/String;");
901 gThreadGroup_mMain = FindStaticFieldOrDie(gThreadGroup, "mMain", "Ljava/lang/ThreadGroup;");
902 gThreadGroup_mSystem = FindStaticFieldOrDie(gThreadGroup, "mSystem", "Ljava/lang/ThreadGroup;");
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700903 gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", "Ljava/lang/Thread;");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700904
905 gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
Elliott Hughes462c9442012-03-23 18:47:50 -0700906 gThreadGroup_removeThread = FindMethodOrDie(gThreadGroup, "removeThread", "(Ljava/lang/Thread;)V");
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700907 gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
908 "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
Elliott Hughes01158d72011-09-19 19:47:10 -0700909
910 // Finish attaching the main thread.
Elliott Hughes462c9442012-03-23 18:47:50 -0700911 Thread::Current()->CreatePeer("main", false, Thread::GetMainThreadGroup());
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500912
913 InitBoxingMethods();
914 class_linker->RunRootClinits();
Carl Shapirob5573532011-07-12 18:22:59 -0700915}
916
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700917void Thread::Shutdown() {
Elliott Hughes8d768a92011-09-14 16:35:25 -0700918 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700919}
920
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700921uint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
922 if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
923 return ThreadList::kInvalidId;
924 }
925 Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
926 if (managed_thread == NULL) {
927 return ThreadList::kInvalidId;
928 }
929 uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
930 Thread* thread = reinterpret_cast<Thread*>(vmData);
931 if (thread == NULL) {
932 return ThreadList::kInvalidId;
933 }
934 return thread->GetThinLockId();
935}
936
Elliott Hughesdcc24742011-09-07 14:02:44 -0700937Thread::Thread()
Elliott Hughes47179f72011-10-27 16:44:39 -0700938 : thin_lock_id_(0),
939 tid_(0),
940 peer_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700941 top_of_managed_stack_(),
942 top_of_managed_stack_pc_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700943 wait_mutex_(new Mutex("Thread wait mutex")),
944 wait_cond_(new ConditionVariable("Thread wait condition variable")),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700945 wait_monitor_(NULL),
946 interrupted_(false),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700947 wait_next_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700948 monitor_enter_object_(NULL),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700949 card_table_(0),
Elliott Hughes8daa0922011-09-11 13:46:25 -0700950 stack_end_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700951 native_to_managed_record_(NULL),
952 top_sirt_(NULL),
Logan Chienf7ad17e2012-03-15 03:10:03 +0800953 top_shadow_frame_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700954 jni_env_(NULL),
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700955 state_(Thread::kNative),
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700956 self_(NULL),
957 runtime_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -0700958 exception_(NULL),
959 suspend_count_(0),
Elliott Hughes234ab152011-10-26 14:02:26 -0700960 debug_suspend_count_(0),
Elliott Hughes85d15452011-09-16 17:33:01 -0700961 class_loader_override_(NULL),
Elliott Hughes418dfe72011-10-06 18:56:27 -0700962 long_jump_context_(NULL),
Elliott Hughes726079d2011-10-07 18:43:44 -0700963 throwing_OutOfMemoryError_(false),
Elliott Hughes475fc232011-10-25 15:00:35 -0700964 pre_allocated_OutOfMemoryError_(NULL),
jeffhaoe343b762011-12-05 16:36:44 -0800965 debug_invoke_req_(new DebugInvokeReq),
Elliott Hughes899e7892012-01-24 14:57:32 -0800966 trace_stack_(new std::vector<TraceStackFrame>),
967 name_(new std::string("<native thread without managed peer>")) {
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700968 CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800969 memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
Elliott Hughesdcc24742011-09-07 14:02:44 -0700970}
971
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700972static void MonitorExitVisitor(const Object* object, void*) {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700973 Object* entered_monitor = const_cast<Object*>(object);
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700974 LOG(WARNING) << "Calling MonitorExit on object " << object << " (" << PrettyTypeOf(object) << ")"
975 << " left locked by native thread " << *Thread::Current() << " which is detaching";
Elliott Hughes5f791332011-09-15 17:45:30 -0700976 entered_monitor->MonitorExit(Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -0700977}
978
Elliott Hughesc0f09332012-03-26 13:27:06 -0700979void Thread::Destroy() {
Elliott Hughes02b48d12011-09-07 17:15:51 -0700980 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700981 if (jni_env_ != NULL) {
982 jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
983 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700984
Elliott Hughes93e74e82011-09-13 11:07:03 -0700985 if (peer_ != NULL) {
Elliott Hughesc0f09332012-03-26 13:27:06 -0700986 Thread* self = this;
Elliott Hughes29f27422011-09-18 16:02:18 -0700987
988 // this.vmData = 0;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700989 SetVmData(peer_, NULL);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700990
Elliott Hughesc0f09332012-03-26 13:27:06 -0700991 Dbg::PostThreadDeath(self);
Elliott Hughes02b48d12011-09-07 17:15:51 -0700992
Elliott Hughes29f27422011-09-18 16:02:18 -0700993 // Thread.join() is implemented as an Object.wait() on the Thread.lock
994 // object. Signal anyone who is waiting.
Elliott Hughes038a8062011-09-18 14:12:41 -0700995 Object* lock = gThread_lock->GetObject(peer_);
996 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Elliott Hughes5f791332011-09-15 17:45:30 -0700997 if (lock != NULL) {
998 lock->MonitorEnter(self);
999 lock->NotifyAll();
1000 lock->MonitorExit(self);
1001 }
1002 }
Elliott Hughesc0f09332012-03-26 13:27:06 -07001003}
Elliott Hughes02b48d12011-09-07 17:15:51 -07001004
Elliott Hughesc0f09332012-03-26 13:27:06 -07001005Thread::~Thread() {
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001006 delete jni_env_;
Elliott Hughes02b48d12011-09-07 17:15:51 -07001007 jni_env_ = NULL;
1008
1009 SetState(Thread::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07001010
1011 delete wait_cond_;
1012 delete wait_mutex_;
1013
1014 delete long_jump_context_;
Elliott Hughes475fc232011-10-25 15:00:35 -07001015
1016 delete debug_invoke_req_;
jeffhaoe343b762011-12-05 16:36:44 -08001017 delete trace_stack_;
Elliott Hughes899e7892012-01-24 14:57:32 -08001018 delete name_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001019}
1020
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001021void Thread::HandleUncaughtExceptions() {
1022 if (!IsExceptionPending()) {
1023 return;
1024 }
1025
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001026 // Get and clear the exception.
1027 Object* exception = GetException();
1028 ClearException();
1029
1030 // If the thread has its own handler, use that.
1031 Object* handler = gThread_uncaughtHandler->GetObject(peer_);
1032 if (handler == NULL) {
1033 // Otherwise use the thread group's default handler.
Elliott Hughesa2155262011-11-16 16:26:58 -08001034 handler = GetThreadGroup();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001035 }
1036
1037 // Call the handler.
1038 Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
Elliott Hughes77405792012-03-15 15:22:12 -07001039 JValue args[2];
1040 args[0].l = peer_;
1041 args[1].l = exception;
1042 m->Invoke(this, handler, args, NULL);
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001043
1044 // If the handler threw, clear that exception too.
1045 ClearException();
1046}
1047
Elliott Hughesa2155262011-11-16 16:26:58 -08001048Object* Thread::GetThreadGroup() const {
1049 return gThread_group->GetObject(peer_);
1050}
1051
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001052void Thread::RemoveFromThreadGroup() {
1053 // this.group.removeThread(this);
1054 // group can be null if we're in the compiler or a test.
Elliott Hughesa2155262011-11-16 16:26:58 -08001055 Object* group = GetThreadGroup();
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001056 if (group != NULL) {
1057 Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
Elliott Hughes77405792012-03-15 15:22:12 -07001058 JValue args[1];
1059 args[0].l = peer_;
1060 m->Invoke(this, group, args, NULL);
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07001061 }
1062}
1063
Ian Rogers408f79a2011-08-23 18:22:33 -07001064size_t Thread::NumSirtReferences() {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001065 size_t count = 0;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001066 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001067 count += cur->NumberOfReferences();
1068 }
1069 return count;
1070}
1071
TDYa12728f1a142012-03-15 21:51:52 -07001072size_t Thread::NumShadowFrameReferences() {
1073 size_t count = 0;
1074 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
1075 count += cur->NumberOfReferences();
1076 }
1077 return count;
1078}
1079
Ian Rogers408f79a2011-08-23 18:22:33 -07001080bool Thread::SirtContains(jobject obj) {
1081 Object** sirt_entry = reinterpret_cast<Object**>(obj);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001082 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
1083 if (cur->Contains(sirt_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07001084 return true;
1085 }
1086 }
1087 return false;
1088}
1089
TDYa12728f1a142012-03-15 21:51:52 -07001090bool Thread::ShadowFrameContains(jobject obj) {
1091 Object** shadow_frame_entry = reinterpret_cast<Object**>(obj);
1092 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
1093 if (cur->Contains(shadow_frame_entry)) {
1094 return true;
1095 }
1096 }
1097 return false;
1098}
1099
1100bool Thread::StackReferencesContain(jobject obj) {
1101 return SirtContains(obj) || ShadowFrameContains(obj);
1102}
1103
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001104void Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001105 for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001106 size_t num_refs = cur->NumberOfReferences();
1107 for (size_t j = 0; j < num_refs; j++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001108 Object* object = cur->GetReference(j);
Brian Carlstrom5e73f9c2011-10-11 11:28:12 -07001109 if (object != NULL) {
1110 visitor(object, arg);
1111 }
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001112 }
1113 }
1114}
1115
Logan Chienf7ad17e2012-03-15 03:10:03 +08001116void Thread::ShadowFrameVisitRoots(Heap::RootVisitor* visitor, void* arg) {
1117 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
1118 size_t num_refs = cur->NumberOfReferences();
1119 for (size_t j = 0; j < num_refs; j++) {
1120 Object* object = cur->GetReference(j);
1121 if (object != NULL) {
1122 visitor(object, arg);
1123 }
1124 }
1125 }
1126}
1127
Ian Rogers408f79a2011-08-23 18:22:33 -07001128Object* Thread::DecodeJObject(jobject obj) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001129 DCHECK(CanAccessDirectReferences());
Ian Rogers408f79a2011-08-23 18:22:33 -07001130 if (obj == NULL) {
1131 return NULL;
1132 }
1133 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1134 IndirectRefKind kind = GetIndirectRefKind(ref);
1135 Object* result;
1136 switch (kind) {
1137 case kLocal:
1138 {
Elliott Hughes69f5bc62011-08-24 09:26:14 -07001139 IndirectReferenceTable& locals = jni_env_->locals;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001140 result = const_cast<Object*>(locals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001141 break;
1142 }
1143 case kGlobal:
1144 {
1145 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1146 IndirectReferenceTable& globals = vm->globals;
1147 MutexLock mu(vm->globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001148 result = const_cast<Object*>(globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001149 break;
1150 }
1151 case kWeakGlobal:
1152 {
1153 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1154 IndirectReferenceTable& weak_globals = vm->weak_globals;
1155 MutexLock mu(vm->weak_globals_lock);
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001156 result = const_cast<Object*>(weak_globals.Get(ref));
Ian Rogers408f79a2011-08-23 18:22:33 -07001157 if (result == kClearedJniWeakGlobal) {
1158 // This is a special case where it's okay to return NULL.
1159 return NULL;
1160 }
1161 break;
1162 }
1163 case kSirtOrInvalid:
1164 default:
1165 // TODO: make stack indirect reference table lookup more efficient
1166 // Check if this is a local reference in the SIRT
TDYa12728f1a142012-03-15 21:51:52 -07001167 if (StackReferencesContain(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001168 result = *reinterpret_cast<Object**>(obj); // Read from SIRT
Elliott Hughesc2dc62d2012-01-17 20:06:12 -08001169 } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
Ian Rogers408f79a2011-08-23 18:22:33 -07001170 // Assume an invalid local reference is actually a direct pointer.
1171 result = reinterpret_cast<Object*>(obj);
1172 } else {
Elliott Hughesa2501992011-08-26 19:39:54 -07001173 result = kInvalidIndirectRefObject;
Ian Rogers408f79a2011-08-23 18:22:33 -07001174 }
1175 }
1176
1177 if (result == NULL) {
Elliott Hughesa2501992011-08-26 19:39:54 -07001178 LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1179 JniAbort(NULL);
1180 } else {
1181 if (result != kInvalidIndirectRefObject) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001182 Runtime::Current()->GetHeap()->VerifyObject(result);
Elliott Hughesa2501992011-08-26 19:39:54 -07001183 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001184 }
Ian Rogers408f79a2011-08-23 18:22:33 -07001185 return result;
1186}
1187
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001188class CountStackDepthVisitor : public Thread::StackVisitor {
1189 public:
Elliott Hughes29f27422011-09-18 16:02:18 -07001190 CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07001191
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001192 bool VisitFrame(const Frame& frame, uintptr_t /*pc*/) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001193 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07001194 // Note we also skip the frame if it doesn't have a method (namely the callee
1195 // save frame)
Ian Rogers5167c972012-02-03 10:41:20 -08001196 if (skipping_ && frame.HasMethod() &&
1197 !Throwable::GetJavaLangThrowable()->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07001198 skipping_ = false;
1199 }
1200 if (!skipping_) {
Ian Rogers6b0870d2011-12-15 19:38:12 -08001201 if (frame.HasMethod()) { // ignore callee save frames
1202 ++depth_;
1203 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001204 } else {
1205 ++skip_depth_;
1206 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001207 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001208 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001209
1210 int GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001211 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001212 }
1213
Elliott Hughes29f27422011-09-18 16:02:18 -07001214 int GetSkipDepth() const {
1215 return skip_depth_;
1216 }
1217
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001218 private:
Ian Rogersaaa20802011-09-11 21:47:37 -07001219 uint32_t depth_;
Elliott Hughes29f27422011-09-18 16:02:18 -07001220 uint32_t skip_depth_;
1221 bool skipping_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001222};
1223
Ian Rogersaaa20802011-09-11 21:47:37 -07001224class BuildInternalStackTraceVisitor : public Thread::StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001225 public:
Ian Rogers283ed0d2012-02-16 15:25:09 -08001226 explicit BuildInternalStackTraceVisitor(int skip_depth)
Elliott Hughes726079d2011-10-07 18:43:44 -07001227 : skip_depth_(skip_depth), count_(0), pc_trace_(NULL), method_trace_(NULL), local_ref_(NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001228 }
1229
1230 bool Init(int depth, ScopedJniThreadState& ts) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001231 // Allocate method trace with an extra slot that will hold the PC trace
Elliott Hughes01158d72011-09-19 19:47:10 -07001232 method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
Elliott Hughes726079d2011-10-07 18:43:44 -07001233 if (method_trace_ == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001234 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001235 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001236 // Register a local reference as IntArray::Alloc may trigger GC
1237 local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1238 pc_trace_ = IntArray::Alloc(depth);
Elliott Hughes726079d2011-10-07 18:43:44 -07001239 if (pc_trace_ == NULL) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001240 return false;
Elliott Hughes726079d2011-10-07 18:43:44 -07001241 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001242#ifdef MOVING_GARBAGE_COLLECTOR
1243 // Re-read after potential GC
Brian Carlstrom26736442012-02-16 18:24:26 -08001244 method_trace_ = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
Ian Rogersaaa20802011-09-11 21:47:37 -07001245#endif
1246 // Save PC trace in last element of method trace, also places it into the
1247 // object graph.
1248 method_trace_->Set(depth, pc_trace_);
Ian Rogers283ed0d2012-02-16 15:25:09 -08001249 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001250 }
1251
Ian Rogersaaa20802011-09-11 21:47:37 -07001252 virtual ~BuildInternalStackTraceVisitor() {}
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001253
Elliott Hughes530fa002012-03-12 11:44:49 -07001254 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Elliott Hughes726079d2011-10-07 18:43:44 -07001255 if (method_trace_ == NULL || pc_trace_ == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001256 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07001257 }
Elliott Hughes29f27422011-09-18 16:02:18 -07001258 if (skip_depth_ > 0) {
1259 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07001260 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07001261 }
Ian Rogers6b0870d2011-12-15 19:38:12 -08001262 if (!frame.HasMethod()) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001263 return true; // ignore callee save frames
Ian Rogers6b0870d2011-12-15 19:38:12 -08001264 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001265 method_trace_->Set(count_, frame.GetMethod());
Ian Rogersbdb03912011-09-14 00:55:44 -07001266 pc_trace_->Set(count_, pc);
Ian Rogersaaa20802011-09-11 21:47:37 -07001267 ++count_;
Elliott Hughes530fa002012-03-12 11:44:49 -07001268 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001269 }
1270
Ian Rogersaaa20802011-09-11 21:47:37 -07001271 jobject GetInternalStackTrace() const {
1272 return local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001273 }
1274
1275 private:
Elliott Hughes29f27422011-09-18 16:02:18 -07001276 // How many more frames to skip.
1277 int32_t skip_depth_;
Ian Rogersaaa20802011-09-11 21:47:37 -07001278 // Current position down stack trace
1279 uint32_t count_;
1280 // Array of return PC values
1281 IntArray* pc_trace_;
1282 // An array of the methods on the stack, the last entry is a reference to the
1283 // PC trace
1284 ObjectArray<Object>* method_trace_;
1285 // Local indirect reference table entry for method trace
1286 jobject local_ref_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001287};
1288
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001289// TODO: remove this.
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001290static uintptr_t ManglePc(uintptr_t pc) {
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001291 // Move the PC back 2 bytes as a call will frequently terminate the
1292 // decoding of a particular instruction and we want to make sure we
1293 // get the Dex PC of the instruction with the call and not the
1294 // instruction following.
1295 if (pc > 0) { pc -= 2; }
1296 return pc;
1297}
1298
1299// TODO: remove this.
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001300static uintptr_t DemanglePc(uintptr_t pc) {
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001301 // Revert mangling for the case where we need the PC to return to the upcall
Ian Rogers9a8a8882012-03-08 02:30:55 -08001302 if (pc > 0) { pc += 2; }
1303 return pc;
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001304}
Ian Rogersf57c47c2011-10-06 00:06:17 -07001305
Logan Chienf7ad17e2012-03-15 03:10:03 +08001306void Thread::PushShadowFrame(ShadowFrame* frame) {
1307 frame->SetLink(top_shadow_frame_);
1308 top_shadow_frame_ = frame;
1309}
1310
1311ShadowFrame* Thread::PopShadowFrame() {
1312 CHECK(top_shadow_frame_ != NULL);
1313 ShadowFrame* frame = top_shadow_frame_;
1314 top_shadow_frame_ = frame->GetLink();
1315 return frame;
1316}
1317
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001318void Thread::PushSirt(StackIndirectReferenceTable* sirt) {
1319 sirt->SetLink(top_sirt_);
1320 top_sirt_ = sirt;
1321}
1322
1323StackIndirectReferenceTable* Thread::PopSirt() {
1324 CHECK(top_sirt_ != NULL);
1325 StackIndirectReferenceTable* sirt = top_sirt_;
1326 top_sirt_ = top_sirt_->GetLink();
1327 return sirt;
1328}
1329
TDYa1279b2ba2e2012-03-19 10:12:32 -07001330#if !defined(ART_USE_LLVM_COMPILER) // LLVM use ShadowFrame
1331
Elliott Hughes530fa002012-03-12 11:44:49 -07001332void Thread::WalkStack(StackVisitor* visitor, bool include_upcalls) const {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001333 Frame frame = GetTopOfStack();
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001334 uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001335#if defined(__arm__)
1336 uint32_t trace_stack_depth = 0;
1337#endif
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001338 // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
1339 // CHECK(native_to_managed_record_ != NULL);
1340 NativeToManagedRecord* record = native_to_managed_record_;
1341
Elliott Hughes530fa002012-03-12 11:44:49 -07001342 while (frame.GetSP() != NULL) {
1343 for ( ; frame.GetMethod() != NULL; frame.Next()) {
Brian Carlstromf8bbb842012-03-14 03:01:42 -07001344 frame.GetMethod()->AssertPcIsWithinCode(pc);
Elliott Hughes530fa002012-03-12 11:44:49 -07001345 bool should_continue = visitor->VisitFrame(frame, pc);
1346 if (!should_continue) {
1347 return;
1348 }
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001349 pc = ManglePc(frame.GetReturnPC());
jeffhao2692b572011-12-16 15:42:28 -08001350 if (Runtime::Current()->IsMethodTracingActive()) {
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001351#if defined(__arm__)
1352 uintptr_t trace_exit = reinterpret_cast<uintptr_t>(art_trace_exit_from_code);
1353 if (ManglePc(trace_exit) == pc) {
1354 TraceStackFrame trace_frame = GetTraceStackFrame(trace_stack_depth++);
jeffhao26c0a1a2012-01-17 16:28:33 -08001355 CHECK(trace_frame.method_ == frame.GetMethod());
jeffhaoa9ef3fd2011-12-13 18:33:43 -08001356 pc = ManglePc(trace_frame.return_pc_);
1357 }
1358#endif
1359 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001360 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001361 if (include_upcalls) {
1362 bool should_continue = visitor->VisitFrame(frame, pc);
1363 if (!should_continue) {
1364 return;
1365 }
1366 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001367 if (record == NULL) {
Elliott Hughes530fa002012-03-12 11:44:49 -07001368 return;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001369 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001370 // last_tos should return Frame instead of sp?
Ian Rogersff1ed472011-09-20 13:46:24 -07001371 frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
Elliott Hughesa43cb5e2011-10-07 11:37:59 -07001372 pc = ManglePc(record->last_top_of_managed_stack_pc_);
Ian Rogersbdb03912011-09-14 00:55:44 -07001373 record = record->link_;
1374 }
1375}
1376
TDYa1279b2ba2e2012-03-19 10:12:32 -07001377#else // defined(ART_USE_LLVM_COMPILER) // LLVM uses ShadowFrame
1378
1379void Thread::WalkStack(StackVisitor* visitor, bool /*include_upcalls*/) const {
1380 for (ShadowFrame* cur = top_shadow_frame_; cur; cur = cur->GetLink()) {
1381 Frame frame;
1382 frame.SetSP(reinterpret_cast<Method**>(reinterpret_cast<byte*>(cur) +
1383 ShadowFrame::MethodOffset()));
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001384 bool should_continue = visitor->VisitFrame(frame, cur->GetLineNumber());
TDYa1279b2ba2e2012-03-19 10:12:32 -07001385 if (!should_continue) {
1386 return;
1387 }
1388 }
1389}
1390
1391/*
1392 * | |
1393 * | |
1394 * | |
1395 * | . |
1396 * | . |
1397 * | . |
1398 * | . |
1399 * | Method* |
1400 * | . |
1401 * | . | <-- top_shadow_frame_ (ShadowFrame*)
1402 * / +------------------------+
1403 * ->| . |
1404 * . | . |
1405 * . | . |
1406 * /+------------------------+
1407 * / | . |
1408 * / | . |
1409 * --- | | . |
1410 * | | | . |
1411 * | | Method* | <-- frame.GetSP() (Method**)
1412 * ShadowFrame \ | . |
1413 * | ->| . | <-- cur (ShadowFrame*)
1414 * --- /+------------------------+
1415 * / | . |
1416 * / | . |
1417 * --- | | . |
1418 * | cur->GetLink() | | . |
1419 * | | Method* |
1420 * ShadowFrame \ | . |
1421 * | ->| . |
1422 * --- +------------------------+
1423 * | . |
1424 * | . |
1425 * | . |
1426 * +========================+
1427 */
1428
1429#endif
1430
Elliott Hughes01158d72011-09-19 19:47:10 -07001431jobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
Ian Rogersaaa20802011-09-11 21:47:37 -07001432 // Compute depth of stack
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001433 CountStackDepthVisitor count_visitor;
1434 WalkStack(&count_visitor);
1435 int32_t depth = count_visitor.GetDepth();
Elliott Hughes29f27422011-09-18 16:02:18 -07001436 int32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07001437
Ian Rogersaaa20802011-09-11 21:47:37 -07001438 // Transition into runnable state to work on Object*/Array*
Elliott Hughes01158d72011-09-19 19:47:10 -07001439 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001440
1441 // Build internal stack trace
Ian Rogers77f74c12012-02-16 22:35:30 -08001442 BuildInternalStackTraceVisitor build_trace_visitor(skip_depth);
1443 if (!build_trace_visitor.Init(depth, ts)) {
Ian Rogers283ed0d2012-02-16 15:25:09 -08001444 return NULL; // Allocation failed
Ian Rogers283ed0d2012-02-16 15:25:09 -08001445 }
Brian Carlstrom26736442012-02-16 18:24:26 -08001446 WalkStack(&build_trace_visitor);
1447 return build_trace_visitor.GetInternalStackTrace();
Ian Rogersaaa20802011-09-11 21:47:37 -07001448}
1449
Elliott Hughes01158d72011-09-19 19:47:10 -07001450jobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
1451 jobjectArray output_array, int* stack_depth) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001452 // Transition into runnable state to work on Object*/Array*
1453 ScopedJniThreadState ts(env);
Ian Rogersaaa20802011-09-11 21:47:37 -07001454 // Decode the internal stack trace into the depth, method trace and PC trace
1455 ObjectArray<Object>* method_trace =
1456 down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
Ian Rogers9074b992011-10-26 17:41:55 -07001457 int32_t depth = method_trace->GetLength() - 1;
Ian Rogersaaa20802011-09-11 21:47:37 -07001458 IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1459
1460 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1461
Elliott Hughes01158d72011-09-19 19:47:10 -07001462 jobjectArray result;
1463 ObjectArray<StackTraceElement>* java_traces;
1464 if (output_array != NULL) {
1465 // Reuse the array we were given.
1466 result = output_array;
1467 java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
1468 output_array));
1469 // ...adjusting the number of frames we'll write to not exceed the array length.
1470 depth = std::min(depth, java_traces->GetLength());
1471 } else {
1472 // Create java_trace array and place in local reference table
1473 java_traces = class_linker->AllocStackTraceElementArray(depth);
Elliott Hughes30646832011-10-13 16:59:46 -07001474 if (java_traces == NULL) {
1475 return NULL;
1476 }
Elliott Hughes01158d72011-09-19 19:47:10 -07001477 result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
1478 }
1479
1480 if (stack_depth != NULL) {
1481 *stack_depth = depth;
1482 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001483
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001484 MethodHelper mh;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07001485 for (int32_t i = 0; i < depth; ++i) {
Ian Rogersaaa20802011-09-11 21:47:37 -07001486 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1487 Method* method = down_cast<Method*>(method_trace->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001488 mh.ChangeMethod(method);
Ian Rogersaaa20802011-09-11 21:47:37 -07001489 uint32_t native_pc = pc_trace->Get(i);
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001490#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001491 int32_t line_number = mh.GetLineNumFromNativePC(native_pc);
Shih-wei Liao02f01fe2012-03-26 12:58:11 -07001492#else
1493 int32_t line_number = native_pc; // LLVM stored line_number in the ShadowFrame
1494#endif
Ian Rogersaaa20802011-09-11 21:47:37 -07001495 // Allocate element, potentially triggering GC
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001496 // TODO: reuse class_name_object via Class::name_?
Ian Rogers48601312011-12-07 16:45:19 -08001497 const char* descriptor = mh.GetDeclaringClassDescriptor();
1498 CHECK(descriptor != NULL);
1499 std::string class_name(PrettyDescriptor(descriptor));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001500 SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
1501 if (class_name_object.get() == NULL) {
1502 return NULL;
1503 }
Ian Rogers48601312011-12-07 16:45:19 -08001504 const char* method_name = mh.GetName();
1505 CHECK(method_name != NULL);
1506 SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001507 if (method_name_object.get() == NULL) {
1508 return NULL;
1509 }
Ian Rogers48601312011-12-07 16:45:19 -08001510 const char* source_file = mh.GetDeclaringClassSourceFile();
1511 SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001512 StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001513 method_name_object.get(),
1514 source_name_object.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001515 line_number);
Elliott Hughes30646832011-10-13 16:59:46 -07001516 if (obj == NULL) {
1517 return NULL;
1518 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001519#ifdef MOVING_GARBAGE_COLLECTOR
1520 // Re-read after potential GC
1521 java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1522 method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1523 pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1524#endif
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001525 java_traces->Set(i, obj);
1526 }
Ian Rogersaaa20802011-09-11 21:47:37 -07001527 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001528}
1529
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001530void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001531 va_list args;
1532 va_start(args, fmt);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001533 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001534 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001535}
1536
1537void Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
1538 std::string msg;
1539 StringAppendV(&msg, fmt, ap);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001540 ThrowNewException(exception_class_descriptor, msg.c_str());
1541}
Elliott Hughes37f7a402011-08-22 18:56:01 -07001542
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001543void Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001544 // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001545 CHECK_EQ('L', exception_class_descriptor[0]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001546 std::string descriptor(exception_class_descriptor + 1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001547 CHECK_EQ(';', descriptor[descriptor.length() - 1]);
Elliott Hughese5b0dc82011-08-23 09:59:02 -07001548 descriptor.erase(descriptor.length() - 1);
1549
1550 JNIEnv* env = GetJniEnv();
Elliott Hughes726079d2011-10-07 18:43:44 -07001551 ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001552 if (exception_class.get() == NULL) {
1553 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
1554 << PrettyTypeOf(GetException());
1555 CHECK(IsExceptionPending());
1556 return;
1557 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001558 if (!Runtime::Current()->IsStarted()) {
1559 // Something is trying to throw an exception without a started
1560 // runtime, which is the common case in the compiler. We won't be
1561 // able to invoke the constructor of the exception, so use
1562 // AllocObject which will not invoke a constructor.
1563 ScopedLocalRef<jthrowable> exception(
1564 env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1565 if (exception.get() != NULL) {
1566 ScopedJniThreadState ts(env);
1567 Throwable* t = reinterpret_cast<Throwable*>(ts.Self()->DecodeJObject(exception.get()));
Ian Rogers02fbef02012-01-31 22:15:33 -08001568 t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
Brian Carlstromebd1fd22011-12-07 15:46:26 -08001569 ts.Self()->SetException(t);
1570 } else {
1571 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1572 << PrettyTypeOf(GetException());
1573 CHECK(IsExceptionPending());
1574 }
1575 return;
1576 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001577 int rc = env->ThrowNew(exception_class.get(), msg);
Elliott Hughes30646832011-10-13 16:59:46 -07001578 if (rc != JNI_OK) {
1579 LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
1580 << PrettyTypeOf(GetException());
1581 CHECK(IsExceptionPending());
Elliott Hughes30646832011-10-13 16:59:46 -07001582 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07001583}
1584
Elliott Hughes418dfe72011-10-06 18:56:27 -07001585void Thread::ThrowOutOfMemoryError(Class* c, size_t byte_count) {
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001586 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s", byte_count,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001587 PrettyDescriptor(c).c_str()));
Elliott Hughes2ced6a52011-10-16 18:44:48 -07001588 ThrowOutOfMemoryError(msg.c_str());
1589}
1590
1591void Thread::ThrowOutOfMemoryError(const char* msg) {
1592 LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
1593 msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
Elliott Hughes726079d2011-10-07 18:43:44 -07001594 if (!throwing_OutOfMemoryError_) {
1595 throwing_OutOfMemoryError_ = true;
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001596 ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001597 } else {
Elliott Hughes726079d2011-10-07 18:43:44 -07001598 SetException(pre_allocated_OutOfMemoryError_);
Elliott Hughes418dfe72011-10-06 18:56:27 -07001599 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001600 throwing_OutOfMemoryError_ = false;
Elliott Hughes79082e32011-08-25 12:07:32 -07001601}
1602
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001603
Elliott Hughes498508c2011-10-17 14:58:22 -07001604Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001605 return Thread::Current();
1606}
1607
1608void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001609 std::ostringstream ss;
1610 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08001611 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001612 // log to stderr for debugging command line processes
1613 std::cerr << str;
1614#ifdef HAVE_ANDROID_OS
1615 // log to logcat for debugging frameworks processes
1616 LOG(INFO) << str;
1617#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07001618}
1619
Ian Rogersbdb03912011-09-14 00:55:44 -07001620class CatchBlockStackVisitor : public Thread::StackVisitor {
1621 public:
1622 CatchBlockStackVisitor(Class* to_find, Context* ljc)
Elliott Hughes530fa002012-03-12 11:44:49 -07001623 : to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
Ian Rogers67375ac2011-09-14 00:55:44 -07001624#ifndef NDEBUG
1625 handler_pc_ = 0xEBADC0DE;
1626 handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
1627#endif
1628 }
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001629
Elliott Hughes530fa002012-03-12 11:44:49 -07001630 bool VisitFrame(const Frame& fr, uintptr_t pc) {
1631 Method* method = fr.GetMethod();
1632 if (method == NULL) {
1633 // This is the upcall, we remember the frame and last_pc so that we may
1634 // long jump to them
1635 handler_pc_ = DemanglePc(pc);
1636 handler_frame_ = fr;
1637 return false;
1638 }
1639 uint32_t dex_pc = DexFile::kDexNoIndex;
1640 if (method->IsCalleeSaveMethod()) {
1641 // ignore callee save method
1642 } else if (method->IsNative()) {
1643 native_method_count_++;
1644 } else {
1645 // Unwind stack during method tracing
1646 if (Runtime::Current()->IsMethodTracingActive()) {
jeffhaoe343b762011-12-05 16:36:44 -08001647#if defined(__arm__)
Elliott Hughes530fa002012-03-12 11:44:49 -07001648 uintptr_t trace_exit = reinterpret_cast<uintptr_t>(art_trace_exit_from_code);
1649 if (ManglePc(trace_exit) == pc) {
1650 pc = ManglePc(TraceMethodUnwindFromCode(Thread::Current()));
1651 }
jeffhaoe343b762011-12-05 16:36:44 -08001652#else
Elliott Hughes530fa002012-03-12 11:44:49 -07001653 UNIMPLEMENTED(WARNING);
jeffhaoe343b762011-12-05 16:36:44 -08001654#endif
Ian Rogers67375ac2011-09-14 00:55:44 -07001655 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001656 dex_pc = method->ToDexPC(pc);
1657 }
1658 if (dex_pc != DexFile::kDexNoIndex) {
1659 uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1660 if (found_dex_pc != DexFile::kDexNoIndex) {
1661 handler_pc_ = method->ToNativePC(found_dex_pc);
1662 handler_frame_ = fr;
1663 return false;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001664 }
1665 }
Elliott Hughes530fa002012-03-12 11:44:49 -07001666 // Caller may be handler, fill in callee saves in context
1667 long_jump_context_->FillCalleeSaves(fr);
1668 return true;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001669 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001670
Ian Rogersbdb03912011-09-14 00:55:44 -07001671 // The type of the exception catch block to find
1672 Class* to_find_;
1673 // Frame with found handler or last frame if no handler found
1674 Frame handler_frame_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001675 // PC to branch to for the handler
1676 uintptr_t handler_pc_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001677 // Context that will be the target of the long jump
1678 Context* long_jump_context_;
Ian Rogers67375ac2011-09-14 00:55:44 -07001679 // Number of native methods passed in crawl (equates to number of SIRTs to pop)
1680 uint32_t native_method_count_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001681};
1682
Ian Rogersff1ed472011-09-20 13:46:24 -07001683void Thread::DeliverException() {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001684 const bool kDebugExceptionDelivery = false;
Elliott Hughesd07986f2011-12-06 18:27:45 -08001685 Throwable* exception = GetException(); // Get exception from thread
Ian Rogersff1ed472011-09-20 13:46:24 -07001686 CHECK(exception != NULL);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001687 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08001688 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001689 ClearException();
1690 if (kDebugExceptionDelivery) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -08001691 String* msg = exception->GetDetailMessage();
1692 std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1693 DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
1694 << ": " << str_msg << std::endl);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001695 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001696
1697 Context* long_jump_context = GetLongJumpContext();
1698 CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
Elliott Hughes530fa002012-03-12 11:44:49 -07001699 WalkStack(&catch_finder, true);
Ian Rogersbdb03912011-09-14 00:55:44 -07001700
Elliott Hughesd07986f2011-12-06 18:27:45 -08001701 Method** sp;
1702 uintptr_t throw_native_pc;
1703 Method* throw_method = GetCurrentMethod(&throw_native_pc, &sp);
1704 uintptr_t catch_native_pc = catch_finder.handler_pc_;
1705 Method* catch_method = catch_finder.handler_frame_.GetMethod();
1706 Dbg::PostException(sp, throw_method, throw_native_pc, catch_method, catch_native_pc, exception);
1707
Ian Rogers28ad40d2011-10-27 15:19:26 -07001708 if (kDebugExceptionDelivery) {
Elliott Hughesd07986f2011-12-06 18:27:45 -08001709 if (catch_method == NULL) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001710 LOG(INFO) << "Handler is upcall";
1711 } else {
1712 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1713 const DexFile& dex_file =
Elliott Hughesd07986f2011-12-06 18:27:45 -08001714 class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1715 int line_number = dex_file.GetLineNumFromPC(catch_method,
1716 catch_method->ToDexPC(catch_finder.handler_pc_));
1717 LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
Ian Rogers28ad40d2011-10-27 15:19:26 -07001718 }
1719 }
1720 SetException(exception);
Ian Rogers9a8a8882012-03-08 02:30:55 -08001721 CHECK_NE(catch_native_pc, 0u);
Elliott Hughesd07986f2011-12-06 18:27:45 -08001722 long_jump_context->SetSP(reinterpret_cast<uintptr_t>(catch_finder.handler_frame_.GetSP()));
Ian Rogers9a8a8882012-03-08 02:30:55 -08001723 long_jump_context->SetPC(catch_native_pc);
Ian Rogersbdb03912011-09-14 00:55:44 -07001724 long_jump_context->DoLongJump();
Ian Rogers9a8a8882012-03-08 02:30:55 -08001725 LOG(FATAL) << "UNREACHABLE";
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001726}
1727
Ian Rogersbdb03912011-09-14 00:55:44 -07001728Context* Thread::GetLongJumpContext() {
Elliott Hughes85d15452011-09-16 17:33:01 -07001729 Context* result = long_jump_context_;
Ian Rogersbdb03912011-09-14 00:55:44 -07001730 if (result == NULL) {
1731 result = Context::Create();
Elliott Hughes85d15452011-09-16 17:33:01 -07001732 long_jump_context_ = result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001733 }
Ian Rogersbdb03912011-09-14 00:55:44 -07001734 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07001735}
1736
Elliott Hughesd07986f2011-12-06 18:27:45 -08001737Method* Thread::GetCurrentMethod(uintptr_t* pc, Method*** sp) const {
1738 Frame f = top_of_managed_stack_;
1739 Method* m = f.GetMethod();
Elliott Hughes8be2d402012-02-23 14:22:41 -08001740 uintptr_t native_pc = top_of_managed_stack_pc_;
1741
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001742 // We use JNI internally for exception throwing, so it's possible to arrive
1743 // here via a "FromCode" function, in which case there's a synthetic
1744 // callee-save method at the top of the stack. These shouldn't be user-visible,
1745 // so if we find one, skip it and return the compiled method underneath.
jeffhao33dc7712011-11-09 17:54:24 -08001746 if (m != NULL && m->IsCalleeSaveMethod()) {
Elliott Hughes8be2d402012-02-23 14:22:41 -08001747 native_pc = f.GetReturnPC();
Elliott Hughes9fd66f52011-10-16 12:13:26 -07001748 f.Next();
1749 m = f.GetMethod();
1750 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001751 if (pc != NULL) {
Elliott Hughes8be2d402012-02-23 14:22:41 -08001752 *pc = (m != NULL) ? ManglePc(native_pc) : 0;
jeffhao33dc7712011-11-09 17:54:24 -08001753 }
Elliott Hughesd07986f2011-12-06 18:27:45 -08001754 if (sp != NULL) {
1755 *sp = f.GetSP();
1756 }
1757 return m;
jeffhao33dc7712011-11-09 17:54:24 -08001758}
1759
Elliott Hughes5f791332011-09-15 17:45:30 -07001760bool Thread::HoldsLock(Object* object) {
1761 if (object == NULL) {
1762 return false;
1763 }
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07001764 return object->GetThinLockId() == thin_lock_id_;
Elliott Hughes5f791332011-09-15 17:45:30 -07001765}
1766
Elliott Hughes038a8062011-09-18 14:12:41 -07001767bool Thread::IsDaemon() {
1768 return gThread_daemon->GetBoolean(peer_);
1769}
1770
Ian Rogersd6b1f612011-09-27 13:38:14 -07001771class ReferenceMapVisitor : public Thread::StackVisitor {
1772 public:
1773 ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1774 context_(context), root_visitor_(root_visitor), arg_(arg) {
1775 }
1776
Elliott Hughes530fa002012-03-12 11:44:49 -07001777 bool VisitFrame(const Frame& frame, uintptr_t pc) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001778 Method* m = frame.GetMethod();
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001779 if (false) {
jeffhao25045522012-03-13 19:34:37 -07001780 LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m)
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001781 << StringPrintf("@ PC:%04x", m->ToDexPC(pc));
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07001782 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001783 // Process register map (which native and callee save methods don't have)
Ian Rogers3891c772011-12-06 15:38:28 -08001784 if (!m->IsNative() && !m->IsCalleeSaveMethod() && !m->IsProxyMethod()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001785 CHECK(m->GetGcMap() != NULL) << PrettyMethod(m);
1786 CHECK_NE(0U, m->GetGcMapLength()) << PrettyMethod(m);
1787 verifier::PcToReferenceMap map(m->GetGcMap(), m->GetGcMapLength());
Ian Rogersd81871c2011-10-03 13:57:23 -07001788 const uint8_t* reg_bitmap = map.FindBitMap(m->ToDexPC(pc));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001789 CHECK(reg_bitmap != NULL);
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001790 const VmapTable vmap_table(m->GetVmapTableRaw());
Elliott Hughes11d1b0c2012-01-23 16:57:47 -08001791 const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001792 DCHECK(code_item != NULL); // can't be NULL or how would we compile its instructions?
1793 uint32_t core_spills = m->GetCoreSpillMask();
1794 uint32_t fp_spills = m->GetFpSpillMask();
1795 size_t frame_size = m->GetFrameSizeInBytes();
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001796 // For all dex registers in the bitmap
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001797 size_t num_regs = std::min(map.RegWidth() * 8,
1798 static_cast<size_t>(code_item->registers_size_));
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001799 for (size_t reg = 0; reg < num_regs; ++reg) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001800 // Does this register hold a reference?
1801 if (TestBitmap(reg, reg_bitmap)) {
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001802 uint32_t vmap_offset;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001803 Object* ref;
Elliott Hughes68fdbd02011-11-29 19:22:47 -08001804 if (vmap_table.IsInContext(reg, vmap_offset)) {
Ian Rogersd6b1f612011-09-27 13:38:14 -07001805 // Compute the register we need to load from the context
1806 uint32_t spill_mask = m->GetCoreSpillMask();
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001807 CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
Ian Rogersf57c47c2011-10-06 00:06:17 -07001808 uint32_t matches = 0;
1809 uint32_t spill_shifts = 0;
1810 while (matches != (vmap_offset + 1)) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -07001811 DCHECK_NE(spill_mask, 0u);
Ian Rogersf57c47c2011-10-06 00:06:17 -07001812 matches += spill_mask & 1; // Add 1 if the low bit is set
1813 spill_mask >>= 1;
1814 spill_shifts++;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001815 }
Ian Rogersf57c47c2011-10-06 00:06:17 -07001816 spill_shifts--; // wind back one as we want the last match
1817 ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001818 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001819 ref = reinterpret_cast<Object*>(frame.GetVReg(code_item, core_spills, fp_spills,
1820 frame_size, reg));
Ian Rogersd6b1f612011-09-27 13:38:14 -07001821 }
Shih-wei Liao4f894e32011-09-27 21:33:19 -07001822 if (ref != NULL) {
1823 root_visitor_(ref, arg_);
1824 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07001825 }
1826 }
1827 }
1828 context_->FillCalleeSaves(frame);
Elliott Hughes530fa002012-03-12 11:44:49 -07001829 return true;
Ian Rogersd6b1f612011-09-27 13:38:14 -07001830 }
1831
1832 private:
1833 bool TestBitmap(int reg, const uint8_t* reg_vector) {
1834 return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1835 }
1836
1837 // Context used to build up picture of callee saves
1838 Context* context_;
1839 // Call-back when we visit a root
1840 Heap::RootVisitor* root_visitor_;
1841 // Argument to call-back
1842 void* arg_;
1843};
1844
1845void Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001846 if (exception_ != NULL) {
1847 visitor(exception_, arg);
1848 }
1849 if (peer_ != NULL) {
1850 visitor(peer_, arg);
1851 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001852 if (pre_allocated_OutOfMemoryError_ != NULL) {
1853 visitor(pre_allocated_OutOfMemoryError_, arg);
1854 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001855 if (class_loader_override_ != NULL) {
1856 visitor(class_loader_override_, arg);
1857 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07001858 jni_env_->locals.VisitRoots(visitor, arg);
1859 jni_env_->monitors.VisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001860
1861 SirtVisitRoots(visitor, arg);
Logan Chienf7ad17e2012-03-15 03:10:03 +08001862 ShadowFrameVisitRoots(visitor, arg);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07001863
Ian Rogersd6b1f612011-09-27 13:38:14 -07001864 // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1865 // delivery.
1866 Context* context = GetLongJumpContext();
1867 // Visit roots on this thread's stack
1868 ReferenceMapVisitor mapper(context, visitor, arg);
1869 WalkStack(&mapper);
Elliott Hughes410c0c82011-09-01 17:58:25 -07001870}
1871
jeffhao25045522012-03-13 19:34:37 -07001872#if VERIFY_OBJECT_ENABLED
Elliott Hughesab7b9dc2012-03-27 13:16:29 -07001873static void VerifyObject(const Object* obj, void*) {
jeffhao25045522012-03-13 19:34:37 -07001874 Runtime::Current()->GetHeap()->VerifyObject(obj);
1875}
1876
1877void Thread::VerifyStack() {
jeffhaoe66ac792012-03-19 16:08:46 -07001878 UniquePtr<Context> context(Context::Create());
1879 ReferenceMapVisitor mapper(context.get(), VerifyObject, NULL);
jeffhao25045522012-03-13 19:34:37 -07001880 WalkStack(&mapper);
1881}
1882#endif
1883
Ian Rogersb033c752011-07-20 12:22:35 -07001884static const char* kStateNames[] = {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001885 "Terminated",
Ian Rogersb033c752011-07-20 12:22:35 -07001886 "Runnable",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001887 "TimedWaiting",
Ian Rogersb033c752011-07-20 12:22:35 -07001888 "Blocked",
1889 "Waiting",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001890 "Initializing",
1891 "Starting",
Ian Rogersb033c752011-07-20 12:22:35 -07001892 "Native",
Elliott Hughes93e74e82011-09-13 11:07:03 -07001893 "VmWait",
1894 "Suspended",
Ian Rogersb033c752011-07-20 12:22:35 -07001895};
1896std::ostream& operator<<(std::ostream& os, const Thread::State& state) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001897 int32_t int_state = static_cast<int32_t>(state);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001898 if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
1899 os << kStateNames[int_state];
Ian Rogersb033c752011-07-20 12:22:35 -07001900 } else {
Elliott Hughes93e74e82011-09-13 11:07:03 -07001901 os << "State[" << int_state << "]";
Ian Rogersb033c752011-07-20 12:22:35 -07001902 }
1903 return os;
1904}
1905
Elliott Hughes330304d2011-08-12 14:28:05 -07001906std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Elliott Hughes899e7892012-01-24 14:57:32 -08001907 thread.Dump(os, false);
Elliott Hughes330304d2011-08-12 14:28:05 -07001908 return os;
1909}
1910
Elliott Hughesa4060e52012-03-02 16:51:35 -08001911void Thread::CheckSafeToLockOrUnlock(MutexRank rank, bool is_locking) {
Elliott Hughesffb465f2012-03-01 18:46:05 -08001912 if (is_locking) {
1913 if (held_mutexes_[rank] == 0) {
1914 bool bad_mutexes_held = false;
1915 for (int i = kMaxMutexRank; i > rank; --i) {
1916 if (held_mutexes_[i] != 0) {
1917 LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while " << (is_locking ? "locking" : "unlocking") << " " << rank;
1918 bad_mutexes_held = true;
1919 }
1920 }
1921 CHECK(!bad_mutexes_held);
1922 }
1923 ++held_mutexes_[rank];
1924 } else {
1925 CHECK_GT(held_mutexes_[rank], 0U);
1926 --held_mutexes_[rank];
1927 }
1928}
1929
Elliott Hughesa4060e52012-03-02 16:51:35 -08001930void Thread::CheckSafeToWait(MutexRank rank) {
1931 bool bad_mutexes_held = false;
1932 for (int i = kMaxMutexRank; i >= 0; --i) {
1933 if (i != rank && held_mutexes_[i] != 0) {
1934 LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while doing condition variable wait on " << rank;
1935 bad_mutexes_held = true;
1936 }
1937 }
1938 if (held_mutexes_[rank] == 0) {
1939 LOG(ERROR) << "*not* holding " << rank << " while doing condition variable wait on it";
1940 bad_mutexes_held = true;
1941 }
1942 CHECK(!bad_mutexes_held);
1943}
1944
Elliott Hughes8daa0922011-09-11 13:46:25 -07001945} // namespace art