thread.cc revision 40381fb9dc4b4cf274f1e58b2cdf4396202c6189
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>
22a09576416788b916095739e43a16917e7948f3a4Elliott Hughes
23b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro#include <algorithm>
24dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes#include <bitset>
25eb4f614f2eb53b92ebd416fa418f550861655887Elliott Hughes#include <cerrno>
26a09576416788b916095739e43a16917e7948f3a4Elliott Hughes#include <iostream>
27b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro#include <list>
28b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
29a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes#include "class_linker.h"
30df143242f4beaad4cc9fbabebfc033b68c40964eBrian Carlstrom#include "class_loader.h"
31bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers#include "context.h"
32d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers#include "dex_verifier.h"
33408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers#include "heap.h"
34c5f7c91ab89055cffb573fff7e06dbdd860bccedElliott Hughes#include "jni_internal.h"
358e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes#include "monitor.h"
36a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes#include "object.h"
37578bbdc684db8ed68e9fedbc678669d27fa68b6eBrian Carlstrom#include "runtime.h"
385433072f589b61413e042eddf76e8190a048f71dbuzbee#include "runtime_support.h"
39726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes#include "ScopedLocalRef.h"
40aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#include "scoped_jni_thread_state.h"
4168e76526e98432625464022cb26f66b9ef6f5af4Elliott Hughes#include "stack.h"
4268e76526e98432625464022cb26f66b9ef6f5af4Elliott Hughes#include "stack_indirect_reference_table.h"
438daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes#include "thread_list.h"
44a09576416788b916095739e43a16917e7948f3a4Elliott Hughes#include "utils.h"
45b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
46b557353b22c728eecbd1c68593b482622c7782a8Carl Shapironamespace art {
47b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
48b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiropthread_key_t Thread::pthread_key_self_;
49b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
508e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesstatic Class* gThreadLock = NULL;
5129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughesstatic Class* gThrowable = NULL;
52038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_daemon = NULL;
53038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_group = NULL;
54038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_lock = NULL;
55038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_name = NULL;
56038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_priority = NULL;
5729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughesstatic Field* gThread_uncaughtHandler = NULL;
58038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThread_vmData = NULL;
59038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Field* gThreadGroup_name = NULL;
608e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesstatic Field* gThreadLock_thread = NULL;
61038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesstatic Method* gThread_run = NULL;
6229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughesstatic Method* gThreadGroup_removeThread = NULL;
6329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughesstatic Method* gUncaughtExceptionHandler_uncaughtException = NULL;
64038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
653ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbeevoid Thread::InitFunctionPointers() {
665433072f589b61413e042eddf76e8190a048f71dbuzbee#if defined(__arm__)
675433072f589b61413e042eddf76e8190a048f71dbuzbee  pShlLong = art_shl_long;
685433072f589b61413e042eddf76e8190a048f71dbuzbee  pShrLong = art_shr_long;
695433072f589b61413e042eddf76e8190a048f71dbuzbee  pUshrLong = art_ushr_long;
707b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pIdiv = __aeabi_idiv;
717b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pIdivmod = __aeabi_idivmod;
727b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pI2f = __aeabi_i2f;
737b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pF2iz = __aeabi_f2iz;
747b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pD2f = __aeabi_d2f;
757b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pF2d = __aeabi_f2d;
767b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pD2iz = __aeabi_d2iz;
777b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pL2f = __aeabi_l2f;
787b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pL2d = __aeabi_l2d;
797b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFadd = __aeabi_fadd;
807b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFsub = __aeabi_fsub;
817b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFdiv = __aeabi_fdiv;
827b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFmul = __aeabi_fmul;
837b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFmodf = fmodf;
847b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pDadd = __aeabi_dadd;
857b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pDsub = __aeabi_dsub;
867b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pDdiv = __aeabi_ddiv;
877b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pDmul = __aeabi_dmul;
887b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pFmod = fmod;
897b1b86d68244b0bb4ea3f43505eb45fdd46814d6buzbee  pLdivmod = __aeabi_ldivmod;
90439c4fa0db980fb19e4a585723a64a3461e4c278buzbee  pLmul = __aeabi_lmul;
91b408de744566a5c5a80be1ba7f5c88407e816945Elliott Hughes  pAllocArrayFromCode = art_alloc_array_from_code;
926fd03fb67e4628689f0abf34edeacc0e35b6295eBrian Carlstrom  pAllocObjectFromCode = art_alloc_object_from_code;
93e51a511ccee3f3c0120807321bcc160fcaa664beIan Rogers  pCanPutArrayElementFromCode = art_can_put_array_element_from_code;
94b408de744566a5c5a80be1ba7f5c88407e816945Elliott Hughes  pCheckAndAllocArrayFromCode = art_check_and_alloc_array_from_code;
95ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pCheckCastFromCode = art_check_cast_from_code;
96ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pFindInstanceFieldFromCode = art_find_instance_field_from_code;
97ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pGet32Static = art_get32_static_from_code;
98ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pGet64Static = art_get64_static_from_code;
99ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pGetObjStatic = art_get_obj_static_from_code;
100ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pHandleFillArrayDataFromCode = art_handle_fill_data_from_code;
101cbba6ac9bf9a6c630a7aafae6d8767b5ddbb6fd5Ian Rogers  pInitializeStaticStorage = art_initialize_static_storage_from_code;
1024a3164faefd255b1c1e911e7ad7c3d57749caaf6buzbee  pInvokeInterfaceTrampoline = art_invoke_interface_trampoline;
1036fd03fb67e4628689f0abf34edeacc0e35b6295eBrian Carlstrom  pLockObjectFromCode = art_lock_object_from_code;
1046fd03fb67e4628689f0abf34edeacc0e35b6295eBrian Carlstrom  pObjectInit = art_object_init_from_code;
1056fd03fb67e4628689f0abf34edeacc0e35b6295eBrian Carlstrom  pResolveStringFromCode = art_resolve_string_from_code;
106ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pSet32Static = art_set32_static_from_code;
107ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pSet64Static = art_set64_static_from_code;
108ce9eca6de042f26e9eebc41c9bee8b4d14f753aaIan Rogers  pSetObjStatic = art_set_obj_static_from_code;
1096fd03fb67e4628689f0abf34edeacc0e35b6295eBrian Carlstrom  pTestSuspendFromCode = art_test_suspend;
110ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pThrowArrayBoundsFromCode = art_throw_array_bounds_from_code;
111ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pThrowDivZeroFromCode = art_throw_div_zero_from_code;
112c0c8dc8e677957d167066a2d06973126f108a6aaIan Rogers  pThrowNegArraySizeFromCode = art_throw_neg_array_size_from_code;
113c0c8dc8e677957d167066a2d06973126f108a6aaIan Rogers  pThrowNoSuchMethodFromCode = art_throw_no_such_method_from_code;
114ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pThrowNullPointerFromCode = art_throw_null_pointer_exception_from_code;
115932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  pThrowStackOverflowFromCode = art_throw_stack_overflow_from_code;
116c0c8dc8e677957d167066a2d06973126f108a6aaIan Rogers  pThrowVerificationErrorFromCode = art_throw_verification_error_from_code;
117ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  pUnlockObjectFromCode = art_unlock_object_from_code;
11867375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers#endif
119c396efc1baec875160afe34a3e65c46cce2bd72fbuzbee  pF2l = F2L;
120c396efc1baec875160afe34a3e65c46cce2bd72fbuzbee  pD2l = D2L;
1213ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbee  pMemcpy = memcpy;
1224a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pCheckSuspendFromCode = CheckSuspendFromCode;
1234a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pDebugMe = DebugMe;
1244a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pDecodeJObjectInThread = DecodeJObjectInThread;
1254a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pDeliverException = art_deliver_exception_from_code;
1264a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pFindNativeMethod = FindNativeMethod;
1271b4c85959b3d9a4a33bc2160c46c1bbde67350c7buzbee  pInitializeTypeFromCode = InitializeTypeFromCode;
128caab8c4ef372db5c119bfac1911fa27b174a935cIan Rogers  pInstanceofNonTrivialFromCode = IsAssignableFromCode;
1294a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pResolveMethodFromCode = ResolveMethodFromCode;
1304a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pThrowAbstractMethodErrorFromCode = ThrowAbstractMethodErrorFromCode;
1314a510d8750d50b77353d0a5a891d1b9b3a48ecd5Ian Rogers  pUnresolvedDirectMethodTrampolineFromCode = UnresolvedDirectMethodTrampolineFromCode;
1323ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbee}
1333ea4ec5629613013ad9b0d7a69abdb94491ac46fbuzbee
134caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstromvoid Thread::InitTid() {
135caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  tid_ = ::art::GetTid();
136caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom}
137caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom
138caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstromvoid Thread::InitAfterFork() {
139caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  InitTid();
1403147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes#if defined(__BIONIC__)
1413147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  // Work around a bionic bug.
1423147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  struct bionic_pthread_internal_t {
1433147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    void*  next;
1443147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    void** pref;
1453147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    pthread_attr_t attr;
1463147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    pid_t kernel_id;
1473147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes    // et cetera. we just need 'kernel_id' so we can stop here.
1483147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  };
1493147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  reinterpret_cast<bionic_pthread_internal_t*>(pthread_self())->kernel_id = tid_;
1503147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes#endif
151caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom}
152caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom
15378128a63b2615744760b7f8ab83df9764a5d4a95Brian Carlstromvoid* Thread::CreateCallback(void* arg) {
15493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Thread* self = reinterpret_cast<Thread*>(arg);
15593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Runtime* runtime = Runtime::Current();
15693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
15793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  self->Attach(runtime);
15893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
159038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  String* thread_name = reinterpret_cast<String*>(gThread_name->GetObject(self->peer_));
16093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  if (thread_name != NULL) {
16193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    SetThreadName(thread_name->ToModifiedUtf8().c_str());
16293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  }
16393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
16493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Wait until it's safe to start running code. (There may have been a suspend-all
16593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // in progress while we were starting up.)
16693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  runtime->GetThreadList()->WaitForGo();
16793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
16893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // TODO: say "hi" to the debugger.
16993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  //if (gDvm.debuggerConnected) {
17093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  //  dvmDbgPostThreadStart(self);
17193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  //}
17293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
17393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Invoke the 'run' method of our java.lang.Thread.
17493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  CHECK(self->peer_ != NULL);
17593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Object* receiver = self->peer_;
176038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  Method* m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(gThread_run);
17793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  m->Invoke(self, receiver, NULL, NULL);
17893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
17993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Detach.
18093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  runtime->GetThreadList()->Unregister();
18193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
182b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  return NULL;
183b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
184b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
18593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughesvoid SetVmData(Object* managed_thread, Thread* native_thread) {
186038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  gThread_vmData->SetInt(managed_thread, reinterpret_cast<uintptr_t>(native_thread));
18793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
18893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
18901158d7a57c8321370667a6045220237d16e0da8Elliott HughesThread* Thread::FromManagedThread(JNIEnv* env, jobject java_thread) {
19001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  Object* thread = Decode<Object*>(env, java_thread);
19101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  return reinterpret_cast<Thread*>(static_cast<uintptr_t>(gThread_vmData->GetInt(thread)));
19201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes}
19301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
1947502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughessize_t FixStackSize(size_t stack_size) {
1957502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // A stack size of zero means "use the default".
196d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (stack_size == 0) {
197d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    stack_size = Runtime::Current()->GetDefaultStackSize();
198d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
19961e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
2007502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
2017502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  if (stack_size < PTHREAD_STACK_MIN) {
2027502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes    stack_size = PTHREAD_STACK_MIN;
2037502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  }
2047502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2057502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // It's likely that callers are trying to ensure they have at least a certain amount of
2067502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // stack space, so we should add our reserved space on top of what they requested, rather
2077502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // than implicitly take it away from them.
2087502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size += Thread::kStackOverflowReservedBytes;
2097502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2107502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  // Some systems require the stack size to be a multiple of the system page size, so round up.
2117502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size = RoundUp(stack_size, kPageSize);
2127502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2137502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  return stack_size;
2147502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes}
2157502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2167502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughesvoid Thread::Create(Object* peer, size_t stack_size) {
2177502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  CHECK(peer != NULL);
2187502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
2197502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes  stack_size = FixStackSize(stack_size);
2207502e2a419f84808518cf212b3d7145c7b959c76Elliott Hughes
22193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Thread* native_thread = new Thread;
22293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  native_thread->peer_ = peer;
22393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
22493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Thread.start is synchronized, so we know that vmData is 0,
22593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // and know that we're not racing to assign it.
22693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  SetVmData(peer, native_thread);
22761e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
2283147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  pthread_t new_pthread;
22961e019d291583029c01b61b93bea750f2b663c37Carl Shapiro  pthread_attr_t attr;
2308d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
2318d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED), "PTHREAD_CREATE_DETACHED");
2328d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
2333147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  CHECK_PTHREAD_CALL(pthread_create, (&new_pthread, &attr, Thread::CreateCallback, native_thread), "new thread");
2348d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
23561e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
23693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  // Let the child know when it's safe to start running.
23793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Runtime::Current()->GetThreadList()->SignalGo(native_thread);
23893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
23961e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
24093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughesvoid Thread::Attach(const Runtime* runtime) {
24193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitCpu();
24293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitFunctionPointers();
24361e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
24493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  thin_lock_id_ = Runtime::Current()->GetThreadList()->AllocThreadId();
245be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
246caabb1b77b4a55eb1bb45ebcd3071c9ea01dd3cfBrian Carlstrom  InitTid();
24793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  InitStackHwm();
248dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes
2493147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach");
250a5780dad67556297c8ca5f2608c53b193e6c4514Elliott Hughes
25193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  jni_env_ = new JNIEnvExt(this, runtime->GetJavaVM());
2525fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
2537a3aeb4d7580164c6a6905c63b96823b77ff5a64Elliott Hughes  runtime->GetThreadList()->Register();
25493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes}
25593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
25693e74e8d879270071c3aa163f8495ada8d21f42fElliott HughesThread* Thread::Attach(const Runtime* runtime, const char* name, bool as_daemon) {
25793e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  Thread* self = new Thread;
25893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  self->Attach(runtime);
25993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
2607a3aeb4d7580164c6a6905c63b96823b77ff5a64Elliott Hughes  self->SetState(Thread::kNative);
26193e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes
26293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  SetThreadName(name);
2635fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
2645fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  // If we're the main thread, ClassLinker won't be created until after we're attached,
2655fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  // so that thread needs a two-stage attach. Regular threads don't need this hack.
2665fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  if (self->thin_lock_id_ != ThreadList::kMainId) {
2675fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes    self->CreatePeer(name, as_daemon);
2685fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  }
2695fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
270726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  self->GetJniEnv()->locals.AssertEmpty();
271726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes
2725fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  return self;
2735fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes}
2745fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
275d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughesjobject GetWellKnownThreadGroup(JNIEnv* env, const char* field_name) {
276726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jclass> thread_group_class(env, env->FindClass("java/lang/ThreadGroup"));
277726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  jfieldID fid = env->GetStaticFieldID(thread_group_class.get(), field_name, "Ljava/lang/ThreadGroup;");
278726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  return env->GetStaticObjectField(thread_group_class.get(), fid);
279d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes}
280d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
2815fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughesvoid Thread::CreatePeer(const char* name, bool as_daemon) {
2825fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  JNIEnv* env = jni_env_;
2835fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
284d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  const char* field_name = (GetThinLockId() == ThreadList::kMainId) ? "mMain" : "mSystem";
285726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jobject> thread_group(env, GetWellKnownThreadGroup(env, field_name));
286726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
2878daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes  jint thread_priority = GetNativePriority();
2885fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes  jboolean thread_is_daemon = as_daemon;
2895fe594f576225dd7d333835e39c448a71ea9b433Elliott Hughes
290726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/Thread"));
291726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  jmethodID mid = env->GetMethodID(c.get(), "<init>", "(Ljava/lang/ThreadGroup;Ljava/lang/String;IZ)V");
292330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes
293726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jobject> peer(env,
294726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      env->NewObject(c.get(), mid, thread_group.get(), thread_name.get(), thread_priority, thread_is_daemon));
295726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  peer_ = DecodeJObject(peer.get());
2967a3aeb4d7580164c6a6905c63b96823b77ff5a64Elliott Hughes  SetVmData(peer_, Thread::Current());
297d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
298d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  // Because we mostly run without code available (in the compiler, in tests), we
299d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  // manually assign the fields the constructor should have set.
300d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  // TODO: lose this.
30101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  gThread_daemon->SetBoolean(peer_, thread_is_daemon);
302726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  gThread_group->SetObject(peer_, Decode<Object*>(env, thread_group.get()));
303726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  gThread_name->SetObject(peer_, Decode<Object*>(env, thread_name.get()));
30401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  gThread_priority->SetInt(peer_, thread_priority);
305726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes
306726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  // Pre-allocate an OutOfMemoryError for the double-OOME case.
307726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ThrowNewException("Ljava/lang/OutOfMemoryError;",
308726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      "OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available");
309726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jthrowable> exception(env, env->ExceptionOccurred());
310726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  env->ExceptionClear();
311726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  pre_allocated_OutOfMemoryError_ = Decode<Throwable*>(env, exception.get());
31261e019d291583029c01b61b93bea750f2b663c37Carl Shapiro}
31361e019d291583029c01b61b93bea750f2b663c37Carl Shapiro
314be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::InitStackHwm() {
315be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  pthread_attr_t attributes;
3163147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
317be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
318932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  void* temp_stack_base;
319932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &temp_stack_base, &stack_size_),
320932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers                     __FUNCTION__);
321932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  stack_base_ = reinterpret_cast<byte*>(temp_stack_base);
322be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
323932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  if (stack_size_ <= kStackOverflowReservedBytes) {
324932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers    LOG(FATAL) << "attempt to attach a thread with a too-small stack (" << stack_size_ << " bytes)";
325be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  }
326449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes
327932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  // Set stack_end_ to the bottom of the stack saving space of stack overflows
328932746a4f22951abcba7b7c4c94c27b1bf164272Ian Rogers  ResetDefaultStackEnd();
329449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes
330449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes  // Sanity check.
331449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes  int stack_variable;
332449b4bdf90b527ef7a42faaf087494538e62363cElliott Hughes  CHECK_GT(&stack_variable, (void*) stack_end_);
333be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
3348d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
335be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes}
336be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes
337a09576416788b916095739e43a16917e7948f3a4Elliott Hughesvoid Thread::Dump(std::ostream& os) const {
338d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  DumpState(os);
339d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  DumpStack(os);
340d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes}
341d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
342d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughesstd::string GetSchedulerGroup(pid_t tid) {
343d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // /proc/<pid>/group looks like this:
344d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // 2:devices:/
345d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // 1:cpuacct,cpu:/
346d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // We want the third field from the line whose second field contains the "cpu" token.
347d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::string cgroup_file;
348d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  if (!ReadFileToString("/proc/self/cgroup", &cgroup_file)) {
349d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    return "";
350d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
351d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::vector<std::string> cgroup_lines;
352d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  Split(cgroup_file, '\n', cgroup_lines);
353d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  for (size_t i = 0; i < cgroup_lines.size(); ++i) {
354d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    std::vector<std::string> cgroup_fields;
355d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    Split(cgroup_lines[i], ':', cgroup_fields);
356d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    std::vector<std::string> cgroups;
357d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    Split(cgroup_fields[1], ',', cgroups);
358d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    for (size_t i = 0; i < cgroups.size(); ++i) {
359d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes      if (cgroups[i] == "cpu") {
360d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes        return cgroup_fields[2].substr(1); // Skip the leading slash.
361d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes      }
362d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    }
363d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
364d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  return "";
365d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes}
366d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
367fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott HughesString* Thread::GetName() const {
368fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  return (peer_ != NULL) ? reinterpret_cast<String*>(gThread_name->GetObject(peer_)) : NULL;
369fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes}
370fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes
371d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughesvoid Thread::DumpState(std::ostream& os) const {
372d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  std::string thread_name("<native thread without managed peer>");
373d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  std::string group_name;
374d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  int priority;
375d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  bool is_daemon = false;
376d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
377d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (peer_ != NULL) {
378038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    String* thread_name_string = reinterpret_cast<String*>(gThread_name->GetObject(peer_));
379d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    thread_name = (thread_name_string != NULL) ? thread_name_string->ToModifiedUtf8() : "<null>";
380038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    priority = gThread_priority->GetInt(peer_);
381038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    is_daemon = gThread_daemon->GetBoolean(peer_);
382d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
383038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    Object* thread_group = gThread_group->GetObject(peer_);
384d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    if (thread_group != NULL) {
385038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes      String* group_name_string = reinterpret_cast<String*>(gThreadGroup_name->GetObject(thread_group));
386d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes      group_name = (group_name_string != NULL) ? group_name_string->ToModifiedUtf8() : "<null>";
387d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    }
388d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  } else {
389d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    // This name may be truncated, but it's the best we can do in the absence of a managed peer.
390dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes    std::string stats;
391dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes    if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
392dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      size_t start = stats.find('(') + 1;
393dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      size_t end = stats.find(')') - start;
394dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      thread_name = stats.substr(start, end);
395dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes    }
396d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    priority = GetNativePriority();
397dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes  }
398d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
399d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int policy;
400d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  sched_param sp;
4013147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes  CHECK_PTHREAD_CALL(pthread_getschedparam, (pthread_self(), &policy, &sp), __FUNCTION__);
402d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
403d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::string scheduler_group(GetSchedulerGroup(GetTid()));
404d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  if (scheduler_group.empty()) {
405d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    scheduler_group = "default";
406d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
407d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
408d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << '"' << thread_name << '"';
409d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (is_daemon) {
410d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    os << " daemon";
411d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
412d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << " prio=" << priority
413dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes     << " tid=" << GetThinLockId()
41493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes     << " " << GetState() << "\n";
415d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
416d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int debug_suspend_count = 0; // TODO
417d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << "  | group=\"" << group_name << "\""
4188d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     << " sCount=" << suspend_count_
419d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " dsCount=" << debug_suspend_count
420dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes     << " obj=" << reinterpret_cast<void*>(peer_)
421d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " self=" << reinterpret_cast<const void*>(this) << "\n";
422d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << "  | sysTid=" << GetTid()
423d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " nice=" << getpriority(PRIO_PROCESS, GetTid())
424d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " sched=" << policy << "/" << sp.sched_priority
425d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " cgrp=" << scheduler_group
4263147a2347d4fd775d51ec0a558955332beb9d1feElliott Hughes     << " handle=" << pthread_self() << "\n";
427d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
428d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  // Grab the scheduler stats for this thread.
429d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::string scheduler_stats;
430d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  if (ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", GetTid()).c_str(), &scheduler_stats)) {
431d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    scheduler_stats.resize(scheduler_stats.size() - 1); // Lose the trailing '\n'.
432d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  } else {
433d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    scheduler_stats = "0 0 0";
434d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
435d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
436d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int utime = 0;
437d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int stime = 0;
438d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  int task_cpu = 0;
439d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  std::string stats;
440d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  if (ReadFileToString(StringPrintf("/proc/self/task/%d/stat", GetTid()).c_str(), &stats)) {
441d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    // Skip the command, which may contain spaces.
442d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    stats = stats.substr(stats.find(')') + 2);
443d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    // Extract the three fields we care about.
444d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    std::vector<std::string> fields;
445d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    Split(stats, ' ', fields);
446d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    utime = strtoull(fields[11].c_str(), NULL, 10);
447d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    stime = strtoull(fields[12].c_str(), NULL, 10);
448d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes    task_cpu = strtoull(fields[36].c_str(), NULL, 10);
449d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  }
450d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes
451d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes  os << "  | schedstat=( " << scheduler_stats << " )"
452d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " utm=" << utime
453d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " stm=" << stime
454d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " core=" << task_cpu
455d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughes     << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
456a09576416788b916095739e43a16917e7948f3a4Elliott Hughes}
457a09576416788b916095739e43a16917e7948f3a4Elliott Hughes
458b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogersvoid Thread::PushNativeToManagedRecord(NativeToManagedRecord* record) {
459b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  Method **sp = top_of_managed_stack_.GetSP();
460b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers#ifndef NDEBUG
461b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  if (sp != NULL) {
462b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers    Method* m = *sp;
463b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers    Heap::VerifyObject(m);
464b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers    DCHECK((m == NULL) || m->IsMethod());
465b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  }
466b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers#endif
467b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  record->last_top_of_managed_stack_ = reinterpret_cast<void*>(sp);
468b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  record->last_top_of_managed_stack_pc_ = top_of_managed_stack_pc_;
469b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  record->link_ = native_to_managed_record_;
470b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  native_to_managed_record_ = record;
471b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  top_of_managed_stack_.SetSP(NULL);
472b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers}
473b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers
474b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogersvoid Thread::PopNativeToManagedRecord(const NativeToManagedRecord& record) {
475b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  native_to_managed_record_ = record.link_;
476b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  top_of_managed_stack_.SetSP(reinterpret_cast<Method**>(record.last_top_of_managed_stack_));
477b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers  top_of_managed_stack_pc_ = record.last_top_of_managed_stack_pc_;
478b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers}
479b04f69f90d2594092bec5b294bbe7329d295bd66Ian Rogers
480d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughesstruct StackDumpVisitor : public Thread::StackVisitor {
4818e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  StackDumpVisitor(std::ostream& os, const Thread* thread)
4828e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      : os(os), thread(thread), frame_count(0) {
483d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
484d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
485bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  virtual ~StackDumpVisitor() {
486d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
487d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
488bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  void VisitFrame(const Frame& frame, uintptr_t pc) {
4899086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    if (!frame.HasMethod()) {
4909086572fa809d1a19d886b467e4da3ce42016982Ian Rogers      return;
4919086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    }
492d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
493d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    Method* m = frame.GetMethod();
494d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    Class* c = m->GetDeclaringClass();
4958e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
496d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    const DexFile& dex_file = class_linker->FindDexFile(c->GetDexCache());
497d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
498d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    os << "  at " << PrettyMethod(m, false);
499d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    if (m->IsNative()) {
500d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes      os << "(Native method)";
501d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    } else {
502bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      int line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
503d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes      os << "(" << c->GetSourceFile()->ToModifiedUtf8() << ":" << line_number << ")";
504d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    }
505d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    os << "\n";
5068e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
5078e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    if (frame_count++ == 0) {
5088e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      Monitor::DescribeWait(os, thread);
5098e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    }
510d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
511d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
512d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  std::ostream& os;
5138e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  const Thread* thread;
5148e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  int frame_count;
515d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes};
516d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
517d92bec457dc6c506c80e9da6b8e0c958266b5cdcElliott Hughesvoid Thread::DumpStack(std::ostream& os) const {
5188e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  StackDumpVisitor dumper(os, this);
519d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  WalkStack(&dumper);
520e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes}
521e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes
5228d768a954b101a9532f980253ac46be2c53aba11Elliott HughesThread::State Thread::SetState(Thread::State new_state) {
5238d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  Thread::State old_state = state_;
5248d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  if (old_state == new_state) {
5258d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    return old_state;
5268d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
5278d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
5288d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  volatile void* raw = reinterpret_cast<volatile void*>(&state_);
5298d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  volatile int32_t* addr = reinterpret_cast<volatile int32_t*>(raw);
5308d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
5318d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  if (new_state == Thread::kRunnable) {
5328d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    /*
5338d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * Change our status to Thread::kRunnable.  The transition requires
5348d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that we check for pending suspension, because the VM considers
5358d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * us to be "asleep" in all other states, and another thread could
5368d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * be performing a GC now.
5378d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
5388d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * The order of operations is very significant here.  One way to
5398d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * do this wrong is:
5408d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
5418d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   GCing thread                   Our thread (in kNative)
5428d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   ------------                   ----------------------
5438d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  check suspend count (== 0)
5448d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   SuspendAllThreads()
5458d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   grab suspend-count lock
5468d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   increment all suspend counts
5478d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   release suspend-count lock
5488d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   check thread state (== kNative)
5498d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *   all are suspended, begin GC
5508d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  set state to kRunnable
5518d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *                                  (continue executing)
5528d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
5538d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We can correct this by grabbing the suspend-count lock and
5548d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * performing both of our operations (check suspend count, set
5558d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * state) while holding it, now we need to grab a mutex on every
5568d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * transition to kRunnable.
5578d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
5588d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * What we do instead is change the order of operations so that
5598d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * the transition to kRunnable happens first.  If we then detect
5608d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that the suspend count is nonzero, we switch to kSuspended.
5618d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
5628d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * Appropriate compiler and memory barriers are required to ensure
5638d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * that the operations are observed in the expected order.
5648d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
5658d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * This does create a small window of opportunity where a GC in
5668d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * progress could observe what appears to be a running thread (if
5678d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * it happens to look between when we set to kRunnable and when we
5688d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * switch to kSuspended).  At worst this only affects assertions
5698d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * and thread logging.  (We could work around it with some sort
5708d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * of intermediate "pre-running" state that is generally treated
5718d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * as equivalent to running, but that doesn't seem worthwhile.)
5728d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
5738d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We can also solve this by combining the "status" and "suspend
5748d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * count" fields into a single 32-bit value.  This trades the
5758d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * store/load barrier on transition to kRunnable for an atomic RMW
5768d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * op on all transitions and all suspend count updates (also, all
5778d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * accesses to status or the thread count require bit-fiddling).
5788d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * It also eliminates the brief transition through kRunnable when
5798d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * the thread is supposed to be suspended.  This is possibly faster
5808d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * on SMP and slightly more correct, but less convenient.
5818d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     */
5828d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    android_atomic_acquire_store(new_state, addr);
5838d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    if (ANNOTATE_UNPROTECTED_READ(suspend_count_) != 0) {
5848d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      Runtime::Current()->GetThreadList()->FullSuspendCheck(this);
5858d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    }
5868d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  } else {
5878d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    /*
5888d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * Not changing to Thread::kRunnable. No additional work required.
5898d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     *
5908d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * We use a releasing store to ensure that, if we were runnable,
5918d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * any updates we previously made to objects on the managed heap
5928d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     * will be observed before the state change.
5938d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes     */
5948d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    android_atomic_release_store(new_state, addr);
5958d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
5968d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
5978d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  return old_state;
5988d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes}
5998d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
6008d768a954b101a9532f980253ac46be2c53aba11Elliott Hughesvoid Thread::WaitUntilSuspended() {
6018d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  // TODO: dalvik dropped the waiting thread's priority after a while.
6028d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  // TODO: dalvik timed out and aborted.
6038d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  useconds_t delay = 0;
6048d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  while (GetState() == Thread::kRunnable) {
6058d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    useconds_t new_delay = delay * 2;
6068d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    CHECK_GE(new_delay, delay);
6078d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    delay = new_delay;
6088d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    if (delay == 0) {
6098d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      sched_yield();
6108d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      delay = 10000;
6118d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    } else {
6128d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes      usleep(delay);
6138d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes    }
6148d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  }
6158d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes}
6168d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes
617be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::ThreadExitCallback(void* arg) {
618be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  Thread* self = reinterpret_cast<Thread*>(arg);
619be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes  LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
620b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
621b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
622be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughesvoid Thread::Startup() {
623b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  // Allocate a TLS slot.
6248d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback), "self key");
625b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
626b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  // Double-check the TLS slot allocation.
627b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  if (pthread_getspecific(pthread_key_self_) != NULL) {
628be759c63c6bb58b76ac71cad2c5a736bd31f374dElliott Hughes    LOG(FATAL) << "newly-created pthread TLS slot is not NULL";
629b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro  }
630038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes}
631038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
6328e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
6338e4aac52962d54cb4be2078b9cd95685e067133aElliott HughesClass* FindPrimitiveClassOrDie(ClassLinker* class_linker, char descriptor) {
6348e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* c = class_linker->FindPrimitiveClass(descriptor);
6358e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(c != NULL) << descriptor;
6368e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return c;
6378e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
6388e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
6398e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
6408e4aac52962d54cb4be2078b9cd95685e067133aElliott HughesClass* FindClassOrDie(ClassLinker* class_linker, const char* descriptor) {
6418e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* c = class_linker->FindSystemClass(descriptor);
6428e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(c != NULL) << descriptor;
6438e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return c;
6448e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
6458e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
6468e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
6478e4aac52962d54cb4be2078b9cd95685e067133aElliott HughesField* FindFieldOrDie(Class* c, const char* name, Class* type) {
6488e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Field* f = c->FindDeclaredInstanceField(name, type);
6498e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(f != NULL) << PrettyClass(c) << " " << name << " " << PrettyClass(type);
6508e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return f;
6518e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
6528e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
6538e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes// TODO: make more accessible?
6548e4aac52962d54cb4be2078b9cd95685e067133aElliott HughesMethod* FindMethodOrDie(Class* c, const char* name, const char* signature) {
6558e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Method* m = c->FindVirtualMethod(name, signature);
6568e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  CHECK(m != NULL) << PrettyClass(c) << " " << name << " " << signature;
6578e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return m;
6588e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
6598e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
660038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesvoid Thread::FinishStartup() {
661038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  // Now the ClassLinker is ready, we can find the various Class*, Field*, and Method*s we need.
662038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
6638e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
6648e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* boolean_class = FindPrimitiveClassOrDie(class_linker, 'Z');
6658e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* int_class = FindPrimitiveClassOrDie(class_linker, 'I');
666df143242f4beaad4cc9fbabebfc033b68c40964eBrian Carlstrom  Class* ClassLoader_class = FindClassOrDie(class_linker, "Ljava/lang/ClassLoader;");
6678e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* String_class = FindClassOrDie(class_linker, "Ljava/lang/String;");
6688e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* Thread_class = FindClassOrDie(class_linker, "Ljava/lang/Thread;");
6698e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* ThreadGroup_class = FindClassOrDie(class_linker, "Ljava/lang/ThreadGroup;");
6708e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Class* UncaughtExceptionHandler_class = FindClassOrDie(class_linker, "Ljava/lang/Thread$UncaughtExceptionHandler;");
6718e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThreadLock = FindClassOrDie(class_linker, "Ljava/lang/ThreadLock;");
6728e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThrowable = FindClassOrDie(class_linker, "Ljava/lang/Throwable;");
6738e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
6748e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_daemon = FindFieldOrDie(Thread_class, "daemon", boolean_class);
6758e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_group = FindFieldOrDie(Thread_class, "group", ThreadGroup_class);
6768e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_lock = FindFieldOrDie(Thread_class, "lock", gThreadLock);
6778e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_name = FindFieldOrDie(Thread_class, "name", String_class);
6788e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_priority = FindFieldOrDie(Thread_class, "priority", int_class);
6798e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_uncaughtHandler = FindFieldOrDie(Thread_class, "uncaughtHandler", UncaughtExceptionHandler_class);
6808e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_vmData = FindFieldOrDie(Thread_class, "vmData", int_class);
6818e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThreadGroup_name = FindFieldOrDie(ThreadGroup_class, "name", String_class);
6828e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThreadLock_thread = FindFieldOrDie(gThreadLock, "thread", Thread_class);
6838e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
6848e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThread_run = FindMethodOrDie(Thread_class, "run", "()V");
6858e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gThreadGroup_removeThread = FindMethodOrDie(ThreadGroup_class, "removeThread", "(Ljava/lang/Thread;)V");
6868e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  gUncaughtExceptionHandler_uncaughtException = FindMethodOrDie(UncaughtExceptionHandler_class,
6878e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      "uncaughtException", "(Ljava/lang/Thread;Ljava/lang/Throwable;)V");
68801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
68901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  // Finish attaching the main thread.
690df143242f4beaad4cc9fbabebfc033b68c40964eBrian Carlstrom  Thread* self = Thread::Current();
691df143242f4beaad4cc9fbabebfc033b68c40964eBrian Carlstrom  self->CreatePeer("main", false);
692df143242f4beaad4cc9fbabebfc033b68c40964eBrian Carlstrom
693df143242f4beaad4cc9fbabebfc033b68c40964eBrian Carlstrom  const Field* Thread_contextClassLoader = FindFieldOrDie(Thread_class , "contextClassLoader", ClassLoader_class);
694df143242f4beaad4cc9fbabebfc033b68c40964eBrian Carlstrom  Thread_contextClassLoader->SetObject(self->GetPeer(), self->GetClassLoaderOverride());
695b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro}
696b557353b22c728eecbd1c68593b482622c7782a8Carl Shapiro
697c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughesvoid Thread::Shutdown() {
6988d768a954b101a9532f980253ac46be2c53aba11Elliott Hughes  CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
699c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes}
700c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes
7018e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesuint32_t Thread::LockOwnerFromThreadLock(Object* thread_lock) {
7028e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (thread_lock == NULL || thread_lock->GetClass() != gThreadLock) {
7038e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
7048e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
7058e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Object* managed_thread = gThreadLock_thread->GetObject(thread_lock);
7068e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (managed_thread == NULL) {
7078e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
7088e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
7098e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  uintptr_t vmData = static_cast<uintptr_t>(gThread_vmData->GetInt(managed_thread));
7108e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  Thread* thread = reinterpret_cast<Thread*>(vmData);
7118e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  if (thread == NULL) {
7128e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    return ThreadList::kInvalidId;
7138e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
7148e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  return thread->GetThinLockId();
7158e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
7168e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
717dcc247493fd8fb243e335c3ec08e5e625896a47cElliott HughesThread::Thread()
71802b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes    : peer_(NULL),
7198e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      top_of_managed_stack_(),
7208e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      top_of_managed_stack_pc_(0),
72185d1545e985ac689db4bad7849880e843707c862Elliott Hughes      wait_mutex_(new Mutex("Thread wait mutex")),
72285d1545e985ac689db4bad7849880e843707c862Elliott Hughes      wait_cond_(new ConditionVariable("Thread wait condition variable")),
7238daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      wait_monitor_(NULL),
7248daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      interrupted_(false),
725dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      wait_next_(NULL),
7268e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      monitor_enter_object_(NULL),
727dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      card_table_(0),
7288daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes      stack_end_(NULL),
729dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      native_to_managed_record_(NULL),
730dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      top_sirt_(NULL),
731dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      jni_env_(NULL),
7328e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes      state_(Thread::kNative),
733dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      self_(NULL),
734dc33ad5db2dc6ed9b76d5219888626a604debbe1Elliott Hughes      runtime_(NULL),
735dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      exception_(NULL),
736dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes      suspend_count_(0),
73785d1545e985ac689db4bad7849880e843707c862Elliott Hughes      class_loader_override_(NULL),
738418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes      long_jump_context_(NULL),
739726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      throwing_OutOfMemoryError_(false),
740726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      pre_allocated_OutOfMemoryError_(NULL) {
741f5a7a476e7ea63e094ff0f011dccc170607e6f6bElliott Hughes  CHECK_EQ((sizeof(Thread) % 4), 0U) << sizeof(Thread);
742dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes}
743dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes
74402b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughesvoid MonitorExitVisitor(const Object* object, void*) {
74502b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  Object* entered_monitor = const_cast<Object*>(object);
7465f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  entered_monitor->MonitorExit(Thread::Current());
74702b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes}
74802b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
749c1674ed06662420213441ff2b818f2f71f9098dcElliott HughesThread::~Thread() {
7507a3aeb4d7580164c6a6905c63b96823b77ff5a64Elliott Hughes  SetState(Thread::kRunnable);
7517a3aeb4d7580164c6a6905c63b96823b77ff5a64Elliott Hughes
75202b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
75393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  if (jni_env_ != NULL) {
75493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    jni_env_->monitors.VisitRoots(MonitorExitVisitor, NULL);
75593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  }
75602b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
75729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  if (peer_ != NULL) {
75829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // this.group.removeThread(this);
759081be7fcd72490937e188e9ef56e72df06b7b006Elliott Hughes    // group can be null if we're in the compiler or a test.
760accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    Object* group = gThread_group->GetObject(peer_);
761081be7fcd72490937e188e9ef56e72df06b7b006Elliott Hughes    if (group != NULL) {
762081be7fcd72490937e188e9ef56e72df06b7b006Elliott Hughes      Method* m = group->GetClass()->FindVirtualMethodForVirtualOrInterface(gThreadGroup_removeThread);
763081be7fcd72490937e188e9ef56e72df06b7b006Elliott Hughes      Object* args = peer_;
764081be7fcd72490937e188e9ef56e72df06b7b006Elliott Hughes      m->Invoke(this, group, reinterpret_cast<byte*>(&args), NULL);
765081be7fcd72490937e188e9ef56e72df06b7b006Elliott Hughes    }
76629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes
76729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // this.vmData = 0;
76893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    SetVmData(peer_, NULL);
76902b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
77029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // TODO: say "bye" to the debugger.
77129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    //if (gDvm.debuggerConnected) {
77229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    //  dvmDbgPostThreadDeath(self);
77329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    //}
77402b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
77529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // Thread.join() is implemented as an Object.wait() on the Thread.lock
77629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // object. Signal anyone who is waiting.
7775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    Thread* self = Thread::Current();
778038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    Object* lock = gThread_lock->GetObject(peer_);
779038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes    // (This conditional is only needed for tests, where Thread.lock won't have been set.)
7805f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    if (lock != NULL) {
7815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->MonitorEnter(self);
7825f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->NotifyAll();
7835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock->MonitorExit(self);
7845f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
7855f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
78602b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
787c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes  delete jni_env_;
78802b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  jni_env_ = NULL;
78902b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes
79002b48d1dae0c3adc01ef6668226fb648fb52990aElliott Hughes  SetState(Thread::kTerminated);
79185d1545e985ac689db4bad7849880e843707c862Elliott Hughes
79285d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete wait_cond_;
79385d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete wait_mutex_;
79485d1545e985ac689db4bad7849880e843707c862Elliott Hughes
79585d1545e985ac689db4bad7849880e843707c862Elliott Hughes  delete long_jump_context_;
796c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes}
797c1674ed06662420213441ff2b818f2f71f9098dcElliott Hughes
798accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughesvoid Thread::HandleUncaughtExceptions() {
799accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  if (!IsExceptionPending()) {
800accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    return;
801accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  }
802accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
803accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  ScopedThreadStateChange tsc(this, Thread::kRunnable);
804accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
805accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // Get and clear the exception.
806accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* exception = GetException();
807accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  ClearException();
808accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
809accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // If the thread has its own handler, use that.
810accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* handler = gThread_uncaughtHandler->GetObject(peer_);
811accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  if (handler == NULL) {
812accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    // Otherwise use the thread group's default handler.
813accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    handler = gThread_group->GetObject(peer_);
814accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  }
815accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
816accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // Call the handler.
817accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Method* m = handler->GetClass()->FindVirtualMethodForVirtualOrInterface(gUncaughtExceptionHandler_uncaughtException);
818accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Object* args[2];
819accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  args[0] = peer_;
820accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  args[1] = exception;
821accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  m->Invoke(this, handler, reinterpret_cast<byte*>(&args), NULL);
822accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
823accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  // If the handler threw, clear that exception too.
824accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  ClearException();
825accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
826accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
827408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogerssize_t Thread::NumSirtReferences() {
828a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  size_t count = 0;
82940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
830a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers    count += cur->NumberOfReferences();
831a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  }
832a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  return count;
833a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers}
834a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers
835408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogersbool Thread::SirtContains(jobject obj) {
836408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  Object** sirt_entry = reinterpret_cast<Object**>(obj);
83740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
83840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    if (cur->Contains(sirt_entry)) {
839a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers      return true;
840a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers    }
841a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  }
842a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers  return false;
843a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers}
844a8cd9f4a849835af7856f9c9782ea59e11ddef85Ian Rogers
8458dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liaovoid Thread::SirtVisitRoots(Heap::RootVisitor* visitor, void* arg) {
84640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  for (StackIndirectReferenceTable* cur = top_sirt_; cur; cur = cur->GetLink()) {
8478dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    size_t num_refs = cur->NumberOfReferences();
8488dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    for (size_t j = 0; j < num_refs; j++) {
84940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom      Object* object = cur->GetReference(j);
8505e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom      if (object != NULL) {
8515e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom        visitor(object, arg);
8525e73f9c8990819054f8e0a60061ee8beff1e024aBrian Carlstrom      }
8538dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao    }
8548dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao  }
8558dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao}
8568dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
857408f79aeb676251ba35667a64e86c20638d7cb0bIan RogersObject* Thread::DecodeJObject(jobject obj) {
8580cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  DCHECK(CanAccessDirectReferences());
859408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  if (obj == NULL) {
860408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    return NULL;
861408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
862408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
863408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  IndirectRefKind kind = GetIndirectRefKind(ref);
864408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  Object* result;
865408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  switch (kind) {
866408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kLocal:
867408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
86869f5bc6759f256a146eefd8a7141d39fcc3b0421Elliott Hughes      IndirectReferenceTable& locals = jni_env_->locals;
869cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(locals.Get(ref));
870408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
871408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
872408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kGlobal:
873408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
874408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
875408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      IndirectReferenceTable& globals = vm->globals;
876408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      MutexLock mu(vm->globals_lock);
877cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(globals.Get(ref));
878408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
879408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
880408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kWeakGlobal:
881408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    {
882408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      JavaVMExt* vm = Runtime::Current()->GetJavaVM();
883408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      IndirectReferenceTable& weak_globals = vm->weak_globals;
884408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      MutexLock mu(vm->weak_globals_lock);
885cf4c6c41b0084dc4567ff709fb8ce9ebd72b26acElliott Hughes      result = const_cast<Object*>(weak_globals.Get(ref));
886408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      if (result == kClearedJniWeakGlobal) {
887408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers        // This is a special case where it's okay to return NULL.
888408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers        return NULL;
889408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      }
890408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      break;
891408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
892408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  case kSirtOrInvalid:
893408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  default:
894408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    // TODO: make stack indirect reference table lookup more efficient
895408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    // Check if this is a local reference in the SIRT
896408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    if (SirtContains(obj)) {
8970cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers      result = *reinterpret_cast<Object**>(obj);  // Read from SIRT
898c5bfa8f49d8548d7c685a99b411311ef56bedffaElliott Hughes    } else if (jni_env_->work_around_app_jni_bugs) {
899408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      // Assume an invalid local reference is actually a direct pointer.
900408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers      result = reinterpret_cast<Object*>(obj);
901408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    } else {
902a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes      result = kInvalidIndirectRefObject;
903408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers    }
904408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
905408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers
906408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  if (result == NULL) {
907a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    LOG(ERROR) << "JNI ERROR (app bug): use of deleted " << kind << ": " << obj;
908a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    JniAbort(NULL);
909a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes  } else {
910a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    if (result != kInvalidIndirectRefObject) {
911a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes      Heap::VerifyObject(result);
912a2501990dd0f68baf38ce19251949d7bb3ecfe5aElliott Hughes    }
913408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  }
914408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers  return result;
915408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers}
916408f79aeb676251ba35667a64e86c20638d7cb0bIan Rogers
9179b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liaoclass CountStackDepthVisitor : public Thread::StackVisitor {
9189b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao public:
91929f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  CountStackDepthVisitor() : depth_(0), skip_depth_(0), skipping_(true) {}
920d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes
92129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
92229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    // We want to skip frames up to and including the exception's constructor.
9239086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    // Note we also skip the frame if it doesn't have a method (namely the callee
9249086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    // save frame)
92525c3325bf95036bf325fc7cb21b4fd6d40282857Brian Carlstrom    DCHECK(gThrowable != NULL);
9269086572fa809d1a19d886b467e4da3ce42016982Ian Rogers    if (skipping_ && frame.HasMethod() && !gThrowable->IsAssignableFrom(frame.GetMethod()->GetDeclaringClass())) {
92729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      skipping_ = false;
92829f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
92929f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    if (!skipping_) {
93029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      ++depth_;
93129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    } else {
93229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      ++skip_depth_;
93329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
9349b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
9359b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
9369b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  int GetDepth() const {
937aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    return depth_;
9389b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
9399b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
94029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int GetSkipDepth() const {
94129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    return skip_depth_;
94229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  }
94329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes
9449b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao private:
945aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  uint32_t depth_;
94629f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  uint32_t skip_depth_;
94729f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  bool skipping_;
9489b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao};
9499b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
950aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogersclass BuildInternalStackTraceVisitor : public Thread::StackVisitor {
9519b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao public:
95229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  explicit BuildInternalStackTraceVisitor(int depth, int skip_depth, ScopedJniThreadState& ts)
953726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      : skip_depth_(skip_depth), count_(0), pc_trace_(NULL), method_trace_(NULL), local_ref_(NULL) {
954aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Allocate method trace with an extra slot that will hold the PC trace
95501158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    method_trace_ = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(depth + 1);
956726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (method_trace_ == NULL) {
957726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      return;
958726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
959aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Register a local reference as IntArray::Alloc may trigger GC
960aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    local_ref_ = AddLocalReference<jobject>(ts.Env(), method_trace_);
961aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    pc_trace_ = IntArray::Alloc(depth);
962726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (pc_trace_ == NULL) {
963726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      return;
964726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
965aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#ifdef MOVING_GARBAGE_COLLECTOR
966aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Re-read after potential GC
967aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace = Decode<ObjectArray<Object>*>(ts.Env(), local_ref_);
968aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#endif
969aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Save PC trace in last element of method trace, also places it into the
970aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // object graph.
971aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace_->Set(depth, pc_trace_);
9729b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
9739b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
974aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  virtual ~BuildInternalStackTraceVisitor() {}
9759b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
976bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  virtual void VisitFrame(const Frame& frame, uintptr_t pc) {
977726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    if (method_trace_ == NULL || pc_trace_ == NULL) {
978726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes      return; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
979726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    }
98029f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    if (skip_depth_ > 0) {
98129f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      skip_depth_--;
98229f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes      return;
98329f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes    }
984aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace_->Set(count_, frame.GetMethod());
985bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    pc_trace_->Set(count_, pc);
986aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    ++count_;
9879b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
9889b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
989aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  jobject GetInternalStackTrace() const {
990aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    return local_ref_;
9919b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  }
9929b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
9939b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao private:
99429f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  // How many more frames to skip.
99529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int32_t skip_depth_;
996aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Current position down stack trace
997aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  uint32_t count_;
998aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Array of return PC values
999aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  IntArray* pc_trace_;
1000aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // An array of the methods on the stack, the last entry is a reference to the
1001aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // PC trace
1002aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ObjectArray<Object>* method_trace_;
1003aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Local indirect reference table entry for method trace
1004aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  jobject local_ref_;
10059b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao};
10069b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao
1007a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes// TODO: remove this.
1008a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughesuintptr_t ManglePc(uintptr_t pc) {
1009a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // Move the PC back 2 bytes as a call will frequently terminate the
1010a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // decoding of a particular instruction and we want to make sure we
1011a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // get the Dex PC of the instruction with the call and not the
1012a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // instruction following.
1013a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  if (pc > 0) { pc -= 2; }
1014a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  return pc;
1015a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes}
1016a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes
1017a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes// TODO: remove this.
1018a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughesuintptr_t DemanglePc(uintptr_t pc) {
1019a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  // Revert mangling for the case where we need the PC to return to the upcall
1020a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  return pc + 2;
1021a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes}
1022f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers
102340381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstromvoid Thread::PushSirt(StackIndirectReferenceTable* sirt) {
102440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  sirt->SetLink(top_sirt_);
102540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  top_sirt_ = sirt;
102640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom}
102740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom
102840381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian CarlstromStackIndirectReferenceTable* Thread::PopSirt() {
102940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  CHECK(top_sirt_ != NULL);
103040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  StackIndirectReferenceTable* sirt = top_sirt_;
103140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  top_sirt_ = top_sirt_->GetLink();
103240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  return sirt;
103340381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom}
103440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom
1035aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogersvoid Thread::WalkStack(StackVisitor* visitor) const {
1036d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  Frame frame = GetTopOfStack();
1037a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
10389b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  // TODO: enable this CHECK after native_to_managed_record_ is initialized during startup.
10399b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  // CHECK(native_to_managed_record_ != NULL);
10409b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  NativeToManagedRecord* record = native_to_managed_record_;
10414417536522fd2a9d8215d8672331984769c9520bShih-wei Liao
1042bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  while (frame.GetSP() != 0) {
10439b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    for ( ; frame.GetMethod() != 0; frame.Next()) {
10443320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom      // DCHECK(frame.GetMethod()->IsWithinCode(pc));  // TODO: restore IsWithinCode
10453ddac99d4dc6a036fac59d8f0bdc664ef619fb04Shih-wei Liao      visitor->VisitFrame(frame, pc);
1046a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes      pc = ManglePc(frame.GetReturnPC());
10479b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    }
10489b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    if (record == NULL) {
10499b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao      break;
10509b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao    }
1051bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    // last_tos should return Frame instead of sp?
1052ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers    frame.SetSP(reinterpret_cast<Method**>(record->last_top_of_managed_stack_));
1053a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes    pc = ManglePc(record->last_top_of_managed_stack_pc_);
1054bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    record = record->link_;
1055bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  }
1056bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers}
1057bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
105867375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogersvoid Thread::WalkStackUntilUpCall(StackVisitor* visitor, bool include_upcall) const {
1059bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Frame frame = GetTopOfStack();
1060a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes  uintptr_t pc = ManglePc(top_of_managed_stack_pc_);
1061bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1062bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  if (frame.GetSP() != 0) {
1063bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    for ( ; frame.GetMethod() != 0; frame.Next()) {
10643320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom      // DCHECK(frame.GetMethod()->IsWithinCode(pc));  // TODO: restore IsWithinCode
10653ddac99d4dc6a036fac59d8f0bdc664ef619fb04Shih-wei Liao      visitor->VisitFrame(frame, pc);
1066a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes      pc = ManglePc(frame.GetReturnPC());
1067bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    }
106867375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    if (include_upcall) {
106967375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers      visitor->VisitFrame(frame, pc);
107067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    }
107155df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao  }
107255df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao}
107355df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
107401158d7a57c8321370667a6045220237d16e0da8Elliott Hughesjobject Thread::CreateInternalStackTrace(JNIEnv* env) const {
1075aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Compute depth of stack
10769b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  CountStackDepthVisitor count_visitor;
10779b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  WalkStack(&count_visitor);
10789b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  int32_t depth = count_visitor.GetDepth();
107929f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  int32_t skip_depth = count_visitor.GetSkipDepth();
10804417536522fd2a9d8215d8672331984769c9520bShih-wei Liao
1081aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Transition into runnable state to work on Object*/Array*
108201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  ScopedJniThreadState ts(env);
1083aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
1084aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Build internal stack trace
108529f2742a478e4f5bd2ec7473410c5e5e7134a6f2Elliott Hughes  BuildInternalStackTraceVisitor build_trace_visitor(depth, skip_depth, ts);
10869b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  WalkStack(&build_trace_visitor);
10874417536522fd2a9d8215d8672331984769c9520bShih-wei Liao
1088aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  return build_trace_visitor.GetInternalStackTrace();
1089aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers}
1090aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
109101158d7a57c8321370667a6045220237d16e0da8Elliott HughesjobjectArray Thread::InternalStackTraceToStackTraceElementArray(JNIEnv* env, jobject internal,
109201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    jobjectArray output_array, int* stack_depth) {
1093aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Transition into runnable state to work on Object*/Array*
1094aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ScopedJniThreadState ts(env);
1095aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
1096aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  // Decode the internal stack trace into the depth, method trace and PC trace
1097aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ObjectArray<Object>* method_trace =
1098aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers      down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1099aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  int32_t depth = method_trace->GetLength()-1;
1100aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  IntArray* pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1101aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
1102aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1103aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers
110401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  jobjectArray result;
110501158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  ObjectArray<StackTraceElement>* java_traces;
110601158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  if (output_array != NULL) {
110701158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // Reuse the array we were given.
110801158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    result = output_array;
110901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    java_traces = reinterpret_cast<ObjectArray<StackTraceElement>*>(Decode<Array*>(env,
111001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes        output_array));
111101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // ...adjusting the number of frames we'll write to not exceed the array length.
111201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    depth = std::min(depth, java_traces->GetLength());
111301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  } else {
111401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    // Create java_trace array and place in local reference table
111501158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    java_traces = class_linker->AllocStackTraceElementArray(depth);
111630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    if (java_traces == NULL) {
111730646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes      return NULL;
111830646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    }
111901158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    result = AddLocalReference<jobjectArray>(ts.Env(), java_traces);
112001158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  }
112101158d7a57c8321370667a6045220237d16e0da8Elliott Hughes
112201158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  if (stack_depth != NULL) {
112301158d7a57c8321370667a6045220237d16e0da8Elliott Hughes    *stack_depth = depth;
112401158d7a57c8321370667a6045220237d16e0da8Elliott Hughes  }
112555df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
11269b576b4ed1dbe035952f3106d8f4b6993125ed6fShih-wei Liao  for (int32_t i = 0; i < depth; ++i) {
1127aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
1128aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    Method* method = down_cast<Method*>(method_trace->Get(i));
1129aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    uint32_t native_pc = pc_trace->Get(i);
1130aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    Class* klass = method->GetDeclaringClass();
113138933579b15c74baa09b8713ee8bf715529d05ebElliott Hughes    std::string class_name(PrettyDescriptor(klass->GetDescriptor()));
1132466bb25416b88fabd5d4387b7c7e5cc1ece78b8cIan Rogers    int32_t line_number = -1;
1133466bb25416b88fabd5d4387b7c7e5cc1ece78b8cIan Rogers    DexCache* dex_cache = klass->GetDexCache();
1134466bb25416b88fabd5d4387b7c7e5cc1ece78b8cIan Rogers    if (dex_cache != NULL) {
1135466bb25416b88fabd5d4387b7c7e5cc1ece78b8cIan Rogers      const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
1136466bb25416b88fabd5d4387b7c7e5cc1ece78b8cIan Rogers      line_number = dex_file.GetLineNumFromPC(method, method->ToDexPC(native_pc));
1137466bb25416b88fabd5d4387b7c7e5cc1ece78b8cIan Rogers    }
1138aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Allocate element, potentially triggering GC
113940381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    // TODO: reuse class_name_object via Class::name_?
114040381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    SirtRef<String> class_name_object(String::AllocFromModifiedUtf8(class_name.c_str()));
114140381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    if (class_name_object.get() == NULL) {
114240381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom      return NULL;
114340381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    }
114440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    StackTraceElement* obj = StackTraceElement::Alloc(class_name_object.get(),
114540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom                                                      method->GetName(),
114640381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom                                                      klass->GetSourceFile(),
114740381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom                                                      line_number);
114830646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    if (obj == NULL) {
114930646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes      return NULL;
115030646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    }
1151aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#ifdef MOVING_GARBAGE_COLLECTOR
1152aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    // Re-read after potential GC
1153aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    java_traces = Decode<ObjectArray<Object>*>(ts.Env(), result);
1154aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    method_trace = down_cast<ObjectArray<Object>*>(Decode<Object*>(ts.Env(), internal));
1155aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers    pc_trace = down_cast<IntArray*>(method_trace->Get(depth));
1156aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers#endif
115755df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao    java_traces->Set(i, obj);
115855df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao  }
1159aaa208006d7c8cc0f381c4aa9b525be24066c495Ian Rogers  return result;
116055df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao}
116155df06be4369f5d8ab5eb61a5d22809255171036Shih-wei Liao
1162fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughesvoid Thread::GetCurrentLocation(const char*& source_file, uint32_t& line_number) const {
1163fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  Frame f = top_of_managed_stack_;
1164fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  Method* m = f.GetMethod();
1165fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  // TODO: can this ever happen?
1166fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  if (m->IsCalleeSaveMethod()) {
1167fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes    f.Next();
1168fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes    m = f.GetMethod();
1169fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  }
1170fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes
1171fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1172fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  Class* c = m->GetDeclaringClass();
1173fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  DexCache* dex_cache = c->GetDexCache();
1174fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  const DexFile& dex_file = class_linker->FindDexFile(dex_cache);
1175fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  const DexFile::ClassDef* class_def = dex_file.FindClassDef(c->GetDescriptor()->ToModifiedUtf8());
1176fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes
1177fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  source_file = dex_file.dexGetSourceFile(*class_def);
1178fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes
1179fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  uint32_t pc = ManglePc(f.GetReturnPC());
1180fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  line_number = dex_file.GetLineNumFromPC(m, m->ToDexPC(pc));
1181fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes}
1182fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes
11835cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughesvoid Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
1184a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_list args;
1185a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_start(args, fmt);
11864a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  ThrowNewExceptionV(exception_class_descriptor, fmt, args);
1187a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes  va_end(args);
11884a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes}
11894a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes
11904a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughesvoid Thread::ThrowNewExceptionV(const char* exception_class_descriptor, const char* fmt, va_list ap) {
11914a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  std::string msg;
11924a2b41793d18d402286ae37e9de4fd392bc75a08Elliott Hughes  StringAppendV(&msg, fmt, ap);
11935cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughes  ThrowNewException(exception_class_descriptor, msg.c_str());
11945cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughes}
119537f7a40f6789bb287f287a9af00777af9d6428eeElliott Hughes
11965cb5ad27944efb08d4556b3c0d362302e37e832bElliott Hughesvoid Thread::ThrowNewException(const char* exception_class_descriptor, const char* msg) {
1197e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  // Convert "Ljava/lang/Exception;" into JNI-style "java/lang/Exception".
11980cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  CHECK_EQ('L', exception_class_descriptor[0]);
1199e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  std::string descriptor(exception_class_descriptor + 1);
12000cfe1fb7060576d047f7f894fc0d8b87de84fcabIan Rogers  CHECK_EQ(';', descriptor[descriptor.length() - 1]);
1201e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  descriptor.erase(descriptor.length() - 1);
1202e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes
1203e5b0dc83537bf915c6abe4efeae6e501daf75a27Elliott Hughes  JNIEnv* env = GetJniEnv();
1204726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  ScopedLocalRef<jclass> exception_class(env, env->FindClass(descriptor.c_str()));
120530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  if (exception_class.get() == NULL) {
120630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI FindClass failed: "
120730646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes               << PrettyTypeOf(GetException());
120830646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    CHECK(IsExceptionPending());
120930646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    return;
121030646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  }
1211726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  int rc = env->ThrowNew(exception_class.get(), msg);
121230646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  if (rc != JNI_OK) {
121330646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    LOG(ERROR) << "Couldn't throw new " << descriptor << " because JNI ThrowNew failed: "
121430646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes               << PrettyTypeOf(GetException());
121530646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    CHECK(IsExceptionPending());
121630646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes    return;
121730646836b4a1c6e5e80ddaea246cf9669eaa0628Elliott Hughes  }
1218a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes}
1219a5b897eae4b6f9f9608faa9eada7ddf42bf1bfd2Elliott Hughes
1220418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughesvoid Thread::ThrowOutOfMemoryError(Class* c, size_t byte_count) {
12212ced6a534157d5d963693346904389c19775d2daElliott Hughes  std::string msg(StringPrintf("Failed to allocate a %zd-byte %s", byte_count,
12222ced6a534157d5d963693346904389c19775d2daElliott Hughes      PrettyDescriptor(c->GetDescriptor()).c_str()));
12232ced6a534157d5d963693346904389c19775d2daElliott Hughes  ThrowOutOfMemoryError(msg.c_str());
12242ced6a534157d5d963693346904389c19775d2daElliott Hughes}
12252ced6a534157d5d963693346904389c19775d2daElliott Hughes
12262ced6a534157d5d963693346904389c19775d2daElliott Hughesvoid Thread::ThrowOutOfMemoryError(const char* msg) {
12272ced6a534157d5d963693346904389c19775d2daElliott Hughes  LOG(ERROR) << StringPrintf("Throwing OutOfMemoryError \"%s\"%s",
12282ced6a534157d5d963693346904389c19775d2daElliott Hughes      msg, (throwing_OutOfMemoryError_ ? " (recursive case)" : ""));
1229726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  if (!throwing_OutOfMemoryError_) {
1230726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    throwing_OutOfMemoryError_ = true;
1231accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes    ThrowNewException("Ljava/lang/OutOfMemoryError;", NULL);
1232418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes  } else {
1233726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    SetException(pre_allocated_OutOfMemoryError_);
1234418dfe7849f45535b5388a91bd7a16cfc20a612bElliott Hughes  }
1235726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  throwing_OutOfMemoryError_ = false;
123679082e367845bbd68ec44ef2ddd1be8ef0e1550fElliott Hughes}
123779082e367845bbd68ec44ef2ddd1be8ef0e1550fElliott Hughes
1238accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1239498508c1187dc07d3eae5476784cde20f5224d93Elliott HughesThread* Thread::CurrentFromGdb() {
1240accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  return Thread::Current();
1241accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
1242accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1243accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughesvoid Thread::DumpFromGdb() const {
1244accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes  Dump(std::cerr);
1245accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes}
1246accd83d1523545ac69bafd38e72a7d5cff8e2facElliott Hughes
1247bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogersclass CatchBlockStackVisitor : public Thread::StackVisitor {
1248bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers public:
1249bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  CatchBlockStackVisitor(Class* to_find, Context* ljc)
125067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers      : found_(false), to_find_(to_find), long_jump_context_(ljc), native_method_count_(0) {
125167375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers#ifndef NDEBUG
125267375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    handler_pc_ = 0xEBADC0DE;
125367375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers    handler_frame_.SetSP(reinterpret_cast<Method**>(0xEBADF00D));
125467375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers#endif
125567375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  }
1256bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1257bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  virtual void VisitFrame(const Frame& fr, uintptr_t pc) {
1258bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    if (!found_) {
1259bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      Method* method = fr.GetMethod();
126067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers      if (method == NULL) {
126167375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers        // This is the upcall, we remember the frame and last_pc so that we may
126267375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers        // long jump to them
1263a43cb5e8fb29989dbb986b9b91a68cda150aa3c8Elliott Hughes        handler_pc_ = DemanglePc(pc);
126467375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers        handler_frame_ = fr;
126567375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers        return;
126667375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers      }
126767375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers      uint32_t dex_pc = DexFile::kDexNoIndex;
12683320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom      if (method->IsCalleeSaveMethod()) {
12699086572fa809d1a19d886b467e4da3ce42016982Ian Rogers        // ignore callee save method
12709086572fa809d1a19d886b467e4da3ce42016982Ian Rogers      } else if (method->IsNative()) {
12719086572fa809d1a19d886b467e4da3ce42016982Ian Rogers        native_method_count_++;
12729086572fa809d1a19d886b467e4da3ce42016982Ian Rogers      } else {
12739086572fa809d1a19d886b467e4da3ce42016982Ian Rogers        dex_pc = method->ToDexPC(pc);
1274bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
1275bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      if (dex_pc != DexFile::kDexNoIndex) {
1276bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers        uint32_t found_dex_pc = method->FindCatchBlock(to_find_, dex_pc);
1277bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers        if (found_dex_pc != DexFile::kDexNoIndex) {
1278bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers          found_ = true;
127967375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers          handler_pc_ = method->ToNativePC(found_dex_pc);
128067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers          handler_frame_ = fr;
1281bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers        }
1282bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
1283bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      if (!found_) {
1284bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers        // Caller may be handler, fill in callee saves in context
1285bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers        long_jump_context_->FillCalleeSaves(fr);
1286bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers      }
12871a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao    }
12881a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao  }
12891a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao
1290bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // Did we find a catch block yet?
1291bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  bool found_;
1292bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // The type of the exception catch block to find
1293bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Class* to_find_;
1294bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // Frame with found handler or last frame if no handler found
1295bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Frame handler_frame_;
129667375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  // PC to branch to for the handler
129767375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  uintptr_t handler_pc_;
1298bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  // Context that will be the target of the long jump
1299bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Context* long_jump_context_;
130067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  // Number of native methods passed in crawl (equates to number of SIRTs to pop)
130167375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  uint32_t native_method_count_;
1302bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers};
1303bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1304ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogersvoid Thread::DeliverException() {
1305ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  Throwable *exception = GetException();  // Set exception on thread
1306ff1ed4770bf7ff024a807b9f909b1a26abb78341Ian Rogers  CHECK(exception != NULL);
1307bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1308bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  Context* long_jump_context = GetLongJumpContext();
1309bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  CatchBlockStackVisitor catch_finder(exception->GetClass(), long_jump_context);
131067375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  WalkStackUntilUpCall(&catch_finder, true);
1311bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
131267375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  long_jump_context->SetSP(reinterpret_cast<intptr_t>(catch_finder.handler_frame_.GetSP()));
131367375acd9fec74cc2054554fe1ed0a7d213e1e47Ian Rogers  long_jump_context->SetPC(catch_finder.handler_pc_);
1314bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  long_jump_context->DoLongJump();
1315bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers}
1316bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers
1317bdb0391258abc54bf77c676e36847d28a783bfe5Ian RogersContext* Thread::GetLongJumpContext() {
131885d1545e985ac689db4bad7849880e843707c862Elliott Hughes  Context* result = long_jump_context_;
1319bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  if (result == NULL) {
1320bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers    result = Context::Create();
132185d1545e985ac689db4bad7849880e843707c862Elliott Hughes    long_jump_context_ = result;
13221a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao  }
1323bdb0391258abc54bf77c676e36847d28a783bfe5Ian Rogers  return result;
13241a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao}
13251a18c8c1c0e4ea1ff06177e93c7ff703376dcee2Shih-wei Liao
13269fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughesconst Method* Thread::GetCurrentMethod() const {
13279fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  Method* m = top_of_managed_stack_.GetMethod();
13289fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // We use JNI internally for exception throwing, so it's possible to arrive
13299fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // here via a "FromCode" function, in which case there's a synthetic
13309fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // callee-save method at the top of the stack. These shouldn't be user-visible,
13319fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  // so if we find one, skip it and return the compiled method underneath.
13329fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  if (m->IsCalleeSaveMethod()) {
13339fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes    Frame f = top_of_managed_stack_;
13349fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes    f.Next();
13359fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes    m = f.GetMethod();
13369fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  }
13379fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes  return m;
13389fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes}
13399fd66f5bb6a514147a53d57b419d18ecc7937122Elliott Hughes
13405f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesbool Thread::HoldsLock(Object* object) {
13415f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (object == NULL) {
13425f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return false;
13435f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
134424a3c2e9924e8765c4a9b4d383cb8f3b922f9c9fBrian Carlstrom  return object->GetThinLockId() == thin_lock_id_;
13455f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
13465f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1347038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughesbool Thread::IsDaemon() {
1348038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes  return gThread_daemon->GetBoolean(peer_);
1349038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes}
1350038a806df72f884d22283a84a31c9a1d35ba1fdfElliott Hughes
1351d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogersclass ReferenceMapVisitor : public Thread::StackVisitor {
1352d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers public:
1353d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  ReferenceMapVisitor(Context* context, Heap::RootVisitor* root_visitor, void* arg) :
1354d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    context_(context), root_visitor_(root_visitor), arg_(arg) {
1355d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1356d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1357d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  void VisitFrame(const Frame& frame, uintptr_t pc) {
1358d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    Method* m = frame.GetMethod();
1359d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    // Process register map (which native and callee save methods don't have)
13603320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom    if (!m->IsNative() && !m->IsCalleeSaveMethod()) {
1361d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      UniquePtr<art::DexVerifier::RegisterMap> map(art::DexVerifier::GetExpandedRegisterMap(m));
1362f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers      const uint8_t* reg_bitmap = art::DexVerifier::RegisterMapGetLine(map.get(), m->ToDexPC(pc));
13639f865379c9ddf03f7363f362a8d63cb5d5b4e722Elliott Hughes      if (false) {
13649f865379c9ddf03f7363f362a8d63cb5d5b4e722Elliott Hughes        LOG(INFO) << "Visiting stack roots in " << PrettyMethod(m, false)
13659f865379c9ddf03f7363f362a8d63cb5d5b4e722Elliott Hughes                  << "@ PC: " << m->ToDexPC(pc);
13669f865379c9ddf03f7363f362a8d63cb5d5b4e722Elliott Hughes      }
1367d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      CHECK(reg_bitmap != NULL);
13683320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom      const uint16_t* vmap = m->GetVmapTable();
1369d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      // For all dex registers
1370d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      for (int reg = 0; reg < m->NumRegisters(); ++reg) {
1371d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        // Does this register hold a reference?
1372d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        if (TestBitmap(reg, reg_bitmap)) {
1373d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          // Is the reference in the context or on the stack?
1374d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          bool in_context = false;
1375f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers          uint32_t vmap_offset = 0xEBAD0FF5;
1376d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          // TODO: take advantage of the registers being ordered
13773320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom          for (int i = 0; i < m->GetVmapTableLength(); i++) {
13783320cf46afd082398aa401b246e6f301cebdf64dBrian Carlstrom            if (vmap[i] == reg) {
1379d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers              in_context = true;
1380d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers              vmap_offset = i;
1381d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers              break;
1382d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            }
1383d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          }
1384d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          Object* ref;
1385d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          if (in_context) {
1386d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            // Compute the register we need to load from the context
1387d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            uint32_t spill_mask = m->GetCoreSpillMask();
1388f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            uint32_t matches = 0;
1389f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            uint32_t spill_shifts = 0;
1390f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            while (matches != (vmap_offset + 1)) {
1391f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              CHECK_NE(spill_mask, 0u);
1392f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              matches += spill_mask & 1;  // Add 1 if the low bit is set
1393f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              spill_mask >>= 1;
1394f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers              spill_shifts++;
1395d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers            }
1396f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            spill_shifts--;  // wind back one as we want the last match
1397f57c47c29cd3388d1d78008a71c4e18f2217b70cIan Rogers            ref = reinterpret_cast<Object*>(context_->GetGPR(spill_shifts));
1398d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          } else {
1399362f9bc807169bcfc8761dde067bbfb79b5ad0fdElliott Hughes            ref = reinterpret_cast<Object*>(frame.GetVReg(m, reg));
1400d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers          }
14014f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao          if (ref != NULL) {
14024f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao            root_visitor_(ref, arg_);
14034f894e385e8ac018f078be75fea0a45696626b15Shih-wei Liao          }
1404d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers        }
1405d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers      }
1406d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    }
1407d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    context_->FillCalleeSaves(frame);
1408d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1409d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1410d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers private:
1411d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  bool TestBitmap(int reg, const uint8_t* reg_vector) {
1412d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers    return ((reg_vector[reg / 8] >> (reg % 8)) & 0x01) != 0;
1413d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  }
1414d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1415d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Context used to build up picture of callee saves
1416d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Context* context_;
1417d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Call-back when we visit a root
1418d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Heap::RootVisitor* root_visitor_;
1419d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Argument to call-back
1420d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  void* arg_;
1421d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers};
1422d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers
1423d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogersvoid Thread::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
1424d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (exception_ != NULL) {
1425d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    visitor(exception_, arg);
1426d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
1427d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  if (peer_ != NULL) {
1428d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes    visitor(peer_, arg);
1429d369bb76dee0df2d2a106e9bf7f4e6446ed6deaaElliott Hughes  }
1430726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  if (pre_allocated_OutOfMemoryError_ != NULL) {
1431726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes    visitor(pre_allocated_OutOfMemoryError_, arg);
1432726079d3e2e50854cd6ca4c393f4529a796dba58Elliott Hughes  }
143340381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  if (class_loader_override_ != NULL) {
143440381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom    visitor(class_loader_override_, arg);
143540381fb9dc4b4cf274f1e58b2cdf4396202c6189Brian Carlstrom  }
1436410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes  jni_env_->locals.VisitRoots(visitor, arg);
1437410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes  jni_env_->monitors.VisitRoots(visitor, arg);
14388dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
14398dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao  SirtVisitRoots(visitor, arg);
14408dfc9d551a9603eb8bc8463621b7bc73c3035169Shih-wei Liao
1441d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Cheat and steal the long jump context. Assume that we are not doing a GC during exception
1442d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // delivery.
1443d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  Context* context = GetLongJumpContext();
1444d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  // Visit roots on this thread's stack
1445d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  ReferenceMapVisitor mapper(context, visitor, arg);
1446d6b1f6190c8ec42facb08aca34b093244774b318Ian Rogers  WalkStack(&mapper);
1447410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes}
1448410c0c876f326e14c176a39ba21fc4dd3f7db8abElliott Hughes
1449b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogersstatic const char* kStateNames[] = {
145093e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Terminated",
1451b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Runnable",
145293e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "TimedWaiting",
1453b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Blocked",
1454b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Waiting",
145593e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Initializing",
145693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Starting",
1457b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  "Native",
145893e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "VmWait",
145993e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  "Suspended",
1460b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers};
1461b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogersstd::ostream& operator<<(std::ostream& os, const Thread::State& state) {
14628e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  int32_t int_state = static_cast<int32_t>(state);
146393e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes  if (state >= Thread::kTerminated && state <= Thread::kSuspended) {
146493e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    os << kStateNames[int_state];
1465b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  } else {
146693e74e8d879270071c3aa163f8495ada8d21f42fElliott Hughes    os << "State[" << int_state << "]";
1467b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  }
1468b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers  return os;
1469b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers}
1470b033c75ebda80ac75f936366fe78d1edf5cec937Ian Rogers
1471330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughesstd::ostream& operator<<(std::ostream& os, const Thread& thread) {
1472330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes  os << "Thread[" << &thread
1473e27955ca3ca960928d4dbd6cb79711fce06950b3Elliott Hughes     << ",tid=" << thread.GetTid()
1474dcc247493fd8fb243e335c3ec08e5e625896a47cElliott Hughes     << ",id=" << thread.GetThinLockId()
14758daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes     << ",state=" << thread.GetState()
14768daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes     << ",peer=" << thread.GetPeer()
14778daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes     << "]";
1478330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes  return os;
1479330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes}
1480330304de14dc7118b45b8e7b5bd11a172fa61701Elliott Hughes
14818daa0929f08a3080ea64dbd4e997e72f411e6fc9Elliott Hughes}  // namespace art
1482