thread.cc revision b3bd5f07884f5a1f2b84224363b1372d7c28d447
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;
96a433b2e8edf91c8124abd8eb5b3bd558a40fc987Ian Rogers  pCmpgFloat = artCmpgFloat;
97a433b2e8edf91c8124abd8eb5b3bd558a40fc987Ian Rogers  pCmplFloat = artCmplFloat;
98a433b2e8edf91c8124abd8eb5b3bd558a40fc987Ian Rogers  pCmpgDouble = artCmpgDouble;
99a433b2e8edf91c8124abd8eb5b3bd558a40fc987Ian Rogers  pCmplDouble = artCmplDouble;
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
569bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  void VisitFrame(const Frame& frame, uintptr_t pc) {
5709086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    if (!frame.HasMethod()) {
5719086572fa809d1a19d886b467e4da3ce42016982Ian Rogers      return;
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    }
609d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
6106d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers  MethodHelper mh;
61128ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  Method* last_method;
61228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  int last_line_number;
61328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  int repetition_count;
614d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  std::ostream& os;
6158e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  const Thread* thread;
6168e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  int frame_count;
617d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes};
618d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
619d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughesvoid Thread::DumpStack(std::ostream& os) const {
620ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  // If we're currently in native code, dump that stack before dumping the managed stack.
621ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  if (GetState() == Thread::kNative || GetState() == Thread::kVmWait) {
622ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    DumpNativeStack(os);
623ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
6248e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  StackDumpVisitor dumper(os, this);
625d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  WalkStack(&dumper);
626e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes}
627e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes
628a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughesvoid Thread::SetStateWithoutSuspendCheck(Thread::State new_state) {
629a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  volatile void* raw = reinterpret_cast<volatile void*>(&state_);
630a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
631a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  android_atomic_release_store(new_state, addr);
632a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes}
633a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes
6348d768a954b101a9532f980253ac46be2c53aba11Elliott HughesThread::State Thread::SetState(Thread::State new_state) {
6358d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  Thread::State old_state = state_;
6368d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  if (old_state == new_state) {
6378d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    return old_state;
6388d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
6398d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
6408d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  volatile void* raw = reinterpret_cast<volatile void*>(&state_);
6418d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
6428d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
6438d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  if (new_state == Thread::kRunnable) {
6448d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    /*
6458d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * Change our status to Thread::kRunnable.  The transition requires
6468d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that we check for pending suspension, because the VM considers
6478d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * us to be "asleep" in all other states, and another thread could
6488d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * be performing a GC now.
6498d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6508d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * The order of operations is very significant here.  One way to
6518d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * do this wrong is:
6528d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6538d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   GCing thread                   Our thread (in kNative)
6548d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   ------------                   ----------------------
6558d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  check suspend count (== 0)
6568d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   SuspendAllThreads()
6578d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   grab suspend-count lock
6588d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   increment all suspend counts
6598d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   release suspend-count lock
6608d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   check thread state (== kNative)
6618d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   all are suspended, begin GC
6628d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  set state to kRunnable
6638d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  (continue executing)
6648d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6658d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We can correct this by grabbing the suspend-count lock and
6668d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * performing both of our operations (check suspend count, set
6678d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * state) while holding it, now we need to grab a mutex on every
6688d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * transition to kRunnable.
6698d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6708d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * What we do instead is change the order of operations so that
6718d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * the transition to kRunnable happens first.  If we then detect
6728d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that the suspend count is nonzero, we switch to kSuspended.
6738d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6748d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * Appropriate compiler and memory barriers are required to ensure
6758d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that the operations are observed in the expected order.
6768d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6778d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * This does create a small window of opportunity where a GC in
6788d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * progress could observe what appears to be a running thread (if
6798d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * it happens to look between when we set to kRunnable and when we
6808d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * switch to kSuspended).  At worst this only affects assertions
6818d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * and thread logging.  (We could work around it with some sort
6828d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * of intermediate "pre-running" state that is generally treated
6838d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * as equivalent to running, but that doesn't seem worthwhile.)
6848d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
6858d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We can also solve this by combining the "status" and "suspend
6868d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * count" fields into a single 32-bit value.  This trades the
6878d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * store/load barrier on transition to kRunnable for an atomic RMW
6888d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * op on all transitions and all suspend count updates (also, all
6898d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * accesses to status or the thread count require bit-fiddling).
6908d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * It also eliminates the brief transition through kRunnable when
6918d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * the thread is supposed to be suspended.  This is possibly faster
6928d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * on SMP and slightly more correct, but less convenient.
6938d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     */
6948d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    android_atomic_acquire_store(new_state, addr);
69506e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    ANNOTATE_IGNORE_READS_BEGIN();
69606e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    int suspend_count = suspend_count_;
69706e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    ANNOTATE_IGNORE_READS_END();
69806e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes    if (suspend_count != 0) {
6998d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
7008d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    }
7018d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  } else {
7028d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    /*
7038d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * Not changing to Thread::kRunnable. No additional work required.
7048d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
7058d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We use a releasing store to ensure that, if we were runnable,
7068d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * any updates we previously made to objects on the managed heap
7078d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * will be observed before the state change.
7088d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     */
7098d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    android_atomic_release_store(new_state, addr);
7108d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
7118d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
7128d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  return old_state;
7138d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes}
7148d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
715761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughesbool Thread::IsSuspended() {
71606e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  ANNOTATE_IGNORE_READS_BEGIN();
71706e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  int suspend_count = suspend_count_;
71806e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  ANNOTATE_IGNORE_READS_END();
71906e3ad4a651c2c58dba5e865cd06d2f98462bf1dElliott Hughes  return suspend_count != 0 && GetState() != Thread::kRunnable;
720761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes}
721761928d24e4e7ed7776b52243eaf9095ad35f448Elliott Hughes
722ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughesstatic void ReportThreadSuspendTimeout(Thread* waiting_thread) {
723ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  Runtime* runtime = Runtime::Current();
724ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  std::ostringstream ss;
725ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  ss << "Thread suspend timeout waiting for thread " << *waiting_thread << "\n";
726ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  runtime->DumpLockHolders(ss);
727ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  ss << "\n";
728ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  runtime->GetThreadList()->DumpLocked(ss);
729ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes  LOG(FATAL) << ss.str();
730ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes}
731ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes
7328d768a954b101a9532f980253ac46be2c53aba11Elliott Hughesvoid Thread::WaitUntilSuspended() {
73321a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes  static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
73421a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes
73521a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes  useconds_t total_delay = 0;
7368d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  useconds_t delay = 0;
7378d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  while (GetState() == Thread::kRunnable) {
73821a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes    if (total_delay >= kTimeoutUs) {
739ff7380681c50129ff689a11ac0f49512b4be7295Elliott Hughes      ReportThreadSuspendTimeout(this);
74021a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes    }
7418d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    useconds_t new_delay = delay * 2;
7428d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    CHECK_GE(new_delay, delay);
7438d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    delay = new_delay;
7448d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    if (delay == 0) {
7458d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      sched_yield();
7468d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      delay = 10000;
7478d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    } else {
7488d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      usleep(delay);
74921a5bf2dc8c9cb3fbe5a30a88d1149c328e3aacaElliott Hughes      total_delay += delay;
7508d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    }
7518d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
7528d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes}
7538d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
754be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::ThreadExitCallback(void* arg) {
755be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  Thread* self = reinterpret_cast<Thread*>(arg);
756be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
757b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
758b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
759be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::Startup() {
760b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  // Allocate a TLS slot.
7618d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
762b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
763b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  // Double-check the TLS slot allocation.
764b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  if (pthread_getspecific(pthread_key_self_) != NULL) {
7653d30d9b09c16542d41554aad9f46ec9109ba5cb5Elliott Hughes    LOG(FATAL) << "Newly-created pthread TLS slot is not NULL";
766b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  }
767038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes}
768038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
7698e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
7708e4aac52962d54cb4be2078b9cd95685e067133aElliott HughesClass* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
7718e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* c = class_linker->FindPrimitiveClass(descriptor);
7728e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(c != NULL) << descriptor;
7738e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return c;
7748e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7758e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
7768e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
7778e4aac52962d54cb4be2078b9cd95685e067133aElliott HughesClass* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
7788e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* c = class_linker->FindSystemClass(descriptor);
7798e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(c != NULL) << descriptor;
7808e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return c;
7818e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7828e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
7838e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
7846b4ef025af12b158d117fc80fc79acf620f411a0Brian CarlstromField* FindFieldOrDie(Class* c, const char* name, const char* descriptor) {
7856b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  Field* f = c->FindDeclaredInstanceField(name, descriptor);
7866b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << descriptor;
7878e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return f;
7888e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7898e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
7908e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
7918e4aac52962d54cb4be2078b9cd95685e067133aElliott HughesMethod* FindMethodOrDie(Class* c, const char* name, const char* signature) {
7928e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Method* m = c->FindVirtualMethod(name, signature);
7938e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
7948e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return m;
7958e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7968e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
797038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesvoid Thread::FinishStartup() {
7989a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  CHECK(Runtime::Current()->IsStarted());
799b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom  Thread* self = Thread::Current();
800b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom
801b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom  // Need to be kRunnable for FindClass
802b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom  ScopedThreadStateChange tsc(self, Thread::kRunnable);
803b82b6878fb000d4731063b1bf15c39ff7c50b61fBrian Carlstrom
804038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
805038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
8068e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
8078e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
8088e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
8098e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
8108e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
8118e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
8126b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_daemon = FindFieldOrDie(Thread_class, "daemon", "Z");
8136b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_group = FindFieldOrDie(Thread_class, "group", "Ljava/lang/ThreadGroup;");
8146b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_lock = FindFieldOrDie(Thread_class, "lock", "Ljava/lang/ThreadLock;");
8156b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_name = FindFieldOrDie(Thread_class, "name", "Ljava/lang/String;");
8166b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_priority = FindFieldOrDie(Thread_class, "priority", "I");
8176b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", "Ljava/lang/Thread$UncaughtExceptionHandler;");
8186b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThread_vmData = FindFieldOrDie(Thread_class, "vmData", "I");
8196b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", "Ljava/lang/String;");
8206b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", "Ljava/lang/Thread;");
8218e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
8228e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
8238e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
8248e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
8258e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
82601158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
82701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  // Finish attaching the main thread.
8289a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  Thread::Current()->CreatePeer("main", false);
8299a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson
8309a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  InitBoxingMethods();
8319a6bae896a2f003d7216603bf29771d105c10ca4Jesse Wilson  class_linker->RunRootClinits();
832b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
833b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
834c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughesvoid Thread::Shutdown() {
8358d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
836c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes}
837c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes
8388e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesuint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
8398e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
8408e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
8418e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
8428e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
8438e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (managed_thread == NULL) {
8448e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
8458e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
8468e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
8478e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Thread* thread = reinterpret_cast<Thread*>(vmData);
8488e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (thread == NULL) {
8498e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
8508e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
8518e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return thread->GetThinLockId();
8528e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
8538e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
854dcc247493fd8fb243e335c3ec08e5e625896a47cElliott HughesThread::Thread()
85547179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes    : thin_lock_id_(0),
85647179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes      tid_(0),
85747179f76e3f03fe3eb21dfb081d50733ca316371Elliott Hughes      peer_(NULL),
8588e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      top_of_managed_stack_(),
8598e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      top_of_managed_stack_pc_(0),
86085d1545e985ac689db4bad7849880e843707c862Elliott Hughes      wait_mutex_(new Mutex("Thread wait mutex")),
86185d1545e985ac689db4bad7849880e843707c862Elliott Hughes      wait_cond_(new ConditionVariable("Thread wait condition variable")),
8628daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      wait_monitor_(NULL),
8638daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      interrupted_(false),
864dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      wait_next_(NULL),
8658e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      monitor_enter_object_(NULL),
866dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      card_table_(0),
8678daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      stack_end_(NULL),
868dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      native_to_managed_record_(NULL),
869dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      top_sirt_(NULL),
870dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      jni_env_(NULL),
8718e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      state_(Thread::kNative),
872dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      self_(NULL),
873dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      runtime_(NULL),
874dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      exception_(NULL),
875dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      suspend_count_(0),
876234ab15b00f8120282d1833e5d7480eca2e35a29Elliott Hughes      debug_suspend_count_(0),
87785d1545e985ac689db4bad7849880e843707c862Elliott Hughes      class_loader_override_(NULL),
878418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes      long_jump_context_(NULL),
879726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      throwing_OutOfMemoryError_(false),
880475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes      pre_allocated_OutOfMemoryError_(NULL),
881e343b76af81a005ef64f5e75a555389fd9147dabjeffhao      debug_invoke_req_(new DebugInvokeReq),
882899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      trace_stack_(new std::vector<TraceStackFrame>),
883899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes      name_(new std::string("<native thread without managed peer>")) {
884f5a7a476e7ea63e094ff0f011dccc170607e6f6bElliott Hughes  CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
885ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  memset(&held_mutexes_[0], 0, sizeof(held_mutexes_));
886dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes}
887dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes
88802b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughesvoid MonitorExitVisitor(const Object* object, void*) {
88902b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  Object* entered_monitor = const_cast<Object*>(object);
8905f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  entered_monitor->MonitorExit(Thread::Current());
89102b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes}
89202b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
893c1674ed06662420213441ff2b818f2f71f9098dcElliott HughesThread::~Thread() {
89402b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
89593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  if (jni_env_ != NULL) {
89693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
89793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  }
89802b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
89929f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  if (peer_ != NULL) {
90029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes
90129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // this.vmData = 0;
90293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    SetVmData(peer_, NULL);
90302b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
904872d4ec7225444d9400d30f9027247deb91012fdElliott Hughes    Dbg::PostThreadDeath(this);
90502b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
90629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // Thread.join() is implemented as an Object.wait() on the Thread.lock
90729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // object. Signal anyone who is waiting.
9085f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    Thread* self = Thread::Current();
909038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    Object* lock = gThread_lock->GetObject(peer_);
910038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    // (This conditional is only needed for tests, where Thread.lock won't have been set.)
9115f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    if (lock != NULL) {
9125f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->MonitorEnter(self);
9135f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->NotifyAll();
9145f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->MonitorExit(self);
9155f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
9165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
91702b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
918c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes  delete jni_env_;
91902b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  jni_env_ = NULL;
92002b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
92102b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  SetState(Thread::kTerminated);
92285d1545e985ac689db4bad7849880e843707c862Elliott Hughes
92385d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete wait_cond_;
92485d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete wait_mutex_;
92585d1545e985ac689db4bad7849880e843707c862Elliott Hughes
92685d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete long_jump_context_;
927475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes
928475fc23a4a7f35d1be87ea0b06c80df317a720acElliott Hughes  delete debug_invoke_req_;
929e343b76af81a005ef64f5e75a555389fd9147dabjeffhao  delete trace_stack_;
930899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  delete name_;
931c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes}
932c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes
933accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughesvoid Thread::HandleUncaughtExceptions() {
934accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  if (!IsExceptionPending()) {
935accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    return;
936accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  }
937accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
938accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // Get and clear the exception.
939accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* exception = GetException();
940accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  ClearException();
941accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
942accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // If the thread has its own handler, use that.
943accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* handler = gThread_uncaughtHandler->GetObject(peer_);
944accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  if (handler == NULL) {
945accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    // Otherwise use the thread group's default handler.
946a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes    handler = GetThreadGroup();
947accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  }
948accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
949accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // Call the handler.
950accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
951accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* args[2];
952accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  args[0] = peer_;
953accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  args[1] = exception;
954accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
955accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
956accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // If the handler threw, clear that exception too.
957accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  ClearException();
958accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
9594514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom
960a215526d5c789cbef0f81a1f9aba22541a841ccaElliott HughesObject* Thread::GetThreadGroup() const {
961a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes  return gThread_group->GetObject(peer_);
962a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes}
963a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes
9644514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstromvoid Thread::RemoveFromThreadGroup() {
9654514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  // this.group.removeThread(this);
9664514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  // group can be null if we're in the compiler or a test.
967a215526d5c789cbef0f81a1f9aba22541a841ccaElliott Hughes  Object* group = GetThreadGroup();
9684514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  if (group != NULL) {
9694514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom    Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
9704514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom    Object* args = peer_;
9714514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom    m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
9724514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom  }
9734514d3c0e69a49f5dbe19138330a2bb2aee36d63Brian Carlstrom}
974accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
975408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogerssize_t Thread::NumSirtReferences() {
976a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  size_t count = 0;
97740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
978a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers    count += cur->NumberOfReferences();
979a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  }
980a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  return count;
981a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers}
982a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers
983408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogersbool Thread::SirtContains(jobject obj) {
984408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  Object** sirt_entry = reinterpret_cast<Object**>(obj);
98540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
98640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    if (cur->Contains(sirt_entry)) {
987a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers      return true;
988a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers    }
989a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  }
990a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  return false;
991a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers}
992a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers
9938dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liaovoid Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
99440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
9958dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    size_t num_refs = cur->NumberOfReferences();
9968dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    for (size_t j = 0; j < num_refs; j++) {
99740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom      Object* object = cur->GetReference(j);
9985e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom      if (object != NULL) {
9995e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom        visitor(object, arg);
10005e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom      }
10018dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    }
10028dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao  }
10038dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao}
10048dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
1005408f79aeb676251ba35667a64e86c20638d7cb0bIan RogersObject* Thread::DecodeJObject(jobject obj) {
10060cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  DCHECK(CanAccessDirectReferences());
1007408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  if (obj == NULL) {
1008408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    return NULL;
1009408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1010408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
1011408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  IndirectRefKind kind = GetIndirectRefKind(ref);
1012408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  Object* result;
1013408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  switch (kind) {
1014408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kLocal:
1015408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
101669f5bc6759f256a146eefd8a7141d39fcc3b0421Elliott Hughes      IndirectReferenceTable& locals = jni_env_->locals;
1017cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(locals.Get(ref));
1018408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1019408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1020408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kGlobal:
1021408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
1022408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1023408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      IndirectReferenceTable& globals = vm->globals;
1024408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      MutexLock mu(vm->globals_lock);
1025cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(globals.Get(ref));
1026408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1027408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1028408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kWeakGlobal:
1029408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
1030408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
1031408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      IndirectReferenceTable& weak_globals = vm->weak_globals;
1032408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      MutexLock mu(vm->weak_globals_lock);
1033cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(weak_globals.Get(ref));
1034408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      if (result == kClearedJniWeakGlobal) {
1035408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers        // This is a special case where it's okay to return NULL.
1036408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers        return NULL;
1037408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      }
1038408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
1039408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1040408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kSirtOrInvalid:
1041408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  default:
1042408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    // TODO: make stack indirect reference table lookup more efficient
1043408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    // Check if this is a local reference in the SIRT
1044408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    if (SirtContains(obj)) {
10450cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers      result = *reinterpret_cast<Object**>(obj);  // Read from SIRT
1046c2dc62d1c9241dfe880a81698713c314b13aa63fElliott Hughes    } else if (Runtime::Current()->GetJavaVM()->work_around_app_jni_bugs) {
1047408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      // Assume an invalid local reference is actually a direct pointer.
1048408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      result = reinterpret_cast<Object*>(obj);
1049408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    } else {
1050a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes      result = kInvalidIndirectRefObject;
1051408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
1052408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1053408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers
1054408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  if (result == NULL) {
1055a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
1056a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    JniAbort(NULL);
1057a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes  } else {
1058a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    if (result != kInvalidIndirectRefObject) {
1059b3bd5f07884f5a1f2b84224363b1372d7c28d447Elliott Hughes      Runtime::Current()->GetHeap()->VerifyObject(result);
1060a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    }
1061408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
1062408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  return result;
1063408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers}
1064408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers
10659b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liaoclass CountStackDepthVisitor : public Thread::StackVisitor {
10669b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao public:
106729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
1068d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
106929f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
107029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // We want to skip frames up to and including the exception's constructor.
10719086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    // Note we also skip the frame if it doesn't have a method (namely the callee
10729086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    // save frame)
10735167c97a4f672ba821453418e3943988fabbfc43Ian Rogers    if (skipping_ && frame.HasMethod() &&
10745167c97a4f672ba821453418e3943988fabbfc43Ian Rogers        !Throwable::GetJavaLangThrowable()->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
107529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      skipping_ = false;
107629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
107729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    if (!skipping_) {
10786b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers      if (frame.HasMethod()) {  // ignore callee save frames
10796b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers        ++depth_;
10806b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers      }
108129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    } else {
108229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      ++skip_depth_;
108329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
10849b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
10859b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
10869b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  int GetDepth() const {
1087aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    return depth_;
10889b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
10899b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
109029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int GetSkipDepth() const {
109129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    return skip_depth_;
109229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  }
109329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes
10949b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao private:
1095aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  uint32_t depth_;
109629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  uint32_t skip_depth_;
109729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  bool skipping_;
10989b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao};
10999b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1100aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogersclass BuildInternalStackTraceVisitor : public Thread::StackVisitor {
11019b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao public:
1102283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  explicit BuildInternalStackTraceVisitor(int skip_depth)
1103726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      : skip_depth_(skip_depth), count_(0), pc_trace_(NULL), method_trace_(NULL), local_ref_(NULL) {
1104283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  }
1105283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers
1106283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  bool Init(int depth, ScopedJniThreadState& ts) {
1107aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Allocate method trace with an extra slot that will hold the PC trace
110801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
1109726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (method_trace_ == NULL) {
1110283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers      return false;
1111726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
1112aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Register a local reference as IntArray::Alloc may trigger GC
1113aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
1114aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    pc_trace_ = IntArray::Alloc(depth);
1115726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (pc_trace_ == NULL) {
1116283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers      return false;
1117726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
1118aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#ifdef MOVING_GARBAGE_COLLECTOR
1119aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Re-read after potential GC
1120267364429db05d964c0922a8b4e49591c00bdc35Brian Carlstrom    method_trace_ = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
1121aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#endif
1122aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Save PC trace in last element of method trace, also places it into the
1123aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // object graph.
1124aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace_->Set(depth, pc_trace_);
1125283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers    return true;
11269b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11279b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1128aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  virtual ~BuildInternalStackTraceVisitor() {}
11299b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1130bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
1131726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (method_trace_ == NULL || pc_trace_ == NULL) {
1132726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      return; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
1133726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
113429f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    if (skip_depth_ > 0) {
113529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      skip_depth_--;
113629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      return;
113729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
11386b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers    if (!frame.HasMethod()) {
11396b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers      return;  // ignore callee save frames
11406b0870dfaaa2e69a900ad7ed88e4e1d3697445aaIan Rogers    }
1141aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace_->Set(count_, frame.GetMethod());
1142bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    pc_trace_->Set(count_, pc);
1143aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    ++count_;
11449b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11459b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1146aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  jobject GetInternalStackTrace() const {
1147aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    return local_ref_;
11489b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
11499b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
11509b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao private:
115129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  // How many more frames to skip.
115229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int32_t skip_depth_;
1153aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Current position down stack trace
1154aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  uint32_t count_;
1155aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Array of return PC values
1156aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  IntArray* pc_trace_;
1157aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // An array of the methods on the stack, the last entry is a reference to the
1158aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // PC trace
1159aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ObjectArray<Object>* method_trace_;
1160aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Local indirect reference table entry for method trace
1161aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  jobject local_ref_;
11629b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao};
11639b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1164a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes// TODO: remove this.
1165a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughesuintptr_t ManglePc(uintptr_t pc) {
1166a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // Move the PC back 2 bytes as a call will frequently terminate the
1167a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // decoding of a particular instruction and we want to make sure we
1168a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // get the Dex PC of the instruction with the call and not the
1169a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // instruction following.
1170a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  if (pc > 0) { pc -= 2; }
1171a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  return pc;
1172a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes}
1173a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes
1174a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes// TODO: remove this.
1175a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughesuintptr_t DemanglePc(uintptr_t pc) {
1176a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // Revert mangling for the case where we need the PC to return to the upcall
11779a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  if (pc > 0) { pc +=  2; }
11789a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  return pc;
1179a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes}
1180f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers
118140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstromvoid Thread::PushSirt(StackIndirectReferenceTable* sirt) {
118240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  sirt->SetLink(top_sirt_);
118340381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  top_sirt_ = sirt;
118440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom}
118540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom
118640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian CarlstromStackIndirectReferenceTable* Thread::PopSirt() {
118740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  CHECK(top_sirt_ != NULL);
118840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  StackIndirectReferenceTable* sirt = top_sirt_;
118940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  top_sirt_ = top_sirt_->GetLink();
119040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  return sirt;
119140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom}
119240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom
1193aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogersvoid Thread::WalkStack(StackVisitor* visitor) const {
1194d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  Frame frame = GetTopOfStack();
1195a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
1196a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao#if defined(__arm__)
1197a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao  uint32_t trace_stack_depth = 0;
1198a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao#endif
11999b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
12009b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  // CHECK(native_to_managed_record_ != NULL);
12019b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  NativeToManagedRecord* record = native_to_managed_record_;
12024417536522fd2a9d8215d8672331984769c9520bShih-wei Liao
1203bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  while (frame.GetSP() != 0) {
12049b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    for ( ; frame.GetMethod() != 0; frame.Next()) {
12053320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom      // DCHECK(frame.GetMethod()->IsWithinCode(pc));  // TODO: restore IsWithinCode
12063ddac99d4dc6a036fac59d8f0bdc664ef619fb04Shih-wei Liao      visitor->VisitFrame(frame, pc);
1207a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes      pc = ManglePc(frame.GetReturnPC());
12082692b573a56cd63a3c8c8aa1636e3766b6d8c9c4jeffhao      if (Runtime::Current()->IsMethodTracingActive()) {
1209a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao#if defined(__arm__)
1210a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao        uintptr_t trace_exit = reinterpret_cast<uintptr_t>(art_trace_exit_from_code);
1211a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao        if (ManglePc(trace_exit) == pc) {
1212a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao          TraceStackFrame trace_frame = GetTraceStackFrame(trace_stack_depth++);
121326c0a1a376d8cd639fe6b16594fcb55a723450c0jeffhao          CHECK(trace_frame.method_ == frame.GetMethod());
1214a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao          pc = ManglePc(trace_frame.return_pc_);
1215a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao        }
1216a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao#endif
1217a9ef3fd82bebc6370fc3ddbb094988feb6c83022jeffhao      }
12189b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    }
12199b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    if (record == NULL) {
12209b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao      break;
12219b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    }
1222bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    // last_tos should return Frame instead of sp?
1223ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers    frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
1224a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes    pc = ManglePc(record->last_top_of_managed_stack_pc_);
1225bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    record = record->link_;
1226bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  }
1227bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers}
1228bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
122967375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogersvoid Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
1230bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Frame frame = GetTopOfStack();
1231a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
1232bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1233bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  if (frame.GetSP() != 0) {
1234bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    for ( ; frame.GetMethod() != 0; frame.Next()) {
12353320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom      // DCHECK(frame.GetMethod()->IsWithinCode(pc));  // TODO: restore IsWithinCode
12363ddac99d4dc6a036fac59d8f0bdc664ef619fb04Shih-wei Liao      visitor->VisitFrame(frame, pc);
1237a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes      pc = ManglePc(frame.GetReturnPC());
1238bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    }
123967375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    if (include_upcall) {
124067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers      visitor->VisitFrame(frame, pc);
124167375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    }
124255df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao  }
124355df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao}
124455df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
124501158d7a57c8321370667a6045220237d16e0da8Elliott Hughesjobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
1246aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Compute depth of stack
12479b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  CountStackDepthVisitor count_visitor;
12489b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  WalkStack(&count_visitor);
12499b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  int32_t depth = count_visitor.GetDepth();
125029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int32_t skip_depth = count_visitor.GetSkipDepth();
12514417536522fd2a9d8215d8672331984769c9520bShih-wei Liao
1252aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Transition into runnable state to work on Object*/Array*
125301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  ScopedJniThreadState ts(env);
1254aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
1255aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Build internal stack trace
125677f74c1455bd8d29deb8a9367cea35deb930ed10Ian Rogers  BuildInternalStackTraceVisitor build_trace_visitor(skip_depth);
125777f74c1455bd8d29deb8a9367cea35deb930ed10Ian Rogers  if (!build_trace_visitor.Init(depth, ts)) {
1258283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers    return NULL;  // Allocation failed
1259283ed0d9db3084d0fee46d47cd73bf84bd0cfc16Ian Rogers  }
1260267364429db05d964c0922a8b4e49591c00bdc35Brian Carlstrom  WalkStack(&build_trace_visitor);
1261267364429db05d964c0922a8b4e49591c00bdc35Brian Carlstrom  return build_trace_visitor.GetInternalStackTrace();
1262aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers}
1263aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
126401158d7a57c8321370667a6045220237d16e0da8Elliott HughesjobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
126501158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    jobjectArray output_array, int* stack_depth) {
1266aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Transition into runnable state to work on Object*/Array*
1267aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ScopedJniThreadState ts(env);
1268aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Decode the internal stack trace into the depth, method trace and PC trace
1269aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ObjectArray<Object>* method_trace =
1270aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers      down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
12719074b99bfbd5419e340f138a018b673ce71f77e8Ian Rogers  int32_t depth = method_trace->GetLength() - 1;
1272aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1273aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
1274aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1275aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
127601158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  jobjectArray result;
127701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  ObjectArray<StackTraceElement>* java_traces;
127801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  if (output_array != NULL) {
127901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // Reuse the array we were given.
128001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    result = output_array;
128101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
128201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes        output_array));
128301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // ...adjusting the number of frames we'll write to not exceed the array length.
128401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    depth = std::min(depth, java_traces->GetLength());
128501158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  } else {
128601158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // Create java_trace array and place in local reference table
128701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    java_traces = class_linker->AllocStackTraceElementArray(depth);
128830646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    if (java_traces == NULL) {
128930646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes      return NULL;
129030646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    }
129101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
129201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  }
129301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
129401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  if (stack_depth != NULL) {
129501158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    *stack_depth = depth;
129601158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  }
129755df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
12986d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers  MethodHelper mh;
12999b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  for (int32_t i = 0; i < depth; ++i) {
1300aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1301aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    Method* method = down_cast<Method*>(method_trace->Get(i));
13026d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    mh.ChangeMethod(method);
1303aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    uint32_t native_pc = pc_trace->Get(i);
13046d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    int32_t line_number = mh.GetLineNumFromNativePC(native_pc);
1305aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Allocate element, potentially triggering GC
130640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    // TODO: reuse class_name_object via Class::name_?
1307486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* descriptor = mh.GetDeclaringClassDescriptor();
1308486013193c94b4321414c28ce9251911e14a0599Ian Rogers    CHECK(descriptor != NULL);
1309486013193c94b4321414c28ce9251911e14a0599Ian Rogers    std::string class_name(PrettyDescriptor(descriptor));
131040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
131140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    if (class_name_object.get() == NULL) {
131240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom      return NULL;
131340381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    }
1314486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* method_name = mh.GetName();
1315486013193c94b4321414c28ce9251911e14a0599Ian Rogers    CHECK(method_name != NULL);
1316486013193c94b4321414c28ce9251911e14a0599Ian Rogers    SirtRef<String> method_name_object(String::AllocFromModifiedUtf8(method_name));
13176d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    if (method_name_object.get() == NULL) {
13186d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      return NULL;
13196d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers    }
1320486013193c94b4321414c28ce9251911e14a0599Ian Rogers    const char* source_file = mh.GetDeclaringClassSourceFile();
1321486013193c94b4321414c28ce9251911e14a0599Ian Rogers    SirtRef<String> source_name_object(String::AllocFromModifiedUtf8(source_file));
132240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
13236d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                      method_name_object.get(),
13246d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                      source_name_object.get(),
132540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom                                                      line_number);
132630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    if (obj == NULL) {
132730646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes      return NULL;
132830646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    }
1329aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#ifdef MOVING_GARBAGE_COLLECTOR
1330aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Re-read after potential GC
1331aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1332aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1333aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1334aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#endif
133555df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao    java_traces->Set(i, obj);
133655df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao  }
1337aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  return result;
133855df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao}
133955df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
13405cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughesvoid Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
1341a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_list args;
1342a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_start(args, fmt);
13434a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  ThrowNewExceptionV(exception_class_descriptor, fmt, args);
1344a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_end(args);
13454a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes}
13464a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes
13474a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughesvoid Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
13484a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  std::string msg;
13494a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  StringAppendV(&msg, fmt, ap);
13505cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughes  ThrowNewException(exception_class_descriptor, msg.c_str());
13515cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughes}
135237f7a40f6789bb287f287a9af00777af9d6428eeElliott Hughes
13535cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughesvoid Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
1354e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
13550cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  CHECK_EQ('L', exception_class_descriptor[0]);
1356e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  std::string descriptor(exception_class_descriptor + 1);
13570cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  CHECK_EQ(';', descriptor[descriptor.length() - 1]);
1358e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  descriptor.erase(descriptor.length() - 1);
1359e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes
1360e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  JNIEnv* env = GetJniEnv();
1361726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
136230646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  if (exception_class.get() == NULL) {
136330646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
136430646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes               << PrettyTypeOf(GetException());
136530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    CHECK(IsExceptionPending());
136630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    return;
136730646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  }
1368ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom  if (!Runtime::Current()->IsStarted()) {
1369ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // Something is trying to throw an exception without a started
1370ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // runtime, which is the common case in the compiler. We won't be
1371ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // able to invoke the constructor of the exception, so use
1372ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    // AllocObject which will not invoke a constructor.
1373ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    ScopedLocalRef<jthrowable> exception(
1374ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom        env, reinterpret_cast<jthrowable>(env->AllocObject(exception_class.get())));
1375ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    if (exception.get() != NULL) {
1376ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      ScopedJniThreadState ts(env);
1377ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      Throwable* t = reinterpret_cast<Throwable*>(ts.Self()->DecodeJObject(exception.get()));
137802fbef0e356ca43b2032044f870d59de4a4ae92aIan Rogers      t->SetDetailMessage(String::AllocFromModifiedUtf8(msg));
1379ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      ts.Self()->SetException(t);
1380ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    } else {
1381ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI AllocObject failed: "
1382ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom                 << PrettyTypeOf(GetException());
1383ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom      CHECK(IsExceptionPending());
1384ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    }
1385ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom    return;
1386ebd1fd233c8e14f50844f15109ccd50b27079722Brian Carlstrom  }
1387726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  int rc = env->ThrowNew(exception_class.get(), msg);
138830646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  if (rc != JNI_OK) {
138930646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
139030646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes               << PrettyTypeOf(GetException());
139130646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    CHECK(IsExceptionPending());
139230646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  }
1393a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes}
1394a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes
1395418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughesvoid Thread::ThrowOutOfMemoryError(Class* c, size_t byte_count) {
13962ced6a534157d5d963693346904389c19775d2daElliott Hughes  std::string msg(StringPrintf("Failed to allocate a %zd-byte %s", byte_count,
13976d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      PrettyDescriptor(c).c_str()));
13982ced6a534157d5d963693346904389c19775d2daElliott Hughes  ThrowOutOfMemoryError(msg.c_str());
13992ced6a534157d5d963693346904389c19775d2daElliott Hughes}
14002ced6a534157d5d963693346904389c19775d2daElliott Hughes
14012ced6a534157d5d963693346904389c19775d2daElliott Hughesvoid Thread::ThrowOutOfMemoryError(const char* msg) {
14022ced6a534157d5d963693346904389c19775d2daElliott Hughes  LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
14032ced6a534157d5d963693346904389c19775d2daElliott Hughes      msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
1404726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  if (!throwing_OutOfMemoryError_) {
1405726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    throwing_OutOfMemoryError_ = true;
1406accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
1407418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes  } else {
1408726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    SetException(pre_allocated_OutOfMemoryError_);
1409418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes  }
1410726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  throwing_OutOfMemoryError_ = false;
141179082e367845bbd68ec44ef2ddd1be8ef0e1550fElliott Hughes}
141279082e367845bbd68ec44ef2ddd1be8ef0e1550fElliott Hughes
1413accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1414498508c1187dc07d3eae5476784cde20f5224d93Elliott HughesThread* Thread::CurrentFromGdb() {
1415accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  return Thread::Current();
1416accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
1417accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1418accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughesvoid Thread::DumpFromGdb() const {
14196b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  std::ostringstream ss;
14206b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  Dump(ss);
1421955724179c6c739524f610023287f56b24dc31deElliott Hughes  std::string str(ss.str());
14226b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  // log to stderr for debugging command line processes
14236b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  std::cerr << str;
14246b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom#ifdef HAVE_ANDROID_OS
14256b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  // log to logcat for debugging frameworks processes
14266b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom  LOG(INFO) << str;
14276b4ef025af12b158d117fc80fc79acf620f411a0Brian Carlstrom#endif
1428accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
1429accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1430bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogersclass CatchBlockStackVisitor : public Thread::StackVisitor {
1431bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers public:
1432bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  CatchBlockStackVisitor(Class* to_find, Context* ljc)
143367375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers      : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
143467375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers#ifndef NDEBUG
143567375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    handler_pc_ = 0xEBADC0DE;
143667375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
143767375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers#endif
143867375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  }
1439bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1440bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1441bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    if (!found_) {
1442bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      Method* method = fr.GetMethod();
144367375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers      if (method == NULL) {
144467375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers        // This is the upcall, we remember the frame and last_pc so that we may
144567375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers        // long jump to them
1446a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes        handler_pc_ = DemanglePc(pc);
144767375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers        handler_frame_ = fr;
144867375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers        return;
144967375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers      }
145067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers      uint32_t dex_pc = DexFile::kDexNoIndex;
14513320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom      if (method->IsCalleeSaveMethod()) {
14529086572fa809d1a19d886b467e4da3ce42016982Ian Rogers        // ignore callee save method
14539086572fa809d1a19d886b467e4da3ce42016982Ian Rogers      } else if (method->IsNative()) {
14549086572fa809d1a19d886b467e4da3ce42016982Ian Rogers        native_method_count_++;
14559086572fa809d1a19d886b467e4da3ce42016982Ian Rogers      } else {
1456e343b76af81a005ef64f5e75a555389fd9147dabjeffhao        // Unwind stack during method tracing
14572692b573a56cd63a3c8c8aa1636e3766b6d8c9c4jeffhao        if (Runtime::Current()->IsMethodTracingActive()) {
1458e343b76af81a005ef64f5e75a555389fd9147dabjeffhao#if defined(__arm__)
1459e343b76af81a005ef64f5e75a555389fd9147dabjeffhao          uintptr_t trace_exit = reinterpret_cast<uintptr_t>(art_trace_exit_from_code);
1460e343b76af81a005ef64f5e75a555389fd9147dabjeffhao          if (ManglePc(trace_exit) == pc) {
1461e343b76af81a005ef64f5e75a555389fd9147dabjeffhao            pc = ManglePc(artTraceMethodUnwindFromCode(Thread::Current()));
1462e343b76af81a005ef64f5e75a555389fd9147dabjeffhao          }
1463e343b76af81a005ef64f5e75a555389fd9147dabjeffhao#else
1464e343b76af81a005ef64f5e75a555389fd9147dabjeffhao          UNIMPLEMENTED(WARNING);
1465e343b76af81a005ef64f5e75a555389fd9147dabjeffhao#endif
1466e343b76af81a005ef64f5e75a555389fd9147dabjeffhao        }
14679086572fa809d1a19d886b467e4da3ce42016982Ian Rogers        dex_pc = method->ToDexPC(pc);
1468bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
1469bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      if (dex_pc != DexFile::kDexNoIndex) {
1470bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers        uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1471bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers        if (found_dex_pc != DexFile::kDexNoIndex) {
1472bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers          found_ = true;
147367375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers          handler_pc_ = method->ToNativePC(found_dex_pc);
147467375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers          handler_frame_ = fr;
1475bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers        }
1476bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
1477bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      if (!found_) {
1478bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers        // Caller may be handler, fill in callee saves in context
1479bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers        long_jump_context_->FillCalleeSaves(fr);
1480bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
14811a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao    }
14821a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao  }
14831a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao
1484bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // Did we find a catch block yet?
1485bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  bool found_;
1486bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // The type of the exception catch block to find
1487bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Class* to_find_;
1488bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // Frame with found handler or last frame if no handler found
1489bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Frame handler_frame_;
149067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  // PC to branch to for the handler
149167375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  uintptr_t handler_pc_;
1492bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // Context that will be the target of the long jump
1493bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Context* long_jump_context_;
149467375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  // Number of native methods passed in crawl (equates to number of SIRTs to pop)
149567375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  uint32_t native_method_count_;
1496bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers};
1497bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1498ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogersvoid Thread::DeliverException() {
149928ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  const bool kDebugExceptionDelivery = false;
1500d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Throwable* exception = GetException();  // Get exception from thread
1501ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  CHECK(exception != NULL);
150228ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  // Don't leave exception visible while we try to find the handler, which may cause class
1503d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  // resolution.
150428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  ClearException();
150528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  if (kDebugExceptionDelivery) {
1506a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    String* msg = exception->GetDetailMessage();
1507a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    std::string str_msg(msg != NULL ? msg->ToModifiedUtf8() : "");
1508a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers    DumpStack(LOG(INFO) << "Delivering exception: " << PrettyTypeOf(exception)
1509a32a6fd4a781262dff4fec102da053d16b7ef6c0Ian Rogers                        << ": " << str_msg << std::endl);
151028ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  }
1511bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1512bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Context* long_jump_context = GetLongJumpContext();
1513bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
151467375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  WalkStackUntilUpCall(&catch_finder, true);
1515bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1516d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method** sp;
1517d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  uintptr_t throw_native_pc;
1518d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method* throw_method = GetCurrentMethod(&throw_native_pc, &sp);
1519d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  uintptr_t catch_native_pc = catch_finder.handler_pc_;
1520d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method* catch_method = catch_finder.handler_frame_.GetMethod();
1521d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Dbg::PostException(sp, throw_method, throw_native_pc, catch_method, catch_native_pc, exception);
1522d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes
152328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  if (kDebugExceptionDelivery) {
1524d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes    if (catch_method == NULL) {
152528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      LOG(INFO) << "Handler is upcall";
152628ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    } else {
152728ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
152828ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers      const DexFile& dex_file =
1529d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes          class_linker->FindDexFile(catch_method->GetDeclaringClass()->GetDexCache());
1530d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes      int line_number = dex_file.GetLineNumFromPC(catch_method,
1531d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes          catch_method->ToDexPC(catch_finder.handler_pc_));
1532d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes      LOG(INFO) << "Handler: " << PrettyMethod(catch_method) << " (line: " << line_number << ")";
153328ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers    }
153428ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  }
153528ad40dc3ec2f09b0ffd4f6d6787bf1b532ccd5dIan Rogers  SetException(exception);
15369a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  CHECK_NE(catch_native_pc, 0u);
1537d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  long_jump_context->SetSP(reinterpret_cast<uintptr_t>(catch_finder.handler_frame_.GetSP()));
15389a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  long_jump_context->SetPC(catch_native_pc);
1539bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  long_jump_context->DoLongJump();
15409a8a8889418e09bf2d4ae3f683fbb40a71c3c8f4Ian Rogers  LOG(FATAL) << "UNREACHABLE";
1541bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers}
1542bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1543bdb0391258abc54bf77c676e36847d28a783bfe5Ian RogersContext* Thread::GetLongJumpContext() {
154485d1545e985ac689db4bad7849880e843707c862Elliott Hughes  Context* result = long_jump_context_;
1545bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  if (result == NULL) {
1546bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    result = Context::Create();
154785d1545e985ac689db4bad7849880e843707c862Elliott Hughes    long_jump_context_ = result;
15481a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao  }
1549bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  return result;
15501a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao}
15511a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao
1552d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott HughesMethod* Thread::GetCurrentMethod(uintptr_t* pc, Method*** sp) const {
1553d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Frame f = top_of_managed_stack_;
1554d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  Method* m = f.GetMethod();
15558be2d40d42223b515de12629216151a558895969Elliott Hughes  uintptr_t native_pc = top_of_managed_stack_pc_;
15568be2d40d42223b515de12629216151a558895969Elliott Hughes
15579fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // We use JNI internally for exception throwing, so it's possible to arrive
15589fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // here via a "FromCode" function, in which case there's a synthetic
15599fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // callee-save method at the top of the stack. These shouldn't be user-visible,
15609fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // so if we find one, skip it and return the compiled method underneath.
156133dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  if (m != NULL && m->IsCalleeSaveMethod()) {
15628be2d40d42223b515de12629216151a558895969Elliott Hughes    native_pc = f.GetReturnPC();
15639fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes    f.Next();
15649fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes    m = f.GetMethod();
15659fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  }
1566d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  if (pc != NULL) {
15678be2d40d42223b515de12629216151a558895969Elliott Hughes    *pc = (m != NULL) ? ManglePc(native_pc) : 0;
156833dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  }
1569d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  if (sp != NULL) {
1570d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes    *sp = f.GetSP();
1571d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  }
1572d07986fad0d08cdf05505cf9230714a2cf0dd9aeElliott Hughes  return m;
157333dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao}
157433dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao
15755f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesbool Thread::HoldsLock(Object* object) {
15765f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (object == NULL) {
15775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return false;
15785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
157924a3c2e9924e8765c4a9b4d383cb8f3b922f9c9fBrian Carlstrom  return object->GetThinLockId() == thin_lock_id_;
15805f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
15815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1582038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesbool Thread::IsDaemon() {
1583038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  return gThread_daemon->GetBoolean(peer_);
1584038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes}
1585038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
1586d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogersclass ReferenceMapVisitor : public Thread::StackVisitor {
1587d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers public:
1588d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1589d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    context_(context), root_visitor_(root_visitor), arg_(arg) {
1590d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1591d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1592d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  void VisitFrame(const Frame& frame, uintptr_t pc) {
1593d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    Method* m = frame.GetMethod();
15946a4be3a6226cec645cf905dd352e44f7968a7fa4Brian Carlstrom    if (false) {
15956a4be3a6226cec645cf905dd352e44f7968a7fa4Brian Carlstrom      LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m, false)
15960dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom                << StringPrintf("@ PC:%04x", m->ToDexPC(pc));
15976a4be3a6226cec645cf905dd352e44f7968a7fa4Brian Carlstrom    }
1598d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    // Process register map (which native and callee save methods don't have)
15993891c775503b1113a918180d9ecdaa79e92c69c6Ian Rogers    if (!m->IsNative() && !m->IsCalleeSaveMethod() && !m->IsProxyMethod()) {
1600e7d856b911222aa000ca2be0f8f63f5b292141c3Brian Carlstrom      CHECK(m->GetGcMap() != NULL) << PrettyMethod(m);
1601e7d856b911222aa000ca2be0f8f63f5b292141c3Brian Carlstrom      CHECK_NE(0U, m->GetGcMapLength()) << PrettyMethod(m);
1602e7d856b911222aa000ca2be0f8f63f5b292141c3Brian Carlstrom      verifier::PcToReferenceMap map(m->GetGcMap(), m->GetGcMapLength());
1603d81871cbbaa34c649e488f94f61a981db33123e5Ian Rogers      const uint8_t* reg_bitmap = map.FindBitMap(m->ToDexPC(pc));
1604d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      CHECK(reg_bitmap != NULL);
160568fdbd07fc2b8856905e06f3cc945b046c3bfcd3Elliott Hughes      const VmapTable vmap_table(m->GetVmapTableRaw());
160611d1b0c31ddd710d26068da8e0e4621002205b4bElliott Hughes      const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
16076d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      DCHECK(code_item != NULL);  // can't be NULL or how would we compile its instructions?
16086d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      uint32_t core_spills = m->GetCoreSpillMask();
16096d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      uint32_t fp_spills = m->GetFpSpillMask();
16106d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      size_t frame_size = m->GetFrameSizeInBytes();
16110dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom      // For all dex registers in the bitmap
16126d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers      size_t num_regs = std::min(map.RegWidth() * 8,
16136d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                 static_cast<size_t>(code_item->registers_size_));
16140dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom      for (size_t reg = 0; reg < num_regs; ++reg) {
1615d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        // Does this register hold a reference?
1616d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        if (TestBitmap(reg, reg_bitmap)) {
161768fdbd07fc2b8856905e06f3cc945b046c3bfcd3Elliott Hughes          uint32_t vmap_offset;
1618d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          Object* ref;
161968fdbd07fc2b8856905e06f3cc945b046c3bfcd3Elliott Hughes          if (vmap_table.IsInContext(reg, vmap_offset)) {
1620d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            // Compute the register we need to load from the context
1621d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            uint32_t spill_mask = m->GetCoreSpillMask();
16220dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom            CHECK_LT(vmap_offset, static_cast<uint32_t>(__builtin_popcount(spill_mask)));
1623f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            uint32_t matches = 0;
1624f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            uint32_t spill_shifts = 0;
1625f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            while (matches != (vmap_offset + 1)) {
16260dd7ddaa36a2cf37490dc166ebc21818364130a7Brian Carlstrom              DCHECK_NE(spill_mask, 0u);
1627f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              matches += spill_mask & 1;  // Add 1 if the low bit is set
1628f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              spill_mask >>= 1;
1629f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              spill_shifts++;
1630d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            }
1631f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            spill_shifts--;  // wind back one as we want the last match
1632f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
1633d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          } else {
16346d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers            ref = reinterpret_cast<Object*>(frame.GetVReg(code_item, core_spills, fp_spills,
16356d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers                                                          frame_size, reg));
1636d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          }
16374f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao          if (ref != NULL) {
16384f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao            root_visitor_(ref, arg_);
16394f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao          }
1640d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        }
1641d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      }
1642d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    }
1643d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    context_->FillCalleeSaves(frame);
1644d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1645d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1646d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers private:
1647d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  bool TestBitmap(int reg, const uint8_t* reg_vector) {
1648d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1649d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1650d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1651d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Context used to build up picture of callee saves
1652d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Context* context_;
1653d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Call-back when we visit a root
1654d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Heap::RootVisitor* root_visitor_;
1655d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Argument to call-back
1656d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  void* arg_;
1657d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers};
1658d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1659d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogersvoid Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
1660d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (exception_ != NULL) {
1661d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    visitor(exception_, arg);
1662d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
1663d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (peer_ != NULL) {
1664d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    visitor(peer_, arg);
1665d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
1666726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  if (pre_allocated_OutOfMemoryError_ != NULL) {
1667726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    visitor(pre_allocated_OutOfMemoryError_, arg);
1668726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  }
166940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  if (class_loader_override_ != NULL) {
167040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    visitor(class_loader_override_, arg);
167140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  }
1672410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes  jni_env_->locals.VisitRoots(visitor, arg);
1673410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes  jni_env_->monitors.VisitRoots(visitor, arg);
16748dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
16758dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao  SirtVisitRoots(visitor, arg);
16768dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
1677d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1678d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // delivery.
1679d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Context* context = GetLongJumpContext();
1680d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Visit roots on this thread's stack
1681d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  ReferenceMapVisitor mapper(context, visitor, arg);
1682d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  WalkStack(&mapper);
1683410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes}
1684410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes
1685b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogersstatic const char* kStateNames[] = {
168693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Terminated",
1687b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Runnable",
168893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "TimedWaiting",
1689b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Blocked",
1690b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Waiting",
169193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Initializing",
169293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Starting",
1693b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Native",
169493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "VmWait",
169593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Suspended",
1696b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers};
1697b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogersstd::ostream& operator<<(std::ostream& os, const Thread::State& state) {
16988e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  int32_t int_state = static_cast<int32_t>(state);
169993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
170093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    os << kStateNames[int_state];
1701b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  } else {
170293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    os << "State[" << int_state << "]";
1703b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  }
1704b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  return os;
1705b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers}
1706b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers
1707330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughesstd::ostream& operator<<(std::ostream& os, const Thread& thread) {
1708899e789bd4741c0172268f7838ce8ab220a5f916Elliott Hughes  thread.Dump(os, false);
1709330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes  return os;
1710330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes}
1711330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes
1712a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughesvoid Thread::CheckSafeToLockOrUnlock(MutexRank rank, bool is_locking) {
1713ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  if (is_locking) {
1714ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    if (held_mutexes_[rank] == 0) {
1715ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      bool bad_mutexes_held = false;
1716ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      for (int i = kMaxMutexRank; i > rank; --i) {
1717ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes        if (held_mutexes_[i] != 0) {
1718ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes          LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while " << (is_locking ? "locking" : "unlocking") << " " << rank;
1719ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes          bad_mutexes_held = true;
1720ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes        }
1721ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      }
1722ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes      CHECK(!bad_mutexes_held);
1723ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    }
1724ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    ++held_mutexes_[rank];
1725ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  } else {
1726ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    CHECK_GT(held_mutexes_[rank], 0U);
1727ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    --held_mutexes_[rank];
1728ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
1729ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes}
1730ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes
1731a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughesvoid Thread::CheckSafeToWait(MutexRank rank) {
1732a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  bool bad_mutexes_held = false;
1733a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  for (int i = kMaxMutexRank; i >= 0; --i) {
1734a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    if (i != rank && held_mutexes_[i] != 0) {
1735a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes      LOG(ERROR) << "holding " << static_cast<MutexRank>(i) << " while doing condition variable wait on " << rank;
1736a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes      bad_mutexes_held = true;
1737a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    }
1738a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  }
1739a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  if (held_mutexes_[rank] == 0) {
1740a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    LOG(ERROR) << "*not* holding " << rank << " while doing condition variable wait on it";
1741a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes    bad_mutexes_held = true;
1742a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  }
1743a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes  CHECK(!bad_mutexes_held);
1744a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes}
1745a4060e5fe4729fa30bde965efc35779690478fa4Elliott Hughes
17468daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes}  // namespace art
1747