thread.cc revision 530fa005e2944d3b12712f80d974f0e753f568ef
18d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes/*
28d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * Copyright (C) 2011 The Android Open Source Project
38d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes *
48d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * Licensed under the Apache License, Version 2.0 (the "License");
58d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * you may not use this file except in compliance with the License.
68d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * You may obtain a copy of the License at
78d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes *
88d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes *      http://www.apache.org/licenses/LICENSE-2.0
98d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes *
108d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * Unless required by applicable law or agreed to in writing, software
118d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * distributed under the License is distributed on an "AS IS" BASIS,
128d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
138d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * See the License for the specific language governing permissions and
148d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes * limitations under the License.
158d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes */
16b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
17578bbdc684db8ed68e9fedbc678669d27fa68b6eBrian Carlstrom#include "thread.h"
18b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
198d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes#include <dynamic_annotations.h>
20b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers#include <pthread.h>
21b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers#include <sys/mman.h>
22dbf05b722af99ba2fd2f4c4fc7eb6c3e9880e5d1Brian Carlstrom#include <sys/resource.h>
23dbf05b722af99ba2fd2f4c4fc7eb6c3e9880e5d1Brian Carlstrom#include <sys/time.h>
24a09576416788b916095739e43a16917e7948f3a4Elliott Hughes
25b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro#include <algorithm>
26dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes#include <bitset>
27eb4f614f2eb53b92ebd416fa418f550861655887Elliott Hughes#include <cerrno>
28a09576416788b916095739e43a16917e7948f3a4Elliott Hughes#include <iostream>
29b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro#include <list>
30b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
31872d4ec7225444d9400d30f9027247deb91012fdElliott Hughes#include "debugger.h"
32a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes#include "class_linker.h"
33df143242f4beaad4cc9fbabebfc033b68c40964eBrian Carlstrom#include "class_loader.h"
34bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers#include "context.h"
35d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers#include "dex_verifier.h"
36408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers#include "heap.h"
37c5f7c91ab89055cffb573fff7e06dbdd860bccedElliott Hughes#include "jni_internal.h"
388e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes#include "monitor.h"
39a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes#include "object.h"
406d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers#include "object_utils.h"
419a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson#include "reflection.h"
42578bbdc684db8ed68e9fedbc678669d27fa68b6eBrian Carlstrom#include "runtime.h"
435433072f589b61413e042eddf76e8190a048f71dbuzbee#include "runtime_support.h"
44726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes#include "ScopedLocalRef.h"
45aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#include "scoped_jni_thread_state.h"
4630fab40ee5a07af6b8c3b6b0e9438071695a57f4Ian Rogers#include "space.h"
4768e76526e98432625464022cb26f66b9ef6f5af4Elliott Hughes#include "stack.h"
4868e76526e98432625464022cb26f66b9ef6f5af4Elliott Hughes#include "stack_indirect_reference_table.h"
498daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes#include "thread_list.h"
50a09576416788b916095739e43a16917e7948f3a4Elliott Hughes#include "utils.h"
51b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
52b557353b22c728eecbd1c68593b482622c7782a8Carl Shapironamespace art {
53b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
54b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiropthread_key_t Thread::pthread_key_self_;
55b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
568e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesstatic Class* gThreadLock = NULL;
57038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_daemon = NULL;
58038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_group = NULL;
59038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_lock = NULL;
60038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_name = NULL;
61038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_priority = NULL;
6229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughesstatic Field* gThread_uncaughtHandler = NULL;
63038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_vmData = NULL;
64038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThreadGroup_name = NULL;
658e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesstatic Field* gThreadLock_thread = NULL;
66038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Method* gThread_run = NULL;
6729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughesstatic Method* gThreadGroup_removeThread = NULL;
6829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughesstatic Method* gUncaughtExceptionHandler_uncaughtException = NULL;
69038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
705d76c435082332ef79a22962386fa92a0870e378Ian Rogersvoid Thread::InitCardTable() {
71b3bd5f07884f5a1f2b84224363b1372d7c28d447Elliott Hughes  card_table_ = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
725d76c435082332ef79a22962386fa92a0870e378Ian Rogers}
735d76c435082332ef79a22962386fa92a0870e378Ian Rogers
743ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbeevoid Thread::InitFunctionPointers() {
7511f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee#if defined(__mips)
7611f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pShlLong = art_shl_long;
7711f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pShrLong = art_shr_long;
7811f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pUshrLong = art_ushr_long;
7911f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pI2f = __floatsisf;
8011f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pF2iz = __fixsfi;
8111f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pD2f = __truncdfsf2;
8211f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pF2d = __extendsfdfs;
8311f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pD2iz = __fixdfsi;
8411f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pL2f = __floatdisf;
8511f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pL2d = __floatdidf;
8611f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pFadd = __addsf3;
8711f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pFsub = __subsf3;
8811f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pFdiv = divsf3;
8911f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pFmul = __mulsf3;
9011f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pFmodf = fmodf;
9111f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pDadd = __adddf3;
9211f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pDsub = __subdf3;
9311f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pDdiv = __divdf3;
9411f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pDmul = muldf3;
9511f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee  pFmod = fmod;
960ece7b950dc5821e79c930acf31fb7e73c570849Elliott Hughes  pCmpgFloat = CmpgFloat;
970ece7b950dc5821e79c930acf31fb7e73c570849Elliott Hughes  pCmplFloat = CmplFloat;
980ece7b950dc5821e79c930acf31fb7e73c570849Elliott Hughes  pCmpgDouble = CmpgDouble;
990ece7b950dc5821e79c930acf31fb7e73c570849Elliott Hughes  pCmplDouble = CmplDouble;
10011f9d2130e938511efceb6d2a4793cee7dfdde35Bill Buzbee#endif
1015433072f589b61413e042eddf76e8190a048f71dbuzbee#if defined(__arm__)
1025433072f589b61413e042eddf76e8190a048f71dbuzbee  pShlLong = art_shl_long;
1035433072f589b61413e042eddf76e8190a048f71dbuzbee  pShrLong = art_shr_long;
1045433072f589b61413e042eddf76e8190a048f71dbuzbee  pUshrLong = art_ushr_long;
1057b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pIdiv = __aeabi_idiv;
1067b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pIdivmod = __aeabi_idivmod;
1077b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pI2f = __aeabi_i2f;
1087b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pF2iz = __aeabi_f2iz;
1097b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pD2f = __aeabi_d2f;
1107b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pF2d = __aeabi_f2d;
1117b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pD2iz = __aeabi_d2iz;
1127b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pL2f = __aeabi_l2f;
1137b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pL2d = __aeabi_l2d;
1147b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFadd = __aeabi_fadd;
1157b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFsub = __aeabi_fsub;
1167b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFdiv = __aeabi_fdiv;
1177b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFmul = __aeabi_fmul;
1187b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFmodf = fmodf;
1197b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pDadd = __aeabi_dadd;
1207b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pDsub = __aeabi_dsub;
1217b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pDdiv = __aeabi_ddiv;
1227b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pDmul = __aeabi_dmul;
1237b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFmod = fmod;
1247b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pLdivmod = __aeabi_ldivmod;
125439c4fa0db980fb19e4a585723a64a3461e4c278buzbee  pLmul = __aeabi_lmul;
126b408de744566a5c5a80be1ba7f5c88407e816945Elliott Hughes  pAllocArrayFromCode = art_alloc_array_from_code;
1270eb7d7e2a0c2767b5fd86bd52436c618fd4c3120Ian Rogers  pAllocArrayFromCodeWithAccessCheck = art_alloc_array_from_code_with_access_check;
1286fd03fb67e4628689f0abf34edeacc0e35b6295eBrian Carlstrom  pAllocObjectFromCode = art_alloc_object_from_code;
12928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  pAllocObjectFromCodeWithAccessCheck = art_alloc_object_from_code_with_access_check;
130e51a511ccee3f3c0120807321bcc160fcaa664beIan Rogers  pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
131b408de744566a5c5a80be1ba7f5c88407e816945Elliott Hughes  pCheckAndAllocArrayFromCode = art_check_and_alloc_array_from_code;
1320eb7d7e2a0c2767b5fd86bd52436c618fd4c3120Ian Rogers  pCheckAndAllocArrayFromCodeWithAccessCheck = art_check_and_alloc_array_from_code_with_access_check;
133ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pCheckCastFromCode = art_check_cast_from_code;
1341bddec3a6521f16df37499754000a3b1787a52e9Ian Rogers  pGet32Instance = art_get32_instance_from_code;
1351bddec3a6521f16df37499754000a3b1787a52e9Ian Rogers  pGet64Instance = art_get64_instance_from_code;
1361bddec3a6521f16df37499754000a3b1787a52e9Ian Rogers  pGetObjInstance = art_get_obj_instance_from_code;
137ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pGet32Static = art_get32_static_from_code;
138ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pGet64Static = art_get64_static_from_code;
139ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pGetObjStatic = art_get_obj_static_from_code;
140ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
141cbba6ac9bf9a6c630a7aafae6d8767b5ddbb6fd5Ian Rogers  pInitializeStaticStorage = art_initialize_static_storage_from_code;
14228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  pInitializeTypeFromCode = art_initialize_type_from_code;
143b093c6b27f8ea9bbe2d49c03ebe345203a121199Ian Rogers  pInitializeTypeAndVerifyAccessFromCode = art_initialize_type_and_verify_access_from_code;
144c8b306f5221658c7e4b5516be8917dc8c9288e7eIan Rogers  pInvokeDirectTrampolineWithAccessCheck = art_invoke_direct_trampoline_with_access_check;
1454a3164faefd255b1c1e911e7ad7c3d57749caaf6buzbee  pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
146a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers  pInvokeInterfaceTrampolineWithAccessCheck = art_invoke_interface_trampoline_with_access_check;
147c8b306f5221658c7e4b5516be8917dc8c9288e7eIan Rogers  pInvokeStaticTrampolineWithAccessCheck = art_invoke_static_trampoline_with_access_check;
148a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers  pInvokeSuperTrampolineWithAccessCheck = art_invoke_super_trampoline_with_access_check;
149a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers  pInvokeVirtualTrampolineWithAccessCheck = art_invoke_virtual_trampoline_with_access_check;
1506fd03fb67e4628689f0abf34edeacc0e35b6295eBrian Carlstrom  pLockObjectFromCode = art_lock_object_from_code;
1516fd03fb67e4628689f0abf34edeacc0e35b6295eBrian Carlstrom  pResolveStringFromCode = art_resolve_string_from_code;
1521bddec3a6521f16df37499754000a3b1787a52e9Ian Rogers  pSet32Instance = art_set32_instance_from_code;
1531bddec3a6521f16df37499754000a3b1787a52e9Ian Rogers  pSet64Instance = art_set64_instance_from_code;
1541bddec3a6521f16df37499754000a3b1787a52e9Ian Rogers  pSetObjInstance = art_set_obj_instance_from_code;
155ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pSet32Static = art_set32_static_from_code;
156ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pSet64Static = art_set64_static_from_code;
157ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pSetObjStatic = art_set_obj_static_from_code;
1586fd03fb67e4628689f0abf34edeacc0e35b6295eBrian Carlstrom  pTestSuspendFromCode = art_test_suspend;
159ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
160ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pThrowDivZeroFromCode = art_throw_div_zero_from_code;
161c0c8dc8e677957d167066a2d06973126f108a6aaIan Rogers  pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
162c0c8dc8e677957d167066a2d06973126f108a6aaIan Rogers  pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
163ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
164932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
165c0c8dc8e677957d167066a2d06973126f108a6aaIan Rogers  pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
166ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pUnlockObjectFromCode = art_unlock_object_from_code;
16744b412bb795fa6999129b2bc16f5eec1ea97e8f8buzbee  pUpdateDebuggerFromCode = NULL;  // To enable, set to art_update_debugger
16867375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers#endif
169c396efc1baec875160afe34a3e65c46cce2bd72fbuzbee  pF2l = F2L;
170c396efc1baec875160afe34a3e65c46cce2bd72fbuzbee  pD2l = D2L;
1713ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbee  pMemcpy = memcpy;
1724a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pCheckSuspendFromCode = CheckSuspendFromCode;
1734a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pDebugMe = DebugMe;
1744a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pDecodeJObjectInThread = DecodeJObjectInThread;
1754a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pDeliverException = art_deliver_exception_from_code;
1764a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pFindNativeMethod = FindNativeMethod;
177caab8c4ef372db5c119bfac1911fa27b174a935cIan Rogers  pInstanceofNonTrivialFromCode = IsAssignableFromCode;
1784a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
1794a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pUnresolvedDirectMethodTrampolineFromCode = UnresolvedDirectMethodTrampolineFromCode;
1803ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbee}
1813ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbee
182caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstromvoid Thread::InitTid() {
183caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  tid_ = ::art::GetTid();
184caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom}
185caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom
186caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstromvoid Thread::InitAfterFork() {
187caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  InitTid();
1883147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes#if defined(__BIONIC__)
1893147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  // Work around a bionic bug.
1903147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  struct bionic_pthread_internal_t {
1913147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    void*  next;
1923147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    void** pref;
1933147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    pthread_attr_t attr;
1943147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    pid_t kernel_id;
1953147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    // et cetera. we just need 'kernel_id' so we can stop here.
1963147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  };
1973147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  reinterpret_cast<bionic_pthread_internal_t*>(pthread_self())->kernel_id = tid_;
1983147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes#endif
199caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom}
200caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom
20178128a63b2615744760b7f8ab83df9764a5d4a95Brian Carlstromvoid* Thread::CreateCallback(void* arg) {
20293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Thread* self = reinterpret_cast<Thread*>(arg);
20393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Runtime* runtime = Runtime::Current();
20493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
20593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  self->Attach(runtime);
20693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
20793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Wait until it's safe to start running code. (There may have been a suspend-all
20893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // in progress while we were starting up.)
20993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  runtime->GetThreadList()->WaitForGo();
21093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
21147179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes  {
21247179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_EQ(self->GetState(), Thread::kRunnable);
213899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    SirtRef<String> thread_name(self->GetThreadName());
214899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    self->SetThreadName(thread_name->ToModifiedUtf8().c_str());
21547179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes  }
21647179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes
217872d4ec7225444d9400d30f9027247deb91012fdElliott Hughes  Dbg::PostThreadStart(self);
21893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
21993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Invoke the 'run' method of our java.lang.Thread.
22093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  CHECK(self->peer_ != NULL);
22193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Object* receiver = self->peer_;
222038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
22393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  m->Invoke(self, receiver, NULL, NULL);
22493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
22593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Detach.
22693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  runtime->GetThreadList()->Unregister();
22793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
228b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  return NULL;
229b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
230b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
23193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughesvoid SetVmData(Object* managed_thread, Thread* native_thread) {
232038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
23393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
23493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
235761928d24e4e7ed7776b52243eaf9095ad35f448Elliott HughesThread* Thread::FromManagedThread(Object* thread_peer) {
236761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes  return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread_peer)));
237761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes}
238761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes
23901158d7a57c8321370667a6045220237d16e0da8Elliott HughesThread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
240761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes  return FromManagedThread(Decode<Object*>(env, java_thread));
24101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes}
24201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
2437502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughessize_t FixStackSize(size_t stack_size) {
2447502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // A stack size of zero means "use the default".
245d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (stack_size == 0) {
246d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    stack_size = Runtime::Current()->GetDefaultStackSize();
247d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
24861e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
2497502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
2507502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  if (stack_size < PTHREAD_STACK_MIN) {
2517502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes    stack_size = PTHREAD_STACK_MIN;
2527502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  }
2537502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2547502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // It's likely that callers are trying to ensure they have at least a certain amount of
2557502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // stack space, so we should add our reserved space on top of what they requested, rather
2567502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // than implicitly take it away from them.
2577502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size += Thread::kStackOverflowReservedBytes;
2587502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2597502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // Some systems require the stack size to be a multiple of the system page size, so round up.
2607502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size = RoundUp(stack_size, kPageSize);
2617502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2627502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  return stack_size;
2637502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes}
2647502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2657502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughesvoid Thread::Create(Object* peer, size_t stack_size) {
2667502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  CHECK(peer != NULL);
2677502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2687502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size = FixStackSize(stack_size);
2697502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
27093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Thread* native_thread = new Thread;
27193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  native_thread->peer_ = peer;
27293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
27393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Thread.start is synchronized, so we know that vmData is 0,
27493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // and know that we're not racing to assign it.
27593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  SetVmData(peer, native_thread);
27661e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
27747179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes  {
27847179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
27947179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    pthread_t new_pthread;
28047179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    pthread_attr_t attr;
28147179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
28247179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
28347179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
28447179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_PTHREAD_CALL(pthread_create, (&new_pthread, &attr, Thread::CreateCallback, native_thread), "new thread");
28547179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
28647179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes  }
28761e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
28893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Let the child know when it's safe to start running.
28993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Runtime::Current()->GetThreadList()->SignalGo(native_thread);
29093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
29161e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
29293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughesvoid Thread::Attach(const Runtime* runtime) {
293cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  CHECK(Thread::Current() == NULL);
294cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes
29593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitCpu();
29693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitFunctionPointers();
2975d76c435082332ef79a22962386fa92a0870e378Ian Rogers  InitCardTable();
29861e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
29993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
300be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
301caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  InitTid();
30293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitStackHwm();
303dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes
3043147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
305a5780dad67556297c8ca5f2608c53b193e6c4514Elliott Hughes
30693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
3075fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
3087a3aeb4d7580164c6a6905c63b96823b77ff5a64Elliott Hughes  runtime->GetThreadList()->Register();
30993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
31093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
31193e74e8d879270071c3aa163f8495ada8d21f42fElliott HughesThread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
312cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  Thread* self = new Thread;
313cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  self->Attach(runtime);
3145fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
315cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  self->SetState(Thread::kNative);
316726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes
317cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  // If we're the main thread, ClassLinker won't be created until after we're attached,
318cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  // so that thread needs a two-stage attach. Regular threads don't need this hack.
319d9c67be7c116875d96b31e640ad47d587b205605Elliott Hughes  // In the compiler, all threads need this hack, because no-one's going to be getting
320d9c67be7c116875d96b31e640ad47d587b205605Elliott Hughes  // a native peer!
321d9c67be7c116875d96b31e640ad47d587b205605Elliott Hughes  if (self->thin_lock_id_ != ThreadList::kMainId && !Runtime::Current()->IsCompiler()) {
322cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes    self->CreatePeer(name, as_daemon);
32306e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  } else {
32406e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
32506e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    self->name_->assign(name);
32606e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    ::art::SetThreadName(name);
32736e0a955e48e9357bff1eab783e493107ebfff62Ian Rogers  }
328cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes
329cac6cc72c3331257fa6437b36a131e5d551e2f3cElliott Hughes  self->GetJniEnv()->locals.AssertEmpty();
3305fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  return self;
3315fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes}
3325fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
333d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughesjobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
334726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jclass> thread_group_class(env, env->FindClass("java/lang/ThreadGroup"));
335726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  jfieldID fid = env->GetStaticFieldID(thread_group_class.get(), field_name, "Ljava/lang/ThreadGroup;");
336726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  return env->GetStaticObjectField(thread_group_class.get(), fid);
337d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes}
338d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
3395fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughesvoid Thread::CreatePeer(const char* name, bool as_daemon) {
3409a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  CHECK(Runtime::Current()->IsStarted());
3415fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  JNIEnv* env = jni_env_;
3425fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
343d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
344726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jobject> thread_group(env, GetWellKnownThreadGroup(env, field_name));
345726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
3468daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes  jint thread_priority = GetNativePriority();
3475fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  jboolean thread_is_daemon = as_daemon;
3485fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
349726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/Thread"));
3505d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers  ScopedLocalRef<jobject> peer(env, env->AllocObject(c.get()));
351726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  peer_ = DecodeJObject(peer.get());
3525d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers  if (peer_ == NULL) {
3535d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers    CHECK(IsExceptionPending());
3545d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers    return;
3555d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers  }
3565d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers  jmethodID mid = env->GetMethodID(c.get(), "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
3575d4bdc29737a693027daaf6ed3f0792368eb4baeIan Rogers  env->CallNonvirtualVoidMethod(peer.get(), c.get(), mid, thread_group.get(), thread_name.get(), thread_priority, thread_is_daemon);
3589a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  CHECK(!IsExceptionPending()) << " " << PrettyTypeOf(GetException());
3597a3aeb4d7580164c6a6905c63b96823b77ff5a64Elliott Hughes  SetVmData(peer_, Thread::Current());
360d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
361899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  SirtRef<String> peer_thread_name(GetThreadName());
36200fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  if (peer_thread_name.get() == NULL) {
36300fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // The Thread constructor should have set the Thread.name to a
36400fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // non-null value. However, because we can run without code
36500fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // available (in the compiler, in tests), we manually assign the
36600fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    // fields the constructor should have set.
36700fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    gThread_daemon->SetBoolean(peer_, thread_is_daemon);
36800fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group.get()));
36900fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name.get()));
37000fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom    gThread_priority->SetInt(peer_, thread_priority);
371899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    peer_thread_name.reset(GetThreadName());
37200fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  }
37300fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  // thread_name may have been null, so don't trust this to be non-null
37400fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  if (peer_thread_name.get() != NULL) {
375899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
37600fae585c6e4a37b964c77f557fbf84f11e2d930Brian Carlstrom  }
377726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes
378726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  // Pre-allocate an OutOfMemoryError for the double-OOME case.
379726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ThrowNewException("Ljava/lang/OutOfMemoryError;",
380726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      "OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available");
381726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jthrowable> exception(env, env->ExceptionOccurred());
382726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  env->ExceptionClear();
383726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  pre_allocated_OutOfMemoryError_ = Decode<Throwable*>(env, exception.get());
38461e019d291583029c01b61b93bea750f2b663c37Carl Shapiro}
38561e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
386899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughesvoid Thread::SetThreadName(const char* name) {
387899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  name_->assign(name);
388899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  ::art::SetThreadName(name);
389899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
390899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes}
391899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes
392be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::InitStackHwm() {
393215f3144be114ac27002059330d903bf1ff5a592Elliott Hughes#if defined(__APPLE__)
3946cc332ef80edf56221676e33ea16bb4022130344Elliott Hughes  // Only needed to run code. Try implementing this with pthread_get_stacksize_np and pthread_get_stackaddr_np.
3956cc332ef80edf56221676e33ea16bb4022130344Elliott Hughes  UNIMPLEMENTED(WARNING);
396215f3144be114ac27002059330d903bf1ff5a592Elliott Hughes#else
397be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  pthread_attr_t attributes;
3983147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
399be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
400932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  void* temp_stack_base;
401932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
402932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers                     __FUNCTION__);
40330fab40ee5a07af6b8c3b6b0e9438071695a57f4Ian Rogers  stack_begin_ = reinterpret_cast<byte*>(temp_stack_base);
404be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
405932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  if (stack_size_ <= kStackOverflowReservedBytes) {
4063d30d9b09c16542d41554aad9f46ec9109ba5cb5Elliott Hughes    LOG(FATAL) << "Attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
407be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  }
408449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes
409932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  // Set stack_end_ to the bottom of the stack saving space of stack overflows
410932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  ResetDefaultStackEnd();
411449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes
412449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes  // Sanity check.
413449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes  int stack_variable;
414449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes  CHECK_GT(&stack_variable, (void*) stack_end_);
415be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
4168d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
417215f3144be114ac27002059330d903bf1ff5a592Elliott Hughes#endif
418be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes}
419be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
420899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughesvoid Thread::Dump(std::ostream& os, bool full) const {
421899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  if (full) {
422899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    DumpState(os);
423899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    DumpStack(os);
424899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  } else {
425899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    os << "Thread[";
426899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    if (GetThinLockId() != 0) {
427899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      // If we're in kStarting, we won't have a thin lock id or tid yet.
428899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      os << GetThinLockId()
429899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes         << ",tid=" << GetTid() << ',';
430899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    }
431899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes    os << GetState()
432899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes       << ",Thread*=" << this
433ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes       << ",peer=" << peer_
434899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes       << ",\"" << *name_ << "\""
435899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes       << "]";
436e0918556e7551de638870dcad3f2023f94f85a50Elliott Hughes  }
437d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes}
438d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
439d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughesstd::string GetSchedulerGroup(pid_t tid) {
440d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // /proc/<pid>/group looks like this:
441d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // 2:devices:/
442d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // 1:cpuacct,cpu:/
443d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // We want the third field from the line whose second field contains the "cpu" token.
444d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::string cgroup_file;
445d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
446d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    return "";
447d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
448d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::vector<std::string> cgroup_lines;
449d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  Split(cgroup_file, '\n', cgroup_lines);
450d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  for (size_t i = 0; i < cgroup_lines.size(); ++i) {
451d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    std::vector<std::string> cgroup_fields;
452d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    Split(cgroup_lines[i], ':', cgroup_fields);
453d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    std::vector<std::string> cgroups;
454d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    Split(cgroup_fields[1], ',', cgroups);
455d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    for (size_t i = 0; i < cgroups.size(); ++i) {
456d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes      if (cgroups[i] == "cpu") {
457d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes        return cgroup_fields[2].substr(1); // Skip the leading slash.
458d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes      }
459d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    }
460d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
461d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  return "";
462d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes}
463d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
464899e789bd4741c0172268f7838ce8ab220a5f916Elliott HughesString* Thread::GetThreadName() const {
465fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  return (peer_ != NULL) ? reinterpret_cast<String*>(gThread_name->GetObject(peer_)) : NULL;
466fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes}
467fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes
468ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughesvoid Thread::GetThreadName(std::string& name) const {
469ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  name.assign(*name_);
470ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes}
471ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes
472d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughesvoid Thread::DumpState(std::ostream& os) const {
473d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  std::string group_name;
474d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  int priority;
475d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  bool is_daemon = false;
476d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
477d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (peer_ != NULL) {
478038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    priority = gThread_priority->GetInt(peer_);
479038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    is_daemon = gThread_daemon->GetBoolean(peer_);
480d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
481a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes    Object* thread_group = GetThreadGroup();
482d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    if (thread_group != NULL) {
483038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes      String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
484d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes      group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
485d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    }
486d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  } else {
487d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    priority = GetNativePriority();
488dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes  }
489d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
490d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int policy;
491d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  sched_param sp;
4923147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_self(), &policy, &sp), __FUNCTION__);
493d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
494d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::string scheduler_group(GetSchedulerGroup(GetTid()));
495d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  if (scheduler_group.empty()) {
496d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    scheduler_group = "default";
497d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
498d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
499899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  os << '"' << *name_ << '"';
500d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (is_daemon) {
501d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    os << " daemon";
502d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
503d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << " prio=" << priority
504dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes     << " tid=" << GetThinLockId()
50593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes     << " " << GetState() << "\n";
506d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
507d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << "  | group=\"" << group_name << "\""
5088d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     << " sCount=" << suspend_count_
509234ab15b00f8120282d1833e5d7480eca2e35a29Elliott Hughes     << " dsCount=" << debug_suspend_count_
510dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes     << " obj=" << reinterpret_cast<void*>(peer_)
511d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " self=" << reinterpret_cast<const void*>(this) << "\n";
512d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << "  | sysTid=" << GetTid()
513d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " nice=" << getpriority(PRIO_PROCESS, GetTid())
514d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " sched=" << policy << "/" << sp.sched_priority
515d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " cgrp=" << scheduler_group
5163147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes     << " handle=" << pthread_self() << "\n";
517d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
518d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // Grab the scheduler stats for this thread.
519d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::string scheduler_stats;
520d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
521d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
522d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  } else {
523d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    scheduler_stats = "0 0 0";
524d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
525d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
526d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int utime = 0;
527d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int stime = 0;
528d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int task_cpu = 0;
529bfe487be25652c5456236661b9d9c3579d2296c1Elliott Hughes  GetTaskStats(GetTid(), utime, stime, task_cpu);
530d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
531d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << "  | schedstat=( " << scheduler_stats << " )"
532d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " utm=" << utime
533d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " stm=" << stime
534d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " core=" << task_cpu
535d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
536a09576416788b916095739e43a16917e7948f3a4Elliott Hughes}
537a09576416788b916095739e43a16917e7948f3a4Elliott Hughes
538b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogersvoid Thread::PushNativeToManagedRecord(NativeToManagedRecord* record) {
539b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  Method **sp = top_of_managed_stack_.GetSP();
540b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers#ifndef NDEBUG
541b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  if (sp != NULL) {
542b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers    Method* m = *sp;
543b3bd5f07884f5a1f2b84224363b1372d7c28d447Elliott Hughes    Runtime::Current()->GetHeap()->VerifyObject(m);
544b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers    DCHECK((m == NULL) || m->IsMethod());
545b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  }
546b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers#endif
547b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  record->last_top_of_managed_stack_ = reinterpret_cast<void*>(sp);
548b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  record->last_top_of_managed_stack_pc_ = top_of_managed_stack_pc_;
549b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  record->link_ = native_to_managed_record_;
550b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  native_to_managed_record_ = record;
551b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  top_of_managed_stack_.SetSP(NULL);
552b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers}
553b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers
554b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogersvoid Thread::PopNativeToManagedRecord(const NativeToManagedRecord& record) {
555b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  native_to_managed_record_ = record.link_;
556b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  top_of_managed_stack_.SetSP(reinterpret_cast<Method**>(record.last_top_of_managed_stack_));
557b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  top_of_managed_stack_pc_ = record.last_top_of_managed_stack_pc_;
558b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers}
559b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers
560d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughesstruct StackDumpVisitor : public Thread::StackVisitor {
5618e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  StackDumpVisitor(std::ostream& os, const Thread* thread)
56228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      : last_method(NULL), last_line_number(0), repetition_count(0), os(os), thread(thread),
56328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers        frame_count(0) {
564d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
565d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
566bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  virtual ~StackDumpVisitor() {
567d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
568d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
569530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  bool VisitFrame(const Frame& frame, uintptr_t pc) {
5709086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    if (!frame.HasMethod()) {
571530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true;
5729086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    }
57328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    const int kMaxRepetition = 3;
574d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    Method* m = frame.GetMethod();
575d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    Class* c = m->GetDeclaringClass();
5768e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
577b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    const DexCache* dex_cache = c->GetDexCache();
578b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    int line_number = -1;
579b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    if (dex_cache != NULL) {  // be tolerant of bad input
580b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers      const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
581b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers      line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
582b861dc0077342d5a1d2dd9cade3f6990620778ecIan Rogers    }
58328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    if (line_number == last_line_number && last_method == m) {
58428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      repetition_count++;
585d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    } else {
58628ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      if (repetition_count >= kMaxRepetition) {
58728ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers        os << "  ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
58828ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      }
58928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      repetition_count = 0;
59028ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      last_line_number = line_number;
59128ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      last_method = m;
59228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    }
59328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    if (repetition_count < kMaxRepetition) {
59428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      os << "  at " << PrettyMethod(m, false);
59528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      if (m->IsNative()) {
59628ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers        os << "(Native method)";
59728ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      } else {
5986d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers        mh.ChangeMethod(m);
5996d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers        const char* source_file(mh.GetDeclaringClassSourceFile());
6006d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers        os << "(" << (source_file != NULL ? source_file : "unavailable")
60128ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers           << ":" << line_number << ")";
60228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      }
60328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      os << "\n";
604d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    }
6058e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
6068e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    if (frame_count++ == 0) {
6078e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      Monitor::DescribeWait(os, thread);
6088e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    }
609530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
610d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
6116d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers  MethodHelper mh;
61228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  Method* last_method;
61328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  int last_line_number;
61428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  int repetition_count;
615d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  std::ostream& os;
6168e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  const Thread* thread;
6178e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  int frame_count;
618d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes};
619d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
620d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughesvoid Thread::DumpStack(std::ostream& os) const {
621ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  // If we're currently in native code, dump that stack before dumping the managed stack.
622ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  if (GetState() == Thread::kNative || GetState() == Thread::kVmWait) {
623ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    DumpNativeStack(os);
624ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
6258e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  StackDumpVisitor dumper(os, this);
626d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  WalkStack(&dumper);
627e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes}
628e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes
629a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughesvoid Thread::SetStateWithoutSuspendCheck(Thread::State new_state) {
630a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  volatile void* raw = reinterpret_cast<volatile void*>(&state_);
631a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
632a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  android_atomic_release_store(new_state, addr);
633a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes}
634a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes
6358d768a954b101a9532f980253ac46be2c53aba11Elliott HughesThread::State Thread::SetState(Thread::State new_state) {
6368d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  Thread::State old_state = state_;
6378d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  if (old_state == new_state) {
6388d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    return old_state;
6398d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
6408d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
6418d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  volatile void* raw = reinterpret_cast<volatile void*>(&state_);
6428d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
6438d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
6448d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  if (new_state == Thread::kRunnable) {
6458d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    /*
6468d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * Change our status to Thread::kRunnable.  The transition requires
6478d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that we check for pending suspension, because the VM considers
6488d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * us to be "asleep" in all other states, and another thread could
6498d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * be performing a GC now.
6508d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6518d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * The order of operations is very significant here.  One way to
6528d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * do this wrong is:
6538d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6548d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   GCing thread                   Our thread (in kNative)
6558d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   ------------                   ----------------------
6568d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  check suspend count (== 0)
6578d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   SuspendAllThreads()
6588d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   grab suspend-count lock
6598d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   increment all suspend counts
6608d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   release suspend-count lock
6618d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   check thread state (== kNative)
6628d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   all are suspended, begin GC
6638d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  set state to kRunnable
6648d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  (continue executing)
6658d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6668d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We can correct this by grabbing the suspend-count lock and
6678d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * performing both of our operations (check suspend count, set
6688d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * state) while holding it, now we need to grab a mutex on every
6698d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * transition to kRunnable.
6708d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6718d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * What we do instead is change the order of operations so that
6728d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * the transition to kRunnable happens first.  If we then detect
6738d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that the suspend count is nonzero, we switch to kSuspended.
6748d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6758d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * Appropriate compiler and memory barriers are required to ensure
6768d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that the operations are observed in the expected order.
6778d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6788d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * This does create a small window of opportunity where a GC in
6798d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * progress could observe what appears to be a running thread (if
6808d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * it happens to look between when we set to kRunnable and when we
6818d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * switch to kSuspended).  At worst this only affects assertions
6828d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * and thread logging.  (We could work around it with some sort
6838d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * of intermediate "pre-running" state that is generally treated
6848d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * as equivalent to running, but that doesn't seem worthwhile.)
6858d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6868d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We can also solve this by combining the "status" and "suspend
6878d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * count" fields into a single 32-bit value.  This trades the
6888d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * store/load barrier on transition to kRunnable for an atomic RMW
6898d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * op on all transitions and all suspend count updates (also, all
6908d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * accesses to status or the thread count require bit-fiddling).
6918d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * It also eliminates the brief transition through kRunnable when
6928d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * the thread is supposed to be suspended.  This is possibly faster
6938d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * on SMP and slightly more correct, but less convenient.
6948d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     */
6958d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    android_atomic_acquire_store(new_state, addr);
69606e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    ANNOTATE_IGNORE_READS_BEGIN();
69706e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    int suspend_count = suspend_count_;
69806e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    ANNOTATE_IGNORE_READS_END();
69906e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    if (suspend_count != 0) {
7008d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
7018d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    }
7028d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  } else {
7038d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    /*
7048d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * Not changing to Thread::kRunnable. No additional work required.
7058d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
7068d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We use a releasing store to ensure that, if we were runnable,
7078d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * any updates we previously made to objects on the managed heap
7088d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * will be observed before the state change.
7098d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     */
7108d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    android_atomic_release_store(new_state, addr);
7118d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
7128d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
7138d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  return old_state;
7148d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes}
7158d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
716761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughesbool Thread::IsSuspended() {
71706e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  ANNOTATE_IGNORE_READS_BEGIN();
71806e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  int suspend_count = suspend_count_;
71906e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  ANNOTATE_IGNORE_READS_END();
72006e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  return suspend_count != 0 && GetState() != Thread::kRunnable;
721761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes}
722761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes
723ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughesstatic void ReportThreadSuspendTimeout(Thread* waiting_thread) {
724ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  Runtime* runtime = Runtime::Current();
725ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  std::ostringstream ss;
726ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  ss << "Thread suspend timeout waiting for thread " << *waiting_thread << "\n";
727ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  runtime->DumpLockHolders(ss);
728ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  ss << "\n";
729ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  runtime->GetThreadList()->DumpLocked(ss);
730ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  LOG(FATAL) << ss.str();
731ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes}
732ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes
7338d768a954b101a9532f980253ac46be2c53aba11Elliott Hughesvoid Thread::WaitUntilSuspended() {
73421a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes  static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
73521a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes
73621a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes  useconds_t total_delay = 0;
7378d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  useconds_t delay = 0;
7388d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  while (GetState() == Thread::kRunnable) {
73921a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes    if (total_delay >= kTimeoutUs) {
740ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes      ReportThreadSuspendTimeout(this);
74121a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes    }
7428d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    useconds_t new_delay = delay * 2;
7438d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    CHECK_GE(new_delay, delay);
7448d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    delay = new_delay;
7458d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    if (delay == 0) {
7468d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      sched_yield();
7478d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      delay = 10000;
7488d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    } else {
7498d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      usleep(delay);
75021a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes      total_delay += delay;
7518d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    }
7528d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
7538d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes}
7548d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
755be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::ThreadExitCallback(void* arg) {
756be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  Thread* self = reinterpret_cast<Thread*>(arg);
757be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
758b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
759b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
760be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::Startup() {
761b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  // Allocate a TLS slot.
7628d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
763b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
764b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  // Double-check the TLS slot allocation.
765b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  if (pthread_getspecific(pthread_key_self_) != NULL) {
7663d30d9b09c16542d41554aad9f46ec9109ba5cb5Elliott Hughes    LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
767b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  }
768038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes}
769038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
7708e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
7718e4aac52962d54cb4be2078b9cd95685e067133aElliott HughesClass* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
7728e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* c = class_linker->FindPrimitiveClass(descriptor);
7738e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(c != NULL) << descriptor;
7748e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return c;
7758e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7768e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
7778e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
7788e4aac52962d54cb4be2078b9cd95685e067133aElliott HughesClass* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
7798e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* c = class_linker->FindSystemClass(descriptor);
7808e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(c != NULL) << descriptor;
7818e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return c;
7828e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7838e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
7848e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
7856b4ef025af12b158d117fc80fc79acf620f411a0Brian CarlstromField* FindFieldOrDie(Class* c, const char* name, const char* descriptor) {
7866b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  Field* f = c->FindDeclaredInstanceField(name, descriptor);
7876b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
7888e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return f;
7898e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7908e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
7918e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
7928e4aac52962d54cb4be2078b9cd95685e067133aElliott HughesMethod* FindMethodOrDie(Class* c, const char* name, const char* signature) {
7938e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Method* m = c->FindVirtualMethod(name, signature);
7948e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
7958e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return m;
7968e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7978e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
798038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesvoid Thread::FinishStartup() {
7999a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  CHECK(Runtime::Current()->IsStarted());
800b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom  Thread* self = Thread::Current();
801b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom
802b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom  // Need to be kRunnable for FindClass
803b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom  ScopedThreadStateChange tsc(self, Thread::kRunnable);
804b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom
805038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
806038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
8078e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
8088e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
8098e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
8108e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
8118e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
8128e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
8136b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_daemon = FindFieldOrDie(Thread_class, "daemon", "Z");
8146b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_group = FindFieldOrDie(Thread_class, "group", "Ljava/lang/ThreadGroup;");
8156b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_lock = FindFieldOrDie(Thread_class, "lock", "Ljava/lang/ThreadLock;");
8166b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_name = FindFieldOrDie(Thread_class, "name", "Ljava/lang/String;");
8176b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_priority = FindFieldOrDie(Thread_class, "priority", "I");
8186b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
8196b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_vmData = FindFieldOrDie(Thread_class, "vmData", "I");
8206b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", "Ljava/lang/String;");
8216b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", "Ljava/lang/Thread;");
8228e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
8238e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
8248e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
8258e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
8268e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
82701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
82801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  // Finish attaching the main thread.
8299a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  Thread::Current()->CreatePeer("main", false);
8309a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson
8319a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  InitBoxingMethods();
8329a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  class_linker->RunRootClinits();
833b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
834b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
835c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughesvoid Thread::Shutdown() {
8368d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
837c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes}
838c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes
8398e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesuint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
8408e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
8418e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
8428e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
8438e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
8448e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (managed_thread == NULL) {
8458e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
8468e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
8478e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
8488e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Thread* thread = reinterpret_cast<Thread*>(vmData);
8498e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (thread == NULL) {
8508e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
8518e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
8528e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return thread->GetThinLockId();
8538e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
8548e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
855dcc247493fd8fb243e335c3ec08e5e625896a47cElliott HughesThread::Thread()
85647179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    : thin_lock_id_(0),
85747179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes      tid_(0),
85847179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes      peer_(NULL),
8598e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      top_of_managed_stack_(),
8608e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      top_of_managed_stack_pc_(0),
86185d1545e985ac689db4bad7849880e843707c862Elliott Hughes      wait_mutex_(new Mutex("Thread wait mutex")),
86285d1545e985ac689db4bad7849880e843707c862Elliott Hughes      wait_cond_(new ConditionVariable("Thread wait condition variable")),
8638daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      wait_monitor_(NULL),
8648daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      interrupted_(false),
865dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      wait_next_(NULL),
8668e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      monitor_enter_object_(NULL),
867dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      card_table_(0),
8688daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      stack_end_(NULL),
869dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      native_to_managed_record_(NULL),
870dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      top_sirt_(NULL),
871dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      jni_env_(NULL),
8728e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      state_(Thread::kNative),
873dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      self_(NULL),
874dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      runtime_(NULL),
875dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      exception_(NULL),
876dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      suspend_count_(0),
877234ab15b00f8120282d1833e5d7480eca2e35a29Elliott Hughes      debug_suspend_count_(0),
87885d1545e985ac689db4bad7849880e843707c862Elliott Hughes      class_loader_override_(NULL),
879418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes      long_jump_context_(NULL),
880726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      throwing_OutOfMemoryError_(false),
881475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes      pre_allocated_OutOfMemoryError_(NULL),
882e343b76af81a005ef64f5e75a555389fd9147dabjeffhao      debug_invoke_req_(new DebugInvokeReq),
883899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      trace_stack_(new std::vector<TraceStackFrame>),
884899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      name_(new std::string("<native thread without managed peer>")) {
885f5a7a476e7ea63e094ff0f011dccc170607e6f6bElliott Hughes  CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
886ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
887dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes}
888dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes
88902b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughesvoid MonitorExitVisitor(const Object* object, void*) {
89002b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  Object* entered_monitor = const_cast<Object*>(object);
8915f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  entered_monitor->MonitorExit(Thread::Current());
89202b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes}
89302b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
894c1674ed06662420213441ff2b818f2f71f9098dcElliott HughesThread::~Thread() {
89502b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
89693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  if (jni_env_ != NULL) {
89793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
89893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  }
89902b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
90029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  if (peer_ != NULL) {
90129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes
90229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // this.vmData = 0;
90393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    SetVmData(peer_, NULL);
90402b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
905872d4ec7225444d9400d30f9027247deb91012fdElliott Hughes    Dbg::PostThreadDeath(this);
90602b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
90729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // Thread.join() is implemented as an Object.wait() on the Thread.lock
90829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // object. Signal anyone who is waiting.
9095f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    Thread* self = Thread::Current();
910038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    Object* lock = gThread_lock->GetObject(peer_);
911038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    // (This conditional is only needed for tests, where Thread.lock won't have been set.)
9125f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    if (lock != NULL) {
9135f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->MonitorEnter(self);
9145f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->NotifyAll();
9155f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->MonitorExit(self);
9165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
9175f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
91802b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
919c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes  delete jni_env_;
92002b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  jni_env_ = NULL;
92102b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
92202b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  SetState(Thread::kTerminated);
92385d1545e985ac689db4bad7849880e843707c862Elliott Hughes
92485d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete wait_cond_;
92585d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete wait_mutex_;
92685d1545e985ac689db4bad7849880e843707c862Elliott Hughes
92785d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete long_jump_context_;
928475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes
929475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes  delete debug_invoke_req_;
930e343b76af81a005ef64f5e75a555389fd9147dabjeffhao  delete trace_stack_;
931899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  delete name_;
932c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes}
933c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes
934accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughesvoid Thread::HandleUncaughtExceptions() {
935accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  if (!IsExceptionPending()) {
936accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    return;
937accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  }
938accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
939accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // Get and clear the exception.
940accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* exception = GetException();
941accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  ClearException();
942accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
943accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // If the thread has its own handler, use that.
944accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* handler = gThread_uncaughtHandler->GetObject(peer_);
945accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  if (handler == NULL) {
946accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    // Otherwise use the thread group's default handler.
947a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes    handler = GetThreadGroup();
948accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  }
949accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
950accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // Call the handler.
951accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
952accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* args[2];
953accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  args[0] = peer_;
954accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  args[1] = exception;
955accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
956accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
957accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // If the handler threw, clear that exception too.
958accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  ClearException();
959accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
9604514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom
961a215526d5c789cbef0f81a1f9aba22541a841ccaElliott HughesObject* Thread::GetThreadGroup() const {
962a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes  return gThread_group->GetObject(peer_);
963a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes}
964a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes
9654514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstromvoid Thread::RemoveFromThreadGroup() {
9664514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  // this.group.removeThread(this);
9674514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  // group can be null if we're in the compiler or a test.
968a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes  Object* group = GetThreadGroup();
9694514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  if (group != NULL) {
9704514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom    Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
9714514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom    Object* args = peer_;
9724514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom    m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
9734514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  }
9744514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom}
975accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
976408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogerssize_t Thread::NumSirtReferences() {
977a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  size_t count = 0;
97840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
979a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers    count += cur->NumberOfReferences();
980a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  }
981a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  return count;
982a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers}
983a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers
984408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogersbool Thread::SirtContains(jobject obj) {
985408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  Object** sirt_entry = reinterpret_cast<Object**>(obj);
98640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
98740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    if (cur->Contains(sirt_entry)) {
988a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers      return true;
989a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers    }
990a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  }
991a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  return false;
992a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers}
993a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers
9948dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liaovoid Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
99540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
9968dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    size_t num_refs = cur->NumberOfReferences();
9978dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    for (size_t j = 0; j < num_refs; j++) {
99840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom      Object* object = cur->GetReference(j);
9995e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom      if (object != NULL) {
10005e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom        visitor(object, arg);
10015e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom      }
10028dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    }
10038dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao  }
10048dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao}
10058dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
1006408f79aeb676251ba35667a64e86c20638d7cb0bIan RogersObject* Thread::DecodeJObject(jobject obj) {
10070cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  DCHECK(CanAccessDirectReferences());
1008408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  if (obj == NULL) {
1009408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    return NULL;
1010408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1011408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1012408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  IndirectRefKind kind = GetIndirectRefKind(ref);
1013408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  Object* result;
1014408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  switch (kind) {
1015408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kLocal:
1016408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
101769f5bc6759f256a146eefd8a7141d39fcc3b0421Elliott Hughes      IndirectReferenceTable& locals = jni_env_->locals;
1018cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(locals.Get(ref));
1019408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1020408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1021408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kGlobal:
1022408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
1023408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1024408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      IndirectReferenceTable& globals = vm->globals;
1025408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      MutexLock mu(vm->globals_lock);
1026cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(globals.Get(ref));
1027408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1028408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1029408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kWeakGlobal:
1030408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
1031408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1032408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      IndirectReferenceTable& weak_globals = vm->weak_globals;
1033408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      MutexLock mu(vm->weak_globals_lock);
1034cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(weak_globals.Get(ref));
1035408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      if (result == kClearedJniWeakGlobal) {
1036408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers        // This is a special case where it's okay to return NULL.
1037408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers        return NULL;
1038408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      }
1039408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1040408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1041408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kSirtOrInvalid:
1042408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  default:
1043408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    // TODO: make stack indirect reference table lookup more efficient
1044408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    // Check if this is a local reference in the SIRT
1045408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    if (SirtContains(obj)) {
10460cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers      result = *reinterpret_cast<Object**>(obj);  // Read from SIRT
1047c2dc62d1c9241dfe880a81698713c314b13aa63fElliott Hughes    } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
1048408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      // Assume an invalid local reference is actually a direct pointer.
1049408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      result = reinterpret_cast<Object*>(obj);
1050408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    } else {
1051a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes      result = kInvalidIndirectRefObject;
1052408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1053408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1054408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers
1055408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  if (result == NULL) {
1056a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1057a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    JniAbort(NULL);
1058a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes  } else {
1059a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    if (result != kInvalidIndirectRefObject) {
1060b3bd5f07884f5a1f2b84224363b1372d7c28d447Elliott Hughes      Runtime::Current()->GetHeap()->VerifyObject(result);
1061a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    }
1062408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1063408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  return result;
1064408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers}
1065408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers
10669b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liaoclass CountStackDepthVisitor : public Thread::StackVisitor {
10679b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao public:
106829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
1069d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
1070530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  bool VisitFrame(const Frame& frame, uintptr_t pc) {
107129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // We want to skip frames up to and including the exception's constructor.
10729086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    // Note we also skip the frame if it doesn't have a method (namely the callee
10739086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    // save frame)
10745167c97a4f672ba821453418e3943988fabbfc43Ian Rogers    if (skipping_ && frame.HasMethod() &&
10755167c97a4f672ba821453418e3943988fabbfc43Ian Rogers        !Throwable::GetJavaLangThrowable()->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
107629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      skipping_ = false;
107729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
107829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    if (!skipping_) {
10796b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers      if (frame.HasMethod()) {  // ignore callee save frames
10806b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers        ++depth_;
10816b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers      }
108229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    } else {
108329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      ++skip_depth_;
108429f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
1085530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
10869b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
10879b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
10889b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  int GetDepth() const {
1089aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    return depth_;
10909b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
10919b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
109229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int GetSkipDepth() const {
109329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    return skip_depth_;
109429f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  }
109529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes
10969b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao private:
1097aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  uint32_t depth_;
109829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  uint32_t skip_depth_;
109929f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  bool skipping_;
11009b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao};
11019b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1102aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogersclass BuildInternalStackTraceVisitor : public Thread::StackVisitor {
11039b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao public:
1104283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  explicit BuildInternalStackTraceVisitor(int skip_depth)
1105726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      : skip_depth_(skip_depth), count_(0), pc_trace_(NULL), method_trace_(NULL), local_ref_(NULL) {
1106283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  }
1107283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers
1108283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  bool Init(int depth, ScopedJniThreadState& ts) {
1109aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Allocate method trace with an extra slot that will hold the PC trace
111001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
1111726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (method_trace_ == NULL) {
1112283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers      return false;
1113726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
1114aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Register a local reference as IntArray::Alloc may trigger GC
1115aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1116aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    pc_trace_ = IntArray::Alloc(depth);
1117726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (pc_trace_ == NULL) {
1118283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers      return false;
1119726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
1120aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#ifdef MOVING_GARBAGE_COLLECTOR
1121aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Re-read after potential GC
1122267364429db05d964c0922a8b4e49591c00bdc35Brian Carlstrom    method_trace_ = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1123aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#endif
1124aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Save PC trace in last element of method trace, also places it into the
1125aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // object graph.
1126aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace_->Set(depth, pc_trace_);
1127283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers    return true;
11289b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11299b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1130aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  virtual ~BuildInternalStackTraceVisitor() {}
11319b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1132530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  bool VisitFrame(const Frame& frame, uintptr_t pc) {
1133726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (method_trace_ == NULL || pc_trace_ == NULL) {
1134530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
1135726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
113629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    if (skip_depth_ > 0) {
113729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      skip_depth_--;
1138530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true;
113929f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
11406b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers    if (!frame.HasMethod()) {
1141530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return true;  // ignore callee save frames
11426b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers    }
1143aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace_->Set(count_, frame.GetMethod());
1144bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    pc_trace_->Set(count_, pc);
1145aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    ++count_;
1146530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
11479b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11489b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1149aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  jobject GetInternalStackTrace() const {
1150aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    return local_ref_;
11519b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11529b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
11539b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao private:
115429f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  // How many more frames to skip.
115529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int32_t skip_depth_;
1156aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Current position down stack trace
1157aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  uint32_t count_;
1158aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Array of return PC values
1159aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  IntArray* pc_trace_;
1160aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // An array of the methods on the stack, the last entry is a reference to the
1161aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // PC trace
1162aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ObjectArray<Object>* method_trace_;
1163aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Local indirect reference table entry for method trace
1164aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  jobject local_ref_;
11659b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao};
11669b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1167a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes// TODO: remove this.
1168a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughesuintptr_t ManglePc(uintptr_t pc) {
1169a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // Move the PC back 2 bytes as a call will frequently terminate the
1170a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // decoding of a particular instruction and we want to make sure we
1171a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // get the Dex PC of the instruction with the call and not the
1172a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // instruction following.
1173a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  if (pc > 0) { pc -= 2; }
1174a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  return pc;
1175a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes}
1176a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes
1177a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes// TODO: remove this.
1178a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughesuintptr_t DemanglePc(uintptr_t pc) {
1179a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // Revert mangling for the case where we need the PC to return to the upcall
11809a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  if (pc > 0) { pc +=  2; }
11819a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  return pc;
1182a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes}
1183f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers
118440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstromvoid Thread::PushSirt(StackIndirectReferenceTable* sirt) {
118540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  sirt->SetLink(top_sirt_);
118640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  top_sirt_ = sirt;
118740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom}
118840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom
118940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian CarlstromStackIndirectReferenceTable* Thread::PopSirt() {
119040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  CHECK(top_sirt_ != NULL);
119140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  StackIndirectReferenceTable* sirt = top_sirt_;
119240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  top_sirt_ = top_sirt_->GetLink();
119340381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  return sirt;
119440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom}
119540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom
1196530fa005e2944d3b12712f80d974f0e753f568efElliott Hughesvoid Thread::WalkStack(StackVisitor* visitor, bool include_upcalls) const {
1197d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  Frame frame = GetTopOfStack();
1198a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
1199a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao#if defined(__arm__)
1200a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao  uint32_t trace_stack_depth = 0;
1201a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao#endif
12029b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
12039b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  // CHECK(native_to_managed_record_ != NULL);
12049b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  NativeToManagedRecord* record = native_to_managed_record_;
12054417536522fd2a9d8215d8672331984769c9520bShih-wei Liao
1206530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  while (frame.GetSP() != NULL) {
1207530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    for ( ; frame.GetMethod() != NULL; frame.Next()) {
12083320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom      // DCHECK(frame.GetMethod()->IsWithinCode(pc));  // TODO: restore IsWithinCode
1209530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      bool should_continue = visitor->VisitFrame(frame, pc);
1210530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      if (!should_continue) {
1211530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        return;
1212530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      }
1213a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes      pc = ManglePc(frame.GetReturnPC());
12142692b573a56cd63a3c8c8aa1636e3766b6d8c9c4jeffhao      if (Runtime::Current()->IsMethodTracingActive()) {
1215a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao#if defined(__arm__)
1216a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao        uintptr_t trace_exit = reinterpret_cast<uintptr_t>(art_trace_exit_from_code);
1217a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao        if (ManglePc(trace_exit) == pc) {
1218a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao          TraceStackFrame trace_frame = GetTraceStackFrame(trace_stack_depth++);
121926c0a1a376d8cd639fe6b16594fcb55a723450c0jeffhao          CHECK(trace_frame.method_ == frame.GetMethod());
1220a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao          pc = ManglePc(trace_frame.return_pc_);
1221a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao        }
1222a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao#endif
1223a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao      }
12249b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    }
1225530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    if (include_upcalls) {
1226530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      bool should_continue = visitor->VisitFrame(frame, pc);
1227530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      if (!should_continue) {
1228530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        return;
1229530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      }
1230530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    }
12319b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    if (record == NULL) {
1232530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return;
12339b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    }
1234bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    // last_tos should return Frame instead of sp?
1235ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers    frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
1236a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes    pc = ManglePc(record->last_top_of_managed_stack_pc_);
1237bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    record = record->link_;
1238bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  }
1239bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers}
1240bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
124101158d7a57c8321370667a6045220237d16e0da8Elliott Hughesjobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
1242aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Compute depth of stack
12439b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  CountStackDepthVisitor count_visitor;
12449b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  WalkStack(&count_visitor);
12459b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  int32_t depth = count_visitor.GetDepth();
124629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int32_t skip_depth = count_visitor.GetSkipDepth();
12474417536522fd2a9d8215d8672331984769c9520bShih-wei Liao
1248aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Transition into runnable state to work on Object*/Array*
124901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  ScopedJniThreadState ts(env);
1250aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
1251aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Build internal stack trace
125277f74c1455bd8d29deb8a9367cea35deb930ed10Ian Rogers  BuildInternalStackTraceVisitor build_trace_visitor(skip_depth);
125377f74c1455bd8d29deb8a9367cea35deb930ed10Ian Rogers  if (!build_trace_visitor.Init(depth, ts)) {
1254283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers    return NULL;  // Allocation failed
1255283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  }
1256267364429db05d964c0922a8b4e49591c00bdc35Brian Carlstrom  WalkStack(&build_trace_visitor);
1257267364429db05d964c0922a8b4e49591c00bdc35Brian Carlstrom  return build_trace_visitor.GetInternalStackTrace();
1258aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers}
1259aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
126001158d7a57c8321370667a6045220237d16e0da8Elliott HughesjobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
126101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    jobjectArray output_array, int* stack_depth) {
1262aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Transition into runnable state to work on Object*/Array*
1263aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ScopedJniThreadState ts(env);
1264aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Decode the internal stack trace into the depth, method trace and PC trace
1265aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ObjectArray<Object>* method_trace =
1266aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers      down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
12679074b99bfbd5419e340f138a018b673ce71f77e8Ian Rogers  int32_t depth = method_trace->GetLength() - 1;
1268aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1269aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
1270aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1271aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
127201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  jobjectArray result;
127301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  ObjectArray<StackTraceElement>* java_traces;
127401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  if (output_array != NULL) {
127501158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // Reuse the array we were given.
127601158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    result = output_array;
127701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
127801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes        output_array));
127901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // ...adjusting the number of frames we'll write to not exceed the array length.
128001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    depth = std::min(depth, java_traces->GetLength());
128101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  } else {
128201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // Create java_trace array and place in local reference table
128301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    java_traces = class_linker->AllocStackTraceElementArray(depth);
128430646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    if (java_traces == NULL) {
128530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes      return NULL;
128630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    }
128701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
128801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  }
128901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
129001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  if (stack_depth != NULL) {
129101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    *stack_depth = depth;
129201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  }
129355df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
12946d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers  MethodHelper mh;
12959b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  for (int32_t i = 0; i < depth; ++i) {
1296aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1297aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    Method* method = down_cast<Method*>(method_trace->Get(i));
12986d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    mh.ChangeMethod(method);
1299aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    uint32_t native_pc = pc_trace->Get(i);
13006d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    int32_t line_number = mh.GetLineNumFromNativePC(native_pc);
1301aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Allocate element, potentially triggering GC
130240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    // TODO: reuse class_name_object via Class::name_?
1303486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* descriptor = mh.GetDeclaringClassDescriptor();
1304486013193c94b4321414c28ce9251911e14a0599Ian Rogers    CHECK(descriptor != NULL);
1305486013193c94b4321414c28ce9251911e14a0599Ian Rogers    std::string class_name(PrettyDescriptor(descriptor));
130640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
130740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    if (class_name_object.get() == NULL) {
130840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom      return NULL;
130940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    }
1310486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* method_name = mh.GetName();
1311486013193c94b4321414c28ce9251911e14a0599Ian Rogers    CHECK(method_name != NULL);
1312486013193c94b4321414c28ce9251911e14a0599Ian Rogers    SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
13136d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    if (method_name_object.get() == NULL) {
13146d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      return NULL;
13156d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    }
1316486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* source_file = mh.GetDeclaringClassSourceFile();
1317486013193c94b4321414c28ce9251911e14a0599Ian Rogers    SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
131840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
13196d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                      method_name_object.get(),
13206d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                      source_name_object.get(),
132140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom                                                      line_number);
132230646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    if (obj == NULL) {
132330646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes      return NULL;
132430646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    }
1325aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#ifdef MOVING_GARBAGE_COLLECTOR
1326aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Re-read after potential GC
1327aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1328aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1329aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1330aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#endif
133155df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao    java_traces->Set(i, obj);
133255df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao  }
1333aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  return result;
133455df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao}
133555df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
13365cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughesvoid Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
1337a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_list args;
1338a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_start(args, fmt);
13394a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  ThrowNewExceptionV(exception_class_descriptor, fmt, args);
1340a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_end(args);
13414a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes}
13424a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes
13434a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughesvoid Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
13444a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  std::string msg;
13454a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  StringAppendV(&msg, fmt, ap);
13465cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughes  ThrowNewException(exception_class_descriptor, msg.c_str());
13475cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughes}
134837f7a40f6789bb287f287a9af00777af9d6428eeElliott Hughes
13495cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughesvoid Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
1350e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
13510cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  CHECK_EQ('L', exception_class_descriptor[0]);
1352e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  std::string descriptor(exception_class_descriptor + 1);
13530cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  CHECK_EQ(';', descriptor[descriptor.length() - 1]);
1354e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  descriptor.erase(descriptor.length() - 1);
1355e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes
1356e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  JNIEnv* env = GetJniEnv();
1357726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
135830646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  if (exception_class.get() == NULL) {
135930646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
136030646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes               << PrettyTypeOf(GetException());
136130646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    CHECK(IsExceptionPending());
136230646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    return;
136330646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  }
1364ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom  if (!Runtime::Current()->IsStarted()) {
1365ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // Something is trying to throw an exception without a started
1366ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // runtime, which is the common case in the compiler. We won't be
1367ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // able to invoke the constructor of the exception, so use
1368ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // AllocObject which will not invoke a constructor.
1369ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    ScopedLocalRef<jthrowable> exception(
1370ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom        env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1371ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    if (exception.get() != NULL) {
1372ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      ScopedJniThreadState ts(env);
1373ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      Throwable* t = reinterpret_cast<Throwable*>(ts.Self()->DecodeJObject(exception.get()));
137402fbef0e356ca43b2032044f870d59de4a4ae92aIan Rogers      t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
1375ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      ts.Self()->SetException(t);
1376ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    } else {
1377ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1378ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom                 << PrettyTypeOf(GetException());
1379ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      CHECK(IsExceptionPending());
1380ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    }
1381ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    return;
1382ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom  }
1383726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  int rc = env->ThrowNew(exception_class.get(), msg);
138430646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  if (rc != JNI_OK) {
138530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
138630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes               << PrettyTypeOf(GetException());
138730646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    CHECK(IsExceptionPending());
138830646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  }
1389a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes}
1390a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes
1391418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughesvoid Thread::ThrowOutOfMemoryError(Class* c, size_t byte_count) {
13922ced6a534157d5d963693346904389c19775d2daElliott Hughes  std::string msg(StringPrintf("Failed to allocate a %zd-byte %s", byte_count,
13936d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      PrettyDescriptor(c).c_str()));
13942ced6a534157d5d963693346904389c19775d2daElliott Hughes  ThrowOutOfMemoryError(msg.c_str());
13952ced6a534157d5d963693346904389c19775d2daElliott Hughes}
13962ced6a534157d5d963693346904389c19775d2daElliott Hughes
13972ced6a534157d5d963693346904389c19775d2daElliott Hughesvoid Thread::ThrowOutOfMemoryError(const char* msg) {
13982ced6a534157d5d963693346904389c19775d2daElliott Hughes  LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
13992ced6a534157d5d963693346904389c19775d2daElliott Hughes      msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
1400726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  if (!throwing_OutOfMemoryError_) {
1401726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    throwing_OutOfMemoryError_ = true;
1402accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
1403418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes  } else {
1404726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    SetException(pre_allocated_OutOfMemoryError_);
1405418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes  }
1406726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  throwing_OutOfMemoryError_ = false;
140779082e367845bbd68ec44ef2ddd1be8ef0e1550fElliott Hughes}
140879082e367845bbd68ec44ef2ddd1be8ef0e1550fElliott Hughes
1409accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1410498508c1187dc07d3eae5476784cde20f5224d93Elliott HughesThread* Thread::CurrentFromGdb() {
1411accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  return Thread::Current();
1412accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
1413accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1414accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughesvoid Thread::DumpFromGdb() const {
14156b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  std::ostringstream ss;
14166b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  Dump(ss);
1417955724179c6c739524f610023287f56b24dc31deElliott Hughes  std::string str(ss.str());
14186b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  // log to stderr for debugging command line processes
14196b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  std::cerr << str;
14206b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom#ifdef HAVE_ANDROID_OS
14216b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  // log to logcat for debugging frameworks processes
14226b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  LOG(INFO) << str;
14236b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom#endif
1424accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
1425accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1426bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogersclass CatchBlockStackVisitor : public Thread::StackVisitor {
1427bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers public:
1428bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  CatchBlockStackVisitor(Class* to_find, Context* ljc)
1429530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      : to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
143067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers#ifndef NDEBUG
143167375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    handler_pc_ = 0xEBADC0DE;
143267375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
143367375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers#endif
143467375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  }
1435bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1436530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  bool VisitFrame(const Frame& fr, uintptr_t pc) {
1437530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    Method* method = fr.GetMethod();
1438530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    if (method == NULL) {
1439530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      // This is the upcall, we remember the frame and last_pc so that we may
1440530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      // long jump to them
1441530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      handler_pc_ = DemanglePc(pc);
1442530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      handler_frame_ = fr;
1443530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      return false;
1444530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    }
1445530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    uint32_t dex_pc = DexFile::kDexNoIndex;
1446530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    if (method->IsCalleeSaveMethod()) {
1447530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      // ignore callee save method
1448530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    } else if (method->IsNative()) {
1449530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      native_method_count_++;
1450530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    } else {
1451530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      // Unwind stack during method tracing
1452530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      if (Runtime::Current()->IsMethodTracingActive()) {
1453e343b76af81a005ef64f5e75a555389fd9147dabjeffhao#if defined(__arm__)
1454530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        uintptr_t trace_exit = reinterpret_cast<uintptr_t>(art_trace_exit_from_code);
1455530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        if (ManglePc(trace_exit) == pc) {
1456530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes          pc = ManglePc(TraceMethodUnwindFromCode(Thread::Current()));
1457530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        }
1458e343b76af81a005ef64f5e75a555389fd9147dabjeffhao#else
1459530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        UNIMPLEMENTED(WARNING);
1460e343b76af81a005ef64f5e75a555389fd9147dabjeffhao#endif
1461bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
1462530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      dex_pc = method->ToDexPC(pc);
1463530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    }
1464530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    if (dex_pc != DexFile::kDexNoIndex) {
1465530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1466530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes      if (found_dex_pc != DexFile::kDexNoIndex) {
1467530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        handler_pc_ = method->ToNativePC(found_dex_pc);
1468530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        handler_frame_ = fr;
1469530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes        return false;
1470bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
14711a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao    }
1472530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    // Caller may be handler, fill in callee saves in context
1473530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    long_jump_context_->FillCalleeSaves(fr);
1474530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
14751a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao  }
14761a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao
1477bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // The type of the exception catch block to find
1478bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Class* to_find_;
1479bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // Frame with found handler or last frame if no handler found
1480bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Frame handler_frame_;
148167375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  // PC to branch to for the handler
148267375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  uintptr_t handler_pc_;
1483bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // Context that will be the target of the long jump
1484bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Context* long_jump_context_;
148567375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  // Number of native methods passed in crawl (equates to number of SIRTs to pop)
148667375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  uint32_t native_method_count_;
1487bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers};
1488bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1489ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogersvoid Thread::DeliverException() {
149028ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  const bool kDebugExceptionDelivery = false;
1491d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Throwable* exception = GetException();  // Get exception from thread
1492ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  CHECK(exception != NULL);
149328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  // Don't leave exception visible while we try to find the handler, which may cause class
1494d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  // resolution.
149528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  ClearException();
149628ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  if (kDebugExceptionDelivery) {
1497a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    String* msg = exception->GetDetailMessage();
1498a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1499a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
1500a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers                        << ": " << str_msg << std::endl);
150128ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  }
1502bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1503bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Context* long_jump_context = GetLongJumpContext();
1504bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
1505530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  WalkStack(&catch_finder, true);
1506bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1507d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method** sp;
1508d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  uintptr_t throw_native_pc;
1509d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method* throw_method = GetCurrentMethod(&throw_native_pc, &sp);
1510d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  uintptr_t catch_native_pc = catch_finder.handler_pc_;
1511d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method* catch_method = catch_finder.handler_frame_.GetMethod();
1512d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Dbg::PostException(sp, throw_method, throw_native_pc, catch_method, catch_native_pc, exception);
1513d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes
151428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  if (kDebugExceptionDelivery) {
1515d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes    if (catch_method == NULL) {
151628ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      LOG(INFO) << "Handler is upcall";
151728ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    } else {
151828ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
151928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      const DexFile& dex_file =
1520d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes          class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1521d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes      int line_number = dex_file.GetLineNumFromPC(catch_method,
1522d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes          catch_method->ToDexPC(catch_finder.handler_pc_));
1523d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes      LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
152428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    }
152528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  }
152628ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  SetException(exception);
15279a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  CHECK_NE(catch_native_pc, 0u);
1528d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  long_jump_context->SetSP(reinterpret_cast<uintptr_t>(catch_finder.handler_frame_.GetSP()));
15299a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  long_jump_context->SetPC(catch_native_pc);
1530bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  long_jump_context->DoLongJump();
15319a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  LOG(FATAL) << "UNREACHABLE";
1532bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers}
1533bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1534bdb0391258abc54bf77c676e36847d28a783bfe5Ian RogersContext* Thread::GetLongJumpContext() {
153585d1545e985ac689db4bad7849880e843707c862Elliott Hughes  Context* result = long_jump_context_;
1536bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  if (result == NULL) {
1537bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    result = Context::Create();
153885d1545e985ac689db4bad7849880e843707c862Elliott Hughes    long_jump_context_ = result;
15391a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao  }
1540bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  return result;
15411a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao}
15421a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao
1543d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott HughesMethod* Thread::GetCurrentMethod(uintptr_t* pc, Method*** sp) const {
1544d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Frame f = top_of_managed_stack_;
1545d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method* m = f.GetMethod();
15468be2d40d42223b515de12629216151a558895969Elliott Hughes  uintptr_t native_pc = top_of_managed_stack_pc_;
15478be2d40d42223b515de12629216151a558895969Elliott Hughes
15489fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // We use JNI internally for exception throwing, so it's possible to arrive
15499fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // here via a "FromCode" function, in which case there's a synthetic
15509fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // callee-save method at the top of the stack. These shouldn't be user-visible,
15519fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // so if we find one, skip it and return the compiled method underneath.
155233dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  if (m != NULL && m->IsCalleeSaveMethod()) {
15538be2d40d42223b515de12629216151a558895969Elliott Hughes    native_pc = f.GetReturnPC();
15549fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes    f.Next();
15559fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes    m = f.GetMethod();
15569fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  }
1557d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  if (pc != NULL) {
15588be2d40d42223b515de12629216151a558895969Elliott Hughes    *pc = (m != NULL) ? ManglePc(native_pc) : 0;
155933dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  }
1560d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  if (sp != NULL) {
1561d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes    *sp = f.GetSP();
1562d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  }
1563d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  return m;
156433dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao}
156533dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao
15665f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesbool Thread::HoldsLock(Object* object) {
15675f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (object == NULL) {
15685f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return false;
15695f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
157024a3c2e9924e8765c4a9b4d383cb8f3b922f9c9fBrian Carlstrom  return object->GetThinLockId() == thin_lock_id_;
15715f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
15725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1573038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesbool Thread::IsDaemon() {
1574038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  return gThread_daemon->GetBoolean(peer_);
1575038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes}
1576038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
1577d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogersclass ReferenceMapVisitor : public Thread::StackVisitor {
1578d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers public:
1579d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1580d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    context_(context), root_visitor_(root_visitor), arg_(arg) {
1581d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1582d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1583530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes  bool VisitFrame(const Frame& frame, uintptr_t pc) {
1584d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    Method* m = frame.GetMethod();
15856a4be3a6226cec645cf905dd352e44f7968a7fa4Brian Carlstrom    if (false) {
15866a4be3a6226cec645cf905dd352e44f7968a7fa4Brian Carlstrom      LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m, false)
15870dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom                << StringPrintf("@ PC:%04x", m->ToDexPC(pc));
15886a4be3a6226cec645cf905dd352e44f7968a7fa4Brian Carlstrom    }
1589d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    // Process register map (which native and callee save methods don't have)
15903891c775503b1113a918180d9ecdaa79e92c69c6Ian Rogers    if (!m->IsNative() && !m->IsCalleeSaveMethod() && !m->IsProxyMethod()) {
1591e7d856b911222aa000ca2be0f8f63f5b292141c3Brian Carlstrom      CHECK(m->GetGcMap() != NULL) << PrettyMethod(m);
1592e7d856b911222aa000ca2be0f8f63f5b292141c3Brian Carlstrom      CHECK_NE(0U, m->GetGcMapLength()) << PrettyMethod(m);
1593e7d856b911222aa000ca2be0f8f63f5b292141c3Brian Carlstrom      verifier::PcToReferenceMap map(m->GetGcMap(), m->GetGcMapLength());
1594d81871cbbaa34c649e488f94f61a981db33123e5Ian Rogers      const uint8_t* reg_bitmap = map.FindBitMap(m->ToDexPC(pc));
1595d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      CHECK(reg_bitmap != NULL);
159668fdbd07fc2b8856905e06f3cc945b046c3bfcd3Elliott Hughes      const VmapTable vmap_table(m->GetVmapTableRaw());
159711d1b0c31ddd710d26068da8e0e4621002205b4bElliott Hughes      const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
15986d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      DCHECK(code_item != NULL);  // can't be NULL or how would we compile its instructions?
15996d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      uint32_t core_spills = m->GetCoreSpillMask();
16006d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      uint32_t fp_spills = m->GetFpSpillMask();
16016d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      size_t frame_size = m->GetFrameSizeInBytes();
16020dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom      // For all dex registers in the bitmap
16036d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      size_t num_regs = std::min(map.RegWidth() * 8,
16046d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                 static_cast<size_t>(code_item->registers_size_));
16050dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom      for (size_t reg = 0; reg < num_regs; ++reg) {
1606d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        // Does this register hold a reference?
1607d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        if (TestBitmap(reg, reg_bitmap)) {
160868fdbd07fc2b8856905e06f3cc945b046c3bfcd3Elliott Hughes          uint32_t vmap_offset;
1609d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          Object* ref;
161068fdbd07fc2b8856905e06f3cc945b046c3bfcd3Elliott Hughes          if (vmap_table.IsInContext(reg, vmap_offset)) {
1611d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            // Compute the register we need to load from the context
1612d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            uint32_t spill_mask = m->GetCoreSpillMask();
16130dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom            CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
1614f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            uint32_t matches = 0;
1615f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            uint32_t spill_shifts = 0;
1616f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            while (matches != (vmap_offset + 1)) {
16170dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom              DCHECK_NE(spill_mask, 0u);
1618f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              matches += spill_mask & 1;  // Add 1 if the low bit is set
1619f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              spill_mask >>= 1;
1620f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              spill_shifts++;
1621d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            }
1622f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            spill_shifts--;  // wind back one as we want the last match
1623f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
1624d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          } else {
16256d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers            ref = reinterpret_cast<Object*>(frame.GetVReg(code_item, core_spills, fp_spills,
16266d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                          frame_size, reg));
1627d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          }
16284f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao          if (ref != NULL) {
16294f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao            root_visitor_(ref, arg_);
16304f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao          }
1631d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        }
1632d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      }
1633d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    }
1634d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    context_->FillCalleeSaves(frame);
1635530fa005e2944d3b12712f80d974f0e753f568efElliott Hughes    return true;
1636d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1637d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1638d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers private:
1639d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  bool TestBitmap(int reg, const uint8_t* reg_vector) {
1640d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1641d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1642d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1643d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Context used to build up picture of callee saves
1644d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Context* context_;
1645d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Call-back when we visit a root
1646d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Heap::RootVisitor* root_visitor_;
1647d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Argument to call-back
1648d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  void* arg_;
1649d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers};
1650d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1651d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogersvoid Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
1652d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (exception_ != NULL) {
1653d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    visitor(exception_, arg);
1654d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
1655d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (peer_ != NULL) {
1656d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    visitor(peer_, arg);
1657d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
1658726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  if (pre_allocated_OutOfMemoryError_ != NULL) {
1659726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    visitor(pre_allocated_OutOfMemoryError_, arg);
1660726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  }
166140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  if (class_loader_override_ != NULL) {
166240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    visitor(class_loader_override_, arg);
166340381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  }
1664410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes  jni_env_->locals.VisitRoots(visitor, arg);
1665410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes  jni_env_->monitors.VisitRoots(visitor, arg);
16668dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
16678dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao  SirtVisitRoots(visitor, arg);
16688dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
1669d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1670d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // delivery.
1671d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Context* context = GetLongJumpContext();
1672d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Visit roots on this thread's stack
1673d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  ReferenceMapVisitor mapper(context, visitor, arg);
1674d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  WalkStack(&mapper);
1675410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes}
1676410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes
1677b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogersstatic const char* kStateNames[] = {
167893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Terminated",
1679b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Runnable",
168093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "TimedWaiting",
1681b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Blocked",
1682b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Waiting",
168393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Initializing",
168493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Starting",
1685b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Native",
168693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "VmWait",
168793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Suspended",
1688b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers};
1689b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogersstd::ostream& operator<<(std::ostream& os, const Thread::State& state) {
16908e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  int32_t int_state = static_cast<int32_t>(state);
169193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
169293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    os << kStateNames[int_state];
1693b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  } else {
169493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    os << "State[" << int_state << "]";
1695b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  }
1696b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  return os;
1697b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers}
1698b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers
1699330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughesstd::ostream& operator<<(std::ostream& os, const Thread& thread) {
1700899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  thread.Dump(os, false);
1701330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes  return os;
1702330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes}
1703330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes
1704a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughesvoid Thread::CheckSafeToLockOrUnlock(MutexRank rank, bool is_locking) {
1705ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  if (is_locking) {
1706ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    if (held_mutexes_[rank] == 0) {
1707ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      bool bad_mutexes_held = false;
1708ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      for (int i = kMaxMutexRank; i > rank; --i) {
1709ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes        if (held_mutexes_[i] != 0) {
1710ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes          LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while " << (is_locking ? "locking" : "unlocking") << " " << rank;
1711ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes          bad_mutexes_held = true;
1712ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes        }
1713ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      }
1714ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      CHECK(!bad_mutexes_held);
1715ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    }
1716ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    ++held_mutexes_[rank];
1717ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  } else {
1718ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    CHECK_GT(held_mutexes_[rank], 0U);
1719ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    --held_mutexes_[rank];
1720ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
1721ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes}
1722ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes
1723a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughesvoid Thread::CheckSafeToWait(MutexRank rank) {
1724a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  bool bad_mutexes_held = false;
1725a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  for (int i = kMaxMutexRank; i >= 0; --i) {
1726a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    if (i != rank && held_mutexes_[i] != 0) {
1727a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes      LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while doing condition variable wait on " << rank;
1728a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes      bad_mutexes_held = true;
1729a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    }
1730a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  }
1731a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  if (held_mutexes_[rank] == 0) {
1732a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    LOG(ERROR) << "*not* holding " << rank << " while doing condition variable wait on it";
1733a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    bad_mutexes_held = true;
1734a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  }
1735a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  CHECK(!bad_mutexes_held);
1736a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes}
1737a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes
17388daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes}  // namespace art
1739